From 0afbcc773b98ddb46c114baa889ca223a875fa71 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 00:23:20 +0200 Subject: [PATCH 01/38] refactor: using eslint-config-neon on mainlib --- eslint.config.js | 23 +- .../{.eslintrc.json => .eslintrc.json.bak} | 0 packages/discord.js/.lintstagedrc.json | 2 +- packages/discord.js/package.json | 4 +- packages/discord.js/src/client/BaseClient.js | 11 +- packages/discord.js/src/client/Client.js | 117 +++++++-- .../discord.js/src/client/WebhookClient.js | 33 ++- .../discord.js/src/client/actions/Action.js | 1 + .../src/client/actions/ActionsManager.js | 2 + .../src/client/actions/ChannelCreate.js | 4 +- .../src/client/actions/ChannelDelete.js | 3 +- .../src/client/actions/ChannelUpdate.js | 2 +- .../src/client/actions/GuildEmojiCreate.js | 3 +- .../src/client/actions/GuildEmojiDelete.js | 3 +- .../src/client/actions/GuildEmojiUpdate.js | 3 +- .../src/client/actions/GuildMemberRemove.js | 5 +- .../src/client/actions/GuildMemberUpdate.js | 4 +- .../src/client/actions/GuildRoleCreate.js | 4 +- .../src/client/actions/GuildRoleDelete.js | 3 +- .../actions/GuildScheduledEventDelete.js | 3 +- .../actions/GuildScheduledEventUserAdd.js | 3 +- .../actions/GuildScheduledEventUserRemove.js | 3 +- .../actions/GuildSoundboardSoundDelete.js | 3 +- .../src/client/actions/GuildStickerCreate.js | 3 +- .../src/client/actions/GuildStickerDelete.js | 3 +- .../src/client/actions/GuildStickerUpdate.js | 3 +- .../src/client/actions/GuildUpdate.js | 3 +- .../src/client/actions/InteractionCreate.js | 6 +- .../src/client/actions/MessageCreate.js | 3 +- .../src/client/actions/MessageDelete.js | 3 +- .../src/client/actions/MessageDeleteBulk.js | 4 +- .../src/client/actions/MessagePollVoteAdd.js | 3 +- .../client/actions/MessagePollVoteRemove.js | 3 +- .../src/client/actions/MessageReactionAdd.js | 6 +- .../client/actions/MessageReactionRemove.js | 3 +- .../actions/MessageReactionRemoveAll.js | 3 +- .../actions/MessageReactionRemoveEmoji.js | 3 +- .../src/client/actions/StageInstanceCreate.js | 3 +- .../src/client/actions/StageInstanceDelete.js | 3 +- .../src/client/actions/StageInstanceUpdate.js | 3 +- .../src/client/actions/ThreadCreate.js | 4 +- .../src/client/actions/ThreadMembersUpdate.js | 4 +- .../src/client/actions/TypingStart.js | 3 +- .../src/client/actions/UserUpdate.js | 3 +- .../src/client/voice/ClientVoiceManager.js | 4 +- .../APPLICATION_COMMAND_PERMISSIONS_UPDATE.js | 1 + .../AUTO_MODERATION_ACTION_EXECUTION.js | 1 + .../handlers/AUTO_MODERATION_RULE_CREATE.js | 1 + .../handlers/AUTO_MODERATION_RULE_DELETE.js | 1 + .../handlers/AUTO_MODERATION_RULE_UPDATE.js | 1 + .../websocket/handlers/CHANNEL_PINS_UPDATE.js | 1 + .../websocket/handlers/CHANNEL_UPDATE.js | 1 + .../websocket/handlers/ENTITLEMENT_CREATE.js | 1 + .../websocket/handlers/ENTITLEMENT_DELETE.js | 1 + .../websocket/handlers/ENTITLEMENT_UPDATE.js | 1 + .../handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js | 1 + .../websocket/handlers/GUILD_BAN_ADD.js | 1 + .../websocket/handlers/GUILD_BAN_REMOVE.js | 1 + .../client/websocket/handlers/GUILD_CREATE.js | 2 + .../client/websocket/handlers/GUILD_DELETE.js | 2 + .../handlers/GUILD_INTEGRATIONS_UPDATE.js | 1 + .../websocket/handlers/GUILD_MEMBERS_CHUNK.js | 4 +- .../websocket/handlers/GUILD_MEMBER_ADD.js | 1 + .../websocket/handlers/GUILD_ROLE_UPDATE.js | 1 + .../handlers/GUILD_SCHEDULED_EVENT_CREATE.js | 1 + .../handlers/GUILD_SCHEDULED_EVENT_UPDATE.js | 1 + .../GUILD_SOUNDBOARD_SOUNDS_UPDATE.js | 1 + .../handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js | 1 + .../handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js | 1 + .../websocket/handlers/INVITE_CREATE.js | 1 + .../websocket/handlers/INVITE_DELETE.js | 1 + .../websocket/handlers/MESSAGE_UPDATE.js | 1 + .../websocket/handlers/PRESENCE_UPDATE.js | 6 +- .../src/client/websocket/handlers/READY.js | 1 + .../websocket/handlers/SOUNDBOARD_SOUNDS.js | 1 + .../websocket/handlers/SUBSCRIPTION_CREATE.js | 1 + .../websocket/handlers/SUBSCRIPTION_DELETE.js | 1 + .../websocket/handlers/SUBSCRIPTION_UPDATE.js | 1 + .../websocket/handlers/THREAD_DELETE.js | 1 + .../websocket/handlers/THREAD_LIST_SYNC.js | 1 + .../handlers/THREAD_MEMBER_UPDATE.js | 1 + .../websocket/handlers/THREAD_UPDATE.js | 1 + .../handlers/VOICE_CHANNEL_EFFECT_SEND.js | 1 + .../websocket/handlers/VOICE_STATE_UPDATE.js | 1 + .../websocket/handlers/WEBHOOKS_UPDATE.js | 1 + packages/discord.js/src/errors/DJSError.js | 2 + packages/discord.js/src/errors/ErrorCodes.js | 76 +++--- .../src/managers/ApplicationCommandManager.js | 31 ++- .../ApplicationCommandPermissionsManager.js | 68 ++++-- .../src/managers/ApplicationEmojiManager.js | 14 +- .../src/managers/AutoModerationRuleManager.js | 38 ++- .../discord.js/src/managers/BaseManager.js | 2 + .../discord.js/src/managers/CachedManager.js | 6 +- .../managers/CategoryChannelChildManager.js | 12 +- .../discord.js/src/managers/ChannelManager.js | 15 +- .../src/managers/DMMessageManager.js | 2 + .../discord.js/src/managers/DataManager.js | 13 +- .../src/managers/EntitlementManager.js | 25 +- .../GuildApplicationCommandManager.js | 3 + .../src/managers/GuildBanManager.js | 28 ++- .../src/managers/GuildChannelManager.js | 59 +++-- .../src/managers/GuildEmojiManager.js | 38 ++- .../src/managers/GuildEmojiRoleManager.js | 14 +- .../src/managers/GuildForumThreadManager.js | 6 +- .../src/managers/GuildInviteManager.js | 40 +++- .../discord.js/src/managers/GuildManager.js | 57 +++-- .../src/managers/GuildMemberManager.js | 85 +++++-- .../src/managers/GuildMemberRoleManager.js | 21 +- .../src/managers/GuildMessageManager.js | 5 +- .../managers/GuildScheduledEventManager.js | 46 ++-- .../managers/GuildSoundboardSoundManager.js | 24 +- .../src/managers/GuildStickerManager.js | 30 ++- .../src/managers/GuildTextThreadManager.js | 6 +- .../discord.js/src/managers/MessageManager.js | 41 +++- .../managers/PartialGroupDMMessageManager.js | 2 + .../managers/PermissionOverwriteManager.js | 20 +- .../src/managers/PollAnswerVoterManager.js | 8 +- .../src/managers/PresenceManager.js | 13 +- .../src/managers/ReactionManager.js | 15 +- .../src/managers/ReactionUserManager.js | 13 +- .../discord.js/src/managers/RoleManager.js | 37 ++- .../src/managers/StageInstanceManager.js | 22 +- .../src/managers/SubscriptionManager.js | 11 +- .../discord.js/src/managers/ThreadManager.js | 35 ++- .../src/managers/ThreadMemberManager.js | 29 ++- .../discord.js/src/managers/UserManager.js | 22 +- .../src/managers/VoiceStateManager.js | 7 +- packages/discord.js/src/sharding/Shard.js | 75 ++++-- .../src/sharding/ShardClientUtil.js | 66 +++-- .../src/sharding/ShardingManager.js | 77 ++++-- .../discord.js/src/structures/ActionRow.js | 5 +- .../src/structures/AnnouncementChannel.js | 2 + .../src/structures/AnonymousGuild.js | 14 +- .../src/structures/ApplicationCommand.js | 109 ++++++--- .../src/structures/ApplicationEmoji.js | 19 +- .../ApplicationRoleConnectionMetadata.js | 10 +- .../discord.js/src/structures/Attachment.js | 17 +- .../src/structures/AttachmentBuilder.js | 15 +- .../AutoModerationActionExecution.js | 15 ++ .../src/structures/AutoModerationRule.js | 67 ++++-- .../src/structures/AutocompleteInteraction.js | 12 +- packages/discord.js/src/structures/Base.js | 2 + .../discord.js/src/structures/BaseChannel.js | 23 +- .../discord.js/src/structures/BaseGuild.js | 21 +- .../src/structures/BaseGuildEmoji.js | 6 + .../src/structures/BaseGuildTextChannel.js | 56 +++-- .../src/structures/BaseGuildVoiceChannel.js | 50 +++- .../src/structures/BaseInteraction.js | 46 +++- .../src/structures/BaseSelectMenuComponent.js | 6 + .../src/structures/ButtonComponent.js | 7 + .../src/structures/ButtonInteraction.js | 1 + .../src/structures/CategoryChannel.js | 7 +- .../structures/ChannelSelectMenuComponent.js | 2 + .../ChannelSelectMenuInteraction.js | 3 + .../structures/ChatInputCommandInteraction.js | 5 +- .../src/structures/ClientApplication.js | 58 ++++- .../src/structures/ClientPresence.js | 7 +- .../discord.js/src/structures/ClientUser.js | 53 +++-- .../src/structures/CommandInteraction.js | 28 ++- .../CommandInteractionOptionResolver.js | 59 +++-- .../discord.js/src/structures/Component.js | 5 + .../ContextMenuCommandInteraction.js | 6 +- .../discord.js/src/structures/DMChannel.js | 26 +- .../src/structures/DirectoryChannel.js | 4 + packages/discord.js/src/structures/Embed.js | 23 +- packages/discord.js/src/structures/Emoji.js | 11 +- .../discord.js/src/structures/Entitlement.js | 22 +- .../discord.js/src/structures/ForumChannel.js | 5 +- packages/discord.js/src/structures/Guild.js | 225 +++++++++++++----- .../src/structures/GuildAuditLogs.js | 8 +- .../src/structures/GuildAuditLogsEntry.js | 121 ++++++---- .../discord.js/src/structures/GuildBan.js | 10 +- .../discord.js/src/structures/GuildChannel.js | 48 +++- .../discord.js/src/structures/GuildEmoji.js | 22 +- .../discord.js/src/structures/GuildMember.js | 84 +++++-- .../src/structures/GuildOnboarding.js | 7 + .../src/structures/GuildOnboardingPrompt.js | 10 + .../structures/GuildOnboardingPromptOption.js | 10 + .../discord.js/src/structures/GuildPreview.js | 32 ++- .../src/structures/GuildPreviewEmoji.js | 3 + .../src/structures/GuildScheduledEvent.js | 79 ++++-- .../src/structures/GuildTemplate.js | 29 ++- .../discord.js/src/structures/Integration.js | 33 ++- .../src/structures/IntegrationApplication.js | 7 + .../src/structures/InteractionCallback.js | 9 + .../structures/InteractionCallbackResource.js | 7 +- .../structures/InteractionCallbackResponse.js | 3 + .../src/structures/InteractionCollector.js | 22 +- .../src/structures/InteractionWebhook.js | 15 +- packages/discord.js/src/structures/Invite.js | 31 ++- .../discord.js/src/structures/InviteGuild.js | 4 +- .../discord.js/src/structures/MediaChannel.js | 1 + .../MentionableSelectMenuComponent.js | 1 + .../MentionableSelectMenuInteraction.js | 7 +- packages/discord.js/src/structures/Message.js | 175 ++++++++++---- .../src/structures/MessageCollector.js | 18 +- .../structures/MessageComponentInteraction.js | 35 ++- .../MessageContextMenuCommandInteraction.js | 2 + .../src/structures/MessageMentions.js | 29 ++- .../src/structures/MessagePayload.js | 19 +- .../src/structures/MessageReaction.js | 27 ++- .../src/structures/ModalSubmitFields.js | 4 + .../src/structures/ModalSubmitInteraction.js | 25 +- .../discord.js/src/structures/OAuth2Guild.js | 5 +- .../src/structures/PartialGroupDMChannel.js | 24 +- .../src/structures/PermissionOverwrites.js | 37 ++- packages/discord.js/src/structures/Poll.js | 20 +- .../discord.js/src/structures/PollAnswer.js | 21 +- .../discord.js/src/structures/Presence.js | 70 ++++-- .../PrimaryEntryPointCommandInteraction.js | 1 + .../src/structures/ReactionCollector.js | 25 +- .../src/structures/ReactionEmoji.js | 4 +- packages/discord.js/src/structures/Role.js | 76 ++++-- .../src/structures/RoleSelectMenuComponent.js | 1 + .../structures/RoleSelectMenuInteraction.js | 3 + packages/discord.js/src/structures/SKU.js | 9 +- .../src/structures/SoundboardSound.js | 20 +- .../discord.js/src/structures/StageChannel.js | 13 +- .../src/structures/StageInstance.js | 22 +- packages/discord.js/src/structures/Sticker.js | 30 ++- .../discord.js/src/structures/StickerPack.js | 14 +- .../structures/StringSelectMenuComponent.js | 2 + .../structures/StringSelectMenuInteraction.js | 2 + .../discord.js/src/structures/Subscription.js | 14 ++ packages/discord.js/src/structures/Team.js | 14 +- .../discord.js/src/structures/TeamMember.js | 7 + .../discord.js/src/structures/TextChannel.js | 5 +- .../src/structures/TextInputComponent.js | 3 + .../src/structures/ThreadChannel.js | 99 ++++++-- .../discord.js/src/structures/ThreadMember.js | 14 +- .../src/structures/ThreadOnlyChannel.js | 55 +++-- packages/discord.js/src/structures/Typing.js | 8 + packages/discord.js/src/structures/User.js | 51 +++- .../UserContextMenuCommandInteraction.js | 3 + .../src/structures/UserSelectMenuComponent.js | 1 + .../structures/UserSelectMenuInteraction.js | 6 +- .../discord.js/src/structures/VoiceChannel.js | 13 +- .../src/structures/VoiceChannelEffect.js | 10 + .../discord.js/src/structures/VoiceRegion.js | 5 + .../discord.js/src/structures/VoiceState.js | 55 +++-- packages/discord.js/src/structures/Webhook.js | 67 ++++-- .../src/structures/WelcomeChannel.js | 9 +- .../src/structures/WelcomeScreen.js | 5 + packages/discord.js/src/structures/Widget.js | 12 +- .../discord.js/src/structures/WidgetMember.js | 17 +- .../src/structures/interfaces/Application.js | 19 +- .../src/structures/interfaces/Collector.js | 49 +++- .../interfaces/InteractionResponses.js | 42 +++- .../structures/interfaces/TextBasedChannel.js | 67 ++++-- packages/discord.js/src/util/APITypes.js | 2 +- .../src/util/ActivityFlagsBitField.js | 4 +- .../src/util/ApplicationFlagsBitField.js | 14 +- .../src/util/AttachmentFlagsBitField.js | 4 +- packages/discord.js/src/util/BitField.js | 38 ++- .../src/util/ChannelFlagsBitField.js | 14 +- packages/discord.js/src/util/Channels.js | 18 +- packages/discord.js/src/util/Colors.js | 2 +- packages/discord.js/src/util/Components.js | 7 +- packages/discord.js/src/util/Constants.js | 170 +++++++------ packages/discord.js/src/util/DataResolver.js | 33 ++- packages/discord.js/src/util/Enums.js | 1 + packages/discord.js/src/util/Events.js | 2 +- .../src/util/GuildMemberFlagsBitField.js | 14 +- .../discord.js/src/util/IntentsBitField.js | 13 +- .../discord.js/src/util/LimitedCollection.js | 19 +- .../src/util/MessageFlagsBitField.js | 14 +- packages/discord.js/src/util/Options.js | 37 ++- packages/discord.js/src/util/Partials.js | 17 +- .../src/util/PermissionsBitField.js | 30 ++- .../discord.js/src/util/RoleFlagsBitField.js | 4 +- .../discord.js/src/util/SKUFlagsBitField.js | 4 +- packages/discord.js/src/util/ShardEvents.js | 2 +- packages/discord.js/src/util/Status.js | 8 +- packages/discord.js/src/util/Sweepers.js | 83 +++++-- .../src/util/SystemChannelFlagsBitField.js | 14 +- .../src/util/ThreadMemberFlagsBitField.js | 7 +- packages/discord.js/src/util/Transformers.js | 5 + .../discord.js/src/util/UserFlagsBitField.js | 5 +- packages/discord.js/src/util/Util.js | 82 +++++-- packages/discord.js/tsconfig.eslint.json | 25 ++ 280 files changed, 4089 insertions(+), 1265 deletions(-) rename packages/discord.js/{.eslintrc.json => .eslintrc.json.bak} (100%) create mode 100644 packages/discord.js/tsconfig.eslint.json diff --git a/eslint.config.js b/eslint.config.js index 842c2cc0f3fd..4894a87bc700 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -88,7 +88,7 @@ export default tseslint.config( '**/storybook-static/', '**/.next/', '**/shiki.bundle.ts', - 'packages/discord.js/', + // 'packages/discord.js/', ], }, commonRuleset, @@ -137,6 +137,27 @@ export default tseslint.config( '@typescript-eslint/no-empty-object-type': 0, }, }, + { + files: [`packages/discord.js/**/*${commonFiles}`], + languageOptions: { + sourceType: 'commonjs', + parserOptions: { + ecmaFeatures: { + impliedStrict: false, + }, + }, + }, + rules: { + '@typescript-eslint/no-var-requires': 0, + '@typescript-eslint/no-require-imports': 0, + 'jsdoc/no-undefined-types': 0, + '@typescript-eslint/explicit-member-accessibility': 0, + '@typescript-eslint/class-literal-property-style': 0, + 'unicorn/no-array-for-each': 0, + strict: ['error', 'global'], + 'unicorn/consistent-function-scoping': 0, + }, + }, { files: [`packages/rest/**/*${commonFiles}`], rules: { diff --git a/packages/discord.js/.eslintrc.json b/packages/discord.js/.eslintrc.json.bak similarity index 100% rename from packages/discord.js/.eslintrc.json rename to packages/discord.js/.eslintrc.json.bak diff --git a/packages/discord.js/.lintstagedrc.json b/packages/discord.js/.lintstagedrc.json index e4e385774d7f..55af9a21847e 100644 --- a/packages/discord.js/.lintstagedrc.json +++ b/packages/discord.js/.lintstagedrc.json @@ -1,5 +1,5 @@ { "$schema": "https://json.schemastore.org/lintstagedrc.schema.json", "*": "prettier --ignore-unknown --write", - "{src/**,test/**,typings/**,scripts/**}.{mjs,js,ts}": "cross-env ESLINT_USE_FLAT_CONFIG=false eslint --ext mjs,js,ts --fix" + "{src/**,test/**,typings/**,scripts/**}.{mjs,js,ts}": "cross-env TIMING=1 eslint --fix --format=pretty" } diff --git a/packages/discord.js/package.json b/packages/discord.js/package.json index 8abe524ee6dd..4e83ed0728bb 100644 --- a/packages/discord.js/package.json +++ b/packages/discord.js/package.json @@ -6,8 +6,8 @@ "scripts": { "test": "pnpm run docs:test && pnpm run test:typescript", "test:typescript": "tsc --noEmit && tsd", - "lint": "prettier --check . && tslint typings/index.d.ts && cross-env ESLINT_USE_FLAT_CONFIG=false eslint --format=pretty src typings", - "format": "prettier --write . && cross-env ESLINT_USE_FLAT_CONFIG=false eslint --fix --format=pretty src", + "lint": "prettier --check . && tslint typings/index.d.ts && cross-env TIMING=1 eslint --format=pretty src typings", + "format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src", "fmt": "pnpm run format", "docs": "docgen -i \"./src/*.js\" \"./src/**/*.js\" -c ./docs/index.json -r ../../ -o ./docs/docs.json && pnpm run docs:new", "docs:test": "docgen -i \"./src/*.js\" \"./src/**/*.js\" -c ./docs/index.json -r ../../", diff --git a/packages/discord.js/src/client/BaseClient.js b/packages/discord.js/src/client/BaseClient.js index acb846b81b7e..fd2ce3f84539 100644 --- a/packages/discord.js/src/client/BaseClient.js +++ b/packages/discord.js/src/client/BaseClient.js @@ -10,6 +10,7 @@ const { flatten } = require('../util/Util.js'); /** * The base class for all clients. + * * @extends {AsyncEventEmitter} */ class BaseClient extends AsyncEventEmitter { @@ -23,6 +24,7 @@ class BaseClient extends AsyncEventEmitter { const defaultOptions = Options.createDefault(); /** * The options the client was instantiated with + * * @type {ClientOptions} */ this.options = { @@ -51,6 +53,7 @@ class BaseClient extends AsyncEventEmitter { /** * The REST manager of the client + * * @type {REST} */ this.rest = new REST(this.options.rest); @@ -60,6 +63,7 @@ class BaseClient extends AsyncEventEmitter { /** * Destroys all assets used by the base client. + * * @returns {void} */ destroy() { @@ -69,13 +73,15 @@ class BaseClient extends AsyncEventEmitter { /** * Options used for deleting a webhook. - * @typedef {Object} WebhookDeleteOptions + * + * @typedef {object} WebhookDeleteOptions * @property {string} [token] Token of the webhook * @property {string} [reason] The reason for deleting the webhook */ /** * Deletes a webhook. + * * @param {Snowflake} id The webhook's id * @param {WebhookDeleteOptions} [options] Options for deleting the webhook * @returns {Promise} @@ -86,6 +92,7 @@ class BaseClient extends AsyncEventEmitter { /** * Increments max listeners by one, if they are not zero. + * * @private */ incrementMaxListeners() { @@ -97,6 +104,7 @@ class BaseClient extends AsyncEventEmitter { /** * Decrements max listeners by one, if they are not zero. + * * @private */ decrementMaxListeners() { @@ -111,6 +119,7 @@ class BaseClient extends AsyncEventEmitter { } async [Symbol.asyncDispose]() { + // eslint-disable-next-line @typescript-eslint/await-thenable, @typescript-eslint/no-confusing-void-expression await this.destroy(); } } diff --git a/packages/discord.js/src/client/Client.js b/packages/discord.js/src/client/Client.js index 34500ebe545a..1b7488602fba 100644 --- a/packages/discord.js/src/client/Client.js +++ b/packages/discord.js/src/client/Client.js @@ -6,10 +6,6 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { WebSocketManager, WebSocketShardEvents, WebSocketShardStatus } = require('@discordjs/ws'); const { GatewayDispatchEvents, GatewayIntentBits, OAuth2Scopes, Routes } = require('discord-api-types/v10'); -const { BaseClient } = require('./BaseClient.js'); -const { ActionsManager } = require('./actions/ActionsManager.js'); -const { ClientVoiceManager } = require('./voice/ClientVoiceManager.js'); -const { PacketHandlers } = require('./websocket/handlers/index.js'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { ChannelManager } = require('../managers/ChannelManager.js'); const { GuildManager } = require('../managers/GuildManager.js'); @@ -32,6 +28,10 @@ const { Options } = require('../util/Options.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); const { Status } = require('../util/Status.js'); const { Sweepers } = require('../util/Sweepers.js'); +const { BaseClient } = require('./BaseClient.js'); +const { ActionsManager } = require('./actions/ActionsManager.js'); +const { ClientVoiceManager } = require('./voice/ClientVoiceManager.js'); +const { PacketHandlers } = require('./websocket/handlers/index.js'); const WaitingForGuildEvents = [GatewayDispatchEvents.GuildCreate, GatewayDispatchEvents.GuildDelete]; const BeforeReadyWhitelist = [ @@ -46,6 +46,7 @@ const BeforeReadyWhitelist = [ /** * The main hub for interacting with the Discord API, and the starting point for any bot. + * * @extends {BaseClient} */ class Client extends BaseClient { @@ -69,6 +70,7 @@ class Client extends BaseClient { /** * The presence of the Client + * * @private * @type {ClientPresence} */ @@ -78,6 +80,7 @@ class Client extends BaseClient { /** * The current status of this Client + * * @type {Status} * @private */ @@ -85,6 +88,7 @@ class Client extends BaseClient { /** * A set of guild ids this Client expects to receive + * * @name Client#expectedGuilds * @type {Set} * @private @@ -93,6 +97,7 @@ class Client extends BaseClient { /** * The ready timeout + * * @name Client#readyTimeout * @type {?NodeJS.Timeout} * @private @@ -101,6 +106,7 @@ class Client extends BaseClient { /** * The action manager of the client + * * @type {ActionsManager} * @private */ @@ -108,6 +114,7 @@ class Client extends BaseClient { /** * The user manager of this client + * * @type {UserManager} */ this.users = new UserManager(this); @@ -115,6 +122,7 @@ class Client extends BaseClient { /** * A manager of all the guilds the client is currently handling - * as long as sharding isn't being used, this will be *every* guild the bot is a member of + * * @type {GuildManager} */ this.guilds = new GuildManager(this); @@ -124,12 +132,14 @@ class Client extends BaseClient { * as long as sharding isn't being used, this will be *every* channel in *every* guild the bot * is a member of. Note that DM channels will not be initially cached, and thus not be present * in the Manager without their explicit fetching or use. + * * @type {ChannelManager} */ this.channels = new ChannelManager(this); /** * The sweeping functions and their intervals used to periodically sweep caches + * * @type {Sweepers} */ this.sweepers = new Sweepers(this, this.options.sweepers); @@ -140,6 +150,7 @@ class Client extends BaseClient { * Authorization token for the logged in bot. * If present, this defaults to `process.env.DISCORD_TOKEN` when instantiating the client * This should be kept private at all times. + * * @type {?string} */ this.token = process.env.DISCORD_TOKEN; @@ -159,12 +170,14 @@ class Client extends BaseClient { /** * The WebSocket manager of the client + * * @type {WebSocketManager} */ this.ws = new WebSocketManager(wsOptions); /** * Shard helpers for the client (only if the process was spawned from a {@link ShardingManager}) + * * @type {?ShardClientUtil} */ this.shard = process.env.SHARDING_MANAGER @@ -173,43 +186,50 @@ class Client extends BaseClient { /** * The voice manager of the client + * * @type {ClientVoiceManager} */ this.voice = new ClientVoiceManager(this); /** * User that the client is logged in as + * * @type {?ClientUser} */ this.user = null; /** * The application of this bot + * * @type {?ClientApplication} */ this.application = null; /** * The latencies of the WebSocketShard connections + * * @type {Collection} */ this.pings = new Collection(); /** * The last time a ping was sent (a timestamp) for each WebSocketShard connection + * * @type {Collection} */ this.lastPingTimestamps = new Collection(); /** * Timestamp of the time the client was last {@link Status.Ready} at + * * @type {?number} */ this.readyTimestamp = null; /** * An array of queued events before this Client became ready - * @type {Object[]} + * + * @type {object[]} * @private * @name Client#incomingPacketQueue */ @@ -221,6 +241,7 @@ class Client extends BaseClient { /** * Time at which the client was last regarded as being in the {@link Status.Ready} state * (each time the client disconnects and successfully reconnects, this will be overwritten) + * * @type {?Date} * @readonly */ @@ -230,6 +251,7 @@ class Client extends BaseClient { /** * How long it has been since the client last entered the {@link Status.Ready} state in milliseconds + * * @type {?number} * @readonly */ @@ -239,14 +261,15 @@ class Client extends BaseClient { /** * Logs the client in, establishing a WebSocket connection to Discord. - * @param {string} [token=this.token] Token of the account to log in with + * + * @param {string} [token] Token of the account to log in with * @returns {Promise} Token of the account used * @example * client.login('my token'); */ async login(token = this.token) { if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid); - this.token = token.replace(/^(Bot|Bearer)\s*/i, ''); + this.token = token.replace(/^(?:bot|bearer)\s*/i, ''); this.rest.setToken(this.token); @@ -266,6 +289,7 @@ class Client extends BaseClient { /** * Checks if the client can be marked as ready + * * @private */ async _checkReady() { @@ -274,6 +298,7 @@ class Client extends BaseClient { clearTimeout(this.readyTimeout); this.readyTimeout = null; } + // Step 1. If we don't have any other guilds pending, we are ready if ( !this.expectedGuilds.size && @@ -284,6 +309,7 @@ class Client extends BaseClient { this._triggerClientReady(); return; } + const hasGuildsIntent = this.options.intents.has(GatewayIntentBits.Guilds); // Step 2. Create a timeout that will mark the client as ready if there are still unavailable guilds // * The timeout is 15 seconds by default @@ -311,6 +337,7 @@ class Client extends BaseClient { /** * Attaches event handlers to the WebSocketShardManager from `@discordjs/ws`. + * * @private */ _attachEvents() { @@ -319,12 +346,13 @@ class Client extends BaseClient { ); this.ws.on(WebSocketShardEvents.Dispatch, this._handlePacket.bind(this)); - this.ws.on(WebSocketShardEvents.Ready, data => { + this.ws.on(WebSocketShardEvents.Ready, async data => { for (const guild of data.guilds) { this.expectedGuilds.add(guild.id); } + this.status = Status.WaitingForGuilds; - this._checkReady(); + await this._checkReady(); }); this.ws.on(WebSocketShardEvents.HeartbeatComplete, ({ heartbeatAt, latency }, shardId) => { @@ -336,18 +364,19 @@ class Client extends BaseClient { /** * Processes a packet and queues it if this WebSocketManager is not ready. + * * @param {GatewayDispatchPayload} packet The packet to be handled * @param {number} shardId The shardId that received this packet * @private */ - _handlePacket(packet, shardId) { + async _handlePacket(packet, shardId) { if (this.status !== Status.Ready && !BeforeReadyWhitelist.includes(packet.t)) { this.incomingPacketQueue.push({ packet, shardId }); } else { if (this.incomingPacketQueue.length) { const item = this.incomingPacketQueue.shift(); - setImmediate(() => { - this._handlePacket(item.packet, item.shardId); + setImmediate(async () => { + await this._handlePacket(item.packet, item.shardId); }).unref(); } @@ -357,14 +386,15 @@ class Client extends BaseClient { if (this.status === Status.WaitingForGuilds && WaitingForGuildEvents.includes(packet.t)) { this.expectedGuilds.delete(packet.d.id); - this._checkReady(); + await this._checkReady(); } } } /** * Broadcasts a packet to every shard of this client handles. - * @param {Object} packet The packet to send + * + * @param {object} packet The packet to send * @private */ async _broadcast(packet) { @@ -374,6 +404,7 @@ class Client extends BaseClient { /** * Causes the client to be marked as ready and emits the ready event. + * * @private */ _triggerClientReady() { @@ -383,6 +414,7 @@ class Client extends BaseClient { /** * Emitted when the client becomes ready to start working. + * * @event Client#clientReady * @param {Client} client The client */ @@ -392,6 +424,7 @@ class Client extends BaseClient { /** * Returns whether the client has logged in, indicative of being able to access * properties such as `user` and `application`. + * * @returns {boolean} */ isReady() { @@ -400,6 +433,7 @@ class Client extends BaseClient { /** * The average ping of all WebSocketShards + * * @type {?number} * @readonly */ @@ -409,6 +443,7 @@ class Client extends BaseClient { /** * Logs out, terminates the connection to Discord, and destroys the client. + * * @returns {Promise} */ async destroy() { @@ -422,13 +457,15 @@ class Client extends BaseClient { /** * Options used when fetching an invite from Discord. - * @typedef {Object} ClientFetchInviteOptions + * + * @typedef {object} ClientFetchInviteOptions * @property {Snowflake} [guildScheduledEventId] The id of the guild scheduled event to include with * the invite */ /** * Obtains an invite from Discord. + * * @param {InviteResolvable} invite Invite code or URL * @param {ClientFetchInviteOptions} [options] Options for fetching the invite * @returns {Promise} @@ -450,6 +487,7 @@ class Client extends BaseClient { /** * Obtains a template from Discord. + * * @param {GuildTemplateResolvable} template Template code or URL * @returns {Promise} * @example @@ -465,6 +503,7 @@ class Client extends BaseClient { /** * Obtains a webhook from Discord. + * * @param {Snowflake} id The webhook's id * @param {string} [token] Token for the webhook * @returns {Promise} @@ -480,6 +519,7 @@ class Client extends BaseClient { /** * Obtains the available voice regions from Discord. + * * @returns {Promise>} * @example * client.fetchVoiceRegions() @@ -495,6 +535,7 @@ class Client extends BaseClient { /** * Obtains a sticker from Discord. + * * @param {Snowflake} id The sticker's id * @returns {Promise} * @example @@ -509,13 +550,15 @@ class Client extends BaseClient { /** * Options for fetching sticker packs. - * @typedef {Object} StickerPackFetchOptions + * + * @typedef {object} StickerPackFetchOptions * @property {Snowflake} [packId] The id of the sticker pack to fetch */ /** * Obtains the list of available sticker packs. - * @param {StickerPackFetchOptions} [options={}] Options for fetching sticker packs + * + * @param {StickerPackFetchOptions} [options] Options for fetching sticker packs * @returns {Promise|StickerPack>} * A collection of sticker packs, or a single sticker pack if a packId was provided * @example @@ -539,6 +582,7 @@ class Client extends BaseClient { /** * Obtains the list of default soundboard sounds. + * * @returns {Promise>} * @example * client.fetchDefaultSoundboardSounds() @@ -552,6 +596,7 @@ class Client extends BaseClient { /** * Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds. + * * @param {GuildResolvable} guild The guild to fetch the preview for * @returns {Promise} */ @@ -564,6 +609,7 @@ class Client extends BaseClient { /** * Obtains the widget data of a guild from Discord, available for guilds with the widget enabled. + * * @param {GuildResolvable} guild The guild to fetch the widget data for * @returns {Promise} */ @@ -576,7 +622,8 @@ class Client extends BaseClient { /** * Options for {@link Client#generateInvite}. - * @typedef {Object} InviteGenerationOptions + * + * @typedef {object} InviteGenerationOptions * @property {OAuth2Scopes[]} scopes Scopes that should be requested * @property {PermissionResolvable} [permissions] Permissions to request * @property {GuildResolvable} [guild] Guild to preselect @@ -585,7 +632,8 @@ class Client extends BaseClient { /** * Generates a link that can be used to invite the bot to a guild. - * @param {InviteGenerationOptions} [options={}] Options for the invite + * + * @param {InviteGenerationOptions} [options] Options for the invite * @returns {string} * @example * const link = client.generateInvite({ @@ -611,15 +659,19 @@ class Client extends BaseClient { if (scopes === undefined) { throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes); } + if (!Array.isArray(scopes)) { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'scopes', 'Array of Invite Scopes', true); } + if (!scopes.some(scope => [OAuth2Scopes.Bot, OAuth2Scopes.ApplicationsCommands].includes(scope))) { throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes); } + if (!scopes.includes(OAuth2Scopes.Bot) && options.permissions) { throw new DiscordjsTypeError(ErrorCodes.InvalidScopesWithPermissions); } + const validScopes = Object.values(OAuth2Scopes); const invalidScope = scopes.find(scope => !validScopes.includes(scope)); if (invalidScope) { @@ -655,6 +707,7 @@ class Client extends BaseClient { /** * Partially censored client token for debug logging purposes. + * * @type {?string} * @readonly * @private @@ -664,24 +717,27 @@ class Client extends BaseClient { return this.token .split('.') - .map((val, i) => (i > 1 ? val.replace(/./g, '*') : val)) + .map((val, index) => (index > 1 ? val.replaceAll(/./g, '*') : val)) .join('.'); } /** * Calls {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval} on a script * with the client as `this`. + * * @param {string} script Script to eval * @returns {*} * @private */ _eval(script) { + // eslint-disable-next-line no-eval return eval(script); } /** * Validates the client options. - * @param {ClientOptions} [options=this.options] Options to validate + * + * @param {ClientOptions} [options] Options to validate * @private */ _validateOptions(options = this.options) { @@ -690,30 +746,38 @@ class Client extends BaseClient { } else { options.intents = new IntentsBitField(options.intents ?? options.ws.intents).freeze(); } + if (typeof options.sweepers !== 'object' || options.sweepers === null) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'sweepers', 'an object'); } + if (!Array.isArray(options.partials)) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'partials', 'an Array'); } - if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) { + + if (typeof options.waitGuildTimeout !== 'number' || Number.isNaN(options.waitGuildTimeout)) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'waitGuildTimeout', 'a number'); } + if (typeof options.failIfNotExists !== 'boolean') { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'failIfNotExists', 'a boolean'); } + if (typeof options.enforceNonce !== 'boolean') { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'enforceNonce', 'a boolean'); } + if ( (typeof options.allowedMentions !== 'object' && options.allowedMentions !== undefined) || options.allowedMentions === null ) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'allowedMentions', 'an object'); } + if (typeof options.ws !== 'object' || options.ws === null) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'ws', 'an object'); } + if ( (typeof options.presence !== 'object' || options.presence === null) && options.ws.initialPresence === undefined @@ -722,9 +786,11 @@ class Client extends BaseClient { } else { options.ws.initialPresence = options.ws.initialPresence ?? this.presence._parse(this.options.presence); } + if (typeof options.rest !== 'object' || options.rest === null) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'rest', 'an object'); } + if (typeof options.jsonTransformer !== 'function') { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'jsonTransformer', 'a function'); } @@ -752,20 +818,23 @@ exports.Client = Client; * If we have a snowflake '266241948824764416' we can represent it as binary: * ``` * 64 22 17 12 0 - * 000000111011000111100001101001000101000000 00001 00000 000000000000 - * number of milliseconds since Discord epoch worker pid increment + * 000000111011000111100001101001000101000000 00001 00000 000000000000 + * number of milliseconds since Discord epoch worker pid increment * ``` + * * @typedef {string} Snowflake */ /** * Emitted for general debugging information. + * * @event Client#debug * @param {string} info The debug information */ /** * Emitted for general warnings. + * * @event Client#warn * @param {string} info The warning */ diff --git a/packages/discord.js/src/client/WebhookClient.js b/packages/discord.js/src/client/WebhookClient.js index 6608a4edd0c6..7d9b606e57c8 100644 --- a/packages/discord.js/src/client/WebhookClient.js +++ b/packages/discord.js/src/client/WebhookClient.js @@ -1,37 +1,42 @@ 'use strict'; -const { BaseClient } = require('./BaseClient.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { Webhook } = require('../structures/Webhook.js'); const { parseWebhookURL } = require('../util/Util.js'); +const { BaseClient } = require('./BaseClient.js'); /** * The webhook client. + * * @implements {Webhook} * @extends {BaseClient} */ class WebhookClient extends BaseClient { /** * Represents the credentials used for a webhook in the form of its id and token. - * @typedef {Object} WebhookClientDataIdWithToken + * + * @typedef {object} WebhookClientDataIdWithToken * @property {Snowflake} id The webhook's id * @property {string} token The webhook's token */ /** * Represents the credentials used for a webhook in the form of a URL. - * @typedef {Object} WebhookClientDataURL + * + * @typedef {object} WebhookClientDataURL * @property {string} url The full URL for the webhook */ /** * Represents the credentials used for a webhook. + * * @typedef {WebhookClientDataIdWithToken|WebhookClientDataURL} WebhookClientData */ /** * Options for a webhook client. - * @typedef {Object} WebhookClientOptions + * + * @typedef {object} WebhookClientOptions * @property {MessageMentionOptions} [allowedMentions] Default value for {@link BaseMessageOptions#allowedMentions} * @property {RESTOptions} [rest] Options for the REST manager */ @@ -60,41 +65,51 @@ class WebhookClient extends BaseClient { /** * The options the webhook client was instantiated with. + * * @type {WebhookClientOptions} * @name WebhookClient#options */ // These are here only for documentation purposes - they are implemented by Webhook - /* eslint-disable no-empty-function */ + /** * Sends a message with this webhook. + * * @param {string|MessagePayload|WebhookMessageCreateOptions} options The content for the reply * @returns {Promise} */ - send() {} + async send(options) {} /** * Gets a message that was sent by this webhook. + * * @param {Snowflake} message The id of the message to fetch - * @param {WebhookFetchMessageOptions} [options={}] The options to provide to fetch the message. + * @param {WebhookFetchMessageOptions} [options] The options to provide to fetch the message. * @returns {Promise} Returns the message sent by this webhook */ - fetchMessage() {} + async fetchMessage(message, options) {} /** * Edits a message that was sent by this webhook. + * * @param {MessageResolvable} message The message to edit * @param {string|MessagePayload|WebhookMessageEditOptions} options The options to provide * @returns {Promise} Returns the message edited by this webhook */ - editMessage() {} + async editMessage(message, options) {} sendSlackMessage() {} + edit() {} + delete() {} + deleteMessage() {} + get createdTimestamp() {} + get createdAt() {} + get url() {} } diff --git a/packages/discord.js/src/client/actions/Action.js b/packages/discord.js/src/client/actions/Action.js index 9ed55e4a01c6..791fe480d0e6 100644 --- a/packages/discord.js/src/client/actions/Action.js +++ b/packages/discord.js/src/client/actions/Action.js @@ -114,6 +114,7 @@ class Action { return this.client.users._add(data.member.user); } } + return this.getUser(data); } diff --git a/packages/discord.js/src/client/actions/ActionsManager.js b/packages/discord.js/src/client/actions/ActionsManager.js index 01dacb33cbec..22e574815c32 100644 --- a/packages/discord.js/src/client/actions/ActionsManager.js +++ b/packages/discord.js/src/client/actions/ActionsManager.js @@ -5,7 +5,9 @@ class ActionsManager { // Action#getUser, for example, will return the injected data (which is assumed to be a built structure) // instead of trying to make it from provided data injectedUser = Symbol('djs.actions.injectedUser'); + injectedChannel = Symbol('djs.actions.injectedChannel'); + injectedMessage = Symbol('djs.actions.injectedMessage'); constructor(client) { diff --git a/packages/discord.js/src/client/actions/ChannelCreate.js b/packages/discord.js/src/client/actions/ChannelCreate.js index 2ff82ca324cd..07844bdd1926 100644 --- a/packages/discord.js/src/client/actions/ChannelCreate.js +++ b/packages/discord.js/src/client/actions/ChannelCreate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class ChannelCreateAction extends Action { handle(data) { @@ -11,11 +11,13 @@ class ChannelCreateAction extends Action { if (!existing && channel) { /** * Emitted whenever a guild channel is created. + * * @event Client#channelCreate * @param {GuildChannel} channel The channel that was created */ client.emit(Events.ChannelCreate, channel); } + return { channel }; } } diff --git a/packages/discord.js/src/client/actions/ChannelDelete.js b/packages/discord.js/src/client/actions/ChannelDelete.js index 33e4665596cd..1aa9928365e3 100644 --- a/packages/discord.js/src/client/actions/ChannelDelete.js +++ b/packages/discord.js/src/client/actions/ChannelDelete.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class ChannelDeleteAction extends Action { handle(data) { @@ -12,6 +12,7 @@ class ChannelDeleteAction extends Action { client.channels._remove(channel.id); /** * Emitted whenever a channel is deleted. + * * @event Client#channelDelete * @param {DMChannel|GuildChannel} channel The channel that was deleted */ diff --git a/packages/discord.js/src/client/actions/ChannelUpdate.js b/packages/discord.js/src/client/actions/ChannelUpdate.js index ade6feb21013..8a3b15d7bab1 100644 --- a/packages/discord.js/src/client/actions/ChannelUpdate.js +++ b/packages/discord.js/src/client/actions/ChannelUpdate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { createChannel } = require('../../util/Channels.js'); +const { Action } = require('./Action.js'); class ChannelUpdateAction extends Action { handle(data) { diff --git a/packages/discord.js/src/client/actions/GuildEmojiCreate.js b/packages/discord.js/src/client/actions/GuildEmojiCreate.js index 57b81ff09686..0bf6ae0fb7af 100644 --- a/packages/discord.js/src/client/actions/GuildEmojiCreate.js +++ b/packages/discord.js/src/client/actions/GuildEmojiCreate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildEmojiCreateAction extends Action { handle(guild, createdEmoji) { @@ -9,6 +9,7 @@ class GuildEmojiCreateAction extends Action { const emoji = guild.emojis._add(createdEmoji); /** * Emitted whenever a custom emoji is created in a guild. + * * @event Client#emojiCreate * @param {GuildEmoji} emoji The emoji that was created */ diff --git a/packages/discord.js/src/client/actions/GuildEmojiDelete.js b/packages/discord.js/src/client/actions/GuildEmojiDelete.js index 9b93e3750d59..b81db5804fb7 100644 --- a/packages/discord.js/src/client/actions/GuildEmojiDelete.js +++ b/packages/discord.js/src/client/actions/GuildEmojiDelete.js @@ -1,13 +1,14 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildEmojiDeleteAction extends Action { handle(emoji) { emoji.guild.emojis.cache.delete(emoji.id); /** * Emitted whenever a custom emoji is deleted in a guild. + * * @event Client#emojiDelete * @param {GuildEmoji} emoji The emoji that was deleted */ diff --git a/packages/discord.js/src/client/actions/GuildEmojiUpdate.js b/packages/discord.js/src/client/actions/GuildEmojiUpdate.js index 7da11c2df05c..eeb5df0dd8bc 100644 --- a/packages/discord.js/src/client/actions/GuildEmojiUpdate.js +++ b/packages/discord.js/src/client/actions/GuildEmojiUpdate.js @@ -1,13 +1,14 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildEmojiUpdateAction extends Action { handle(current, data) { const old = current._update(data); /** * Emitted whenever a custom emoji is updated in a guild. + * * @event Client#emojiUpdate * @param {GuildEmoji} oldEmoji The old emoji * @param {GuildEmoji} newEmoji The new emoji diff --git a/packages/discord.js/src/client/actions/GuildMemberRemove.js b/packages/discord.js/src/client/actions/GuildMemberRemove.js index 984a84100036..79d9b658ec50 100644 --- a/packages/discord.js/src/client/actions/GuildMemberRemove.js +++ b/packages/discord.js/src/client/actions/GuildMemberRemove.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildMemberRemoveAction extends Action { handle(data) { @@ -15,14 +15,17 @@ class GuildMemberRemoveAction extends Action { guild.members.cache.delete(member.id); /** * Emitted whenever a member leaves a guild, or is kicked. + * * @event Client#guildMemberRemove * @param {GuildMember} member The member that has left/been kicked from the guild */ client.emit(Events.GuildMemberRemove, member); } + guild.presences.cache.delete(data.user.id); guild.voiceStates.cache.delete(data.user.id); } + return { guild, member }; } } diff --git a/packages/discord.js/src/client/actions/GuildMemberUpdate.js b/packages/discord.js/src/client/actions/GuildMemberUpdate.js index 6184e4897d61..fc999d952f6e 100644 --- a/packages/discord.js/src/client/actions/GuildMemberUpdate.js +++ b/packages/discord.js/src/client/actions/GuildMemberUpdate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildMemberUpdateAction extends Action { handle(data) { @@ -22,6 +22,7 @@ class GuildMemberUpdateAction extends Action { const old = member._update(data); /** * Emitted whenever a guild member changes - i.e. new role, removed role, nickname. + * * @event Client#guildMemberUpdate * @param {GuildMember} oldMember The member before the update * @param {GuildMember} newMember The member after the update @@ -31,6 +32,7 @@ class GuildMemberUpdateAction extends Action { const newMember = guild.members._add(data); /** * Emitted whenever a member becomes available. + * * @event Client#guildMemberAvailable * @param {GuildMember} member The member that became available */ diff --git a/packages/discord.js/src/client/actions/GuildRoleCreate.js b/packages/discord.js/src/client/actions/GuildRoleCreate.js index aa8551699771..2db31c6cd232 100644 --- a/packages/discord.js/src/client/actions/GuildRoleCreate.js +++ b/packages/discord.js/src/client/actions/GuildRoleCreate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildRoleCreateAction extends Action { handle(data) { @@ -13,11 +13,13 @@ class GuildRoleCreateAction extends Action { role = guild.roles._add(data.role); /** * Emitted whenever a role is created. + * * @event Client#roleCreate * @param {Role} role The role that was created */ if (!already) client.emit(Events.GuildRoleCreate, role); } + return { role }; } } diff --git a/packages/discord.js/src/client/actions/GuildRoleDelete.js b/packages/discord.js/src/client/actions/GuildRoleDelete.js index cddc4ce563a1..504c0caff7a1 100644 --- a/packages/discord.js/src/client/actions/GuildRoleDelete.js +++ b/packages/discord.js/src/client/actions/GuildRoleDelete.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildRoleDeleteAction extends Action { handle(data) { @@ -15,6 +15,7 @@ class GuildRoleDeleteAction extends Action { guild.roles.cache.delete(data.role_id); /** * Emitted whenever a guild role is deleted. + * * @event Client#roleDelete * @param {Role} role The role that was deleted */ diff --git a/packages/discord.js/src/client/actions/GuildScheduledEventDelete.js b/packages/discord.js/src/client/actions/GuildScheduledEventDelete.js index e5e0f00db4df..f42b0be72421 100644 --- a/packages/discord.js/src/client/actions/GuildScheduledEventDelete.js +++ b/packages/discord.js/src/client/actions/GuildScheduledEventDelete.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildScheduledEventDeleteAction extends Action { handle(data) { @@ -15,6 +15,7 @@ class GuildScheduledEventDeleteAction extends Action { /** * Emitted whenever a guild scheduled event is deleted. + * * @event Client#guildScheduledEventDelete * @param {GuildScheduledEvent} guildScheduledEvent The deleted guild scheduled event */ diff --git a/packages/discord.js/src/client/actions/GuildScheduledEventUserAdd.js b/packages/discord.js/src/client/actions/GuildScheduledEventUserAdd.js index c70ac57eb5e5..dd6783e3e517 100644 --- a/packages/discord.js/src/client/actions/GuildScheduledEventUserAdd.js +++ b/packages/discord.js/src/client/actions/GuildScheduledEventUserAdd.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildScheduledEventUserAddAction extends Action { handle(data) { @@ -15,6 +15,7 @@ class GuildScheduledEventUserAddAction extends Action { if (guildScheduledEvent && user) { /** * Emitted whenever a user subscribes to a guild scheduled event + * * @event Client#guildScheduledEventUserAdd * @param {GuildScheduledEvent} guildScheduledEvent The guild scheduled event * @param {User} user The user who subscribed diff --git a/packages/discord.js/src/client/actions/GuildScheduledEventUserRemove.js b/packages/discord.js/src/client/actions/GuildScheduledEventUserRemove.js index c4b9d6988b62..1406e50af4dd 100644 --- a/packages/discord.js/src/client/actions/GuildScheduledEventUserRemove.js +++ b/packages/discord.js/src/client/actions/GuildScheduledEventUserRemove.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildScheduledEventUserRemoveAction extends Action { handle(data) { @@ -15,6 +15,7 @@ class GuildScheduledEventUserRemoveAction extends Action { if (guildScheduledEvent && user) { /** * Emitted whenever a user unsubscribes from a guild scheduled event + * * @event Client#guildScheduledEventUserRemove * @param {GuildScheduledEvent} guildScheduledEvent The guild scheduled event * @param {User} user The user who unsubscribed diff --git a/packages/discord.js/src/client/actions/GuildSoundboardSoundDelete.js b/packages/discord.js/src/client/actions/GuildSoundboardSoundDelete.js index 6783a981335f..de66d051c5f7 100644 --- a/packages/discord.js/src/client/actions/GuildSoundboardSoundDelete.js +++ b/packages/discord.js/src/client/actions/GuildSoundboardSoundDelete.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildSoundboardSoundDeleteAction extends Action { handle(data) { @@ -16,6 +16,7 @@ class GuildSoundboardSoundDeleteAction extends Action { /** * Emitted whenever a soundboard sound is deleted in a guild. + * * @event Client#guildSoundboardSoundDelete * @param {SoundboardSound} soundboardSound The soundboard sound that was deleted */ diff --git a/packages/discord.js/src/client/actions/GuildStickerCreate.js b/packages/discord.js/src/client/actions/GuildStickerCreate.js index a6bbeedb2a97..bd88c357a581 100644 --- a/packages/discord.js/src/client/actions/GuildStickerCreate.js +++ b/packages/discord.js/src/client/actions/GuildStickerCreate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildStickerCreateAction extends Action { handle(guild, createdSticker) { @@ -9,6 +9,7 @@ class GuildStickerCreateAction extends Action { const sticker = guild.stickers._add(createdSticker); /** * Emitted whenever a custom sticker is created in a guild. + * * @event Client#stickerCreate * @param {Sticker} sticker The sticker that was created */ diff --git a/packages/discord.js/src/client/actions/GuildStickerDelete.js b/packages/discord.js/src/client/actions/GuildStickerDelete.js index 560691b6fa79..f09140b3b6a4 100644 --- a/packages/discord.js/src/client/actions/GuildStickerDelete.js +++ b/packages/discord.js/src/client/actions/GuildStickerDelete.js @@ -1,13 +1,14 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildStickerDeleteAction extends Action { handle(sticker) { sticker.guild.stickers.cache.delete(sticker.id); /** * Emitted whenever a custom sticker is deleted in a guild. + * * @event Client#stickerDelete * @param {Sticker} sticker The sticker that was deleted */ diff --git a/packages/discord.js/src/client/actions/GuildStickerUpdate.js b/packages/discord.js/src/client/actions/GuildStickerUpdate.js index 423e146bb64e..5f0723d887cc 100644 --- a/packages/discord.js/src/client/actions/GuildStickerUpdate.js +++ b/packages/discord.js/src/client/actions/GuildStickerUpdate.js @@ -1,13 +1,14 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildStickerUpdateAction extends Action { handle(current, data) { const old = current._update(data); /** * Emitted whenever a custom sticker is updated in a guild. + * * @event Client#stickerUpdate * @param {Sticker} oldSticker The old sticker * @param {Sticker} newSticker The new sticker diff --git a/packages/discord.js/src/client/actions/GuildUpdate.js b/packages/discord.js/src/client/actions/GuildUpdate.js index b3662e5a7a2b..eeda8cf2e4ff 100644 --- a/packages/discord.js/src/client/actions/GuildUpdate.js +++ b/packages/discord.js/src/client/actions/GuildUpdate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class GuildUpdateAction extends Action { handle(data) { @@ -12,6 +12,7 @@ class GuildUpdateAction extends Action { const old = guild._update(data); /** * Emitted whenever a guild is updated - e.g. name change. + * * @event Client#guildUpdate * @param {Guild} oldGuild The guild before the update * @param {Guild} newGuild The guild after the update diff --git a/packages/discord.js/src/client/actions/InteractionCreate.js b/packages/discord.js/src/client/actions/InteractionCreate.js index 59b97742a89c..a33cde44cb78 100644 --- a/packages/discord.js/src/client/actions/InteractionCreate.js +++ b/packages/discord.js/src/client/actions/InteractionCreate.js @@ -1,7 +1,7 @@ +/* eslint-disable sonarjs/no-nested-switch */ 'use strict'; const { InteractionType, ComponentType, ApplicationCommandType } = require('discord-api-types/v10'); -const { Action } = require('./Action.js'); const { AutocompleteInteraction } = require('../../structures/AutocompleteInteraction.js'); const { ButtonInteraction } = require('../../structures/ButtonInteraction.js'); const { ChannelSelectMenuInteraction } = require('../../structures/ChannelSelectMenuInteraction.js'); @@ -15,6 +15,7 @@ const { StringSelectMenuInteraction } = require('../../structures/StringSelectMe const { UserContextMenuCommandInteraction } = require('../../structures/UserContextMenuCommandInteraction.js'); const { UserSelectMenuInteraction } = require('../../structures/UserSelectMenuInteraction.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class InteractionCreateAction extends Action { handle(data) { @@ -49,6 +50,7 @@ class InteractionCreateAction extends Action { ); return; } + break; case InteractionType.MessageComponent: if (channel && !channel.isTextBased()) return; @@ -79,6 +81,7 @@ class InteractionCreateAction extends Action { ); return; } + break; case InteractionType.ApplicationCommandAutocomplete: InteractionClass = AutocompleteInteraction; @@ -95,6 +98,7 @@ class InteractionCreateAction extends Action { /** * Emitted when an interaction is created. + * * @event Client#interactionCreate * @param {BaseInteraction} interaction The interaction which was created */ diff --git a/packages/discord.js/src/client/actions/MessageCreate.js b/packages/discord.js/src/client/actions/MessageCreate.js index a54298e0ba0b..15aa785d0c93 100644 --- a/packages/discord.js/src/client/actions/MessageCreate.js +++ b/packages/discord.js/src/client/actions/MessageCreate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class MessageCreateAction extends Action { handle(data) { @@ -26,6 +26,7 @@ class MessageCreateAction extends Action { /** * Emitted whenever a message is created. + * * @event Client#messageCreate * @param {Message} message The created message */ diff --git a/packages/discord.js/src/client/actions/MessageDelete.js b/packages/discord.js/src/client/actions/MessageDelete.js index cad1a37eff99..753b88b48d14 100644 --- a/packages/discord.js/src/client/actions/MessageDelete.js +++ b/packages/discord.js/src/client/actions/MessageDelete.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class MessageDeleteAction extends Action { handle(data) { @@ -18,6 +18,7 @@ class MessageDeleteAction extends Action { channel.messages.cache.delete(message.id); /** * Emitted whenever a message is deleted. + * * @event Client#messageDelete * @param {Message} message The deleted message */ diff --git a/packages/discord.js/src/client/actions/MessageDeleteBulk.js b/packages/discord.js/src/client/actions/MessageDeleteBulk.js index 445a9e7a689f..44e5c0732e80 100644 --- a/packages/discord.js/src/client/actions/MessageDeleteBulk.js +++ b/packages/discord.js/src/client/actions/MessageDeleteBulk.js @@ -1,8 +1,8 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class MessageDeleteBulkAction extends Action { handle(data) { @@ -33,6 +33,7 @@ class MessageDeleteBulkAction extends Action { /** * Emitted whenever messages are deleted in bulk. + * * @event Client#messageDeleteBulk * @param {Collection} messages The deleted messages, mapped by their id * @param {GuildTextBasedChannel} channel The channel that the messages were deleted in @@ -40,6 +41,7 @@ class MessageDeleteBulkAction extends Action { if (messages.size > 0) client.emit(Events.MessageBulkDelete, messages, channel); return { messages }; } + return {}; } } diff --git a/packages/discord.js/src/client/actions/MessagePollVoteAdd.js b/packages/discord.js/src/client/actions/MessagePollVoteAdd.js index 9f2927c382bf..8c653fc049b0 100644 --- a/packages/discord.js/src/client/actions/MessagePollVoteAdd.js +++ b/packages/discord.js/src/client/actions/MessagePollVoteAdd.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class MessagePollVoteAddAction extends Action { handle(data) { @@ -27,6 +27,7 @@ class MessagePollVoteAddAction extends Action { /** * Emitted whenever a user votes in a poll. + * * @event Client#messagePollVoteAdd * @param {PollAnswer} pollAnswer The answer that was voted on * @param {Snowflake} userId The id of the user that voted diff --git a/packages/discord.js/src/client/actions/MessagePollVoteRemove.js b/packages/discord.js/src/client/actions/MessagePollVoteRemove.js index f2a4ee0cc208..a8f1c87b3861 100644 --- a/packages/discord.js/src/client/actions/MessagePollVoteRemove.js +++ b/packages/discord.js/src/client/actions/MessagePollVoteRemove.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class MessagePollVoteRemoveAction extends Action { handle(data) { @@ -25,6 +25,7 @@ class MessagePollVoteRemoveAction extends Action { /** * Emitted whenever a user removes their vote in a poll. + * * @event Client#messagePollVoteRemove * @param {PollAnswer} pollAnswer The answer where the vote was removed * @param {Snowflake} userId The id of the user that removed their vote diff --git a/packages/discord.js/src/client/actions/MessageReactionAdd.js b/packages/discord.js/src/client/actions/MessageReactionAdd.js index 5f25cf6f28af..d7fd02878b21 100644 --- a/packages/discord.js/src/client/actions/MessageReactionAdd.js +++ b/packages/discord.js/src/client/actions/MessageReactionAdd.js @@ -1,8 +1,8 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); const { Partials } = require('../../util/Partials.js'); +const { Action } = require('./Action.js'); /* { user_id: 'id', @@ -50,12 +50,14 @@ class MessageReactionAddAction extends Action { if (fromStructure) return { message, reaction, user }; /** * Provides additional information about altered reaction - * @typedef {Object} MessageReactionEventDetails + * + * @typedef {object} MessageReactionEventDetails * @property {ReactionType} type The type of the reaction * @property {boolean} burst Determines whether a super reaction was used */ /** * Emitted whenever a reaction is added to a cached message. + * * @event Client#messageReactionAdd * @param {MessageReaction} messageReaction The reaction object * @param {User} user The user that applied the guild or reaction emoji diff --git a/packages/discord.js/src/client/actions/MessageReactionRemove.js b/packages/discord.js/src/client/actions/MessageReactionRemove.js index ad4b471eac03..6d4cb21f06a3 100644 --- a/packages/discord.js/src/client/actions/MessageReactionRemove.js +++ b/packages/discord.js/src/client/actions/MessageReactionRemove.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); /* { user_id: 'id', @@ -36,6 +36,7 @@ class MessageReactionRemoveAction extends Action { reaction._remove(user, data.burst); /** * Emitted whenever a reaction is removed from a cached message. + * * @event Client#messageReactionRemove * @param {MessageReaction} messageReaction The reaction object * @param {User} user The user whose emoji or reaction emoji was removed diff --git a/packages/discord.js/src/client/actions/MessageReactionRemoveAll.js b/packages/discord.js/src/client/actions/MessageReactionRemoveAll.js index 1dfe00d64f77..1338ad54bcb0 100644 --- a/packages/discord.js/src/client/actions/MessageReactionRemoveAll.js +++ b/packages/discord.js/src/client/actions/MessageReactionRemoveAll.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class MessageReactionRemoveAllAction extends Action { handle(data) { @@ -25,6 +25,7 @@ class MessageReactionRemoveAllAction extends Action { /** * Emitted whenever all reactions are removed from a cached message. + * * @event Client#messageReactionRemoveAll * @param {Message} message The message the reactions were removed from * @param {Collection} reactions The cached message reactions that were removed. diff --git a/packages/discord.js/src/client/actions/MessageReactionRemoveEmoji.js b/packages/discord.js/src/client/actions/MessageReactionRemoveEmoji.js index 02a97efb65fb..34c68af40aea 100644 --- a/packages/discord.js/src/client/actions/MessageReactionRemoveEmoji.js +++ b/packages/discord.js/src/client/actions/MessageReactionRemoveEmoji.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class MessageReactionRemoveEmojiAction extends Action { handle(data) { @@ -17,6 +17,7 @@ class MessageReactionRemoveEmojiAction extends Action { /** * Emitted when a bot removes an emoji reaction from a cached message. + * * @event Client#messageReactionRemoveEmoji * @param {MessageReaction} reaction The reaction that was removed */ diff --git a/packages/discord.js/src/client/actions/StageInstanceCreate.js b/packages/discord.js/src/client/actions/StageInstanceCreate.js index 8b6412016822..d29a207a3a55 100644 --- a/packages/discord.js/src/client/actions/StageInstanceCreate.js +++ b/packages/discord.js/src/client/actions/StageInstanceCreate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class StageInstanceCreateAction extends Action { handle(data) { @@ -13,6 +13,7 @@ class StageInstanceCreateAction extends Action { /** * Emitted whenever a stage instance is created. + * * @event Client#stageInstanceCreate * @param {StageInstance} stageInstance The created stage instance */ diff --git a/packages/discord.js/src/client/actions/StageInstanceDelete.js b/packages/discord.js/src/client/actions/StageInstanceDelete.js index eea25fd52241..d82a02ddd74b 100644 --- a/packages/discord.js/src/client/actions/StageInstanceDelete.js +++ b/packages/discord.js/src/client/actions/StageInstanceDelete.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class StageInstanceDeleteAction extends Action { handle(data) { @@ -15,6 +15,7 @@ class StageInstanceDeleteAction extends Action { /** * Emitted whenever a stage instance is deleted. + * * @event Client#stageInstanceDelete * @param {StageInstance} stageInstance The deleted stage instance */ diff --git a/packages/discord.js/src/client/actions/StageInstanceUpdate.js b/packages/discord.js/src/client/actions/StageInstanceUpdate.js index 88f193ed75cf..3c0fbcba90e3 100644 --- a/packages/discord.js/src/client/actions/StageInstanceUpdate.js +++ b/packages/discord.js/src/client/actions/StageInstanceUpdate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class StageInstanceUpdateAction extends Action { handle(data) { @@ -14,6 +14,7 @@ class StageInstanceUpdateAction extends Action { /** * Emitted whenever a stage instance gets updated - e.g. change in topic or privacy level + * * @event Client#stageInstanceUpdate * @param {?StageInstance} oldStageInstance The stage instance before the update * @param {StageInstance} newStageInstance The stage instance after the update diff --git a/packages/discord.js/src/client/actions/ThreadCreate.js b/packages/discord.js/src/client/actions/ThreadCreate.js index fa6cb6ad5e80..44f9364f11f3 100644 --- a/packages/discord.js/src/client/actions/ThreadCreate.js +++ b/packages/discord.js/src/client/actions/ThreadCreate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class ThreadCreateAction extends Action { handle(data) { @@ -11,12 +11,14 @@ class ThreadCreateAction extends Action { if (!existing && thread) { /** * Emitted whenever a thread is created or when the client user is added to a thread. + * * @event Client#threadCreate * @param {ThreadChannel} thread The thread that was created * @param {boolean} newlyCreated Whether the thread was newly created */ client.emit(Events.ThreadCreate, thread, data.newly_created ?? false); } + return { thread }; } } diff --git a/packages/discord.js/src/client/actions/ThreadMembersUpdate.js b/packages/discord.js/src/client/actions/ThreadMembersUpdate.js index ca3c182f2864..2e1ebf1ad3ce 100644 --- a/packages/discord.js/src/client/actions/ThreadMembersUpdate.js +++ b/packages/discord.js/src/client/actions/ThreadMembersUpdate.js @@ -1,8 +1,8 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class ThreadMembersUpdateAction extends Action { handle(data) { @@ -33,6 +33,7 @@ class ThreadMembersUpdateAction extends Action { /** * Emitted whenever members are added or removed from a thread. * This event requires the {@link GatewayIntentBits.GuildMembers} privileged gateway intent. + * * @event Client#threadMembersUpdate * @param {Collection} addedMembers The members that were added * @param {Collection} removedMembers The members that were removed @@ -40,6 +41,7 @@ class ThreadMembersUpdateAction extends Action { */ client.emit(Events.ThreadMembersUpdate, addedMembers, removedMembers, thread); } + return {}; } } diff --git a/packages/discord.js/src/client/actions/TypingStart.js b/packages/discord.js/src/client/actions/TypingStart.js index cf895e5b65cb..aa3e9a0914c7 100644 --- a/packages/discord.js/src/client/actions/TypingStart.js +++ b/packages/discord.js/src/client/actions/TypingStart.js @@ -1,8 +1,8 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Typing } = require('../../structures/Typing.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class TypingStartAction extends Action { handle(data) { @@ -18,6 +18,7 @@ class TypingStartAction extends Action { if (user) { /** * Emitted whenever a user starts typing in a channel. + * * @event Client#typingStart * @param {Typing} typing The typing state */ diff --git a/packages/discord.js/src/client/actions/UserUpdate.js b/packages/discord.js/src/client/actions/UserUpdate.js index 1fe56fadeb02..302c951304a3 100644 --- a/packages/discord.js/src/client/actions/UserUpdate.js +++ b/packages/discord.js/src/client/actions/UserUpdate.js @@ -1,7 +1,7 @@ 'use strict'; -const { Action } = require('./Action.js'); const { Events } = require('../../util/Events.js'); +const { Action } = require('./Action.js'); class UserUpdateAction extends Action { handle(data) { @@ -15,6 +15,7 @@ class UserUpdateAction extends Action { * Emitted whenever a user's details (e.g. username) are changed. * Triggered by the Discord gateway events {@link Events.UserUpdate}, * {@link Events.GuildMemberUpdate}, and {@link Events.PresenceUpdate}. + * * @event Client#userUpdate * @param {User} oldUser The user before the update * @param {User} newUser The user after the update diff --git a/packages/discord.js/src/client/voice/ClientVoiceManager.js b/packages/discord.js/src/client/voice/ClientVoiceManager.js index df3df1b0c63b..c92a633da5d3 100644 --- a/packages/discord.js/src/client/voice/ClientVoiceManager.js +++ b/packages/discord.js/src/client/voice/ClientVoiceManager.js @@ -9,6 +9,7 @@ class ClientVoiceManager { constructor(client) { /** * The client that instantiated this voice manager + * * @type {Client} * @readonly * @name ClientVoiceManager#client @@ -17,7 +18,8 @@ class ClientVoiceManager { /** * Maps guild ids to voice adapters created for use with `@discordjs/voice`. - * @type {Map} + * + * @type {Map} */ this.adapters = new Map(); diff --git a/packages/discord.js/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js index e8e403df5e21..39e286e3df09 100644 --- a/packages/discord.js/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js @@ -7,6 +7,7 @@ module.exports = (client, { d: data }) => { * Emitted whenever permissions for an application command in a guild were updated. * This includes permission updates for other applications in addition to the logged in client, * check `data.applicationId` to verify which application the update is for + * * @event Client#applicationCommandPermissionsUpdate * @param {ApplicationCommandPermissionsUpdateData} data The updated permissions */ diff --git a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js index 857348598b1f..9ebc2c0fef68 100644 --- a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +++ b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js @@ -10,6 +10,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever an auto moderation rule is triggered. * This event requires the {@link PermissionFlagsBits.ManageGuild} permission. + * * @event Client#autoModerationActionExecution * @param {AutoModerationActionExecution} autoModerationActionExecution The data of the execution */ diff --git a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js index 24808c95462f..666d7e1a0c39 100644 --- a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js @@ -11,6 +11,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever an auto moderation rule is created. * This event requires the {@link PermissionFlagsBits.ManageGuild} permission. + * * @event Client#autoModerationRuleCreate * @param {AutoModerationRule} autoModerationRule The created auto moderation rule */ diff --git a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js index f73652f70428..cec334fddba0 100644 --- a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js @@ -14,6 +14,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever an auto moderation rule is deleted. * This event requires the {@link PermissionFlagsBits.ManageGuild} permission. + * * @event Client#autoModerationRuleDelete * @param {AutoModerationRule} autoModerationRule The deleted auto moderation rule */ diff --git a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js index bde8a0ed5263..6817069538b8 100644 --- a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js @@ -12,6 +12,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever an auto moderation rule gets updated. * This event requires the {@link PermissionFlagsBits.ManageGuild} permission. + * * @event Client#autoModerationRuleUpdate * @param {?AutoModerationRule} oldAutoModerationRule The auto moderation rule before the update * @param {AutoModerationRule} newAutoModerationRule The auto moderation rule after the update diff --git a/packages/discord.js/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js index b59260daac8b..7f7f1199f094 100644 --- a/packages/discord.js/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js @@ -13,6 +13,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever the pins of a channel are updated. Due to the nature of the WebSocket event, * not much information can be provided easily here - you need to manually check the pins yourself. + * * @event Client#channelPinsUpdate * @param {TextBasedChannels} channel The channel that the pins update occurred in * @param {Date} time The time of the pins update diff --git a/packages/discord.js/src/client/websocket/handlers/CHANNEL_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/CHANNEL_UPDATE.js index e09113fc8a46..3887fad07a33 100644 --- a/packages/discord.js/src/client/websocket/handlers/CHANNEL_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/CHANNEL_UPDATE.js @@ -7,6 +7,7 @@ module.exports = (client, packet) => { if (old && updated) { /** * Emitted whenever a channel is updated - e.g. name change, topic change, channel type change. + * * @event Client#channelUpdate * @param {DMChannel|GuildChannel} oldChannel The channel before the update * @param {DMChannel|GuildChannel} newChannel The channel after the update diff --git a/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_CREATE.js b/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_CREATE.js index 402d420d82fb..10a367f91d04 100644 --- a/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_CREATE.js @@ -7,6 +7,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever an entitlement is created. + * * @event Client#entitlementCreate * @param {Entitlement} entitlement The entitlement that was created */ diff --git a/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_DELETE.js b/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_DELETE.js index a4b0f2f33c23..5f29537d06e8 100644 --- a/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_DELETE.js @@ -11,6 +11,7 @@ module.exports = (client, { d: data }) => { * Emitted whenever an entitlement is deleted. * Entitlements are not deleted when they expire. * This is only triggered when Discord issues a refund or deletes the entitlement manually. + * * @event Client#entitlementDelete * @param {Entitlement} entitlement The entitlement that was deleted */ diff --git a/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_UPDATE.js index 08e6989254bb..080daf58b3cb 100644 --- a/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/ENTITLEMENT_UPDATE.js @@ -8,6 +8,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever an entitlement is updated - i.e. when a user's subscription renews. + * * @event Client#entitlementUpdate * @param {?Entitlement} oldEntitlement The entitlement before the update * @param {Entitlement} newEntitlement The entitlement after the update diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js index 4de70dc9f990..1456118a6c27 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js @@ -11,6 +11,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild audit log entry is created. + * * @event Client#guildAuditLogEntryCreate * @param {GuildAuditLogsEntry} auditLogEntry The entry that was created * @param {Guild} guild The guild where the entry was created diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js b/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js index 970666311247..d88d9c6582e5 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js @@ -8,6 +8,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a member is banned from a guild. + * * @event Client#guildBanAdd * @param {GuildBan} ban The ban that occurred */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js index fd82b2c7477a..e0695a63f496 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js @@ -13,6 +13,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a member is unbanned from a guild. + * * @event Client#guildBanRemove * @param {GuildBan} ban The ban that was removed */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_CREATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_CREATE.js index 6518ccd89420..418bd3aa8c48 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_CREATE.js @@ -12,6 +12,7 @@ module.exports = (client, { d: data }, shardId) => { /** * Emitted whenever a guild becomes available. + * * @event Client#guildAvailable * @param {Guild} guild The guild that became available */ @@ -24,6 +25,7 @@ module.exports = (client, { d: data }, shardId) => { if (client.status === Status.Ready) { /** * Emitted whenever the client joins a guild. + * * @event Client#guildCreate * @param {Guild} guild The created guild */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_DELETE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_DELETE.js index e2a85bcd6f0e..40531348795b 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_DELETE.js @@ -11,6 +11,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild becomes unavailable, likely due to a server outage. + * * @event Client#guildUnavailable * @param {Guild} guild The guild that has become unavailable */ @@ -28,6 +29,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild kicks the client or the guild is deleted/left. + * * @event Client#guildDelete * @param {Guild} guild The guild that was deleted */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js index 788323de5258..61c391054295 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js @@ -8,6 +8,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild integration is updated + * * @event Client#guildIntegrationsUpdate * @param {Guild} guild The guild whose integrations were updated */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js b/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js index b41d1cdfc0bb..fdcf0b1df708 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js @@ -15,7 +15,8 @@ module.exports = (client, { d: data }) => { /** * Represents the properties of a guild members chunk - * @typedef {Object} GuildMembersChunk + * + * @typedef {object} GuildMembersChunk * @property {number} index Index of the received chunk * @property {number} count Number of chunks the client should receive * @property {Array<*>} notFound An array of whatever could not be found @@ -25,6 +26,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a chunk of guild members is received (all members come from the same guild). + * * @event Client#guildMembersChunk * @param {Collection} members The members in the chunk * @param {Guild} guild The guild related to the member chunk diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBER_ADD.js b/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBER_ADD.js index 31d73ffebe90..976046e49a8d 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBER_ADD.js @@ -9,6 +9,7 @@ module.exports = (client, { d: data }) => { const member = guild.members._add(data); /** * Emitted whenever a user joins a guild. + * * @event Client#guildMemberAdd * @param {GuildMember} member The member that has joined a guild */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js index f35510a779b5..e1b61e57fa22 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js @@ -13,6 +13,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild role is updated. + * * @event Client#roleUpdate * @param {Role} oldRole The role before the update * @param {Role} newRole The role after the update diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js index 5fe141db4a1c..ecee9d5ae55f 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js @@ -10,6 +10,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild scheduled event is created. + * * @event Client#guildScheduledEventCreate * @param {GuildScheduledEvent} guildScheduledEvent The created guild scheduled event */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js index f0d90416cedd..50c15501d931 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js @@ -11,6 +11,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild scheduled event gets updated. + * * @event Client#guildScheduledEventUpdate * @param {?GuildScheduledEvent} oldGuildScheduledEvent The guild scheduled event object before the update * @param {GuildScheduledEvent} newGuildScheduledEvent The guild scheduled event object after the update diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js index 208eee1bdead..4445c29632ac 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js @@ -16,6 +16,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever multiple guild soundboard sounds are updated. + * * @event Client#guildSoundboardSoundsUpdate * @param {Collection} soundboardSounds The updated soundboard sounds * @param {Guild} guild The guild that the soundboard sounds are from diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js index b5c0b77d56bc..cdaf6a45bb3d 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js @@ -11,6 +11,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild soundboard sound is created. + * * @event Client#guildSoundboardSoundCreate * @param {SoundboardSound} soundboardSound The created guild soundboard sound */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js index e57cf139f73f..9f2aa43ee8ae 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js @@ -12,6 +12,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a guild soundboard sound is updated. + * * @event Client#guildSoundboardSoundUpdate * @param {?SoundboardSound} oldGuildSoundboardSound The guild soundboard sound before the update * @param {SoundboardSound} newGuildSoundboardSound The guild soundboard sound after the update diff --git a/packages/discord.js/src/client/websocket/handlers/INVITE_CREATE.js b/packages/discord.js/src/client/websocket/handlers/INVITE_CREATE.js index 9f2b2b2da908..16ab2ab413b5 100644 --- a/packages/discord.js/src/client/websocket/handlers/INVITE_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/INVITE_CREATE.js @@ -13,6 +13,7 @@ module.exports = (client, { d: data }) => { /** * Emitted when an invite is created. * This event requires the {@link PermissionFlagsBits.ManageChannels} permission for the channel. + * * @event Client#inviteCreate * @param {Invite} invite The invite that was created */ diff --git a/packages/discord.js/src/client/websocket/handlers/INVITE_DELETE.js b/packages/discord.js/src/client/websocket/handlers/INVITE_DELETE.js index f7212122618f..9ca09a5bbb46 100644 --- a/packages/discord.js/src/client/websocket/handlers/INVITE_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/INVITE_DELETE.js @@ -16,6 +16,7 @@ module.exports = (client, { d: data }) => { /** * Emitted when an invite is deleted. * This event requires the {@link PermissionFlagsBits.ManageChannels} permission for the channel. + * * @event Client#inviteDelete * @param {Invite} invite The invite that was deleted */ diff --git a/packages/discord.js/src/client/websocket/handlers/MESSAGE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/MESSAGE_UPDATE.js index 0ecf1a7e55a6..3c88c3b2ad54 100644 --- a/packages/discord.js/src/client/websocket/handlers/MESSAGE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/MESSAGE_UPDATE.js @@ -7,6 +7,7 @@ module.exports = (client, packet) => { if (old && updated) { /** * Emitted whenever a message is updated - e.g. embed or content change. + * * @event Client#messageUpdate * @param {Message} oldMessage The message before the update * @param {Message} newMessage The message after the update diff --git a/packages/discord.js/src/client/websocket/handlers/PRESENCE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/PRESENCE_UPDATE.js index a4db8a43ea30..bb1d8024e688 100644 --- a/packages/discord.js/src/client/websocket/handlers/PRESENCE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/PRESENCE_UPDATE.js @@ -8,11 +8,10 @@ module.exports = (client, { d: data }) => { if (!user && ('username' in data.user || client.options.partials.includes(Partials.User))) { user = client.users._add(data.user); } + if (!user) return; - if (data.user.username) { - if (!user._equals(data.user)) client.actions.UserUpdate.handle(data.user); - } + if (data.user.username && !user._equals(data.user)) client.actions.UserUpdate.handle(data.user); const guild = client.guilds.cache.get(data.guild_id); if (!guild) return; @@ -34,6 +33,7 @@ module.exports = (client, { d: data }) => { if (client.listenerCount(Events.PresenceUpdate) > 0 && !newPresence.equals(oldPresence)) { /** * Emitted whenever a guild member's presence (e.g. status, activity) is changed. + * * @event Client#presenceUpdate * @param {?Presence} oldPresence The presence before the update, if one at all * @param {Presence} newPresence The presence after the update diff --git a/packages/discord.js/src/client/websocket/handlers/READY.js b/packages/discord.js/src/client/websocket/handlers/READY.js index dcda97ab5228..bf78a1368de6 100644 --- a/packages/discord.js/src/client/websocket/handlers/READY.js +++ b/packages/discord.js/src/client/websocket/handlers/READY.js @@ -1,6 +1,7 @@ 'use strict'; const { ClientApplication } = require('../../../structures/ClientApplication.js'); + let ClientUser; module.exports = (client, { d: data }, shardId) => { diff --git a/packages/discord.js/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js b/packages/discord.js/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js index b898343a1776..fd2e7ac949ab 100644 --- a/packages/discord.js/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js +++ b/packages/discord.js/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js @@ -16,6 +16,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever soundboard sounds are received (all soundboard sounds come from the same guild). + * * @event Client#soundboardSounds * @param {Collection} soundboardSounds The sounds received * @param {Guild} guild The guild that the soundboard sounds are from diff --git a/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_CREATE.js b/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_CREATE.js index b595c88f552a..593b34d69fd3 100644 --- a/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_CREATE.js @@ -7,6 +7,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a subscription is created. + * * @event Client#subscriptionCreate * @param {Subscription} subscription The subscription that was created */ diff --git a/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_DELETE.js b/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_DELETE.js index 96cccf04c5f2..24833996b342 100644 --- a/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_DELETE.js @@ -9,6 +9,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a subscription is deleted. + * * @event Client#subscriptionDelete * @param {Subscription} subscription The subscription that was deleted */ diff --git a/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_UPDATE.js index 19197800e807..b5d2acdf7395 100644 --- a/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/SUBSCRIPTION_UPDATE.js @@ -8,6 +8,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a subscription is updated - i.e. when a user's subscription renews. + * * @event Client#subscriptionUpdate * @param {?Subscription} oldSubscription The subscription before the update * @param {Subscription} newSubscription The subscription after the update diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_DELETE.js b/packages/discord.js/src/client/websocket/handlers/THREAD_DELETE.js index da38947b663d..ba46971816c1 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_DELETE.js @@ -10,6 +10,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a thread is deleted. + * * @event Client#threadDelete * @param {ThreadChannel} thread The thread that was deleted */ diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js index 33361570ec7f..47bc5e593f09 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js @@ -33,6 +33,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever the client user gains access to a text or announcement channel that contains threads + * * @event Client#threadListSync * @param {Collection} threads The threads that were synced * @param {Guild} guild The guild that the threads were synced in diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js index c97ce85c5621..658481c37afe 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js @@ -17,6 +17,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever the client user's thread member is updated. + * * @event Client#threadMemberUpdate * @param {ThreadMember} oldMember The member before the update * @param {ThreadMember} newMember The member after the update diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/THREAD_UPDATE.js index c11a414f30cb..a62afa73aa1c 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_UPDATE.js @@ -7,6 +7,7 @@ module.exports = (client, packet) => { if (old && updated) { /** * Emitted whenever a thread is updated - e.g. name change, archive state change, locked state change. + * * @event Client#threadUpdate * @param {ThreadChannel} oldThread The thread before the update * @param {ThreadChannel} newThread The thread after the update diff --git a/packages/discord.js/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js b/packages/discord.js/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js index 7030e3f07a16..87748880d570 100644 --- a/packages/discord.js/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +++ b/packages/discord.js/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js @@ -9,6 +9,7 @@ module.exports = (client, { d: data }) => { /** * Emitted when someone sends an effect, such as an emoji reaction, in a voice channel the client is connected to. + * * @event Client#voiceChannelEffectSend * @param {VoiceChannelEffect} voiceChannelEffect The sent voice channel effect */ diff --git a/packages/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js index f3a93beeeba9..fdbc5078cd9e 100644 --- a/packages/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js @@ -29,6 +29,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes. + * * @event Client#voiceStateUpdate * @param {VoiceState} oldState The voice state before the update * @param {VoiceState} newState The voice state after the update diff --git a/packages/discord.js/src/client/websocket/handlers/WEBHOOKS_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/WEBHOOKS_UPDATE.js index 4ab913f77890..900d3b379cc6 100644 --- a/packages/discord.js/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/WEBHOOKS_UPDATE.js @@ -8,6 +8,7 @@ module.exports = (client, { d: data }) => { /** * Emitted whenever a channel has its webhooks changed. + * * @event Client#webhooksUpdate * @param {TextChannel|AnnouncementChannel|VoiceChannel|StageChannel|ForumChannel|MediaChannel} channel * The channel that had a webhook update diff --git a/packages/discord.js/src/errors/DJSError.js b/packages/discord.js/src/errors/DJSError.js index 25cf5c9971b9..204bf2325fc1 100644 --- a/packages/discord.js/src/errors/DJSError.js +++ b/packages/discord.js/src/errors/DJSError.js @@ -6,6 +6,7 @@ const { Messages } = require('./Messages.js'); /** * Extend an error of some sort into a DiscordjsError. + * * @param {Error} Base Base error to extend * @returns {DiscordjsError} * @ignore @@ -26,6 +27,7 @@ function makeDiscordjsError(Base) { /** * Format the message for an error. + * * @param {string} code The error code * @param {Array<*>} args Arguments to pass for util format or as function args * @returns {string} Formatted string diff --git a/packages/discord.js/src/errors/ErrorCodes.js b/packages/discord.js/src/errors/ErrorCodes.js index 9edaefdf8833..9a2820a2ce0e 100644 --- a/packages/discord.js/src/errors/ErrorCodes.js +++ b/packages/discord.js/src/errors/ErrorCodes.js @@ -1,19 +1,17 @@ +/* eslint-disable jsdoc/tag-lines */ +/* eslint-disable jsdoc/require-property-description */ 'use strict'; /** - * @typedef {Object} DiscordjsErrorCodes - + * @typedef {object} DiscordjsErrorCodes * @property {'ClientInvalidOption'} ClientInvalidOption * @property {'ClientInvalidProvidedShards'} ClientInvalidProvidedShards * @property {'ClientMissingIntents'} ClientMissingIntents * @property {'ClientNotReady'} ClientNotReady - * @property {'TokenInvalid'} TokenInvalid * @property {'TokenMissing'} TokenMissing * @property {'ApplicationCommandPermissionsTokenMissing'} ApplicationCommandPermissionsTokenMissing - * @property {'BitFieldInvalid'} BitFieldInvalid - * @property {'ShardingNoShards'} ShardingNoShards * @property {'ShardingInProcess'} ShardingInProcess * @property {'ShardingInvalidEvalBroadcast'} ShardingInvalidEvalBroadcast @@ -26,35 +24,35 @@ * @property {'ShardingReadyDied'} ShardingReadyDied * @property {'ShardingNoChildExists'} ShardingNoChildExists * @property {'ShardingShardMiscalculation'} ShardingShardMiscalculation - + * * @property {'ColorRange'} ColorRange * @property {'ColorConvert'} ColorConvert - + * * @property {'InviteOptionsMissingChannel'} InviteOptionsMissingChannel - + * * @property {'InteractionCollectorError'} InteractionCollectorError - + * * @property {'FileNotFound'} FileNotFound - + * * @property {'UserNoDMChannel'} UserNoDMChannel - + * * @property {'VoiceNotStageChannel'} VoiceNotStageChannel - + * * @property {'VoiceStateNotOwn'} VoiceStateNotOwn * @property {'VoiceStateInvalidType'} VoiceStateInvalidType - + * * @property {'ReqResourceType'} ReqResourceType - + * * @property {'MessageBulkDeleteType'} MessageBulkDeleteType * @property {'MessageContentType'} MessageContentType * @property {'MessageNonceRequired'} MessageNonceRequired * @property {'MessageNonceType'} MessageNonceType - + * * @property {'BanResolveId'} BanResolveId * @property {'FetchBanResolveId'} FetchBanResolveId - + * * @property {'PruneDaysType'} PruneDaysType - + * * @property {'GuildChannelResolve'} GuildChannelResolve * @property {'GuildVoiceChannelResolve'} GuildVoiceChannelResolve * @property {'GuildChannelOrphan'} GuildChannelOrphan @@ -67,46 +65,46 @@ * @property {'StageChannelResolve'} StageChannelResolve * @property {'GuildScheduledEventResolve'} GuildScheduledEventResolve * @property {'FetchOwnerId'} FetchOwnerId - + * * @property {'InvalidType'} InvalidType * @property {'InvalidElement'} InvalidElement - + * * @property {'MessageThreadParent'} MessageThreadParent * @property {'MessageExistingThread'} MessageExistingThread * @property {'ThreadInvitableType'} ThreadInvitableType * @property {'NotAThreadOfParent'} NotAThreadOfParent - + * * @property {'WebhookMessage'} WebhookMessage * @property {'WebhookTokenUnavailable'} WebhookTokenUnavailable * @property {'WebhookURLInvalid'} WebhookURLInvalid * @property {'WebhookApplication'} WebhookApplication * @property {'MessageReferenceMissing'} MessageReferenceMissing - + * * @property {'EmojiType'} EmojiType * @property {'EmojiManaged'} EmojiManaged * @property {'MissingManageGuildExpressionsPermission'} MissingManageGuildExpressionsPermission * - + * * @property {'NotGuildSoundboardSound'} NotGuildSoundboardSound * @property {'NotGuildSticker'} NotGuildSticker - + * * @property {'ReactionResolveUser'} ReactionResolveUser - + * * @property {'InviteResolveCode'} InviteResolveCode - + * * @property {'InviteNotFound'} InviteNotFound - + * * @property {'DeleteGroupDMChannel'} DeleteGroupDMChannel * @property {'FetchGroupDMChannel'} FetchGroupDMChannel - + * * @property {'MemberFetchNonceLength'} MemberFetchNonceLength - + * * @property {'GlobalCommandPermissions'} GlobalCommandPermissions * @property {'GuildUncachedEntityResolve'} GuildUncachedEntityResolve - + * * @property {'InteractionAlreadyReplied'} InteractionAlreadyReplied * @property {'InteractionNotReplied'} InteractionNotReplied - + * * @property {'CommandInteractionOptionNotFound'} CommandInteractionOptionNotFound * @property {'CommandInteractionOptionType'} CommandInteractionOptionType * @property {'CommandInteractionOptionEmpty'} CommandInteractionOptionEmpty @@ -114,25 +112,25 @@ * @property {'CommandInteractionOptionNoSubcommandGroup'} CommandInteractionOptionNoSubcommandGroup * @property {'CommandInteractionOptionInvalidChannelType'} CommandInteractionOptionInvalidChannelType * @property {'AutocompleteInteractionOptionNoFocusedOption'} AutocompleteInteractionOptionNoFocusedOption - + * * @property {'ModalSubmitInteractionFieldNotFound'} ModalSubmitInteractionFieldNotFound * @property {'ModalSubmitInteractionFieldType'} ModalSubmitInteractionFieldType - + * * @property {'InvalidMissingScopes'} InvalidMissingScopes * @property {'InvalidScopesWithPermissions'} InvalidScopesWithPermissions - + * * @property {'NotImplemented'} NotImplemented - + * * @property {'GuildForumMessageRequired'} GuildForumMessageRequired - + * * @property {'SweepFilterReturn'} SweepFilterReturn - + * * @property {'EntitlementCreateInvalidOwner'} EntitlementCreateInvalidOwner - + * * @property {'BulkBanUsersOptionEmpty'} BulkBanUsersOptionEmpty - + * * @property {'PollAlreadyExpired'} PollAlreadyExpired - + * * @property {'PermissionOverwritesTypeMandatory'} PermissionOverwritesTypeMandatory * @property {'PermissionOverwritesTypeMismatch'} PermissionOverwritesTypeMismatch */ diff --git a/packages/discord.js/src/managers/ApplicationCommandManager.js b/packages/discord.js/src/managers/ApplicationCommandManager.js index 5cec2bbf0378..179c8d7eaa47 100644 --- a/packages/discord.js/src/managers/ApplicationCommandManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandManager.js @@ -4,14 +4,15 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { isJSONEncodable } = require('@discordjs/util'); const { Routes } = require('discord-api-types/v10'); -const { ApplicationCommandPermissionsManager } = require('./ApplicationCommandPermissionsManager.js'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { ApplicationCommand } = require('../structures/ApplicationCommand.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); +const { ApplicationCommandPermissionsManager } = require('./ApplicationCommandPermissionsManager.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for application commands and stores their cache. + * * @extends {CachedManager} */ class ApplicationCommandManager extends CachedManager { @@ -20,6 +21,7 @@ class ApplicationCommandManager extends CachedManager { /** * The manager for permissions of arbitrary commands on arbitrary guilds + * * @type {ApplicationCommandPermissionsManager} */ this.permissions = new ApplicationCommandPermissionsManager(this); @@ -27,6 +29,7 @@ class ApplicationCommandManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name ApplicationCommandManager#cache */ @@ -37,6 +40,8 @@ class ApplicationCommandManager extends CachedManager { /** * The APIRouter path to the commands + * + * @param {object} [options] The options * @param {Snowflake} [options.id] The application command's id * @param {Snowflake} [options.guildId] The guild's id to use in the path, * ignored when using a {@link GuildApplicationCommandManager} @@ -61,25 +66,29 @@ class ApplicationCommandManager extends CachedManager { /** * Data that resolves to give an ApplicationCommand object. This can be: - * * An ApplicationCommand object - * * A Snowflake + * An ApplicationCommand object + * A Snowflake + * * @typedef {ApplicationCommand|Snowflake} ApplicationCommandResolvable */ /** * Data that resolves to the data of an ApplicationCommand + * * @typedef {ApplicationCommandData|APIApplicationCommand} ApplicationCommandDataResolvable */ /** * Options used to fetch data from Discord - * @typedef {Object} BaseFetchOptions + * + * @typedef {object} BaseFetchOptions * @property {boolean} [cache=true] Whether to cache the fetched data if it wasn't already * @property {boolean} [force=false] Whether to skip the cache check and request the API */ /** * Options used to fetch Application Commands from Discord + * * @typedef {BaseFetchOptions} FetchApplicationCommandOptions * @property {Snowflake} [id] The command's id to fetch * @property {Snowflake} [guildId] The guild's id to fetch commands for, for when the guild is not cached @@ -89,6 +98,7 @@ class ApplicationCommandManager extends CachedManager { /** * Obtains one or multiple application commands from Discord, or the cache if it's already available. + * * @param {Snowflake|FetchApplicationCommandOptions} [options] Options for fetching application command(s) * @returns {Promise>} * @example @@ -147,6 +157,7 @@ class ApplicationCommandManager extends CachedManager { /** * Creates an application command. + * * @param {ApplicationCommandDataResolvable} command The command * @param {Snowflake} [guildId] The guild's id to create this command in, * ignored when using a {@link GuildApplicationCommandManager} @@ -169,6 +180,7 @@ class ApplicationCommandManager extends CachedManager { /** * Sets all the commands for this application or guild. + * * @param {ApplicationCommandDataResolvable[]} commands The commands * @param {Snowflake} [guildId] The guild's id to create the commands in, * ignored when using a {@link GuildApplicationCommandManager} @@ -201,6 +213,7 @@ class ApplicationCommandManager extends CachedManager { /** * Edits an application command. + * * @param {ApplicationCommandResolvable} command The command to edit * @param {Partial} data The data to update the command with * @param {Snowflake} [guildId] The guild's id where the command registered, @@ -226,6 +239,7 @@ class ApplicationCommandManager extends CachedManager { /** * Deletes an application command. + * * @param {ApplicationCommandResolvable} command The command to delete * @param {Snowflake} [guildId] The guild's id where the command is registered, * ignored when using a {@link GuildApplicationCommandManager} @@ -249,6 +263,7 @@ class ApplicationCommandManager extends CachedManager { /** * Transforms an {@link ApplicationCommandData} object into something that can be used with the API. + * * @param {ApplicationCommandDataResolvable} command The command to transform * @returns {APIApplicationCommand} * @private @@ -266,9 +281,9 @@ class ApplicationCommandManager extends CachedManager { if ('defaultMemberPermissions' in command) { default_member_permissions = - command.defaultMemberPermissions !== null - ? new PermissionsBitField(command.defaultMemberPermissions).bitfield.toString() - : command.defaultMemberPermissions; + command.defaultMemberPermissions === null + ? command.defaultMemberPermissions + : new PermissionsBitField(command.defaultMemberPermissions).bitfield.toString(); } return { diff --git a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js index 51484fcb0c95..0a7fbcb0d10c 100644 --- a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js @@ -2,11 +2,12 @@ const { Collection } = require('@discordjs/collection'); const { ApplicationCommandPermissionType, RESTJSONErrorCodes, Routes } = require('discord-api-types/v10'); -const { BaseManager } = require('./BaseManager.js'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); +const { BaseManager } = require('./BaseManager.js'); /** * Manages API methods for permissions of Application Commands. + * * @extends {BaseManager} */ class ApplicationCommandPermissionsManager extends BaseManager { @@ -15,6 +16,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * The manager or command that this manager belongs to + * * @type {ApplicationCommandManager|ApplicationCommand} * @private */ @@ -22,18 +24,21 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * The guild that this manager acts on + * * @type {?Guild} */ this.guild = manager.guild ?? null; /** * The id of the guild that this manager acts on + * * @type {?Snowflake} */ this.guildId = manager.guildId ?? manager.guild?.id ?? null; /** * The id of the command this manager acts on + * * @type {?Snowflake} */ this.commandId = manager.id ?? null; @@ -41,6 +46,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * The APIRouter path to the commands + * * @param {Snowflake} guildId The guild's id to use in the path, * @param {Snowflake} [commandId] The application command's id * @returns {string} @@ -54,22 +60,22 @@ class ApplicationCommandPermissionsManager extends BaseManager { return Routes.guildApplicationCommandsPermissions(this.client.application.id, guildId); } - /* eslint-disable max-len */ /** * The object returned when fetching permissions for an application command. - * @typedef {Object} ApplicationCommandPermissions + * + * @typedef {object} ApplicationCommandPermissions * @property {Snowflake} id The role, user, or channel's id. Can also be a * {@link https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permissions-constants permission constant}. * @property {ApplicationCommandPermissionType} type Whether this permission is for a role or a user * @property {boolean} permission Whether the role or user has the permission to use this command */ - /* eslint-enable max-len */ /** * Options for managing permissions for one or more Application Commands * When passing these options to a manager where `guildId` is `null`, * `guild` is a required parameter - * @typedef {Object} BaseApplicationCommandPermissionsOptions + * + * @typedef {object} BaseApplicationCommandPermissionsOptions * @property {GuildResolvable} [guild] The guild to modify / check permissions for * Ignored when the manager has a non-null `guildId` property * @property {ApplicationCommandResolvable} [command] The command to modify / check permissions for @@ -78,7 +84,8 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * Fetches the permissions for one or multiple commands. Providing the client's id as the "command id" will fetch - * *only* the guild level permissions + * only* the guild level permissions + * * @param {BaseApplicationCommandPermissionsOptions} [options] Options used to fetch permissions * @returns {Promise>} * @example @@ -112,6 +119,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { * Options used to set permissions for one or more Application Commands in a guild * Omitting the `command` parameter edits the guild wide permissions * when the manager's `commandId` is `null` + * * @typedef {BaseApplicationCommandPermissionsOptions} ApplicationCommandPermissionsEditOptions * @property {ApplicationCommandPermissions[]} permissions The new permissions for the guild or overwrite * @property {string} token The bearer token to use that authorizes the permission edit @@ -119,6 +127,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * Sets the permissions for the guild or a command overwrite. + * * @param {ApplicationCommandPermissionsEditOptions} options Options used to set permissions * @returns {Promise>} * @example @@ -155,6 +164,8 @@ class ApplicationCommandPermissionsManager extends BaseManager { if (!token) { throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing); } + + // eslint-disable-next-line prefer-const let { guildId, commandId } = this._validateOptions(guild, command); if (!Array.isArray(permissions)) { @@ -166,9 +177,8 @@ class ApplicationCommandPermissionsManager extends BaseManager { ); } - if (!commandId) { - commandId = this.client.user.id; - } + commandId ??= this.client.user.id; + const data = await this.client.rest.put(this.permissionsPath(guildId, commandId), { body: { permissions }, auth: false, @@ -179,6 +189,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * Add permissions to a command. + * * @param {ApplicationCommandPermissionsEditOptions} options Options used to add permissions * @returns {Promise} * @example @@ -197,10 +208,11 @@ class ApplicationCommandPermissionsManager extends BaseManager { if (!token) { throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing); } + + // eslint-disable-next-line prefer-const let { guildId, commandId } = this._validateOptions(guild, command); - if (!commandId) { - commandId = this.client.user.id; - } + commandId ??= this.client.user.id; + if (!Array.isArray(permissions)) { throw new DiscordjsTypeError( ErrorCodes.InvalidType, @@ -230,12 +242,14 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * A static snowflake that identifies the everyone role for application command permissions. * It is the same as the guild id + * * @typedef {Snowflake} RolePermissionConstant */ /** * A static snowflake that identifies the "all channels" entity for application command permissions. * It will be the result of the calculation `guildId - 1` + * * @typedef {Snowflake} ChannelPermissionConstant */ @@ -244,6 +258,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { * Omitting the `command` parameter removes from the guild wide permissions * when the managers `commandId` is `null` * At least one of `users`, `roles`, and `channels` is required + * * @typedef {BaseApplicationCommandPermissionsOptions} RemoveApplicationCommandPermissionsOptions * @property {string} token The bearer token to use that authorizes the permission removal * @property {UserResolvable[]} [users] The user(s) to remove @@ -253,6 +268,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * Remove permissions from a command. + * * @param {RemoveApplicationCommandPermissionsOptions} options Options used to remove permissions * @returns {Promise} * @example @@ -274,16 +290,16 @@ class ApplicationCommandPermissionsManager extends BaseManager { if (!token) { throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing); } + + // eslint-disable-next-line prefer-const let { guildId, commandId } = this._validateOptions(guild, command); - if (!commandId) { - commandId = this.client.user.id; - } + commandId ??= this.client.user.id; if (!users && !roles && !channels) { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'users OR roles OR channels', 'Array or Resolvable', true); } - let resolvedUserIds = []; + const resolvedUserIds = []; if (Array.isArray(users)) { for (const user of users) { const userId = this.client.users.resolveId(user); @@ -292,13 +308,14 @@ class ApplicationCommandPermissionsManager extends BaseManager { } } - let resolvedRoleIds = []; + const resolvedRoleIds = []; if (Array.isArray(roles)) { for (const role of roles) { if (typeof role === 'string') { resolvedRoleIds.push(role); continue; } + if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles'); const roleId = this.guild.roles.resolveId(role); if (!roleId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', role); @@ -306,13 +323,14 @@ class ApplicationCommandPermissionsManager extends BaseManager { } } - let resolvedChannelIds = []; + const resolvedChannelIds = []; if (Array.isArray(channels)) { for (const channel of channels) { if (typeof channel === 'string') { resolvedChannelIds.push(channel); continue; } + if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'channels'); const channelId = this.guild.channels.resolveId(channel); if (!channelId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel); @@ -336,6 +354,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { case ApplicationCommandPermissionType.Channel: return !resolvedChannelIds.includes(perm.id); } + return true; }); @@ -345,6 +364,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * Options used to check the existence of permissions on a command * The `command` parameter is not optional when the managers `commandId` is `null` + * * @typedef {BaseApplicationCommandPermissionsOptions} HasApplicationCommandPermissionsOptions * @property {ApplicationCommandPermissionIdResolvable} permissionId The entity to check if a permission exists for * on this command. @@ -353,6 +373,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * Check whether a permission exists for a user, role, or channel + * * @param {HasApplicationCommandPermissionsOptions} options Options used to check permissions * @returns {Promise} * @example @@ -371,6 +392,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { 'UserResolvable, RoleResolvable, ChannelResolvable, or Permission Constant', ); } + let resolvedId = permissionId; if (typeof permissionId !== 'string') { resolvedId = this.client.users.resolveId(permissionId); @@ -378,9 +400,9 @@ class ApplicationCommandPermissionsManager extends BaseManager { if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles'); resolvedId = this.guild.roles.resolveId(permissionId); } - if (!resolvedId) { - resolvedId = this.guild.channels.resolveId(permissionId); - } + + resolvedId ??= this.guild.channels.resolveId(permissionId); + if (!resolvedId) { throw new DiscordjsTypeError( ErrorCodes.InvalidType, @@ -410,19 +432,21 @@ class ApplicationCommandPermissionsManager extends BaseManager { if (!commandId && this.guild) { commandId = this.guild.commands.resolveId(command); } + commandId ??= this.client.application?.commands.resolveId(command); if (!commandId) { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable', true); } } + return { guildId, commandId }; } } exports.ApplicationCommandPermissionsManager = ApplicationCommandPermissionsManager; -/* eslint-disable max-len */ /** * Data that resolves to an id used for an application command permission + * * @typedef {UserResolvable|RoleResolvable|GuildChannelResolvable|RolePermissionConstant|ChannelPermissionConstant} ApplicationCommandPermissionIdResolvable */ diff --git a/packages/discord.js/src/managers/ApplicationEmojiManager.js b/packages/discord.js/src/managers/ApplicationEmojiManager.js index 6f5c4e5584b4..e53c39edae77 100644 --- a/packages/discord.js/src/managers/ApplicationEmojiManager.js +++ b/packages/discord.js/src/managers/ApplicationEmojiManager.js @@ -2,13 +2,14 @@ const { Collection } = require('@discordjs/collection'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { ApplicationEmoji } = require('../structures/ApplicationEmoji.js'); const { resolveImage } = require('../util/DataResolver.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for ApplicationEmojis and stores their cache. + * * @extends {CachedManager} */ class ApplicationEmojiManager extends CachedManager { @@ -17,6 +18,7 @@ class ApplicationEmojiManager extends CachedManager { /** * The application this manager belongs to + * * @type {ClientApplication} */ this.application = application; @@ -28,13 +30,15 @@ class ApplicationEmojiManager extends CachedManager { /** * Options used for creating an emoji of the application - * @typedef {Object} ApplicationEmojiCreateOptions + * + * @typedef {object} ApplicationEmojiCreateOptions * @property {BufferResolvable|Base64Resolvable} attachment The image for the emoji * @property {string} name The name for the emoji */ /** * Creates a new custom emoji of the application. + * * @param {ApplicationEmojiCreateOptions} options Options for creating the emoji * @returns {Promise} The created emoji * @example @@ -60,6 +64,7 @@ class ApplicationEmojiManager extends CachedManager { /** * Obtains one or more emojis from Discord, or the emoji cache if they're already available. + * * @param {Snowflake} [id] The emoji's id * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise>} @@ -80,6 +85,7 @@ class ApplicationEmojiManager extends CachedManager { const existing = this.cache.get(id); if (existing) return existing; } + const emoji = await this.client.rest.get(Routes.applicationEmoji(this.application.id, id)); return this._add(emoji, cache); } @@ -92,6 +98,7 @@ class ApplicationEmojiManager extends CachedManager { /** * Deletes an emoji. + * * @param {EmojiResolvable} emoji The Emoji resolvable to delete * @returns {Promise} */ @@ -103,6 +110,7 @@ class ApplicationEmojiManager extends CachedManager { /** * Edits an emoji. + * * @param {EmojiResolvable} emoji The Emoji resolvable to edit * @param {ApplicationEmojiEditOptions} options The options to provide * @returns {Promise} @@ -121,11 +129,13 @@ class ApplicationEmojiManager extends CachedManager { existing._patch(newData); return existing; } + return this._add(newData); } /** * Fetches the author for this emoji + * * @param {EmojiResolvable} emoji The emoji to fetch the author of * @returns {Promise} */ diff --git a/packages/discord.js/src/managers/AutoModerationRuleManager.js b/packages/discord.js/src/managers/AutoModerationRuleManager.js index 7d29b969005e..ffc49d1db01f 100644 --- a/packages/discord.js/src/managers/AutoModerationRuleManager.js +++ b/packages/discord.js/src/managers/AutoModerationRuleManager.js @@ -2,11 +2,12 @@ const { Collection } = require('@discordjs/collection'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { AutoModerationRule } = require('../structures/AutoModerationRule.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for auto moderation rules and stores their cache. + * * @extends {CachedManager} */ class AutoModerationRuleManager extends CachedManager { @@ -15,6 +16,7 @@ class AutoModerationRuleManager extends CachedManager { /** * The guild this manager belongs to. + * * @type {Guild} */ this.guild = guild; @@ -22,12 +24,14 @@ class AutoModerationRuleManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name AutoModerationRuleManager#cache */ /** * Resolves an {@link AutoModerationRuleResolvable} to an {@link AutoModerationRule} object. + * * @method resolve * @memberof AutoModerationRuleManager * @instance @@ -37,6 +41,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Resolves an {@link AutoModerationRuleResolvable} to a {@link AutoModerationRule} id. + * * @method resolveId * @memberof AutoModerationRuleManager * @instance @@ -50,7 +55,8 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to set the trigger metadata of an auto moderation rule. - * @typedef {Object} AutoModerationTriggerMetadataOptions + * + * @typedef {object} AutoModerationTriggerMetadataOptions * @property {string[]} [keywordFilter] The substrings that will be searched for in the content * @property {string[]} [regexPatterns] The regular expression patterns which will be matched against the content * Only Rust-flavored regular expressions are supported. @@ -66,7 +72,8 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to set the actions of an auto moderation rule. - * @typedef {Object} AutoModerationActionOptions + * + * @typedef {object} AutoModerationActionOptions * @property {AutoModerationActionType} type The type of this auto moderation rule action * @property {AutoModerationActionMetadataOptions} [metadata] Additional metadata needed during execution * This property is required if using a `type` of @@ -75,7 +82,8 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to set the metadata of an auto moderation rule action. - * @typedef {Object} AutoModerationActionMetadataOptions + * + * @typedef {object} AutoModerationActionMetadataOptions * @property {GuildTextChannelResolvable|ThreadChannel} [channel] The channel to which content will be logged * @property {number} [durationSeconds] The timeout duration in seconds * @property {string} [customMessage] The custom message that is shown whenever a message is blocked @@ -83,7 +91,8 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to create an auto moderation rule. - * @typedef {Object} AutoModerationRuleCreateOptions + * + * @typedef {object} AutoModerationRuleCreateOptions * @property {string} name The name of the auto moderation rule * @property {AutoModerationRuleEventType} eventType The event type of the auto moderation rule * @property {AutoModerationRuleTriggerType} triggerType The trigger type of the auto moderation rule @@ -105,6 +114,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Creates a new auto moderation rule. + * * @param {AutoModerationRuleCreateOptions} options Options for creating the auto moderation rule * @returns {Promise} */ @@ -152,7 +162,8 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to edit an auto moderation rule. - * @typedef {Object} AutoModerationRuleEditOptions + * + * @typedef {object} AutoModerationRuleEditOptions * @property {string} [name] The name of the auto moderation rule * @property {AutoModerationRuleEventType} [eventType] The event type of the auto moderation rule * @property {AutoModerationTriggerMetadataOptions} [triggerMetadata] The trigger metadata of the auto moderation rule @@ -168,6 +179,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Edits an auto moderation rule. + * * @param {AutoModerationRuleResolvable} autoModerationRule The auto moderation rule to edit * @param {AutoModerationRuleEditOptions} options Options for editing the auto moderation rule * @returns {Promise} @@ -210,25 +222,29 @@ class AutoModerationRuleManager extends CachedManager { /** * Data that can be resolved to give an AutoModerationRule object. This can be: - * * An AutoModerationRule - * * A Snowflake + * An AutoModerationRule + * A Snowflake + * * @typedef {AutoModerationRule|Snowflake} AutoModerationRuleResolvable */ /** * Options used to fetch a single auto moderation rule from a guild. + * * @typedef {BaseFetchOptions} FetchAutoModerationRuleOptions * @property {AutoModerationRuleResolvable} autoModerationRule The auto moderation rule to fetch */ /** * Options used to fetch all auto moderation rules from a guild. - * @typedef {Object} FetchAutoModerationRulesOptions + * + * @typedef {object} FetchAutoModerationRulesOptions * @property {boolean} [cache] Whether to cache the fetched auto moderation rules */ /** * Fetches auto moderation rules from Discord. + * * @param {AutoModerationRuleResolvable|FetchAutoModerationRuleOptions|FetchAutoModerationRulesOptions} [options] * Options for fetching auto moderation rule(s) * @returns {Promise>} @@ -248,13 +264,14 @@ class AutoModerationRuleManager extends CachedManager { * .then(console.log) * .catch(console.error) */ - fetch(options) { + async fetch(options) { if (!options) return this._fetchMany(); const { autoModerationRule, cache, force } = options; const resolvedAutoModerationRule = this.resolveId(autoModerationRule ?? options); if (resolvedAutoModerationRule) { return this._fetchSingle({ autoModerationRule: resolvedAutoModerationRule, cache, force }); } + return this._fetchMany(options); } @@ -279,6 +296,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Deletes an auto moderation rule. + * * @param {AutoModerationRuleResolvable} autoModerationRule The auto moderation rule to delete * @param {string} [reason] The reason for deleting the auto moderation rule * @returns {Promise} diff --git a/packages/discord.js/src/managers/BaseManager.js b/packages/discord.js/src/managers/BaseManager.js index fe6756c49b4f..31093ead19b6 100644 --- a/packages/discord.js/src/managers/BaseManager.js +++ b/packages/discord.js/src/managers/BaseManager.js @@ -2,12 +2,14 @@ /** * Manages the API methods of a data model. + * * @abstract */ class BaseManager { constructor(client) { /** * The client that instantiated this Manager + * * @name BaseManager#client * @type {Client} * @readonly diff --git a/packages/discord.js/src/managers/CachedManager.js b/packages/discord.js/src/managers/CachedManager.js index c325a23ce43c..6a79597076e3 100644 --- a/packages/discord.js/src/managers/CachedManager.js +++ b/packages/discord.js/src/managers/CachedManager.js @@ -1,10 +1,11 @@ 'use strict'; -const { DataManager } = require('./DataManager.js'); const { MakeCacheOverrideSymbol } = require('../util/Symbols.js'); +const { DataManager } = require('./DataManager.js'); /** * Manages the API methods of a data model with a mutable cache of instances. + * * @extends {DataManager} * @abstract */ @@ -14,6 +15,7 @@ class CachedManager extends DataManager { /** * The private cache of items for this manager. + * * @type {Collection} * @private * @readonly @@ -36,6 +38,7 @@ class CachedManager extends DataManager { /** * The cache of items for this manager. + * * @type {Collection} * @abstract */ @@ -50,6 +53,7 @@ class CachedManager extends DataManager { existing._patch(data); return existing; } + const clone = existing._clone(); clone._patch(data); return clone; diff --git a/packages/discord.js/src/managers/CategoryChannelChildManager.js b/packages/discord.js/src/managers/CategoryChannelChildManager.js index 1f69ee160506..d6a0d355efe2 100644 --- a/packages/discord.js/src/managers/CategoryChannelChildManager.js +++ b/packages/discord.js/src/managers/CategoryChannelChildManager.js @@ -1,10 +1,11 @@ 'use strict'; -const { DataManager } = require('./DataManager.js'); const { GuildChannel } = require('../structures/GuildChannel.js'); +const { DataManager } = require('./DataManager.js'); /** * Manages API methods for CategoryChannels' children. + * * @extends {DataManager} */ class CategoryChannelChildManager extends DataManager { @@ -12,6 +13,7 @@ class CategoryChannelChildManager extends DataManager { super(channel.client, GuildChannel); /** * The category channel this manager belongs to + * * @type {CategoryChannel} */ this.channel = channel; @@ -19,6 +21,7 @@ class CategoryChannelChildManager extends DataManager { /** * The channels that are a part of this category + * * @type {Collection} * @readonly */ @@ -28,6 +31,7 @@ class CategoryChannelChildManager extends DataManager { /** * The guild this manager belongs to + * * @type {Guild} * @readonly */ @@ -37,7 +41,8 @@ class CategoryChannelChildManager extends DataManager { /** * Options for creating a channel using {@link CategoryChannelChildManager#create}. - * @typedef {Object} CategoryCreateChannelOptions + * + * @typedef {object} CategoryCreateChannelOptions * @property {string} name The name for the new channel * @property {ChannelType} [type=ChannelType.GuildText] The type of the new channel. * @property {string} [topic] The topic for the new channel @@ -65,10 +70,11 @@ class CategoryChannelChildManager extends DataManager { /** * Creates a new channel within this category. * You cannot create a channel of type {@link ChannelType.GuildCategory} inside a CategoryChannel. + * * @param {CategoryCreateChannelOptions} options Options for creating the new channel * @returns {Promise} */ - create(options) { + async create(options) { return this.guild.channels.create({ ...options, parent: this.channel.id, diff --git a/packages/discord.js/src/managers/ChannelManager.js b/packages/discord.js/src/managers/ChannelManager.js index f29a3213eb63..ca93e50b3721 100644 --- a/packages/discord.js/src/managers/ChannelManager.js +++ b/packages/discord.js/src/managers/ChannelManager.js @@ -3,12 +3,12 @@ const process = require('node:process'); const { lazy } = require('@discordjs/util'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { BaseChannel } = require('../structures/BaseChannel.js'); const { MessagePayload } = require('../structures/MessagePayload.js'); const { createChannel } = require('../util/Channels.js'); const { ThreadChannelTypes } = require('../util/Constants.js'); const { Events } = require('../util/Events.js'); +const { CachedManager } = require('./CachedManager.js'); const getMessage = lazy(() => require('../structures/Message.js').Message); @@ -16,6 +16,7 @@ let cacheWarningEmitted = false; /** * A manager of channels belonging to a client + * * @extends {CachedManager} */ class ChannelManager extends CachedManager { @@ -36,6 +37,7 @@ class ChannelManager extends CachedManager { /** * The cache of Channels + * * @type {Collection} * @name ChannelManager#cache */ @@ -48,6 +50,7 @@ class ChannelManager extends CachedManager { if (ThreadChannelTypes.includes(existing.type)) { existing.parent?.threads?._add(existing); } + return existing; } @@ -77,13 +80,15 @@ class ChannelManager extends CachedManager { /** * Data that can be resolved to give a Channel object. This can be: - * * A Channel object - * * A Snowflake + * A Channel object + * A Snowflake + * * @typedef {BaseChannel|Snowflake} ChannelResolvable */ /** * Resolves a ChannelResolvable to a Channel object. + * * @method resolve * @memberof ChannelManager * @instance @@ -93,6 +98,7 @@ class ChannelManager extends CachedManager { /** * Resolves a ChannelResolvable to a channel id string. + * * @method resolveId * @memberof ChannelManager * @instance @@ -102,6 +108,7 @@ class ChannelManager extends CachedManager { /** * Options for fetching a channel from Discord + * * @typedef {BaseFetchOptions} FetchChannelOptions * @property {boolean} [allowUnknownGuild=false] Allows the channel to be returned even if the guild is not in cache, * it will not be cached. Many of the properties and methods on the returned channel will throw errors @@ -109,6 +116,7 @@ class ChannelManager extends CachedManager { /** * Obtains a channel from Discord, or the channel cache if it's already available. + * * @param {Snowflake} id The channel's id * @param {FetchChannelOptions} [options] Additional options for this fetch * @returns {Promise} @@ -130,6 +138,7 @@ class ChannelManager extends CachedManager { /** * Creates a message in a channel. + * * @param {TextChannelResolvable} channel The channel to send the message to * @param {string|MessagePayload|MessageCreateOptions} options The options to provide * @returns {Promise} diff --git a/packages/discord.js/src/managers/DMMessageManager.js b/packages/discord.js/src/managers/DMMessageManager.js index 00e1ec3fe4ae..18626bb89123 100644 --- a/packages/discord.js/src/managers/DMMessageManager.js +++ b/packages/discord.js/src/managers/DMMessageManager.js @@ -4,11 +4,13 @@ const { MessageManager } = require('./MessageManager.js'); /** * Manages API methods for messages in direct message channels and holds their cache. + * * @extends {MessageManager} */ class DMMessageManager extends MessageManager { /** * The channel that the messages belong to + * * @name DMMessageManager#channel * @type {DMChannel} */ diff --git a/packages/discord.js/src/managers/DataManager.js b/packages/discord.js/src/managers/DataManager.js index bd1912fb446d..944806a442fd 100644 --- a/packages/discord.js/src/managers/DataManager.js +++ b/packages/discord.js/src/managers/DataManager.js @@ -1,10 +1,11 @@ 'use strict'; -const { BaseManager } = require('./BaseManager.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); +const { BaseManager } = require('./BaseManager.js'); /** * Manages the API methods of a data model along with a collection of instances. + * * @extends {BaseManager} * @abstract */ @@ -14,6 +15,7 @@ class DataManager extends BaseManager { /** * The data structure belonging to this manager. + * * @name DataManager#holds * @type {Function} * @private @@ -24,6 +26,7 @@ class DataManager extends BaseManager { /** * The cache of items for this manager. + * * @type {Collection} * @abstract */ @@ -33,8 +36,9 @@ class DataManager extends BaseManager { /** * Resolves a data entry to a data Object. - * @param {string|Object} idOrInstance The id or instance of something in this Manager - * @returns {?Object} An instance from this Manager + * + * @param {string | object} idOrInstance The id or instance of something in this Manager + * @returns {?object} An instance from this Manager */ resolve(idOrInstance) { if (idOrInstance instanceof this.holds) return idOrInstance; @@ -44,7 +48,8 @@ class DataManager extends BaseManager { /** * Resolves a data entry to an instance id. - * @param {string|Object} idOrInstance The id or instance of something in this Manager + * + * @param {string | object} idOrInstance The id or instance of something in this Manager * @returns {?Snowflake} */ resolveId(idOrInstance) { diff --git a/packages/discord.js/src/managers/EntitlementManager.js b/packages/discord.js/src/managers/EntitlementManager.js index e17b24046b78..a98c70da9cc3 100644 --- a/packages/discord.js/src/managers/EntitlementManager.js +++ b/packages/discord.js/src/managers/EntitlementManager.js @@ -3,13 +3,14 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { Routes, EntitlementOwnerType } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { ErrorCodes, DiscordjsTypeError } = require('../errors/index.js'); const { Entitlement } = require('../structures/Entitlement.js'); const { resolveSKUId } = require('../util/Util.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for entitlements and stores their cache. + * * @extends {CachedManager} */ class EntitlementManager extends CachedManager { @@ -19,33 +20,38 @@ class EntitlementManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name EntitlementManager#cache */ /** * Data that resolves to give an Entitlement object. This can be: - * * An Entitlement object - * * A Snowflake + * An Entitlement object + * A Snowflake + * * @typedef {Entitlement|Snowflake} EntitlementResolvable */ /** * Data that resolves to give a SKU object. This can be: - * * A SKU object - * * A Snowflake + * A SKU object + * A Snowflake + * * @typedef {SKU|Snowflake} SKUResolvable */ /** * Options used to fetch an entitlement + * * @typedef {BaseFetchOptions} FetchEntitlementOptions * @property {EntitlementResolvable} entitlement The entitlement to fetch */ /** * Options used to fetch entitlements - * @typedef {Object} FetchEntitlementsOptions + * + * @typedef {object} FetchEntitlementsOptions * @property {number} [limit] The maximum number of entitlements to fetch * @property {GuildResolvable} [guild] The guild to fetch entitlements for * @property {UserResolvable} [user] The user to fetch entitlements for @@ -60,6 +66,7 @@ class EntitlementManager extends CachedManager { /** * Fetches entitlements for this application + * * @param {EntitlementResolvable|FetchEntitlementOptions|FetchEntitlementsOptions} [options] * Options for fetching the entitlements * @returns {Promise>} @@ -112,7 +119,8 @@ class EntitlementManager extends CachedManager { /** * Options used to create a test entitlement * Either `guild` or `user` must be provided, but not both - * @typedef {Object} EntitlementCreateOptions + * + * @typedef {object} EntitlementCreateOptions * @property {SKUResolvable} sku The id of the SKU to create the entitlement for * @property {GuildResolvable} [guild] The guild to create the entitlement for * @property {UserResolvable} [user] The user to create the entitlement for @@ -120,6 +128,7 @@ class EntitlementManager extends CachedManager { /** * Creates a test entitlement + * * @param {EntitlementCreateOptions} options Options for creating the test entitlement * @returns {Promise} */ @@ -150,6 +159,7 @@ class EntitlementManager extends CachedManager { /** * Deletes a test entitlement + * * @param {EntitlementResolvable} entitlement The entitlement to delete * @returns {Promise} */ @@ -163,6 +173,7 @@ class EntitlementManager extends CachedManager { /** * Marks an entitlement as consumed * Only available for One-Time Purchase consumable SKUs. + * * @param {Snowflake} entitlementId The id of the entitlement to consume * @returns {Promise} */ diff --git a/packages/discord.js/src/managers/GuildApplicationCommandManager.js b/packages/discord.js/src/managers/GuildApplicationCommandManager.js index d1040c434902..b60a32515a0f 100644 --- a/packages/discord.js/src/managers/GuildApplicationCommandManager.js +++ b/packages/discord.js/src/managers/GuildApplicationCommandManager.js @@ -5,6 +5,7 @@ const { ApplicationCommandPermissionsManager } = require('./ApplicationCommandPe /** * An extension for guild-specific application commands. + * * @extends {ApplicationCommandManager} */ class GuildApplicationCommandManager extends ApplicationCommandManager { @@ -13,12 +14,14 @@ class GuildApplicationCommandManager extends ApplicationCommandManager { /** * The guild that this manager belongs to + * * @type {Guild} */ this.guild = guild; /** * The manager for permissions of arbitrary commands on this guild + * * @type {ApplicationCommandPermissionsManager} */ this.permissions = new ApplicationCommandPermissionsManager(this); diff --git a/packages/discord.js/src/managers/GuildBanManager.js b/packages/discord.js/src/managers/GuildBanManager.js index 1b78a01ae183..3098edf52e6d 100644 --- a/packages/discord.js/src/managers/GuildBanManager.js +++ b/packages/discord.js/src/managers/GuildBanManager.js @@ -3,12 +3,13 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { GuildBan } = require('../structures/GuildBan.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for guild bans and stores their cache. + * * @extends {CachedManager} */ class GuildBanManager extends CachedManager { @@ -17,6 +18,7 @@ class GuildBanManager extends CachedManager { /** * The guild this Manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -24,6 +26,7 @@ class GuildBanManager extends CachedManager { /** * The cache of this Manager + * * @type {Collection} * @name GuildBanManager#cache */ @@ -34,13 +37,15 @@ class GuildBanManager extends CachedManager { /** * Data that resolves to give a GuildBan object. This can be: - * * A GuildBan object - * * A User resolvable + * A GuildBan object + * A User resolvable + * * @typedef {GuildBan|UserResolvable} GuildBanResolvable */ /** * Resolves a GuildBanResolvable to a GuildBan object. + * * @param {GuildBanResolvable} ban The ban that is in the guild * @returns {?GuildBan} */ @@ -50,13 +55,15 @@ class GuildBanManager extends CachedManager { /** * Options used to fetch a single ban from a guild. + * * @typedef {BaseFetchOptions} FetchBanOptions * @property {UserResolvable} user The ban to fetch */ /** * Options used to fetch multiple bans from a guild. - * @typedef {Object} FetchBansOptions + * + * @typedef {object} FetchBansOptions * @property {number} [limit] The maximum number of bans to return * @property {Snowflake} [before] Consider only bans before this id * @property {Snowflake} [after] Consider only bans after this id @@ -65,6 +72,7 @@ class GuildBanManager extends CachedManager { /** * Fetches ban(s) from Discord. + * * @param {UserResolvable|FetchBanOptions|FetchBansOptions} [options] Options for fetching guild ban(s) * @returns {Promise>} * @example @@ -126,7 +134,8 @@ class GuildBanManager extends CachedManager { /** * Options used to ban a user from a guild. - * @typedef {Object} BanOptions + * + * @typedef {object} BanOptions * @property {number} [deleteMessageSeconds] Number of seconds of messages to delete, * must be between 0 and 604800 (7 days), inclusive * @property {string} [reason] The reason for the ban @@ -134,8 +143,9 @@ class GuildBanManager extends CachedManager { /** * Bans a user from the guild. + * * @param {UserResolvable} user The user to ban - * @param {BanOptions} [options={}] Options for the ban + * @param {BanOptions} [options] Options for the ban * @returns {Promise} * @example * // Ban a user by id (or with a user/guild member object) @@ -156,6 +166,7 @@ class GuildBanManager extends CachedManager { /** * Unbans a user from the guild. + * * @param {UserResolvable} user The user to unban * @param {string} [reason] Reason for unbanning user * @returns {Promise} @@ -171,13 +182,15 @@ class GuildBanManager extends CachedManager { /** * Result of bulk banning users from a guild. - * @typedef {Object} BulkBanResult + * + * @typedef {object} BulkBanResult * @property {Snowflake[]} bannedUsers IDs of the banned users * @property {Snowflake[]} failedUsers IDs of the users that could not be banned or were already banned */ /** * Bulk ban users from a guild, and optionally delete previous messages sent by them. + * * @param {Collection|UserResolvable[]} users The users to ban * @param {BanOptions} [options] The options for bulk banning users * @returns {Promise} Returns an object with `bannedUsers` key containing the IDs of the banned users @@ -194,6 +207,7 @@ class GuildBanManager extends CachedManager { if (!users || !(Array.isArray(users) || users instanceof Collection)) { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'users', 'Array or Collection of UserResolvable', true); } + if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); const userIds = users.map(user => this.client.users.resolveId(user)); diff --git a/packages/discord.js/src/managers/GuildChannelManager.js b/packages/discord.js/src/managers/GuildChannelManager.js index 2d6f2b3411c6..48538cf2f401 100644 --- a/packages/discord.js/src/managers/GuildChannelManager.js +++ b/packages/discord.js/src/managers/GuildChannelManager.js @@ -3,8 +3,6 @@ const process = require('node:process'); const { Collection } = require('@discordjs/collection'); const { ChannelType, Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); -const { GuildTextThreadManager } = require('./GuildTextThreadManager.js'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { GuildChannel } = require('../structures/GuildChannel.js'); const { PermissionOverwrites } = require('../structures/PermissionOverwrites.js'); @@ -15,11 +13,14 @@ const { transformGuildForumTag, transformGuildDefaultReaction } = require('../ut const { ThreadChannelTypes } = require('../util/Constants.js'); const { resolveImage } = require('../util/DataResolver.js'); const { setPosition } = require('../util/Util.js'); +const { CachedManager } = require('./CachedManager.js'); +const { GuildTextThreadManager } = require('./GuildTextThreadManager.js'); let cacheWarningEmitted = false; /** * Manages API methods for GuildChannels and stores their cache. + * * @extends {CachedManager} */ class GuildChannelManager extends CachedManager { @@ -39,6 +40,7 @@ class GuildChannelManager extends CachedManager { /** * The guild this Manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -47,6 +49,7 @@ class GuildChannelManager extends CachedManager { /** * The number of channels in this managers cache excluding thread channels * that do not count towards a guild's maximum channels restriction. + * * @type {number} * @readonly */ @@ -59,6 +62,7 @@ class GuildChannelManager extends CachedManager { /** * The cache of this Manager + * * @type {Collection} * @name GuildChannelManager#cache */ @@ -72,14 +76,16 @@ class GuildChannelManager extends CachedManager { /** * Data that can be resolved to give a Guild Channel object. This can be: - * * A GuildChannel object - * * A ThreadChannel object - * * A Snowflake + * A GuildChannel object + * A ThreadChannel object + * A Snowflake + * * @typedef {GuildChannel|ThreadChannel|Snowflake} GuildChannelResolvable */ /** * Resolves a GuildChannelResolvable to a Channel object. + * * @param {GuildChannelResolvable} channel The GuildChannel resolvable to resolve * @returns {?(GuildChannel|ThreadChannel)} */ @@ -90,6 +96,7 @@ class GuildChannelManager extends CachedManager { /** * Resolves a GuildChannelResolvable to a channel id. + * * @param {GuildChannelResolvable} channel The GuildChannel resolvable to resolve * @returns {?Snowflake} */ @@ -100,20 +107,23 @@ class GuildChannelManager extends CachedManager { /** * Data that can be resolved to an Announcement Channel object. This can be: - * * An Announcement Channel object - * * A Snowflake + * An Announcement Channel object + * A Snowflake + * * @typedef {AnnouncementChannel|Snowflake} AnnouncementChannelResolvable */ /** * Represents the followed channel data. - * @typedef {Object} FollowedChannelData + * + * @typedef {object} FollowedChannelData * @property {Snowflake} channelId Source channel id * @property {Snowflake} webhookId Created webhook id in the target channel */ /** * Adds the target channel to a channel's followers. + * * @param {AnnouncementChannelResolvable} channel The channel to follow * @param {TextChannelResolvable} targetChannel The channel where published announcements will be posted at * @param {string} [reason] Reason for creating the webhook @@ -124,10 +134,12 @@ class GuildChannelManager extends CachedManager { if (!channelId) { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'AnnouncementChannelResolvable'); } + const targetChannelId = this.resolveId(targetChannel); if (!targetChannelId) { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'targetChannel', 'TextChannelResolvable'); } + const data = await this.client.rest.post(Routes.channelFollowers(channelId), { body: { webhook_channel_id: targetChannelId }, reason, @@ -137,12 +149,14 @@ class GuildChannelManager extends CachedManager { /** * Options used to create a new channel in a guild. + * * @typedef {CategoryCreateChannelOptions} GuildChannelCreateOptions * @property {?CategoryChannelResolvable} [parent] Parent of the new channel */ /** * Creates a new channel in the guild. + * * @param {GuildChannelCreateOptions} options Options for creating the new channel * @returns {Promise} * @example @@ -220,6 +234,7 @@ class GuildChannelManager extends CachedManager { /** * Creates a webhook for the channel. + * * @param {WebhookCreateOptions} options Options for creating the webhook * @returns {Promise} Returns the created Webhook * @example @@ -252,7 +267,8 @@ class GuildChannelManager extends CachedManager { /** * Options used to edit a guild channel. - * @typedef {Object} GuildChannelEditOptions + * + * @typedef {object} GuildChannelEditOptions * @property {string} [name] The name of the channel * @property {ChannelType} [type] The type of the channel (only conversion between text and announcement is supported) * @property {number} [position] The position of the channel @@ -281,6 +297,7 @@ class GuildChannelManager extends CachedManager { /** * Edits the channel. + * * @param {GuildChannelResolvable} channel The channel to edit * @param {GuildChannelEditOptions} options Options for editing the channel * @returns {Promise} @@ -350,6 +367,7 @@ class GuildChannelManager extends CachedManager { /** * Sets a new position for the guild channel. + * * @param {GuildChannelResolvable} channel The channel to set the position for * @param {number} position The new position for the guild channel * @param {SetChannelPositionOptions} options Options for setting position @@ -384,6 +402,7 @@ class GuildChannelManager extends CachedManager { /** * Obtains one or more guild channels from Discord, or the channel cache if they're already available. + * * @param {Snowflake} [id] The channel's id * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise>} @@ -419,6 +438,7 @@ class GuildChannelManager extends CachedManager { /** * Fetches all webhooks for the channel. + * * @param {GuildChannelResolvable} channel The channel to fetch webhooks for * @returns {Promise>} * @example @@ -436,14 +456,16 @@ class GuildChannelManager extends CachedManager { /** * Data that can be resolved to give a Category Channel object. This can be: - * * A CategoryChannel object - * * A Snowflake + * A CategoryChannel object + * A Snowflake + * * @typedef {CategoryChannel|Snowflake} CategoryChannelResolvable */ /** * The data needed for updating a channel's position. - * @typedef {Object} ChannelPosition + * + * @typedef {object} ChannelPosition * @property {GuildChannel|Snowflake} channel Channel to update * @property {number} [position] New position for the channel * @property {CategoryChannelResolvable} [parent] Parent channel for this channel @@ -453,6 +475,7 @@ class GuildChannelManager extends CachedManager { /** * Batch-updates the guild's channels' positions. * Only one channel's parent can be changed at a time + * * @param {ChannelPosition[]} channelPositions Channel positions to update * @returns {Promise} * @example @@ -465,7 +488,7 @@ class GuildChannelManager extends CachedManager { id: this.client.channels.resolveId(channelPosition.channel), position: channelPosition.position, lock_permissions: channelPosition.lockPermissions, - parent_id: channelPosition.parent !== undefined ? this.resolveId(channelPosition.parent) : undefined, + parent_id: channelPosition.parent === undefined ? undefined : this.resolveId(channelPosition.parent), })); await this.client.rest.patch(Routes.guildChannels(this.guild.id), { body: resolvedChannelPositions }); @@ -478,14 +501,16 @@ class GuildChannelManager extends CachedManager { /** * Data returned from fetching threads. - * @typedef {Object} FetchedThreads + * + * @typedef {object} FetchedThreads * @property {Collection} threads The threads that were fetched * @property {Collection} members The thread members in the received threads */ /** * Obtains all active thread channels in the guild. - * @param {boolean} [cache=true] Whether to cache the fetched data + * + * @param {boolean} [cache] Whether to cache the fetched data * @returns {Promise} * @example * // Fetch all threads from the guild @@ -500,15 +525,17 @@ class GuildChannelManager extends CachedManager { /** * `GET /guilds/{guild.id}/threads/active` + * * @private * @returns {Promise} */ - rawFetchGuildActiveThreads() { + async rawFetchGuildActiveThreads() { return this.client.rest.get(Routes.guildActiveThreads(this.guild.id)); } /** * Deletes the channel. + * * @param {GuildChannelResolvable} channel The channel to delete * @param {string} [reason] Reason for deleting this channel * @returns {Promise} diff --git a/packages/discord.js/src/managers/GuildEmojiManager.js b/packages/discord.js/src/managers/GuildEmojiManager.js index 53f9bda7a637..3937c7c7a705 100644 --- a/packages/discord.js/src/managers/GuildEmojiManager.js +++ b/packages/discord.js/src/managers/GuildEmojiManager.js @@ -1,16 +1,17 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); const { Routes, PermissionFlagsBits } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { ApplicationEmoji } = require('../structures/ApplicationEmoji.js'); const { GuildEmoji } = require('../structures/GuildEmoji.js'); const { ReactionEmoji } = require('../structures/ReactionEmoji.js'); const { resolveImage } = require('../util/DataResolver.js'); const { parseEmoji } = require('../util/Util.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for GuildEmojis and stores their cache. + * * @extends {CachedManager} */ class GuildEmojiManager extends CachedManager { @@ -19,6 +20,7 @@ class GuildEmojiManager extends CachedManager { /** * The guild this manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -30,21 +32,24 @@ class GuildEmojiManager extends CachedManager { /** * The cache of GuildEmojis + * * @type {Collection} * @name GuildEmojiManager#cache */ /** * Data that can be resolved into a GuildEmoji object. This can be: - * * A Snowflake - * * A GuildEmoji object - * * A ReactionEmoji object - * * An ApplicationEmoji object + * A Snowflake + * A GuildEmoji object + * A ReactionEmoji object + * An ApplicationEmoji object + * * @typedef {Snowflake|GuildEmoji|ReactionEmoji|ApplicationEmoji} EmojiResolvable */ /** * Resolves an EmojiResolvable to an Emoji object. + * * @param {EmojiResolvable} emoji The Emoji resolvable to identify * @returns {?GuildEmoji} */ @@ -56,6 +61,7 @@ class GuildEmojiManager extends CachedManager { /** * Resolves an EmojiResolvable to an Emoji id string. + * * @param {EmojiResolvable} emoji The Emoji resolvable to identify * @returns {?Snowflake} */ @@ -67,14 +73,16 @@ class GuildEmojiManager extends CachedManager { /** * Data that can be resolved to give an emoji identifier. This can be: - * * An EmojiResolvable - * * The ``, `<:name:id>`, `a:name:id` or `name:id` emoji identifier string of an emoji - * * The Unicode representation of an emoji + * An EmojiResolvable + * The ``, `<:name:id>`, `a:name:id` or `name:id` emoji identifier string of an emoji + * The Unicode representation of an emoji + * * @typedef {string|EmojiResolvable} EmojiIdentifierResolvable */ /** * Resolves an EmojiResolvable to an emoji identifier. + * * @param {EmojiIdentifierResolvable} emoji The emoji resolvable to resolve * @returns {?string} */ @@ -89,15 +97,18 @@ class GuildEmojiManager extends CachedManager { if (res?.name.length) { identifier = `${res.animated ? 'a:' : ''}${res.name}${res.id ? `:${res.id}` : ''}`; } + if (!identifier.includes('%')) return encodeURIComponent(identifier); return identifier; } + return null; } /** * Options used for creating an emoji in a guild. - * @typedef {Object} GuildEmojiCreateOptions + * + * @typedef {object} GuildEmojiCreateOptions * @property {BufferResolvable|Base64Resolvable} attachment The image for the emoji * @property {string} name The name for the emoji * @property {Collection|RoleResolvable[]} [roles] The roles to limit the emoji to @@ -106,6 +117,7 @@ class GuildEmojiManager extends CachedManager { /** * Creates a new custom emoji in the guild. + * * @param {GuildEmojiCreateOptions} options Options for creating the emoji * @returns {Promise} The created emoji * @example @@ -133,12 +145,14 @@ class GuildEmojiManager extends CachedManager { true, ); } + body.roles = []; for (const role of roles.values()) { const resolvedRole = this.guild.roles.resolveId(role); if (!resolvedRole) { throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role); } + body.roles.push(resolvedRole); } } @@ -149,6 +163,7 @@ class GuildEmojiManager extends CachedManager { /** * Obtains one or more emojis from Discord, or the emoji cache if they're already available. + * * @param {Snowflake} [id] The emoji's id * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise>} @@ -169,6 +184,7 @@ class GuildEmojiManager extends CachedManager { const existing = this.cache.get(id); if (existing) return existing; } + const emoji = await this.client.rest.get(Routes.guildEmoji(this.guild.id, id)); return this._add(emoji, cache); } @@ -181,6 +197,7 @@ class GuildEmojiManager extends CachedManager { /** * Deletes an emoji. + * * @param {EmojiResolvable} emoji The Emoji resolvable to delete * @param {string} [reason] Reason for deleting the emoji * @returns {Promise} @@ -193,6 +210,7 @@ class GuildEmojiManager extends CachedManager { /** * Edits an emoji. + * * @param {EmojiResolvable} emoji The Emoji resolvable to edit * @param {GuildEmojiEditOptions} options The options to provide * @returns {Promise} @@ -214,11 +232,13 @@ class GuildEmojiManager extends CachedManager { clone._patch(newData); return clone; } + return this._add(newData); } /** * Fetches the author for this emoji + * * @param {EmojiResolvable} emoji The emoji to fetch the author of * @returns {Promise} */ diff --git a/packages/discord.js/src/managers/GuildEmojiRoleManager.js b/packages/discord.js/src/managers/GuildEmojiRoleManager.js index a04e0233671a..c0791bb22fcf 100644 --- a/packages/discord.js/src/managers/GuildEmojiRoleManager.js +++ b/packages/discord.js/src/managers/GuildEmojiRoleManager.js @@ -1,12 +1,13 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); -const { DataManager } = require('./DataManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { Role } = require('../structures/Role.js'); +const { DataManager } = require('./DataManager.js'); /** * Manages API methods for roles belonging to emojis and stores their cache. + * * @extends {DataManager} */ class GuildEmojiRoleManager extends DataManager { @@ -15,11 +16,13 @@ class GuildEmojiRoleManager extends DataManager { /** * The emoji belonging to this manager + * * @type {GuildEmoji} */ this.emoji = emoji; /** * The guild belonging to this manager + * * @type {Guild} */ this.guild = emoji.guild; @@ -27,6 +30,7 @@ class GuildEmojiRoleManager extends DataManager { /** * The cache of roles belonging to this emoji + * * @type {Collection} * @readonly */ @@ -36,6 +40,7 @@ class GuildEmojiRoleManager extends DataManager { /** * Adds a role (or multiple roles) to the list of roles that can use this emoji. + * * @param {RoleResolvable|RoleResolvable[]|Collection} roleOrRoles The role or roles to add * @returns {Promise} */ @@ -48,6 +53,7 @@ class GuildEmojiRoleManager extends DataManager { if (!roleId) { throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role); } + resolvedRoleIds.push(roleId); } @@ -57,6 +63,7 @@ class GuildEmojiRoleManager extends DataManager { /** * Removes a role (or multiple roles) from the list of roles that can use this emoji. + * * @param {RoleResolvable|RoleResolvable[]|Collection} roleOrRoles The role or roles to remove * @returns {Promise} */ @@ -69,6 +76,7 @@ class GuildEmojiRoleManager extends DataManager { if (!roleId) { throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role); } + resolvedRoleIds.push(roleId); } @@ -78,6 +86,7 @@ class GuildEmojiRoleManager extends DataManager { /** * Sets the role(s) that can use this emoji. + * * @param {Collection|RoleResolvable[]} roles The roles or role ids to apply * @returns {Promise} * @example @@ -91,7 +100,7 @@ class GuildEmojiRoleManager extends DataManager { * .then(console.log) * .catch(console.error); */ - set(roles) { + async set(roles) { return this.emoji.edit({ roles }); } @@ -103,6 +112,7 @@ class GuildEmojiRoleManager extends DataManager { /** * Patches the roles for this manager's cache + * * @param {Snowflake[]} roles The new roles * @private */ diff --git a/packages/discord.js/src/managers/GuildForumThreadManager.js b/packages/discord.js/src/managers/GuildForumThreadManager.js index 7deb3518f5ad..d5e4d5fe338d 100644 --- a/packages/discord.js/src/managers/GuildForumThreadManager.js +++ b/packages/discord.js/src/managers/GuildForumThreadManager.js @@ -1,17 +1,19 @@ 'use strict'; const { Routes } = require('discord-api-types/v10'); -const { ThreadManager } = require('./ThreadManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { MessagePayload } = require('../structures/MessagePayload.js'); +const { ThreadManager } = require('./ThreadManager.js'); /** * Manages API methods for threads in forum channels and stores their cache. + * * @extends {ThreadManager} */ class GuildForumThreadManager extends ThreadManager { /** * The channel this Manager belongs to + * * @name GuildForumThreadManager#channel * @type {ForumChannel} */ @@ -25,6 +27,7 @@ class GuildForumThreadManager extends ThreadManager { /** * Options for creating a thread. + * * @typedef {StartThreadOptions} GuildForumThreadCreateOptions * @property {GuildForumThreadMessageCreateOptions|MessagePayload} message The message associated with the thread post * @property {Snowflake[]} [appliedTags] The tags to apply to the thread @@ -32,6 +35,7 @@ class GuildForumThreadManager extends ThreadManager { /** * Creates a new thread in the channel. + * * @param {GuildForumThreadCreateOptions} [options] Options to create a new thread * @returns {Promise} * @example diff --git a/packages/discord.js/src/managers/GuildInviteManager.js b/packages/discord.js/src/managers/GuildInviteManager.js index 301d843c485e..ea8f4394b93f 100644 --- a/packages/discord.js/src/managers/GuildInviteManager.js +++ b/packages/discord.js/src/managers/GuildInviteManager.js @@ -2,13 +2,14 @@ const { Collection } = require('@discordjs/collection'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { Invite } = require('../structures/Invite.js'); const { resolveInviteCode } = require('../util/DataResolver.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for GuildInvites and stores their cache. + * * @extends {CachedManager} */ class GuildInviteManager extends CachedManager { @@ -17,6 +18,7 @@ class GuildInviteManager extends CachedManager { /** * The guild this Manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -24,6 +26,7 @@ class GuildInviteManager extends CachedManager { /** * The cache of this Manager + * * @type {Collection} * @name GuildInviteManager#cache */ @@ -34,26 +37,29 @@ class GuildInviteManager extends CachedManager { /** * Data that resolves to give an Invite object. This can be: - * * An invite code - * * An invite URL + * An invite code + * An invite URL + * * @typedef {string} InviteResolvable */ /** * Data that can be resolved to a channel that an invite can be created on. This can be: - * * TextChannel - * * VoiceChannel - * * AnnouncementChannel - * * StageChannel - * * ForumChannel - * * MediaChannel - * * Snowflake + * TextChannel + * VoiceChannel + * AnnouncementChannel + * StageChannel + * ForumChannel + * MediaChannel + * Snowflake + * * @typedef {TextChannel|VoiceChannel|AnnouncementChannel|StageChannel|ForumChannel|MediaChannel|Snowflake} * GuildInvitableChannelResolvable */ /** * Resolves an InviteResolvable to an Invite object. + * * @method resolve * @memberof GuildInviteManager * @instance @@ -63,6 +69,7 @@ class GuildInviteManager extends CachedManager { /** * Resolves an InviteResolvable to an invite code string. + * * @method resolveId * @memberof GuildInviteManager * @instance @@ -72,7 +79,8 @@ class GuildInviteManager extends CachedManager { /** * Options used to fetch a single invite from a guild. - * @typedef {Object} FetchInviteOptions + * + * @typedef {object} FetchInviteOptions * @property {InviteResolvable} code The invite to fetch * @property {boolean} [cache=true] Whether or not to cache the fetched invite * @property {boolean} [force=false] Whether to skip the cache check and request the API @@ -80,7 +88,8 @@ class GuildInviteManager extends CachedManager { /** * Options used to fetch all invites from a guild. - * @typedef {Object} FetchInvitesOptions + * + * @typedef {object} FetchInvitesOptions * @property {GuildInvitableChannelResolvable} [channelId] * The channel to fetch all invites from * @property {boolean} [cache=true] Whether or not to cache the fetched invites @@ -88,6 +97,7 @@ class GuildInviteManager extends CachedManager { /** * Fetches invite(s) from Discord. + * * @param {InviteResolvable|FetchInviteOptions|FetchInvitesOptions} [options] Options for fetching guild invite(s) * @returns {Promise>} * @example @@ -128,6 +138,7 @@ class GuildInviteManager extends CachedManager { if (!code) throw new DiscordjsError(ErrorCodes.InviteResolveCode); return this._fetchSingle({ code, cache: true }); } + if (!options.code) { if (options.channelId) { const id = this.guild.channels.resolveId(options.channelId); @@ -138,6 +149,7 @@ class GuildInviteManager extends CachedManager { if ('cache' in options) return this._fetchMany(options.cache); throw new DiscordjsError(ErrorCodes.InviteResolveCode); } + return this._fetchSingle({ ...options, code: resolveInviteCode(options.code), @@ -168,8 +180,9 @@ class GuildInviteManager extends CachedManager { /** * Create an invite to the guild from the provided channel. + * * @param {GuildInvitableChannelResolvable} channel The options for creating the invite from a channel. - * @param {InviteCreateOptions} [options={}] The options for creating the invite from a channel. + * @param {InviteCreateOptions} [options] The options for creating the invite from a channel. * @returns {Promise} * @example * // Create an invite to a selected channel @@ -201,6 +214,7 @@ class GuildInviteManager extends CachedManager { /** * Deletes an invite. + * * @param {InviteResolvable} invite The invite to delete * @param {string} [reason] Reason for deleting the invite * @returns {Promise} diff --git a/packages/discord.js/src/managers/GuildManager.js b/packages/discord.js/src/managers/GuildManager.js index 0e3984c240d0..42739d37c14a 100644 --- a/packages/discord.js/src/managers/GuildManager.js +++ b/packages/discord.js/src/managers/GuildManager.js @@ -5,7 +5,6 @@ const { setTimeout, clearTimeout } = require('node:timers'); const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { GatewayOpcodes, Routes, RouteBases } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { ShardClientUtil } = require('../sharding/ShardClientUtil.js'); const { Guild } = require('../structures/Guild.js'); @@ -21,11 +20,13 @@ const { PermissionsBitField } = require('../util/PermissionsBitField.js'); const { SystemChannelFlagsBitField } = require('../util/SystemChannelFlagsBitField.js'); const { _transformAPIIncidentsData } = require('../util/Transformers.js'); const { resolveColor } = require('../util/Util.js'); +const { CachedManager } = require('./CachedManager.js'); let cacheWarningEmitted = false; /** * Manages API methods for Guilds and stores their cache. + * * @extends {CachedManager} */ class GuildManager extends CachedManager { @@ -42,24 +43,27 @@ class GuildManager extends CachedManager { /** * The cache of this Manager + * * @type {Collection} * @name GuildManager#cache */ /** * Data that resolves to give a Guild object. This can be: - * * A Guild object - * * A GuildChannel object - * * A GuildEmoji object - * * A Role object - * * A Snowflake - * * An Invite object + * A Guild object + * A GuildChannel object + * A GuildEmoji object + * A Role object + * A Snowflake + * An Invite object + * * @typedef {Guild|GuildChannel|GuildMember|GuildEmoji|Role|Snowflake|Invite} GuildResolvable */ /** * Partial data for a Role. - * @typedef {Object} PartialRoleData + * + * @typedef {object} PartialRoleData * @property {Snowflake|number} [id] The role's id, used to set channel overrides. * This is a placeholder and will be replaced by the API after consumption * @property {string} [name] The name of the role @@ -72,7 +76,8 @@ class GuildManager extends CachedManager { /** * Partial overwrite data. - * @typedef {Object} PartialOverwriteData + * + * @typedef {object} PartialOverwriteData * @property {Snowflake|number} id The id of the {@link Role} or {@link User} this overwrite belongs to * @property {OverwriteType} [type] The type of this overwrite * @property {PermissionResolvable} [allow] The permissions to allow @@ -81,7 +86,8 @@ class GuildManager extends CachedManager { /** * Partial data for a Channel. - * @typedef {Object} PartialChannelData + * + * @typedef {object} PartialChannelData * @property {Snowflake|number} [id] The channel's id, used to set its parent. * This is a placeholder and will be replaced by the API after consumption * @property {Snowflake|number} [parentId] The parent id for this channel @@ -100,6 +106,7 @@ class GuildManager extends CachedManager { /** * Resolves a {@link GuildResolvable} to a {@link Guild} object. + * * @method resolve * @memberof GuildManager * @instance @@ -116,11 +123,13 @@ class GuildManager extends CachedManager { ) { return super.resolve(guild.guild); } + return super.resolve(guild); } /** * Resolves a {@link GuildResolvable} to a {@link Guild} id string. + * * @method resolveId * @memberof GuildManager * @instance @@ -137,12 +146,14 @@ class GuildManager extends CachedManager { ) { return super.resolveId(guild.guild.id); } + return super.resolveId(guild); } /** * Options used to create a guild. - * @typedef {Object} GuildCreateOptions + * + * @typedef {object} GuildCreateOptions * @property {string} name The name of the guild * @property {?(BufferResolvable|Base64Resolvable)} [icon=null] The icon for the guild * @property {GuildVerificationLevel} [verificationLevel] The verification level for the guild @@ -157,11 +168,11 @@ class GuildManager extends CachedManager { * @property {Snowflake|number} [systemChannelId] The system channel's id * @property {SystemChannelFlagsResolvable} [systemChannelFlags] The flags of the system channel */ - /* eslint-enable max-len */ /** * Creates a guild. * This is only available to bots in fewer than 10 guilds. + * * @param {GuildCreateOptions} options Options for creating the guild * @returns {Promise} The guild that was created */ @@ -226,11 +237,13 @@ class GuildManager extends CachedManager { new Promise(resolve => { const handleGuild = guild => { if (guild.id === data.id) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(timeout); this.client.decrementMaxListeners(); resolve(guild); } }; + this.client.incrementMaxListeners(); this.client.once(Events.GuildCreate, handleGuild); @@ -245,6 +258,7 @@ class GuildManager extends CachedManager { /** * Options used to fetch a single guild. + * * @typedef {BaseFetchOptions} FetchGuildOptions * @property {GuildResolvable} guild The guild to fetch * @property {boolean} [withCounts=true] Whether the approximate member and presence counts should be returned @@ -252,7 +266,8 @@ class GuildManager extends CachedManager { /** * Options used to fetch multiple guilds. - * @typedef {Object} FetchGuildsOptions + * + * @typedef {object} FetchGuildsOptions * @property {Snowflake} [before] Get guilds before this guild id * @property {Snowflake} [after] Get guilds after this guild id * @property {number} [limit] Maximum number of guilds to request (1-200) @@ -260,6 +275,7 @@ class GuildManager extends CachedManager { /** * Obtains one or multiple guilds from Discord, or the guild cache if it's already available. + * * @param {GuildResolvable|FetchGuildOptions|FetchGuildsOptions} [options] The guild's id or options * @returns {Promise>} */ @@ -284,13 +300,14 @@ class GuildManager extends CachedManager { } /** - * @typedef {Object} FetchSoundboardSoundsOptions - * @param {Snowflake[]} guildIds The ids of the guilds to fetch soundboard sounds for - * @param {number} [time=10_000] The timeout for receipt of the soundboard sounds + * @typedef {object} FetchSoundboardSoundsOptions + * @property {Snowflake[]} guildIds The ids of the guilds to fetch soundboard sounds for + * @property {number} [time=10_000] The timeout for receipt of the soundboard sounds */ /** * Fetches soundboard sounds for the specified guilds. + * * @param {FetchSoundboardSoundsOptions} options The options for fetching soundboard sounds * @returns {Promise>>} * @example @@ -308,6 +325,7 @@ class GuildManager extends CachedManager { for (const [shardId, shardGuildIds] of shardIds) { this.client.ws.send(shardId, { op: GatewayOpcodes.RequestSoundboardSounds, + // eslint-disable-next-line id-length d: { guild_ids: shardGuildIds, }, @@ -320,6 +338,7 @@ class GuildManager extends CachedManager { const fetchedSoundboardSounds = new Collection(); const handler = (soundboardSounds, guild) => { + // eslint-disable-next-line @typescript-eslint/no-use-before-define timeout.refresh(); if (!remainingGuildIds.has(guild.id)) return; @@ -329,6 +348,7 @@ class GuildManager extends CachedManager { remainingGuildIds.delete(guild.id); if (remainingGuildIds.size === 0) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(timeout); this.client.removeListener(Events.SoundboardSounds, handler); this.client.decrementMaxListeners(); @@ -350,13 +370,15 @@ class GuildManager extends CachedManager { /** * Options used to set incident actions. Supplying `null` to any option will disable the action. - * @typedef {Object} IncidentActionsEditOptions + * + * @typedef {object} IncidentActionsEditOptions * @property {?DateResolvable} [invitesDisabledUntil] When invites should be enabled again * @property {?DateResolvable} [dmsDisabledUntil] When direct messages should be enabled again */ /** * Sets the incident actions for a guild. + * * @param {GuildResolvable} guild The guild * @param {IncidentActionsEditOptions} incidentActions The incident actions to set * @returns {Promise} @@ -383,6 +405,7 @@ class GuildManager extends CachedManager { /** * Returns a URL for the PNG widget of a guild. + * * @param {GuildResolvable} guild The guild of the widget image * @param {GuildWidgetStyle} [style] The style for the widget image * @returns {string} diff --git a/packages/discord.js/src/managers/GuildMemberManager.js b/packages/discord.js/src/managers/GuildMemberManager.js index cc7db3c20648..3f884da886fc 100644 --- a/packages/discord.js/src/managers/GuildMemberManager.js +++ b/packages/discord.js/src/managers/GuildMemberManager.js @@ -5,7 +5,6 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { DiscordSnowflake } = require('@sapphire/snowflake'); const { Routes, GatewayOpcodes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors/index.js'); const { BaseGuildVoiceChannel } = require('../structures/BaseGuildVoiceChannel.js'); const { GuildMember } = require('../structures/GuildMember.js'); @@ -13,9 +12,11 @@ const { Role } = require('../structures/Role.js'); const { Events } = require('../util/Events.js'); const { GuildMemberFlagsBitField } = require('../util/GuildMemberFlagsBitField.js'); const { Partials } = require('../util/Partials.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for GuildMembers and stores their cache. + * * @extends {CachedManager} */ class GuildMemberManager extends CachedManager { @@ -24,6 +25,7 @@ class GuildMemberManager extends CachedManager { /** * The guild this manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -31,6 +33,7 @@ class GuildMemberManager extends CachedManager { /** * The cache of this Manager + * * @type {Collection} * @name GuildMemberManager#cache */ @@ -41,6 +44,7 @@ class GuildMemberManager extends CachedManager { /** * Resolves a {@link UserResolvable} to a {@link GuildMember} object. + * * @param {UserResolvable} member The user that is part of the guild * @returns {?GuildMember} */ @@ -54,6 +58,7 @@ class GuildMemberManager extends CachedManager { /** * Resolves a {@link UserResolvable} to a member id. + * * @param {UserResolvable} member The user that is part of the guild * @returns {?Snowflake} */ @@ -66,7 +71,8 @@ class GuildMemberManager extends CachedManager { /** * Options used to add a user to a guild using OAuth2. - * @typedef {Object} AddGuildMemberOptions + * + * @typedef {object} AddGuildMemberOptions * @property {string} accessToken An OAuth2 access token for the user with the {@link OAuth2Scopes.GuildsJoin} * scope granted to the bot's application * @property {string} [nick] The nickname to give to the member @@ -84,6 +90,7 @@ class GuildMemberManager extends CachedManager { /** * Adds a user to the guild using OAuth2. * This method requires the {@link PermissionFlagsBits.CreateInstantInvite} permission. + * * @param {UserResolvable} user The user to add to the guild * @param {AddGuildMemberOptions} options Options for adding the user to the guild * @returns {Promise} @@ -95,6 +102,7 @@ class GuildMemberManager extends CachedManager { const cachedUser = this.cache.get(userId); if (cachedUser) return cachedUser; } + const resolvedOptions = { access_token: options.accessToken, nick: options.nick, @@ -110,16 +118,20 @@ class GuildMemberManager extends CachedManager { true, ); } + const resolvedRoles = []; for (const role of options.roles.values()) { const resolvedRole = this.guild.roles.resolveId(role); if (!resolvedRole) { throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role); } + resolvedRoles.push(resolvedRole); } + resolvedOptions.roles = resolvedRoles; } + const data = await this.client.rest.put(Routes.guildMember(this.guild.id, userId), { body: resolvedOptions }); // Data is an empty array buffer if the member is already part of the guild. @@ -132,6 +144,7 @@ class GuildMemberManager extends CachedManager { /** * The client user as a GuildMember of this guild + * * @type {?GuildMember} * @readonly */ @@ -146,13 +159,15 @@ class GuildMemberManager extends CachedManager { /** * Options used to fetch a single member from a guild. + * * @typedef {BaseFetchOptions} FetchMemberOptions * @property {UserResolvable} user The user to fetch */ /** * Options used to fetch multiple members from a guild. - * @typedef {Object} FetchMembersOptions + * + * @typedef {object} FetchMembersOptions * @property {UserResolvable|UserResolvable[]} [user] The user(s) to fetch * @property {?string} [query] Limit fetch to members with similar usernames * @property {number} [limit=0] Maximum number of members to request @@ -163,6 +178,7 @@ class GuildMemberManager extends CachedManager { /** * Fetches member(s) from a guild. + * * @param {UserResolvable|FetchMemberOptions|FetchMembersOptions} [options] Options for fetching member(s). * Omitting the parameter or providing `undefined` will fetch all members. * @returns {Promise>} @@ -197,7 +213,7 @@ class GuildMemberManager extends CachedManager { * .then(console.log) * .catch(console.error); */ - fetch(options) { + async fetch(options) { if (!options) return this._fetchMany(); const { user: users, limit, withPresences, cache, force } = options; const resolvedUser = this.client.users.resolveId(users ?? options); @@ -226,11 +242,12 @@ class GuildMemberManager extends CachedManager { } = {}) { if (nonce.length > 32) throw new DiscordjsRangeError(ErrorCodes.MemberFetchNonceLength); - const query = initialQuery || (!users ? '' : undefined); + const query = initialQuery ?? (users ? undefined : ''); return new Promise((resolve, reject) => { this.guild.client.ws.send(this.guild.shardId, { op: GatewayOpcodes.RequestGuildMembers, + // eslint-disable-next-line id-length d: { guild_id: this.guild.id, presences, @@ -241,21 +258,25 @@ class GuildMemberManager extends CachedManager { }, }); const fetchedMembers = new Collection(); - let i = 0; + let index = 0; const handler = (members, _, chunk) => { if (chunk.nonce !== nonce) return; + // eslint-disable-next-line @typescript-eslint/no-use-before-define timeout.refresh(); - i++; + index++; for (const member of members.values()) { fetchedMembers.set(member.id, member); } - if (members.size < 1_000 || (limit && fetchedMembers.size >= limit) || i === chunk.count) { + + if (members.size < 1_000 || (limit && fetchedMembers.size >= limit) || index === chunk.count) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(timeout); this.client.removeListener(Events.GuildMembersChunk, handler); this.client.decrementMaxListeners(); resolve(users && !Array.isArray(users) && fetchedMembers.size ? fetchedMembers.first() : fetchedMembers); } }; + const timeout = setTimeout(() => { this.client.removeListener(Events.GuildMembersChunk, handler); this.client.decrementMaxListeners(); @@ -268,16 +289,18 @@ class GuildMemberManager extends CachedManager { /** * Fetches the client user as a GuildMember of the guild. + * * @param {BaseFetchOptions} [options] The options for fetching the member * @returns {Promise} */ - fetchMe(options) { + async fetchMe(options) { return this.fetch({ ...options, user: this.client.user.id }); } /** * Options used for searching guild members. - * @typedef {Object} GuildSearchMembersOptions + * + * @typedef {object} GuildSearchMembersOptions * @property {string} query Filter members whose username or nickname start with this query * @property {number} [limit] Maximum number of members to search * @property {boolean} [cache=true] Whether or not to cache the fetched member(s) @@ -285,6 +308,7 @@ class GuildMemberManager extends CachedManager { /** * Searches for members in the guild based on a query. + * * @param {GuildSearchMembersOptions} options Options for searching members * @returns {Promise>} */ @@ -297,7 +321,8 @@ class GuildMemberManager extends CachedManager { /** * Options used for listing guild members. - * @typedef {Object} GuildListMembersOptions + * + * @typedef {object} GuildListMembersOptions * @property {Snowflake} [after] Limit fetching members to those with an id greater than the supplied id * @property {number} [limit] Maximum number of members to list * @property {boolean} [cache=true] Whether or not to cache the fetched member(s) @@ -305,6 +330,7 @@ class GuildMemberManager extends CachedManager { /** * Lists up to 1000 members of the guild. + * * @param {GuildListMembersOptions} [options] Options for listing members * @returns {Promise>} */ @@ -316,7 +342,8 @@ class GuildMemberManager extends CachedManager { /** * The data for editing a guild member. - * @typedef {Object} GuildMemberEditOptions + * + * @typedef {object} GuildMemberEditOptions * @property {?string} [nick] The nickname to set for the member * @property {Collection|RoleResolvable[]} [roles] The roles or role ids to apply * @property {boolean} [mute] Whether or not the member should be muted @@ -332,6 +359,7 @@ class GuildMemberManager extends CachedManager { /** * Edits a member of the guild. * The user must be a member of the guild + * * @param {UserResolvable} user The member to edit * @param {GuildMemberEditOptions} options The options to provide * @returns {Promise} @@ -345,20 +373,22 @@ class GuildMemberManager extends CachedManager { if (!(options.channel instanceof BaseGuildVoiceChannel)) { throw new DiscordjsError(ErrorCodes.GuildVoiceChannelResolve); } + options.channel_id = options.channel.id; options.channel = undefined; } else if (options.channel === null) { options.channel_id = null; options.channel = undefined; } + options.roles &&= options.roles.map(role => (role instanceof Role ? role.id : role)); if (options.communicationDisabledUntil !== undefined) { options.communication_disabled_until = - // eslint-disable-next-line eqeqeq - options.communicationDisabledUntil != null - ? new Date(options.communicationDisabledUntil).toISOString() - : options.communicationDisabledUntil; + // eslint-disable-next-line eqeqeq, no-eq-null + options.communicationDisabledUntil == null + ? options.communicationDisabledUntil + : new Date(options.communicationDisabledUntil).toISOString(); } if (options.flags !== undefined) { @@ -373,10 +403,11 @@ class GuildMemberManager extends CachedManager { } else { endpoint = Routes.guildMember(this.guild.id, id); } - const d = await this.client.rest.patch(endpoint, { body: options, reason }); + + const data = await this.client.rest.patch(endpoint, { body: options, reason }); const clone = this.cache.get(id)?._clone(); - clone?._patch(d); + clone?._patch(data); return clone ?? this._add(d, false); } @@ -384,7 +415,8 @@ class GuildMemberManager extends CachedManager { * Options used for pruning guild members. * It's recommended to set {@link GuildPruneMembersOptions#count options.count} * to `false` for large guilds. - * @typedef {Object} GuildPruneMembersOptions + * + * @typedef {object} GuildPruneMembersOptions * @property {number} [days] Number of days of inactivity required to kick * @property {boolean} [dry=false] Get the number of users that will be kicked, without actually kicking them * @property {boolean} [count] Whether or not to return the number of users that have been kicked. @@ -394,6 +426,7 @@ class GuildMemberManager extends CachedManager { /** * Prunes members from the guild based on how long they have been inactive. + * * @param {GuildPruneMembersOptions} [options] Options for pruning * @returns {Promise} The number of members that were/will be kicked * @example @@ -423,6 +456,7 @@ class GuildMemberManager extends CachedManager { if (!resolvedRole) { throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'options.roles', role); } + resolvedRoles.push(resolvedRole); } @@ -439,10 +473,10 @@ class GuildMemberManager extends CachedManager { return pruned; } - /* eslint-disable consistent-return */ /** * Kicks a user from the guild. * The user must be a member of the guild + * * @param {UserResolvable} user The member to kick * @param {string} [reason] Reason for kicking * @returns {Promise} @@ -456,10 +490,10 @@ class GuildMemberManager extends CachedManager { await this.client.rest.delete(Routes.guildMember(this.guild.id, id), { reason }); } - /* eslint-enable consistent-return */ /** * Bans a user from the guild. Internally calls the {@link GuildBanManager#create} method. + * * @param {UserResolvable} user The user to ban * @param {BanOptions} [options] Options for the ban * @returns {Promise} @@ -473,6 +507,7 @@ class GuildMemberManager extends CachedManager { /** * Unbans a user from the guild. Internally calls the {@link GuildBanManager#remove} method. + * * @param {UserResolvable} user The user to unban * @param {string} [reason] Reason for unbanning user * @returns {Promise} @@ -486,6 +521,7 @@ class GuildMemberManager extends CachedManager { /** * Bulk ban users from a guild, and optionally delete previous messages sent by them. + * * @param {Collection|UserResolvable[]} users The users to ban * @param {BanOptions} [options] The options for bulk banning users * @returns {Promise} Returns an object with `bannedUsers` key containing the IDs of the banned users @@ -499,13 +535,14 @@ class GuildMemberManager extends CachedManager { * }) * .catch(console.error); */ - bulkBan(users, options = {}) { + async bulkBan(users, options = {}) { return this.guild.bans.bulkCreate(users, options); } /** * Options used for adding or removing a role from a member. - * @typedef {Object} AddOrRemoveGuildMemberRoleOptions + * + * @typedef {object} AddOrRemoveGuildMemberRoleOptions * @property {UserResolvable} user The user to add/remove the role from * @property {RoleResolvable} role The role to add/remove * @property {string} [reason] Reason for adding/removing the role @@ -513,6 +550,7 @@ class GuildMemberManager extends CachedManager { /** * Adds a role to a member. + * * @param {AddOrRemoveGuildMemberRoleOptions} options Options for adding the role * @returns {Promise} */ @@ -525,6 +563,7 @@ class GuildMemberManager extends CachedManager { /** * Removes a role from a member. + * * @param {AddOrRemoveGuildMemberRoleOptions} options Options for removing the role * @returns {Promise} */ diff --git a/packages/discord.js/src/managers/GuildMemberRoleManager.js b/packages/discord.js/src/managers/GuildMemberRoleManager.js index f784955e45d2..0454d5f98f64 100644 --- a/packages/discord.js/src/managers/GuildMemberRoleManager.js +++ b/packages/discord.js/src/managers/GuildMemberRoleManager.js @@ -2,12 +2,13 @@ const { Collection } = require('@discordjs/collection'); const { Routes } = require('discord-api-types/v10'); -const { DataManager } = require('./DataManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { Role } = require('../structures/Role.js'); +const { DataManager } = require('./DataManager.js'); /** * Manages API methods for roles of a GuildMember and stores their cache. + * * @extends {DataManager} */ class GuildMemberRoleManager extends DataManager { @@ -16,12 +17,14 @@ class GuildMemberRoleManager extends DataManager { /** * The GuildMember this manager belongs to + * * @type {GuildMember} */ this.member = member; /** * The Guild this manager belongs to + * * @type {Guild} */ this.guild = member.guild; @@ -29,6 +32,7 @@ class GuildMemberRoleManager extends DataManager { /** * The roles of this member + * * @type {Collection} * @readonly */ @@ -39,6 +43,7 @@ class GuildMemberRoleManager extends DataManager { /** * The role of the member used to hoist them in a separate category in the users list + * * @type {?Role} * @readonly */ @@ -50,17 +55,19 @@ class GuildMemberRoleManager extends DataManager { /** * The role of the member used to set their role icon + * * @type {?Role} * @readonly */ get icon() { - const iconRoles = this.cache.filter(role => role.icon || role.unicodeEmoji); + const iconRoles = this.cache.filter(role => role.icon ?? role.unicodeEmoji); if (!iconRoles.size) return null; return iconRoles.reduce((prev, role) => (role.comparePositionTo(prev) > 0 ? role : prev)); } /** * The role of the member used to set their color + * * @type {?Role} * @readonly */ @@ -72,6 +79,7 @@ class GuildMemberRoleManager extends DataManager { /** * The role of the member with the highest position + * * @type {Role} * @readonly */ @@ -81,6 +89,7 @@ class GuildMemberRoleManager extends DataManager { /** * The premium subscriber role of the guild, if present on the member + * * @type {?Role} * @readonly */ @@ -91,6 +100,7 @@ class GuildMemberRoleManager extends DataManager { /** * The managed role this member created when joining the guild, if any * Only ever available on bots + * * @type {?Role} * @readonly */ @@ -103,6 +113,7 @@ class GuildMemberRoleManager extends DataManager { * Adds a role (or multiple roles) to the member. * * Uses the idempotent PUT route for singular roles, otherwise PATCHes the underlying guild member + * * @param {RoleResolvable|RoleResolvable[]|Collection} roleOrRoles The role or roles to add * @param {string} [reason] Reason for adding the role(s) * @returns {Promise} @@ -115,6 +126,7 @@ class GuildMemberRoleManager extends DataManager { if (!resolvedRole) { throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role); } + resolvedRoles.push(resolvedRole); } @@ -142,6 +154,7 @@ class GuildMemberRoleManager extends DataManager { * Removes a role (or multiple roles) from the member. * * Uses the idempotent DELETE route for singular roles, otherwise PATCHes the underlying guild member + * * @param {RoleResolvable|RoleResolvable[]|Collection} roleOrRoles The role or roles to remove * @param {string} [reason] Reason for removing the role(s) * @returns {Promise} @@ -154,6 +167,7 @@ class GuildMemberRoleManager extends DataManager { if (!resolvedRole) { throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role); } + resolvedRoles.push(resolvedRole); } @@ -180,6 +194,7 @@ class GuildMemberRoleManager extends DataManager { /** * Sets the roles applied to the member. + * * @param {Collection|RoleResolvable[]} roles The roles or role ids to apply * @param {string} [reason] Reason for applying the roles * @returns {Promise} @@ -194,7 +209,7 @@ class GuildMemberRoleManager extends DataManager { * .then(member => console.log(`Member roles is now of ${member.roles.cache.size} size`)) * .catch(console.error); */ - set(roles, reason) { + async set(roles, reason) { return this.member.edit({ roles, reason }); } diff --git a/packages/discord.js/src/managers/GuildMessageManager.js b/packages/discord.js/src/managers/GuildMessageManager.js index cc68dabd806f..3a9f17c5d4b1 100644 --- a/packages/discord.js/src/managers/GuildMessageManager.js +++ b/packages/discord.js/src/managers/GuildMessageManager.js @@ -1,22 +1,25 @@ 'use strict'; const { Routes } = require('discord-api-types/v10'); -const { MessageManager } = require('./MessageManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); +const { MessageManager } = require('./MessageManager.js'); /** * Manages API methods for messages in a guild and holds their cache. + * * @extends {MessageManager} */ class GuildMessageManager extends MessageManager { /** * The channel that the messages belong to + * * @name GuildMessageManager#channel * @type {GuildTextBasedChannel} */ /** * Publishes a message in an announcement channel to all channels following it, even if it's not cached. + * * @param {MessageResolvable} message The message to publish * @returns {Promise} */ diff --git a/packages/discord.js/src/managers/GuildScheduledEventManager.js b/packages/discord.js/src/managers/GuildScheduledEventManager.js index 536859566118..feb92bb3de71 100644 --- a/packages/discord.js/src/managers/GuildScheduledEventManager.js +++ b/packages/discord.js/src/managers/GuildScheduledEventManager.js @@ -3,14 +3,15 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { GuildScheduledEventEntityType, Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { GuildScheduledEvent } = require('../structures/GuildScheduledEvent.js'); const { resolveImage } = require('../util/DataResolver.js'); const { _transformGuildScheduledEventRecurrenceRule } = require('../util/Transformers.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for GuildScheduledEvents and stores their cache. + * * @extends {CachedManager} */ class GuildScheduledEventManager extends CachedManager { @@ -19,6 +20,7 @@ class GuildScheduledEventManager extends CachedManager { /** * The guild this manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -26,20 +28,23 @@ class GuildScheduledEventManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name GuildScheduledEventManager#cache */ /** * Data that resolves to give a GuildScheduledEvent object. This can be: - * * A Snowflake - * * A GuildScheduledEvent object + * A Snowflake + * A GuildScheduledEvent object + * * @typedef {Snowflake|GuildScheduledEvent} GuildScheduledEventResolvable */ /** * Options for setting a recurrence rule for a guild scheduled event. - * @typedef {Object} GuildScheduledEventRecurrenceRuleOptions + * + * @typedef {object} GuildScheduledEventRecurrenceRuleOptions * @property {DateResolvable} startAt The time the recurrence rule interval starts at * @property {GuildScheduledEventRecurrenceRuleFrequency} frequency How often the event occurs * @property {number} interval The spacing between the events @@ -51,7 +56,8 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to create a guild scheduled event. - * @typedef {Object} GuildScheduledEventCreateOptions + * + * @typedef {object} GuildScheduledEventCreateOptions * @property {string} name The name of the guild scheduled event * @property {DateResolvable} scheduledStartTime The time to schedule the event at * @property {DateResolvable} [scheduledEndTime] The time to end the event at @@ -73,19 +79,21 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to set entity metadata of a guild scheduled event. - * @typedef {Object} GuildScheduledEventEntityMetadataOptions + * + * @typedef {object} GuildScheduledEventEntityMetadataOptions * @property {string} [location] The location of the guild scheduled event * This is required if `entityType` is {@link GuildScheduledEventEntityType.External} */ /** * Creates a new guild scheduled event. + * * @param {GuildScheduledEventCreateOptions} options Options for creating the guild scheduled event * @returns {Promise} */ async create(options) { if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); - let { + const { privacyLevel, entityType, channel, @@ -99,7 +107,8 @@ class GuildScheduledEventManager extends CachedManager { recurrenceRule, } = options; - let entity_metadata, channel_id; + let channel_id; + let entity_metadata; if (entityType === GuildScheduledEventEntityType.External) { channel_id = channel === undefined ? channel : null; entity_metadata = { location: entityMetadata?.location }; @@ -130,6 +139,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to fetch a single guild scheduled event from a guild. + * * @typedef {BaseFetchOptions} FetchGuildScheduledEventOptions * @property {GuildScheduledEventResolvable} guildScheduledEvent The guild scheduled event to fetch * @property {boolean} [withUserCount=true] Whether to fetch the number of users subscribed to the scheduled event @@ -137,7 +147,8 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to fetch multiple guild scheduled events from a guild. - * @typedef {Object} FetchGuildScheduledEventsOptions + * + * @typedef {object} FetchGuildScheduledEventsOptions * @property {boolean} [cache] Whether or not to cache the fetched guild scheduled events * @property {boolean} [withUserCount=true] Whether to fetch the number of users subscribed to each scheduled event * should be returned @@ -145,6 +156,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Obtains one or more guild scheduled events from Discord, or the guild cache if it's already available. + * * @param {GuildScheduledEventResolvable|FetchGuildScheduledEventOptions|FetchGuildScheduledEventsOptions} [options] * The id of the guild scheduled event or options * @returns {Promise>} @@ -177,7 +189,8 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to edit a guild scheduled event. - * @typedef {Object} GuildScheduledEventEditOptions + * + * @typedef {object} GuildScheduledEventEditOptions * @property {string} [name] The name of the guild scheduled event * @property {DateResolvable} [scheduledStartTime] The time to schedule the event at * @property {DateResolvable} [scheduledEndTime] The time to end the event at @@ -198,6 +211,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Edits a guild scheduled event. + * * @param {GuildScheduledEventResolvable} guildScheduledEvent The guild scheduled event to edit * @param {GuildScheduledEventEditOptions} options Options to edit the guild scheduled event * @returns {Promise} @@ -207,7 +221,7 @@ class GuildScheduledEventManager extends CachedManager { if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve); if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); - let { + const { privacyLevel, entityType, channel, @@ -251,6 +265,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Deletes a guild scheduled event. + * * @param {GuildScheduledEventResolvable} guildScheduledEvent The guild scheduled event to delete * @returns {Promise} */ @@ -263,7 +278,8 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to fetch subscribers of a guild scheduled event - * @typedef {Object} FetchGuildScheduledEventSubscribersOptions + * + * @typedef {object} FetchGuildScheduledEventSubscribersOptions * @property {number} [limit] The maximum numbers of users to fetch * @property {boolean} [withMember] Whether to fetch guild member data of the users * @property {Snowflake} [before] Consider only users before this user id @@ -273,7 +289,8 @@ class GuildScheduledEventManager extends CachedManager { /** * Represents a subscriber of a {@link GuildScheduledEvent} - * @typedef {Object} GuildScheduledEventUser + * + * @typedef {object} GuildScheduledEventUser * @property {Snowflake} guildScheduledEventId The id of the guild scheduled event which the user subscribed to * @property {User} user The user that subscribed to the guild scheduled event * @property {?GuildMember} member The guild member associated with the user, if any @@ -281,8 +298,9 @@ class GuildScheduledEventManager extends CachedManager { /** * Fetches subscribers of a guild scheduled event. + * * @param {GuildScheduledEventResolvable} guildScheduledEvent The guild scheduled event to fetch subscribers of - * @param {FetchGuildScheduledEventSubscribersOptions} [options={}] Options for fetching the subscribers + * @param {FetchGuildScheduledEventSubscribersOptions} [options] Options for fetching the subscribers * @returns {Promise>} */ async fetchSubscribers(guildScheduledEvent, options = {}) { diff --git a/packages/discord.js/src/managers/GuildSoundboardSoundManager.js b/packages/discord.js/src/managers/GuildSoundboardSoundManager.js index 94eb1088c85c..f802ceb7db27 100644 --- a/packages/discord.js/src/managers/GuildSoundboardSoundManager.js +++ b/packages/discord.js/src/managers/GuildSoundboardSoundManager.js @@ -3,15 +3,16 @@ const { Collection } = require('@discordjs/collection'); const { lazy } = require('@discordjs/util'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { SoundboardSound } = require('../structures/SoundboardSound.js'); const { resolveBase64, resolveFile } = require('../util/DataResolver.js'); +const { CachedManager } = require('./CachedManager.js'); const fileTypeMime = lazy(() => require('magic-bytes.js').filetypemime); /** * Manages API methods for Soundboard Sounds and stores their cache. + * * @extends {CachedManager} */ class GuildSoundboardSoundManager extends CachedManager { @@ -20,6 +21,7 @@ class GuildSoundboardSoundManager extends CachedManager { /** * The guild this manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -27,6 +29,7 @@ class GuildSoundboardSoundManager extends CachedManager { /** * The cache of Soundboard Sounds + * * @type {Collection} * @name GuildSoundboardSoundManager#cache */ @@ -37,13 +40,15 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Data that resolves to give a SoundboardSound object. This can be: - * * A SoundboardSound object - * * A Snowflake + * A SoundboardSound object + * A Snowflake + * * @typedef {SoundboardSound|Snowflake} SoundboardSoundResolvable */ /** * Resolves a SoundboardSoundResolvable to a SoundboardSound object. + * * @method resolve * @memberof GuildSoundboardSoundManager * @instance @@ -53,6 +58,7 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Resolves a {@link SoundboardSoundResolvable} to a {@link SoundboardSound} id. + * * @param {SoundboardSoundResolvable} soundboardSound The soundboard sound resolvable to resolve * @returns {?Snowflake} */ @@ -64,7 +70,8 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Options used to create a soundboard sound in a guild. - * @typedef {Object} GuildSoundboardSoundCreateOptions + * + * @typedef {object} GuildSoundboardSoundCreateOptions * @property {BufferResolvable|Stream} file The file for the soundboard sound * @property {string} name The name for the soundboard sound * @property {string} [contentType] The content type for the soundboard sound file @@ -76,6 +83,7 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Creates a new guild soundboard sound. + * * @param {GuildSoundboardSoundCreateOptions} options Options for creating a guild soundboard sound * @returns {Promise} The created soundboard sound * @example @@ -103,7 +111,8 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Data for editing a soundboard sound. - * @typedef {Object} GuildSoundboardSoundEditOptions + * + * @typedef {object} GuildSoundboardSoundEditOptions * @property {string} [name] The name of the soundboard sound * @property {?number} [volume] The volume of the soundboard sound, from 0 to 1 * @property {?Snowflake} [emojiId] The emoji id of the soundboard sound @@ -113,8 +122,9 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Edits a soundboard sound. + * * @param {SoundboardSoundResolvable} soundboardSound The soundboard sound to edit - * @param {GuildSoundboardSoundEditOptions} [options={}] The new data for the soundboard sound + * @param {GuildSoundboardSoundEditOptions} [options] The new data for the soundboard sound * @returns {Promise} */ async edit(soundboardSound, options = {}) { @@ -145,6 +155,7 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Deletes a soundboard sound. + * * @param {SoundboardSoundResolvable} soundboardSound The soundboard sound to delete * @param {string} [reason] Reason for deleting this soundboard sound * @returns {Promise} @@ -159,6 +170,7 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Obtains one or more soundboard sounds from Discord, or the soundboard sound cache if they're already available. + * * @param {Snowflake} [id] The soundboard sound's id * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise>} diff --git a/packages/discord.js/src/managers/GuildStickerManager.js b/packages/discord.js/src/managers/GuildStickerManager.js index add8205d6989..929ba30c2db4 100644 --- a/packages/discord.js/src/managers/GuildStickerManager.js +++ b/packages/discord.js/src/managers/GuildStickerManager.js @@ -2,13 +2,14 @@ const { Collection } = require('@discordjs/collection'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { MessagePayload } = require('../structures/MessagePayload.js'); const { Sticker } = require('../structures/Sticker.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for Guild Stickers and stores their cache. + * * @extends {CachedManager} */ class GuildStickerManager extends CachedManager { @@ -17,6 +18,7 @@ class GuildStickerManager extends CachedManager { /** * The guild this manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -24,6 +26,7 @@ class GuildStickerManager extends CachedManager { /** * The cache of Guild Stickers + * * @type {Collection} * @name GuildStickerManager#cache */ @@ -34,7 +37,8 @@ class GuildStickerManager extends CachedManager { /** * Options used to create a guild sticker. - * @typedef {Object} GuildStickerCreateOptions + * + * @typedef {object} GuildStickerCreateOptions * @property {AttachmentPayload|BufferResolvable|Stream} file The file for the sticker * @property {string} name The name for the sticker * @property {string} tags The Discord name of a unicode emoji representing the sticker's expression @@ -44,6 +48,7 @@ class GuildStickerManager extends CachedManager { /** * Creates a new custom sticker in the guild. + * * @param {GuildStickerCreateOptions} options Options for creating a guild sticker * @returns {Promise} The created sticker * @example @@ -74,13 +79,15 @@ class GuildStickerManager extends CachedManager { /** * Data that resolves to give a Sticker object. This can be: - * * A Sticker object - * * A Snowflake + * A Sticker object + * A Snowflake + * * @typedef {Sticker|Snowflake} StickerResolvable */ /** * Resolves a StickerResolvable to a Sticker object. + * * @method resolve * @memberof GuildStickerManager * @instance @@ -90,6 +97,7 @@ class GuildStickerManager extends CachedManager { /** * Resolves a StickerResolvable to a Sticker id string. + * * @method resolveId * @memberof GuildStickerManager * @instance @@ -99,15 +107,16 @@ class GuildStickerManager extends CachedManager { /** * Edits a sticker. + * * @param {StickerResolvable} sticker The sticker to edit - * @param {GuildStickerEditOptions} [options={}] The new data for the sticker + * @param {GuildStickerEditOptions} [options] The new data for the sticker * @returns {Promise} */ async edit(sticker, options = {}) { const stickerId = this.resolveId(sticker); if (!stickerId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable'); - const d = await this.client.rest.patch(Routes.guildSticker(this.guild.id, stickerId), { + const data = await this.client.rest.patch(Routes.guildSticker(this.guild.id, stickerId), { body: options, reason: options.reason, }); @@ -115,14 +124,16 @@ class GuildStickerManager extends CachedManager { const existing = this.cache.get(stickerId); if (existing) { const clone = existing._clone(); - clone._patch(d); + clone._patch(data); return clone; } - return this._add(d); + + return this._add(data); } /** * Deletes a sticker. + * * @param {StickerResolvable} sticker The sticker to delete * @param {string} [reason] Reason for deleting this sticker * @returns {Promise} @@ -136,6 +147,7 @@ class GuildStickerManager extends CachedManager { /** * Obtains one or more stickers from Discord, or the sticker cache if they're already available. + * * @param {Snowflake} [id] The Sticker's id * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise>} @@ -156,6 +168,7 @@ class GuildStickerManager extends CachedManager { const existing = this.cache.get(id); if (existing) return existing; } + const sticker = await this.client.rest.get(Routes.guildSticker(this.guild.id, id)); return this._add(sticker, cache); } @@ -166,6 +179,7 @@ class GuildStickerManager extends CachedManager { /** * Fetches the user who uploaded this sticker, if this is a guild sticker. + * * @param {StickerResolvable} sticker The sticker to fetch the user for * @returns {Promise} */ diff --git a/packages/discord.js/src/managers/GuildTextThreadManager.js b/packages/discord.js/src/managers/GuildTextThreadManager.js index 157cea673798..aff88df15915 100644 --- a/packages/discord.js/src/managers/GuildTextThreadManager.js +++ b/packages/discord.js/src/managers/GuildTextThreadManager.js @@ -1,22 +1,25 @@ 'use strict'; const { ChannelType, Routes } = require('discord-api-types/v10'); -const { ThreadManager } = require('./ThreadManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); +const { ThreadManager } = require('./ThreadManager.js'); /** * Manages API methods for {@link ThreadChannel} objects and stores their cache. + * * @extends {ThreadManager} */ class GuildTextThreadManager extends ThreadManager { /** * The channel this Manager belongs to + * * @name GuildTextThreadManager#channel * @type {TextChannel|AnnouncementChannel} */ /** * Options for creating a thread. Only one of `startMessage` or `type` can be defined. + * * @typedef {StartThreadOptions} GuildTextThreadCreateOptions * @property {MessageResolvable} [startMessage] The message to start a thread from. * If this is defined, then the `type` of thread gets inferred automatically and cannot be changed. @@ -30,6 +33,7 @@ class GuildTextThreadManager extends ThreadManager { /** * Creates a new thread in the channel. + * * @param {GuildTextThreadCreateOptions} [options] Options to create a new thread * @returns {Promise} * @example diff --git a/packages/discord.js/src/managers/MessageManager.js b/packages/discord.js/src/managers/MessageManager.js index 09fbe044cd5c..ba175cbdaad6 100644 --- a/packages/discord.js/src/managers/MessageManager.js +++ b/packages/discord.js/src/managers/MessageManager.js @@ -3,15 +3,16 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { Message } = require('../structures/Message.js'); const { MessagePayload } = require('../structures/MessagePayload.js'); const { MakeCacheOverrideSymbol } = require('../util/Symbols.js'); const { resolvePartialEmoji } = require('../util/Util.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for Messages and holds their cache. + * * @extends {CachedManager} * @abstract */ @@ -23,6 +24,7 @@ class MessageManager extends CachedManager { /** * The channel that the messages belong to + * * @type {TextBasedChannels} */ this.channel = channel; @@ -30,6 +32,7 @@ class MessageManager extends CachedManager { /** * The cache of Messages + * * @type {Collection} * @name MessageManager#cache */ @@ -40,13 +43,15 @@ class MessageManager extends CachedManager { /** * Data that can be resolved to a Message object. This can be: - * * A Message - * * A Snowflake + * A Message + * A Snowflake + * * @typedef {Message|Snowflake} MessageResolvable */ /** * Options used to fetch a message. + * * @typedef {BaseFetchOptions} FetchMessageOptions * @property {MessageResolvable} message The message to fetch */ @@ -54,7 +59,8 @@ class MessageManager extends CachedManager { /** * Options used to fetch multiple messages. * The `before`, `after`, and `around` parameters are mutually exclusive. - * @typedef {Object} FetchMessagesOptions + * + * @typedef {object} FetchMessagesOptions * @property {number} [limit] The maximum number of messages to return * @property {Snowflake} [before] Consider only messages before this id * @property {Snowflake} [after] Consider only messages after this id @@ -66,6 +72,7 @@ class MessageManager extends CachedManager { * Fetches message(s) from a channel. * The returned Collection does not contain reaction users of the messages if they were not cached. * Those need to be fetched separately in such a case. + * * @param {MessageResolvable|FetchMessageOptions|FetchMessagesOptions} [options] Options for fetching message(s) * @returns {Promise>} * @example @@ -90,7 +97,7 @@ class MessageManager extends CachedManager { * message.author.id === '84484653687267328').size} messages`)) * .catch(console.error); */ - fetch(options) { + async fetch(options) { if (!options) return this._fetchMany(); const { message, cache, force } = options; const resolvedMessage = this.resolveId(message ?? options); @@ -120,7 +127,8 @@ class MessageManager extends CachedManager { * Fetches the pinned messages of this channel and returns a collection of them. * The returned Collection does not contain any reaction data of the messages. * Those need to be fetched separately. - * @param {boolean} [cache=true] Whether to cache the message(s) + * + * @param {boolean} [cache] Whether to cache the message(s) * @returns {Promise>} * @example * // Get pinned messages @@ -137,6 +145,7 @@ class MessageManager extends CachedManager { /** * Resolves a {@link MessageResolvable} to a {@link Message} object. + * * @method resolve * @memberof MessageManager * @instance @@ -146,6 +155,7 @@ class MessageManager extends CachedManager { /** * Resolves a {@link MessageResolvable} to a {@link Message} id. + * * @method resolveId * @memberof MessageManager * @instance @@ -155,12 +165,14 @@ class MessageManager extends CachedManager { /** * Data used to reference an attachment. - * @typedef {Object} MessageEditAttachmentData + * + * @typedef {object} MessageEditAttachmentData * @property {Snowflake} id The id of the attachment */ /** * Options that can be passed to edit a message. + * * @typedef {BaseMessageOptions} MessageEditOptions * @property {Array} [attachments] An array of attachments to keep. * All attachments will be kept if omitted @@ -170,6 +182,7 @@ class MessageManager extends CachedManager { /** * Edits a message, even if it's not cached. + * * @param {MessageResolvable} message The message to edit * @param {string|MessageEditOptions|MessagePayload} options The options to edit the message * @returns {Promise} @@ -185,19 +198,21 @@ class MessageManager extends CachedManager { ) .resolveBody() .resolveFiles(); - const d = await this.client.rest.patch(Routes.channelMessage(this.channel.id, messageId), { body, files }); + const data = await this.client.rest.patch(Routes.channelMessage(this.channel.id, messageId), { body, files }); const existing = this.cache.get(messageId); if (existing) { const clone = existing._clone(); - clone._patch(d); + clone._patch(data); return clone; } - return this._add(d); + + return this._add(data); } /** * Pins a message to the channel's pinned messages, even if it's not cached. + * * @param {MessageResolvable} message The message to pin * @param {string} [reason] Reason for pinning * @returns {Promise} @@ -211,6 +226,7 @@ class MessageManager extends CachedManager { /** * Unpins a message from the channel's pinned messages, even if it's not cached. + * * @param {MessageResolvable} message The message to unpin * @param {string} [reason] Reason for unpinning * @returns {Promise} @@ -224,6 +240,7 @@ class MessageManager extends CachedManager { /** * Adds a reaction to a message, even if it's not cached. + * * @param {MessageResolvable} message The message to react to * @param {EmojiIdentifierResolvable} emoji The emoji to react with * @returns {Promise} @@ -244,6 +261,7 @@ class MessageManager extends CachedManager { /** * Deletes a message, even if it's not cached. + * * @param {MessageResolvable} message The message to delete * @returns {Promise} */ @@ -256,6 +274,7 @@ class MessageManager extends CachedManager { /** * Ends a poll. + * * @param {Snowflake} messageId The id of the message * @returns {Promise} */ @@ -266,6 +285,7 @@ class MessageManager extends CachedManager { /** * Options used for fetching voters of an answer in a poll. + * * @typedef {BaseFetchPollAnswerVotersOptions} FetchPollAnswerVotersOptions * @param {Snowflake} messageId The id of the message * @param {number} answerId The id of the answer @@ -273,6 +293,7 @@ class MessageManager extends CachedManager { /** * Fetches the users that voted for a poll answer. + * * @param {FetchPollAnswerVotersOptions} options The options for fetching the poll answer voters * @returns {Promise>} */ diff --git a/packages/discord.js/src/managers/PartialGroupDMMessageManager.js b/packages/discord.js/src/managers/PartialGroupDMMessageManager.js index 9a36a4da1887..60d165d7ca0f 100644 --- a/packages/discord.js/src/managers/PartialGroupDMMessageManager.js +++ b/packages/discord.js/src/managers/PartialGroupDMMessageManager.js @@ -4,11 +4,13 @@ const { MessageManager } = require('./MessageManager.js'); /** * Manages API methods for messages in group direct message channels and holds their cache. + * * @extends {MessageManager} */ class PartialGroupDMMessageManager extends MessageManager { /** * The channel that the messages belong to + * * @name PartialGroupDMMessageManager#channel * @type {PartialGroupDMChannel} */ diff --git a/packages/discord.js/src/managers/PermissionOverwriteManager.js b/packages/discord.js/src/managers/PermissionOverwriteManager.js index 5406e0844a47..e6bd44d7a348 100644 --- a/packages/discord.js/src/managers/PermissionOverwriteManager.js +++ b/packages/discord.js/src/managers/PermissionOverwriteManager.js @@ -3,15 +3,16 @@ const process = require('node:process'); const { Collection } = require('@discordjs/collection'); const { OverwriteType, Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { PermissionOverwrites } = require('../structures/PermissionOverwrites.js'); const { Role } = require('../structures/Role.js'); +const { CachedManager } = require('./CachedManager.js'); let cacheWarningEmitted = false; /** * Manages API methods for guild channel permission overwrites and stores their cache. + * * @extends {CachedManager} */ class PermissionOverwriteManager extends CachedManager { @@ -27,6 +28,7 @@ class PermissionOverwriteManager extends CachedManager { /** * The channel of the permission overwrite this manager belongs to + * * @type {GuildChannel} */ this.channel = channel; @@ -40,6 +42,7 @@ class PermissionOverwriteManager extends CachedManager { /** * The cache of this Manager + * * @type {Collection} * @name PermissionOverwriteManager#cache */ @@ -50,6 +53,7 @@ class PermissionOverwriteManager extends CachedManager { /** * Replaces the permission overwrites in this channel. + * * @param {OverwriteResolvable[]|Collection} overwrites * Permission overwrites the channel gets updated with * @param {string} [reason] Reason for updating the channel overwrites @@ -71,12 +75,14 @@ class PermissionOverwriteManager extends CachedManager { true, ); } + return this.channel.edit({ permissionOverwrites: overwrites, reason }); } /** * Extra information about the overwrite. - * @typedef {Object} GuildChannelOverwriteOptions + * + * @typedef {object} GuildChannelOverwriteOptions * @property {string} [reason] The reason for creating/editing this overwrite * @property {OverwriteType} [type] The type of overwrite. Use this to bypass automatic resolution of `type` * that results in an error for an uncached structure @@ -84,6 +90,7 @@ class PermissionOverwriteManager extends CachedManager { /** * Creates or edits permission overwrites for a user or role in this channel. + * * @param {RoleResolvable|UserResolvable} userOrRole The user or role to update * @param {PermissionOverwriteOptions} options The options for the update * @param {GuildChannelOverwriteOptions} [overwriteOptions] The extra information for the update @@ -91,7 +98,7 @@ class PermissionOverwriteManager extends CachedManager { * @returns {Promise} * @private */ - async upsert(userOrRole, options, { reason, type } = {}, existing) { + async upsert(userOrRole, options, { reason, type } = {}, existing = undefined) { const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole); let resolvedType = type; @@ -112,6 +119,7 @@ class PermissionOverwriteManager extends CachedManager { /** * Creates permission overwrites for a user or role in this channel, or replaces them if already present. + * * @param {RoleResolvable|UserResolvable} userOrRole The user or role to update * @param {PermissionOverwriteOptions} options The options for the update * @param {GuildChannelOverwriteOptions} [overwriteOptions] The extra information for the update @@ -124,12 +132,13 @@ class PermissionOverwriteManager extends CachedManager { * .then(channel => console.log(channel.permissionOverwrites.cache.get(message.author.id))) * .catch(console.error); */ - create(userOrRole, options, overwriteOptions) { + async create(userOrRole, options, overwriteOptions) { return this.upsert(userOrRole, options, overwriteOptions); } /** * Edits permission overwrites for a user or role in this channel, or creates an entry if not already present. + * * @param {RoleResolvable|UserResolvable} userOrRole The user or role to update * @param {PermissionOverwriteOptions} options The options for the update * @param {GuildChannelOverwriteOptions} [overwriteOptions] The extra information for the update @@ -142,7 +151,7 @@ class PermissionOverwriteManager extends CachedManager { * .then(channel => console.log(channel.permissionOverwrites.cache.get(message.author.id))) * .catch(console.error); */ - edit(userOrRole, options, overwriteOptions) { + async edit(userOrRole, options, overwriteOptions) { const existing = this.cache.get( this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole), ); @@ -151,6 +160,7 @@ class PermissionOverwriteManager extends CachedManager { /** * Deletes permission overwrites for a user or role in this channel. + * * @param {UserResolvable|RoleResolvable} userOrRole The user or role to delete * @param {string} [reason] The reason for deleting the overwrite * @returns {Promise} diff --git a/packages/discord.js/src/managers/PollAnswerVoterManager.js b/packages/discord.js/src/managers/PollAnswerVoterManager.js index 24fb1e1b8448..93d37cba9ac7 100644 --- a/packages/discord.js/src/managers/PollAnswerVoterManager.js +++ b/packages/discord.js/src/managers/PollAnswerVoterManager.js @@ -3,11 +3,12 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { User } = require('../structures/User.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for users who voted on a poll and stores their cache. + * * @extends {CachedManager} */ class PollAnswerVoterManager extends CachedManager { @@ -16,6 +17,7 @@ class PollAnswerVoterManager extends CachedManager { /** * The poll answer that this manager belongs to + * * @type {PollAnswer} */ this.answer = answer; @@ -23,13 +25,15 @@ class PollAnswerVoterManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name PollAnswerVoterManager#cache */ /** * Fetches the users that voted on this poll answer. Resolves with a collection of users, mapped by their ids. - * @param {BaseFetchPollAnswerVotersOptions} [options={}] Options for fetching the users + * + * @param {BaseFetchPollAnswerVotersOptions} [options] Options for fetching the users * @returns {Promise>} */ async fetch({ after, limit } = {}) { diff --git a/packages/discord.js/src/managers/PresenceManager.js b/packages/discord.js/src/managers/PresenceManager.js index 4f780141f1ec..3689f875115b 100644 --- a/packages/discord.js/src/managers/PresenceManager.js +++ b/packages/discord.js/src/managers/PresenceManager.js @@ -1,10 +1,11 @@ 'use strict'; -const { CachedManager } = require('./CachedManager.js'); const { Presence } = require('../structures/Presence.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for Presences and holds their cache. + * * @extends {CachedManager} */ class PresenceManager extends CachedManager { @@ -14,6 +15,7 @@ class PresenceManager extends CachedManager { /** * The cache of Presences + * * @type {Collection} * @name PresenceManager#cache */ @@ -24,14 +26,16 @@ class PresenceManager extends CachedManager { /** * Data that can be resolved to a Presence object. This can be: - * * A Presence - * * A UserResolvable - * * A Snowflake + * A Presence + * A UserResolvable + * A Snowflake + * * @typedef {Presence|UserResolvable|Snowflake} PresenceResolvable */ /** * Resolves a {@link PresenceResolvable} to a {@link Presence} object. + * * @param {PresenceResolvable} presence The presence resolvable to resolve * @returns {?Presence} */ @@ -44,6 +48,7 @@ class PresenceManager extends CachedManager { /** * Resolves a {@link PresenceResolvable} to a {@link Presence} id. + * * @param {PresenceResolvable} presence The presence resolvable to resolve * @returns {?Snowflake} */ diff --git a/packages/discord.js/src/managers/ReactionManager.js b/packages/discord.js/src/managers/ReactionManager.js index 3659edca69fe..3b776f873c6f 100644 --- a/packages/discord.js/src/managers/ReactionManager.js +++ b/packages/discord.js/src/managers/ReactionManager.js @@ -1,11 +1,12 @@ 'use strict'; const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { MessageReaction } = require('../structures/MessageReaction.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for reactions and holds their cache. + * * @extends {CachedManager} */ class ReactionManager extends CachedManager { @@ -14,6 +15,7 @@ class ReactionManager extends CachedManager { /** * The message that this manager belongs to + * * @type {Message} */ this.message = message; @@ -25,20 +27,23 @@ class ReactionManager extends CachedManager { /** * The reaction cache of this manager + * * @type {Collection} * @name ReactionManager#cache */ /** * Data that can be resolved to a MessageReaction object. This can be: - * * A MessageReaction - * * A Snowflake - * * The Unicode representation of an emoji + * A MessageReaction + * A Snowflake + * The Unicode representation of an emoji + * * @typedef {MessageReaction|Snowflake} MessageReactionResolvable */ /** * Resolves a {@link MessageReactionResolvable} to a {@link MessageReaction} object. + * * @method resolve * @memberof ReactionManager * @instance @@ -48,6 +53,7 @@ class ReactionManager extends CachedManager { /** * Resolves a {@link MessageReactionResolvable} to a {@link MessageReaction} id. + * * @method resolveId * @memberof ReactionManager * @instance @@ -57,6 +63,7 @@ class ReactionManager extends CachedManager { /** * Removes all reactions from a message. + * * @returns {Promise} */ async removeAll() { diff --git a/packages/discord.js/src/managers/ReactionUserManager.js b/packages/discord.js/src/managers/ReactionUserManager.js index bafe623ae210..e3cc7467cd11 100644 --- a/packages/discord.js/src/managers/ReactionUserManager.js +++ b/packages/discord.js/src/managers/ReactionUserManager.js @@ -3,12 +3,13 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { ReactionType, Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { User } = require('../structures/User.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for users who reacted to a reaction and stores their cache. + * * @extends {CachedManager} */ class ReactionUserManager extends CachedManager { @@ -17,6 +18,7 @@ class ReactionUserManager extends CachedManager { /** * The reaction that this manager belongs to + * * @type {MessageReaction} */ this.reaction = reaction; @@ -24,13 +26,15 @@ class ReactionUserManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name ReactionUserManager#cache */ /** * Options used to fetch users who gave a reaction. - * @typedef {Object} FetchReactionUsersOptions + * + * @typedef {object} FetchReactionUsersOptions * @property {ReactionType} [type=ReactionType.Normal] The reaction type to fetch * @property {number} [limit=100] The maximum amount of users to fetch, defaults to `100` * @property {Snowflake} [after] Limit fetching users to those with an id greater than the supplied id @@ -38,6 +42,7 @@ class ReactionUserManager extends CachedManager { /** * Fetches all the users that gave this reaction. Resolves with a collection of users, mapped by their ids. + * * @param {FetchReactionUsersOptions} [options] Options for fetching the users * @returns {Promise>} */ @@ -54,12 +59,14 @@ class ReactionUserManager extends CachedManager { this.cache.set(user.id, user); users.set(user.id, user); } + return users; } /** * Removes a user from this reaction. - * @param {UserResolvable} [user=this.client.user] The user to remove the reaction of + * + * @param {UserResolvable} [user] The user to remove the reaction of * @returns {Promise} */ async remove(user = this.client.user) { diff --git a/packages/discord.js/src/managers/RoleManager.js b/packages/discord.js/src/managers/RoleManager.js index 3aa91aa8cb42..3fb9f8ff5568 100644 --- a/packages/discord.js/src/managers/RoleManager.js +++ b/packages/discord.js/src/managers/RoleManager.js @@ -3,17 +3,18 @@ const process = require('node:process'); const { Collection } = require('@discordjs/collection'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { Role } = require('../structures/Role.js'); const { resolveImage } = require('../util/DataResolver.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); const { setPosition, resolveColor } = require('../util/Util.js'); +const { CachedManager } = require('./CachedManager.js'); let cacheWarningEmitted = false; /** * Manages API methods for roles and stores their cache. + * * @extends {CachedManager} */ class RoleManager extends CachedManager { @@ -29,6 +30,7 @@ class RoleManager extends CachedManager { /** * The guild belonging to this manager + * * @type {Guild} */ this.guild = guild; @@ -36,6 +38,7 @@ class RoleManager extends CachedManager { /** * The role cache of this manager + * * @type {Collection} * @name RoleManager#cache */ @@ -46,6 +49,7 @@ class RoleManager extends CachedManager { /** * Obtains a role from Discord, or the role cache if they're already available. + * * @param {Snowflake} [id] The role's id * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise>} @@ -79,13 +83,15 @@ class RoleManager extends CachedManager { /** * Data that can be resolved to a Role object. This can be: - * * A Role - * * A Snowflake + * A Role + * A Snowflake + * * @typedef {Role|Snowflake} RoleResolvable */ /** * Resolves a {@link RoleResolvable} to a {@link Role} object. + * * @method resolve * @memberof RoleManager * @instance @@ -95,6 +101,7 @@ class RoleManager extends CachedManager { /** * Resolves a {@link RoleResolvable} to a {@link Role} id. + * * @method resolveId * @memberof RoleManager * @instance @@ -104,7 +111,8 @@ class RoleManager extends CachedManager { /** * Options used to create a new role. - * @typedef {Object} RoleCreateOptions + * + * @typedef {object} RoleCreateOptions * @property {string} [name] The name of the new role * @property {ColorResolvable} [color] The data to create the role with * @property {boolean} [hoist] Whether or not the new role should be hoisted @@ -121,6 +129,7 @@ class RoleManager extends CachedManager { /** * Creates a new role in the guild with given information. * The position will silently reset to 1 if an invalid one is provided, or none. + * * @param {RoleCreateOptions} [options] Options for creating the new role * @returns {Promise} * @example @@ -139,7 +148,8 @@ class RoleManager extends CachedManager { * .catch(console.error); */ async create(options = {}) { - let { name, color, hoist, permissions, position, mentionable, reason, icon, unicodeEmoji } = options; + let { color, permissions, icon } = options; + const { name, hoist, position, mentionable, reason, unicodeEmoji } = options; color &&= resolveColor(color); if (permissions !== undefined) permissions = new PermissionsBitField(permissions); if (icon) { @@ -170,12 +180,14 @@ class RoleManager extends CachedManager { /** * Options for editing a role + * * @typedef {RoleData} RoleEditOptions * @property {string} [reason] The reason for editing this role */ /** * Edits a role of the guild. + * * @param {RoleResolvable} role The role to edit * @param {RoleEditOptions} options The options to provide * @returns {Promise} @@ -210,18 +222,19 @@ class RoleManager extends CachedManager { unicode_emoji: options.unicodeEmoji, }; - const d = await this.client.rest.patch(Routes.guildRole(this.guild.id, resolvedRole.id), { + const data = await this.client.rest.patch(Routes.guildRole(this.guild.id, resolvedRole.id), { body, reason: options.reason, }); const clone = resolvedRole._clone(); - clone._patch(d); + clone._patch(data); return clone; } /** * Deletes a role. + * * @param {RoleResolvable} role The role to delete * @param {string} [reason] Reason for deleting the role * @returns {Promise} @@ -239,6 +252,7 @@ class RoleManager extends CachedManager { /** * Sets the new position of the role. + * * @param {RoleResolvable} role The role to change the position of * @param {number} position The new position for the role * @param {SetRolePositionOptions} [options] Options for setting the position @@ -271,13 +285,15 @@ class RoleManager extends CachedManager { /** * The data needed for updating a guild role's position - * @typedef {Object} GuildRolePosition + * + * @typedef {object} GuildRolePosition * @property {RoleResolvable} role The role's id * @property {number} position The position to update */ /** * Batch-updates the guild's role positions + * * @param {GuildRolePosition[]} rolePositions Role positions to update * @returns {Promise} * @example @@ -302,6 +318,7 @@ class RoleManager extends CachedManager { /** * Compares the positions of two roles. + * * @param {RoleResolvable} role1 First role to compare * @param {RoleResolvable} role2 Second role to compare * @returns {number} Negative number if the first role's position is lower (second role's is higher), @@ -327,6 +344,7 @@ class RoleManager extends CachedManager { /** * Gets the managed role a user created when joining the guild, if any * Only ever available for bots + * * @param {UserResolvable} user The user to access the bot role for * @returns {?Role} */ @@ -338,6 +356,7 @@ class RoleManager extends CachedManager { /** * The `@everyone` role of the guild + * * @type {Role} * @readonly */ @@ -347,6 +366,7 @@ class RoleManager extends CachedManager { /** * The premium subscriber role of the guild, if any + * * @type {?Role} * @readonly */ @@ -356,6 +376,7 @@ class RoleManager extends CachedManager { /** * The role with the highest position in the cache + * * @type {Role} * @readonly */ diff --git a/packages/discord.js/src/managers/StageInstanceManager.js b/packages/discord.js/src/managers/StageInstanceManager.js index 13f793011112..5d0f21b4e4e3 100644 --- a/packages/discord.js/src/managers/StageInstanceManager.js +++ b/packages/discord.js/src/managers/StageInstanceManager.js @@ -1,12 +1,13 @@ 'use strict'; const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { StageInstance } = require('../structures/StageInstance.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for {@link StageInstance} objects and holds their cache. + * * @extends {CachedManager} */ class StageInstanceManager extends CachedManager { @@ -15,6 +16,7 @@ class StageInstanceManager extends CachedManager { /** * The guild this manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -22,13 +24,15 @@ class StageInstanceManager extends CachedManager { /** * The cache of this Manager + * * @type {Collection} * @name StageInstanceManager#cache */ /** * Options used to create a stage instance. - * @typedef {Object} StageInstanceCreateOptions + * + * @typedef {object} StageInstanceCreateOptions * @property {string} topic The topic of the stage instance * @property {StageInstancePrivacyLevel} [privacyLevel] The privacy level of the stage instance * @property {boolean} [sendStartNotification] Whether to notify `@everyone` that the stage instance has started @@ -38,13 +42,15 @@ class StageInstanceManager extends CachedManager { /** * Data that can be resolved to a Stage Channel object. This can be: - * * A StageChannel - * * A Snowflake + * A StageChannel + * A Snowflake + * * @typedef {StageChannel|Snowflake} StageChannelResolvable */ /** * Creates a new stage instance. + * * @param {StageChannelResolvable} channel The stage channel to associate the created stage instance to * @param {StageInstanceCreateOptions} options The options to create the stage instance * @returns {Promise} @@ -80,6 +86,7 @@ class StageInstanceManager extends CachedManager { /** * Fetches the stage instance associated with a stage channel, if it exists. + * * @param {StageChannelResolvable} channel The stage channel whose associated stage instance is to be fetched * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise} @@ -104,13 +111,15 @@ class StageInstanceManager extends CachedManager { /** * Options used to edit an existing stage instance. - * @typedef {Object} StageInstanceEditOptions + * + * @typedef {object} StageInstanceEditOptions * @property {string} [topic] The new topic of the stage instance * @property {StageInstancePrivacyLevel} [privacyLevel] The new privacy level of the stage instance */ /** * Edits an existing stage instance. + * * @param {StageChannelResolvable} channel The stage channel whose associated stage instance is to be edited * @param {StageInstanceEditOptions} options The options to edit the stage instance * @returns {Promise} @@ -125,7 +134,7 @@ class StageInstanceManager extends CachedManager { const channelId = this.guild.channels.resolveId(channel); if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve); - let { topic, privacyLevel } = options; + const { topic, privacyLevel } = options; const data = await this.client.rest.patch(Routes.stageInstance(channelId), { body: { @@ -145,6 +154,7 @@ class StageInstanceManager extends CachedManager { /** * Deletes an existing stage instance. + * * @param {StageChannelResolvable} channel The stage channel whose associated stage instance is to be deleted * @returns {Promise} */ diff --git a/packages/discord.js/src/managers/SubscriptionManager.js b/packages/discord.js/src/managers/SubscriptionManager.js index ce346d6fa0e4..cfb2e1b35815 100644 --- a/packages/discord.js/src/managers/SubscriptionManager.js +++ b/packages/discord.js/src/managers/SubscriptionManager.js @@ -3,13 +3,14 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { Subscription } = require('../structures/Subscription.js'); const { resolveSKUId } = require('../util/Util.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for subscriptions and stores their cache. + * * @extends {CachedManager} */ class SubscriptionManager extends CachedManager { @@ -19,12 +20,14 @@ class SubscriptionManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name SubscriptionManager#cache */ /** * Options used to fetch a subscription + * * @typedef {BaseFetchOptions} FetchSubscriptionOptions * @property {SKUResolvable} sku The SKU to fetch the subscription for * @property {Snowflake} subscriptionId The id of the subscription to fetch @@ -32,7 +35,8 @@ class SubscriptionManager extends CachedManager { /** * Options used to fetch subscriptions - * @typedef {Object} FetchSubscriptionsOptions + * + * @typedef {object} FetchSubscriptionsOptions * @property {Snowflake} [after] Consider only subscriptions after this subscription id * @property {Snowflake} [before] Consider only subscriptions before this subscription id * @property {number} [limit] The maximum number of subscriptions to fetch @@ -43,7 +47,8 @@ class SubscriptionManager extends CachedManager { /** * Fetches subscriptions for this application - * @param {FetchSubscriptionOptions|FetchSubscriptionsOptions} [options={}] Options for fetching the subscriptions + * + * @param {FetchSubscriptionOptions|FetchSubscriptionsOptions} [options] Options for fetching the subscriptions * @returns {Promise>} */ async fetch(options = {}) { diff --git a/packages/discord.js/src/managers/ThreadManager.js b/packages/discord.js/src/managers/ThreadManager.js index ca456cad7a90..7eea8b8ab8f4 100644 --- a/packages/discord.js/src/managers/ThreadManager.js +++ b/packages/discord.js/src/managers/ThreadManager.js @@ -3,13 +3,14 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { ThreadChannel } = require('../structures/ThreadChannel.js'); const { MakeCacheOverrideSymbol } = require('../util/Symbols.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for thread-based channels and stores their cache. + * * @extends {CachedManager} */ class ThreadManager extends CachedManager { @@ -20,6 +21,7 @@ class ThreadManager extends CachedManager { /** * The channel this Manager belongs to + * * @type {TextChannel|AnnouncementChannel|ForumChannel|MediaChannel} */ this.channel = channel; @@ -27,13 +29,15 @@ class ThreadManager extends CachedManager { /** * Data that can be resolved to a Thread Channel object. This can be: - * * A ThreadChannel object - * * A Snowflake + * A ThreadChannel object + * A Snowflake + * * @typedef {ThreadChannel|Snowflake} ThreadChannelResolvable */ /** * The cache of this Manager + * * @type {Collection} * @name ThreadManager#cache */ @@ -47,6 +51,7 @@ class ThreadManager extends CachedManager { /** * Resolves a {@link ThreadChannelResolvable} to a {@link ThreadChannel} object. + * * @method resolve * @memberof ThreadManager * @instance @@ -56,6 +61,7 @@ class ThreadManager extends CachedManager { /** * Resolves a {@link ThreadChannelResolvable} to a {@link ThreadChannel} id. + * * @method resolveId * @memberof ThreadManager * @instance @@ -65,12 +71,14 @@ class ThreadManager extends CachedManager { /** * Options for fetching multiple threads. - * @typedef {Object} FetchThreadsOptions + * + * @typedef {object} FetchThreadsOptions * @property {FetchArchivedThreadOptions} [archived] Options used to fetch archived threads */ /** * Obtains a thread from Discord, or the channel cache if it's already available. + * * @param {ThreadChannelResolvable|FetchThreadsOptions} [options] The options to fetch threads. If it is a * ThreadChannelResolvable then the specified thread will be fetched. Fetches all active threads if `undefined` * @param {BaseFetchOptions} [cacheOptions] Additional options for this fetch. The `force` field gets ignored @@ -95,20 +103,23 @@ class ThreadManager extends CachedManager { if (options.archived) { return this.fetchArchived(options.archived, cache); } + return this.fetchActive(cache); } /** * Data that can be resolved to a Date object. This can be: - * * A Date object - * * A number representing a timestamp - * * An {@link https://en.wikipedia.org/wiki/ISO_8601 ISO 8601} string + * A Date object + * A number representing a timestamp + * An {@link https://en.wikipedia.org/wiki/ISO_8601 ISO 8601} string + * * @typedef {Date|number|string} DateResolvable */ /** * The options used to fetch archived threads. - * @typedef {Object} FetchArchivedThreadOptions + * + * @typedef {object} FetchArchivedThreadOptions * @property {string} [type='public'] The type of threads to fetch (`public` or `private`) * @property {boolean} [fetchAll=false] Whether to fetch **all** archived threads when `type` is `private` * This property requires the {@link PermissionFlagsBits.ManageThreads} permission if `true`. @@ -120,6 +131,7 @@ class ThreadManager extends CachedManager { /** * Data returned from fetching multiple threads. + * * @typedef {FetchedThreads} FetchedThreadsMore * @property {?boolean} hasMore Whether there are potentially additional threads that require a subsequent call */ @@ -128,8 +140,9 @@ class ThreadManager extends CachedManager { * Obtains a set of archived threads from Discord. * This method requires the {@link PermissionFlagsBits.ReadMessageHistory} permission * in the parent channel. + * * @param {FetchArchivedThreadOptions} [options] The options to fetch archived threads - * @param {boolean} [cache=true] Whether to cache the new thread objects if they aren't already + * @param {boolean} [cache] Whether to cache the new thread objects if they aren't already * @returns {Promise} */ async fetchArchived({ type = 'public', fetchAll = false, before, limit } = {}, cache = true) { @@ -137,6 +150,7 @@ class ThreadManager extends CachedManager { if (type === 'private' && !fetchAll) { path = Routes.channelJoinedArchivedThreads(this.channel.id); } + let timestamp; let id; const query = makeURLSearchParams({ limit }); @@ -166,7 +180,8 @@ class ThreadManager extends CachedManager { /** * Obtains all active threads in the channel. - * @param {boolean} [cache=true] Whether to cache the fetched data + * + * @param {boolean} [cache] Whether to cache the fetched data * @returns {Promise} */ async fetchActive(cache = true) { diff --git a/packages/discord.js/src/managers/ThreadMemberManager.js b/packages/discord.js/src/managers/ThreadMemberManager.js index 901817a312a7..e024169064c2 100644 --- a/packages/discord.js/src/managers/ThreadMemberManager.js +++ b/packages/discord.js/src/managers/ThreadMemberManager.js @@ -3,12 +3,13 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { ThreadMember } = require('../structures/ThreadMember.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for GuildMembers and stores their cache. + * * @extends {CachedManager} */ class ThreadMemberManager extends CachedManager { @@ -17,6 +18,7 @@ class ThreadMemberManager extends CachedManager { /** * The thread this manager belongs to + * * @type {ThreadChannel} */ this.thread = thread; @@ -24,6 +26,7 @@ class ThreadMemberManager extends CachedManager { /** * The cache of this Manager + * * @type {Collection} * @name ThreadMemberManager#cache */ @@ -40,15 +43,17 @@ class ThreadMemberManager extends CachedManager { /** * Fetches the client user as a ThreadMember of the thread. + * * @param {BaseFetchOptions} [options] The options for fetching the member * @returns {Promise} */ - fetchMe(options) { + async fetchMe(options) { return this.fetch({ ...options, member: this.client.user.id }); } /** * The client user as a ThreadMember of this ThreadChannel + * * @type {?ThreadMember} * @readonly */ @@ -58,13 +63,15 @@ class ThreadMemberManager extends CachedManager { /** * Data that resolves to give a ThreadMember object. This can be: - * * A ThreadMember object - * * A User resolvable + * A ThreadMember object + * A User resolvable + * * @typedef {ThreadMember|UserResolvable} ThreadMemberResolvable */ /** * Resolves a {@link ThreadMemberResolvable} to a {@link ThreadMember} object. + * * @param {ThreadMemberResolvable} member The user that is part of the thread * @returns {?GuildMember} */ @@ -78,6 +85,7 @@ class ThreadMemberManager extends CachedManager { /** * Resolves a {@link ThreadMemberResolvable} to a {@link ThreadMember} id string. + * * @param {ThreadMemberResolvable} member The user that is part of the guild * @returns {?Snowflake} */ @@ -90,6 +98,7 @@ class ThreadMemberManager extends CachedManager { /** * Adds a member to the thread. + * * @param {UserResolvable|'@me'} member The member to add * @returns {Promise} */ @@ -102,6 +111,7 @@ class ThreadMemberManager extends CachedManager { /** * Remove a user from the thread. + * * @param {UserResolvable|'@me'} member The member to remove * @returns {Promise} */ @@ -114,6 +124,7 @@ class ThreadMemberManager extends CachedManager { /** * Options used to fetch a thread member. + * * @typedef {BaseFetchOptions} FetchThreadMemberOptions * @property {ThreadMemberResolvable} member The thread member to fetch * @property {boolean} [withMember] Whether to also return the guild member associated with this thread member @@ -122,7 +133,8 @@ class ThreadMemberManager extends CachedManager { /** * Options used to fetch multiple thread members with guild member data. * With `withMember` set to `true`, pagination is enabled. - * @typedef {Object} FetchThreadMembersWithGuildMemberDataOptions + * + * @typedef {object} FetchThreadMembersWithGuildMemberDataOptions * @property {true} withMember Whether to also return the guild member data * @property {Snowflake} [after] Consider only thread members after this id * @property {number} [limit] The maximum number of thread members to return @@ -131,13 +143,15 @@ class ThreadMemberManager extends CachedManager { /** * Options used to fetch multiple thread members without guild member data. - * @typedef {Object} FetchThreadMembersWithoutGuildMemberDataOptions + * + * @typedef {object} FetchThreadMembersWithoutGuildMemberDataOptions * @property {false} [withMember] Whether to also return the guild member data * @property {boolean} [cache] Whether to cache the fetched thread members */ /** * Options used to fetch multiple thread members. + * * @typedef {FetchThreadMembersWithGuildMemberDataOptions| * FetchThreadMembersWithoutGuildMemberDataOptions} FetchThreadMembersOptions */ @@ -145,11 +159,12 @@ class ThreadMemberManager extends CachedManager { /** * Fetches thread member(s) from Discord. * This method requires the {@link GatewayIntentBits.GuildMembers} privileged gateway intent. + * * @param {ThreadMemberResolvable|FetchThreadMemberOptions|FetchThreadMembersOptions} [options] * Options for fetching thread member(s) * @returns {Promise>} */ - fetch(options) { + async fetch(options) { if (!options) return this._fetchMany(); const { member, withMember, cache, force } = options; const resolvedMember = this.resolveId(member ?? options); diff --git a/packages/discord.js/src/managers/UserManager.js b/packages/discord.js/src/managers/UserManager.js index b2fb7081724a..7f91be28b1cf 100644 --- a/packages/discord.js/src/managers/UserManager.js +++ b/packages/discord.js/src/managers/UserManager.js @@ -1,15 +1,16 @@ 'use strict'; const { ChannelType, Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { GuildMember } = require('../structures/GuildMember.js'); const { Message } = require('../structures/Message.js'); const { ThreadMember } = require('../structures/ThreadMember.js'); const { User } = require('../structures/User.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for users and stores their cache. + * * @extends {CachedManager} */ class UserManager extends CachedManager { @@ -19,22 +20,25 @@ class UserManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name UserManager#cache */ /** * Data that resolves to give a User object. This can be: - * * A User object - * * A Snowflake - * * A Message object (resolves to the message author) - * * A GuildMember object - * * A ThreadMember object + * A User object + * A Snowflake + * A Message object (resolves to the message author) + * A GuildMember object + * A ThreadMember object + * * @typedef {User|Snowflake|Message|GuildMember|ThreadMember} UserResolvable */ /** * The DM between the client's user and a user + * * @param {Snowflake} userId The user id * @returns {?DMChannel} * @private @@ -48,6 +52,7 @@ class UserManager extends CachedManager { /** * Creates a {@link DMChannel} between the client and a user. + * * @param {UserResolvable} user The UserResolvable to identify * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise} @@ -66,6 +71,7 @@ class UserManager extends CachedManager { /** * Deletes a {@link DMChannel} (if one exists) between the client and a user. Resolves with the channel if successful. + * * @param {UserResolvable} user The UserResolvable to identify * @returns {Promise} */ @@ -80,6 +86,7 @@ class UserManager extends CachedManager { /** * Obtains a user from Discord, or the user cache if it's already available. + * * @param {UserResolvable} user The user to fetch * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise} @@ -97,6 +104,7 @@ class UserManager extends CachedManager { /** * Sends a message to a user. + * * @param {UserResolvable} user The UserResolvable to identify * @param {string|MessagePayload|MessageCreateOptions} options The options to provide * @returns {Promise} @@ -107,6 +115,7 @@ class UserManager extends CachedManager { /** * Resolves a {@link UserResolvable} to a {@link User} object. + * * @param {UserResolvable} user The UserResolvable to identify * @returns {?User} */ @@ -118,6 +127,7 @@ class UserManager extends CachedManager { /** * Resolves a {@link UserResolvable} to a {@link User} id. + * * @param {UserResolvable} user The UserResolvable to identify * @returns {?Snowflake} */ diff --git a/packages/discord.js/src/managers/VoiceStateManager.js b/packages/discord.js/src/managers/VoiceStateManager.js index 1af9eaa2667a..dc720647ef4a 100644 --- a/packages/discord.js/src/managers/VoiceStateManager.js +++ b/packages/discord.js/src/managers/VoiceStateManager.js @@ -1,11 +1,12 @@ 'use strict'; const { Routes } = require('discord-api-types/v10'); -const { CachedManager } = require('./CachedManager.js'); const { VoiceState } = require('../structures/VoiceState.js'); +const { CachedManager } = require('./CachedManager.js'); /** * Manages API methods for VoiceStates and stores their cache. + * * @extends {CachedManager} */ class VoiceStateManager extends CachedManager { @@ -14,6 +15,7 @@ class VoiceStateManager extends CachedManager { /** * The guild this manager belongs to + * * @type {Guild} */ this.guild = guild; @@ -21,6 +23,7 @@ class VoiceStateManager extends CachedManager { /** * The cache of this manager + * * @type {Collection} * @name VoiceStateManager#cache */ @@ -36,6 +39,7 @@ class VoiceStateManager extends CachedManager { /** * Obtains a user's voice state from discord or from the cache if it's already available. + * * @param {UserResolvable|'@me'} member The member whose voice state is to be fetched * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise} @@ -51,6 +55,7 @@ class VoiceStateManager extends CachedManager { const existing = this.cache.get(id === '@me' ? this.client.user.id : id); if (existing) return existing; } + const data = await this.client.rest.get(Routes.guildVoiceState(this.guild.id, id)); return this._add(data, cache); } diff --git a/packages/discord.js/src/sharding/Shard.js b/packages/discord.js/src/sharding/Shard.js index 72816ae244a4..d43b59831e5e 100644 --- a/packages/discord.js/src/sharding/Shard.js +++ b/packages/discord.js/src/sharding/Shard.js @@ -1,3 +1,6 @@ +/* eslint-disable promise/prefer-await-to-then */ +/* eslint-disable promise/prefer-await-to-callbacks */ +/* eslint-disable @typescript-eslint/no-use-before-define */ 'use strict'; const path = require('node:path'); @@ -17,6 +20,7 @@ let Worker = null; * A self-contained shard created by the {@link ShardingManager}. Each one has a {@link ChildProcess} that contains * an instance of the bot and its {@link Client}. When its child process/worker exits for any reason, the shard will * spawn a new one to replace it as necessary. + * * @extends {AsyncEventEmitter} */ class Shard extends AsyncEventEmitter { @@ -34,65 +38,76 @@ class Shard extends AsyncEventEmitter { /** * Manager that created the shard + * * @type {ShardingManager} */ this.manager = manager; /** * The shard's id in the manager + * * @type {number} */ this.id = id; /** * Whether to pass silent flag to the shard's process (only when {@link ShardingManager#mode} is `process`) + * * @type {boolean} */ this.silent = manager.silent; /** * Arguments for the shard's process/worker + * * @type {string[]} */ this.args = manager.shardArgs ?? []; /** * Arguments for the shard's process/worker executable + * * @type {string[]} */ this.execArgv = manager.execArgv; /** * Environment variables for the shard's process, or workerData for the shard's worker - * @type {Object} + * + * @type {object} */ - this.env = Object.assign({}, process.env, { + this.env = { + ...process.env, SHARDING_MANAGER: true, SHARDS: this.id, SHARD_COUNT: this.manager.totalShards, DISCORD_TOKEN: this.manager.token, - }); + }; /** * Whether the shard's {@link Client} is ready + * * @type {boolean} */ this.ready = false; /** * Process of the shard (if {@link ShardingManager#mode} is `process`) + * * @type {?ChildProcess} */ this.process = null; /** * Worker of the shard (if {@link ShardingManager#mode} is `worker`) + * * @type {?Worker} */ this.worker = null; /** * Ongoing promises for calls to {@link Shard#eval}, mapped by the `script` they were called with + * * @type {Map} * @private */ @@ -100,6 +115,7 @@ class Shard extends AsyncEventEmitter { /** * Ongoing promises for calls to {@link Shard#fetchClientValue}, mapped by the `prop` they were called with + * * @type {Map} * @private */ @@ -107,6 +123,7 @@ class Shard extends AsyncEventEmitter { /** * Listener function for the {@link ChildProcess}' `exit` event + * * @type {Function} * @private */ @@ -116,7 +133,8 @@ class Shard extends AsyncEventEmitter { /** * Forks a child process or creates a worker thread for the shard. * You should not need to call this manually. - * @param {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready + * + * @param {number} [timeout] The amount in milliseconds to wait until the {@link Client} has become ready * before resolving (`-1` or `Infinity` for no wait) * @returns {Promise} */ @@ -156,6 +174,7 @@ class Shard extends AsyncEventEmitter { /** * Emitted upon the creation of the shard's child process/worker. + * * @event Shard#spawn * @param {ChildProcess|Worker} process Child process/worker that was created */ @@ -214,7 +233,8 @@ class Shard extends AsyncEventEmitter { /** * Options used to respawn a shard. - * @typedef {Object} ShardRespawnOptions + * + * @typedef {object} ShardRespawnOptions * @property {number} [delay=500] How long to wait between killing the process/worker and * restarting it (in milliseconds) * @property {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} @@ -223,6 +243,7 @@ class Shard extends AsyncEventEmitter { /** * Kills and restarts the shard's process/worker. + * * @param {ShardRespawnOptions} [options] Options for respawning the shard * @returns {Promise} */ @@ -234,10 +255,11 @@ class Shard extends AsyncEventEmitter { /** * Sends a message to the shard's process/worker. + * * @param {*} message Message to send to the shard * @returns {Promise} */ - send(message) { + async send(message) { return new Promise((resolve, reject) => { if (this.process) { this.process.send(message, err => { @@ -253,6 +275,7 @@ class Shard extends AsyncEventEmitter { /** * Fetches a client property value of the shard. + * * @param {string} prop Name of the client property to get, using periods for nesting * @returns {Promise<*>} * @example @@ -277,18 +300,18 @@ class Shard extends AsyncEventEmitter { child.removeListener('message', listener); this.decrementMaxListeners(child); this._fetches.delete(prop); - if (!message._error) resolve(message._result); - else reject(makeError(message._error)); + if (message._error) reject(makeError(message._error)); + else resolve(message._result); }; this.incrementMaxListeners(child); child.on('message', listener); - this.send({ _fetchProp: prop }).catch(err => { + this.send({ _fetchProp: prop }).catch(error => { child.removeListener('message', listener); this.decrementMaxListeners(child); this._fetches.delete(prop); - reject(err); + reject(error); }); }); @@ -298,6 +321,7 @@ class Shard extends AsyncEventEmitter { /** * Evaluates a script or function on the shard, in the context of the {@link Client}. + * * @param {string|Function} script JavaScript to run on the shard * @param {*} [context] The context for the eval * @returns {Promise<*>} Result of the script execution @@ -322,18 +346,18 @@ class Shard extends AsyncEventEmitter { child.removeListener('message', listener); this.decrementMaxListeners(child); this._evals.delete(_eval); - if (!message._error) resolve(message._result); - else reject(makeError(message._error)); + if (message._error) reject(makeError(message._error)); + else resolve(message._result); }; this.incrementMaxListeners(child); child.on('message', listener); - this.send({ _eval }).catch(err => { + this.send({ _eval }).catch(error => { child.removeListener('message', listener); this.decrementMaxListeners(child); this._evals.delete(_eval); - reject(err); + reject(error); }); }); @@ -343,6 +367,7 @@ class Shard extends AsyncEventEmitter { /** * Handles a message received from the child process/worker. + * * @param {*} message Message received * @private */ @@ -353,6 +378,7 @@ class Shard extends AsyncEventEmitter { this.ready = true; /** * Emitted upon the shard's {@link Client#event:clientReady} event. + * * @event Shard#ready */ this.emit(ShardEvents.Ready); @@ -364,6 +390,7 @@ class Shard extends AsyncEventEmitter { this.ready = false; /** * Emitted upon the shard's {@link WebSocketShardEvents#Closed} event. + * * @event Shard#disconnect */ this.emit(ShardEvents.Disconnect); @@ -375,6 +402,7 @@ class Shard extends AsyncEventEmitter { this.ready = true; /** * Emitted upon the shard's {@link WebSocketShardEvents#Resumed} event. + * * @event Shard#resume */ this.emit(ShardEvents.Resume); @@ -385,8 +413,8 @@ class Shard extends AsyncEventEmitter { if (message._sFetchProp) { const resp = { _sFetchProp: message._sFetchProp, _sFetchPropShard: message._sFetchPropShard }; this.manager.fetchClientValues(message._sFetchProp, message._sFetchPropShard).then( - results => this.send({ ...resp, _result: results }), - err => this.send({ ...resp, _error: makePlainError(err) }), + async results => this.send({ ...resp, _result: results }), + async error => this.send({ ...resp, _error: makePlainError(error) }), ); return; } @@ -395,8 +423,8 @@ class Shard extends AsyncEventEmitter { if (message._sEval) { const resp = { _sEval: message._sEval, _sEvalShard: message._sEvalShard }; this.manager._performOnShards('eval', [message._sEval], message._sEvalShard).then( - results => this.send({ ...resp, _result: results }), - err => this.send({ ...resp, _error: makePlainError(err) }), + async results => this.send({ ...resp, _result: results }), + async error => this.send({ ...resp, _error: makePlainError(error) }), ); return; } @@ -413,6 +441,7 @@ class Shard extends AsyncEventEmitter { /** * Emitted upon receiving a message from the child process/worker. + * * @event Shard#message * @param {*} message Message that was received */ @@ -421,14 +450,16 @@ class Shard extends AsyncEventEmitter { /** * Handles the shard's process/worker exiting. - * @param {boolean} [respawn=this.manager.respawn] Whether to spawn the shard again + * + * @param {boolean} [respawn] Whether to spawn the shard again * @param {number} [timeout] The amount in milliseconds to wait until the {@link Client} * has become ready (`-1` or `Infinity` for no wait) * @private */ - _handleExit(respawn = this.manager.respawn, timeout) { + _handleExit(respawn = this.manager.respawn, timeout = undefined) { /** * Emitted upon the shard's child process/worker exiting. + * * @event Shard#death * @param {ChildProcess|Worker} process Child process/worker that exited */ @@ -440,11 +471,12 @@ class Shard extends AsyncEventEmitter { this._evals.clear(); this._fetches.clear(); - if (respawn) this.spawn(timeout).catch(err => this.emit(ShardEvents.Error, err)); + if (respawn) this.spawn(timeout).catch(error => this.emit(ShardEvents.Error, error)); } /** * Increments max listeners by one for a given emitter, if they are not zero. + * * @param {Worker|ChildProcess} emitter The emitter that emits the events. * @private */ @@ -457,6 +489,7 @@ class Shard extends AsyncEventEmitter { /** * Decrements max listeners by one for a given emitter, if they are not zero. + * * @param {Worker|ChildProcess} emitter The emitter that emits the events. * @private */ diff --git a/packages/discord.js/src/sharding/ShardClientUtil.js b/packages/discord.js/src/sharding/ShardClientUtil.js index 980bfc1ffea6..7057bd53b6c9 100644 --- a/packages/discord.js/src/sharding/ShardClientUtil.js +++ b/packages/discord.js/src/sharding/ShardClientUtil.js @@ -1,3 +1,5 @@ +/* eslint-disable promise/prefer-await-to-callbacks */ +/* eslint-disable promise/prefer-await-to-then */ 'use strict'; const process = require('node:process'); @@ -15,18 +17,21 @@ class ShardClientUtil { constructor(client, mode) { /** * Client for the shard + * * @type {Client} */ this.client = client; /** * Mode the shard was spawned with + * * @type {ShardingManagerMode} */ this.mode = mode; /** * Message port for the master process (only when {@link ShardClientUtil#mode} is `worker`) + * * @type {?MessagePort} */ this.parentPort = null; @@ -62,11 +67,12 @@ class ShardClientUtil { /** * Sends a message to the master process. + * * @param {*} message Message to send * @returns {Promise} * @emits Shard#message */ - send(message) { + async send(message) { return new Promise((resolve, reject) => { switch (this.mode) { case 'process': @@ -85,6 +91,7 @@ class ShardClientUtil { /** * Fetches a client property value of each shard, or a given shard. + * * @param {string} prop Name of the client property to get, using periods for nesting * @param {number} [shard] Shard to fetch property from, all if undefined * @returns {Promise<*|Array<*>>} @@ -94,7 +101,7 @@ class ShardClientUtil { * .catch(console.error); * @see {@link ShardingManager#fetchClientValues} */ - fetchClientValues(prop, shard) { + async fetchClientValues(prop, shard) { return new Promise((resolve, reject) => { const parent = this.parentPort ?? process; @@ -102,24 +109,26 @@ class ShardClientUtil { if (message?._sFetchProp !== prop || message._sFetchPropShard !== shard) return; parent.removeListener('message', listener); this.decrementMaxListeners(parent); - if (!message._error) resolve(message._result); - else reject(makeError(message._error)); + if (message._error) reject(makeError(message._error)); + else resolve(message._result); }; + this.incrementMaxListeners(parent); parent.on('message', listener); - this.send({ _sFetchProp: prop, _sFetchPropShard: shard }).catch(err => { + this.send({ _sFetchProp: prop, _sFetchPropShard: shard }).catch(error => { parent.removeListener('message', listener); this.decrementMaxListeners(parent); - reject(err); + reject(error); }); }); } /** * Evaluates a script or function on all shards, or a given shard, in the context of the {@link Client}s. + * * @param {Function} script JavaScript to run on each shard - * @param {BroadcastEvalOptions} [options={}] The options for the broadcast + * @param {BroadcastEvalOptions} [options] The options for the broadcast * @returns {Promise<*|Array<*>>} Results of the script execution * @example * client.shard.broadcastEval(client => client.guilds.cache.size) @@ -127,44 +136,48 @@ class ShardClientUtil { * .catch(console.error); * @see {@link ShardingManager#broadcastEval} */ - broadcastEval(script, options = {}) { + async broadcastEval(script, options = {}) { return new Promise((resolve, reject) => { const parent = this.parentPort ?? process; if (typeof script !== 'function') { reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast)); return; } + const evalScript = `(${script})(this, ${JSON.stringify(options.context)})`; const listener = message => { if (message?._sEval !== evalScript || message._sEvalShard !== options.shard) return; parent.removeListener('message', listener); this.decrementMaxListeners(parent); - if (!message._error) resolve(message._result); - else reject(makeError(message._error)); + if (message._error) reject(makeError(message._error)); + else resolve(message._result); }; + this.incrementMaxListeners(parent); parent.on('message', listener); - this.send({ _sEval: evalScript, _sEvalShard: options.shard }).catch(err => { + this.send({ _sEval: evalScript, _sEvalShard: options.shard }).catch(error => { parent.removeListener('message', listener); this.decrementMaxListeners(parent); - reject(err); + reject(error); }); }); } /** * Requests a respawn of all shards. + * * @param {MultipleShardRespawnOptions} [options] Options for respawning shards * @returns {Promise} Resolves upon the message being sent * @see {@link ShardingManager#respawnAll} */ - respawnAll({ shardDelay = 5_000, respawnDelay = 500, timeout = 30_000 } = {}) { + async respawnAll({ shardDelay = 5_000, respawnDelay = 500, timeout = 30_000 } = {}) { return this.send({ _sRespawnAll: { shardDelay, respawnDelay, timeout } }); } /** * Handles an IPC message. + * * @param {*} message Message received * @private */ @@ -176,34 +189,36 @@ class ShardClientUtil { let value = this.client; for (const prop of props) value = value[prop]; this._respond('fetchProp', { _fetchProp: message._fetchProp, _result: value }); - } catch (err) { - this._respond('fetchProp', { _fetchProp: message._fetchProp, _error: makePlainError(err) }); + } catch (error) { + this._respond('fetchProp', { _fetchProp: message._fetchProp, _error: makePlainError(error) }); } } else if (message._eval) { try { this._respond('eval', { _eval: message._eval, _result: await this.client._eval(message._eval) }); - } catch (err) { - this._respond('eval', { _eval: message._eval, _error: makePlainError(err) }); + } catch (error) { + this._respond('eval', { _eval: message._eval, _error: makePlainError(error) }); } } } /** * Sends a message to the master process, emitting an error from the client upon failure. + * * @param {string} type Type of response to send * @param {*} message Message to send * @private */ _respond(type, message) { - this.send(message).catch(err => { - const error = new Error(`Error when sending ${type} response to master process: ${err.message}`); - error.stack = err.stack; + this.send(message).catch(error_ => { + const error = new Error(`Error when sending ${type} response to master process: ${error_.message}`); + error.stack = error_.stack; /** * Emitted when the client encounters an error. * Errors thrown within this event do not have a catch handler, it is * recommended to not use async functions as `error` event handlers. See the * {@link https://nodejs.org/api/events.html#capture-rejections-of-promises Node.js documentation} * for details.) + * * @event Client#error * @param {Error} error The error encountered */ @@ -213,24 +228,27 @@ class ShardClientUtil { /** * Creates/gets the singleton of this class. + * * @param {Client} client The client to use * @param {ShardingManagerMode} mode Mode the shard was spawned with * @returns {ShardClientUtil} */ static singleton(client, mode) { - if (!this._singleton) { - this._singleton = new this(client, mode); - } else { + if (this._singleton) { client.emit( Events.Warn, 'Multiple clients created in child process/worker; only the first will handle sharding helpers.', ); + } else { + this._singleton = new this(client, mode); } + return this._singleton; } /** * Get the shard id for a given guild id. + * * @param {Snowflake} guildId Snowflake guild id to get shard id for * @param {number} shardCount Number of shards * @returns {number} @@ -243,6 +261,7 @@ class ShardClientUtil { /** * Increments max listeners by one for a given emitter, if they are not zero. + * * @param {Worker|ChildProcess} emitter The emitter that emits the events. * @private */ @@ -255,6 +274,7 @@ class ShardClientUtil { /** * Decrements max listeners by one for a given emitter, if they are not zero. + * * @param {Worker|ChildProcess} emitter The emitter that emits the events. * @private */ diff --git a/packages/discord.js/src/sharding/ShardingManager.js b/packages/discord.js/src/sharding/ShardingManager.js index c44099c1e975..3363929336d2 100644 --- a/packages/discord.js/src/sharding/ShardingManager.js +++ b/packages/discord.js/src/sharding/ShardingManager.js @@ -6,9 +6,9 @@ const process = require('node:process'); const { setTimeout: sleep } = require('node:timers/promises'); const { Collection } = require('@discordjs/collection'); const { AsyncEventEmitter } = require('@vladfrangu/async_event_emitter'); -const { Shard } = require('./Shard.js'); const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors/index.js'); const { fetchRecommendedShardCount } = require('../util/Util.js'); +const { Shard } = require('./Shard.js'); /** * This is a utility class that makes multi-process sharding of a bot an easy and painless experience. @@ -17,19 +17,22 @@ const { fetchRecommendedShardCount } = require('../util/Util.js'); * process, and there are several useful methods that utilize it in order to simplify tasks that are normally difficult * with sharding. It can spawn a specific number of shards or the amount that Discord suggests for the bot, and takes a * path to your main bot script to launch for each one. + * * @extends {AsyncEventEmitter} */ class ShardingManager extends AsyncEventEmitter { /** * The mode to spawn shards with for a {@link ShardingManager}. Can be either one of: - * * 'process' to use child processes - * * 'worker' to use {@link Worker} threads + * 'process' to use child processes + * 'worker' to use {@link Worker} threads + * * @typedef {string} ShardingManagerMode */ /** * The options to spawn shards with for a {@link ShardingManager}. - * @typedef {Object} ShardingManagerOptions + * + * @typedef {object} ShardingManagerOptions * @property {string|number} [totalShards='auto'] Number of total shards of all shard managers or "auto" * @property {string|number[]} [shardList='auto'] List of shards to spawn or "auto" * @property {ShardingManagerMode} [mode='process'] Which mode to use for shards @@ -60,16 +63,19 @@ class ShardingManager extends AsyncEventEmitter { /** * Path to the shard script file + * * @type {string} */ this.file = file; if (!file) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'specified.'); if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file); + // eslint-disable-next-line n/no-sync const stats = fs.statSync(this.file); if (!stats.isFile()) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'a file'); /** * List of shards this sharding manager spawns + * * @type {string|number[]} */ this.shardList = _options.shardList ?? 'auto'; @@ -77,13 +83,15 @@ class ShardingManager extends AsyncEventEmitter { if (!Array.isArray(this.shardList)) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array.'); } + this.shardList = [...new Set(this.shardList)]; if (this.shardList.length < 1) { throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'shardList', 'at least 1 id.'); } + if ( this.shardList.some( - shardId => typeof shardId !== 'number' || isNaN(shardId) || !Number.isInteger(shardId) || shardId < 0, + shardId => typeof shardId !== 'number' || Number.isNaN(shardId) || !Number.isInteger(shardId) || shardId < 0, ) ) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array of positive integers.'); @@ -92,16 +100,19 @@ class ShardingManager extends AsyncEventEmitter { /** * Amount of shards that all sharding managers spawn in total + * * @type {number} */ this.totalShards = _options.totalShards || 'auto'; if (this.totalShards !== 'auto') { - if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) { + if (typeof this.totalShards !== 'number' || Number.isNaN(this.totalShards)) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.'); } + if (this.totalShards < 1) { throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.'); } + if (!Number.isInteger(this.totalShards)) { throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.'); } @@ -109,6 +120,7 @@ class ShardingManager extends AsyncEventEmitter { /** * Mode for shards to spawn with + * * @type {ShardingManagerMode} */ this.mode = _options.mode; @@ -118,36 +130,42 @@ class ShardingManager extends AsyncEventEmitter { /** * Whether shards should automatically respawn upon exiting + * * @type {boolean} */ this.respawn = _options.respawn; /** * Whether to pass the silent flag to child process (only when {@link ShardingManager#mode} is `process`) + * * @type {boolean} */ this.silent = _options.silent; /** * An array of arguments to pass to shards (only when {@link ShardingManager#mode} is `process`) + * * @type {string[]} */ this.shardArgs = _options.shardArgs; /** * An array of arguments to pass to the executable (only when {@link ShardingManager#mode} is `process`) + * * @type {string[]} */ this.execArgv = _options.execArgv; /** * Token to use for obtaining the automatic shard count, and passing to shards + * * @type {?string} */ - this.token = _options.token?.replace(/^Bot\s*/i, '') ?? null; + this.token = _options.token?.replace(/^bot\s*/i, '') ?? null; /** * A collection of shards that this manager has spawned + * * @type {Collection} */ this.shards = new Collection(); @@ -160,7 +178,8 @@ class ShardingManager extends AsyncEventEmitter { /** * Creates a single shard. * Using this method is usually not necessary if you use the spawn method. - * @param {number} [id=this.shards.size] Id of the shard to create + * + * @param {number} [id] Id of the shard to create * This is usually not necessary to manually specify. * @returns {Shard} Note that the created shard needs to be explicitly spawned using its spawn method. */ @@ -169,6 +188,7 @@ class ShardingManager extends AsyncEventEmitter { this.shards.set(id, shard); /** * Emitted upon creating a shard. + * * @event ShardingManager#shardCreate * @param {Shard} shard Shard that was created */ @@ -178,7 +198,8 @@ class ShardingManager extends AsyncEventEmitter { /** * Options used to spawn multiple shards. - * @typedef {Object} MultipleShardSpawnOptions + * + * @typedef {object} MultipleShardSpawnOptions * @property {number|string} [amount=this.totalShards] Number of shards to spawn * @property {number} [delay=5500] How long to wait in between spawning each shard (in milliseconds) * @property {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready @@ -186,21 +207,25 @@ class ShardingManager extends AsyncEventEmitter { /** * Spawns multiple shards. + * * @param {MultipleShardSpawnOptions} [options] Options for spawning shards * @returns {Promise>} */ - async spawn({ amount = this.totalShards, delay = 5500, timeout = 30_000 } = {}) { + async spawn({ amount = this.totalShards, delay = 5_500, timeout = 30_000 } = {}) { // Obtain/verify the number of shards to spawn let shardAmount = amount; if (shardAmount === 'auto') { + // eslint-disable-next-line require-atomic-updates shardAmount = await fetchRecommendedShardCount(this.token); } else { - if (typeof shardAmount !== 'number' || isNaN(shardAmount)) { + if (typeof shardAmount !== 'number' || Number.isNaN(shardAmount)) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.'); } + if (shardAmount < 1) { throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.'); } + if (!Number.isInteger(shardAmount)) { throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.'); } @@ -209,8 +234,9 @@ class ShardingManager extends AsyncEventEmitter { // Make sure this many shards haven't already been spawned if (this.shards.size >= shardAmount) throw new DiscordjsError(ErrorCodes.ShardingAlreadySpawned, this.shards.size); if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== shardAmount) { - this.shardList = [...Array(shardAmount).keys()]; + this.shardList = [...Array.from({ length: shardAmount }).keys()]; } + if (this.totalShards === 'auto' || this.totalShards !== shardAmount) { this.totalShards = shardAmount; } @@ -229,7 +255,7 @@ class ShardingManager extends AsyncEventEmitter { const shard = this.createShard(shardId); promises.push(shard.spawn(timeout)); if (delay > 0 && this.shards.size !== this.shardList.length) promises.push(sleep(delay)); - await Promise.all(promises); // eslint-disable-line no-await-in-loop + await Promise.all(promises); } return this.shards; @@ -237,10 +263,11 @@ class ShardingManager extends AsyncEventEmitter { /** * Sends a message to all shards. + * * @param {*} message Message to be sent to the shards * @returns {Promise} */ - broadcast(message) { + async broadcast(message) { const promises = []; for (const shard of this.shards.values()) promises.push(shard.send(message)); return Promise.all(promises); @@ -248,26 +275,30 @@ class ShardingManager extends AsyncEventEmitter { /** * Options for {@link ShardingManager#broadcastEval} and {@link ShardClientUtil#broadcastEval}. - * @typedef {Object} BroadcastEvalOptions + * + * @typedef {object} BroadcastEvalOptions * @property {number} [shard] Shard to run script on, all if undefined * @property {*} [context] The JSON-serializable values to call the script with */ /** * Evaluates a script on all shards, or a given shard, in the context of the {@link Client}s. + * * @param {Function} script JavaScript to run on each shard - * @param {BroadcastEvalOptions} [options={}] The options for the broadcast + * @param {BroadcastEvalOptions} [options] The options for the broadcast * @returns {Promise<*|Array<*>>} Results of the script execution */ async broadcastEval(script, options = {}) { if (typeof script !== 'function') { throw new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast); } + return this._performOnShards('eval', [`(${script})(this, ${JSON.stringify(options.context)})`], options.shard); } /** * Fetches a client property value of each shard, or a given shard. + * * @param {string} prop Name of the client property to get, using periods for nesting * @param {number} [shard] Shard to fetch property from, all if undefined * @returns {Promise<*|Array<*>>} @@ -276,12 +307,13 @@ class ShardingManager extends AsyncEventEmitter { * .then(results => console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`)) * .catch(console.error); */ - fetchClientValues(prop, shard) { + async fetchClientValues(prop, shard) { return this._performOnShards('fetchClientValue', [prop], shard); } /** * Runs a method with given arguments on all shards, or a given shard. + * * @param {string} method Method name to run on each shard * @param {Array<*>} args Arguments to pass through to the method call * @param {number} [shard] Shard to run on, all if undefined @@ -307,7 +339,8 @@ class ShardingManager extends AsyncEventEmitter { /** * Options used to respawn all shards. - * @typedef {Object} MultipleShardRespawnOptions + * + * @typedef {object} MultipleShardRespawnOptions * @property {number} [shardDelay=5000] How long to wait between shards (in milliseconds) * @property {number} [respawnDelay=500] How long to wait between killing a shard's process and restarting it * (in milliseconds) @@ -317,16 +350,18 @@ class ShardingManager extends AsyncEventEmitter { /** * Kills all running shards and respawns them. + * * @param {MultipleShardRespawnOptions} [options] Options for respawning shards * @returns {Promise>} */ async respawnAll({ shardDelay = 5_000, respawnDelay = 500, timeout = 30_000 } = {}) { - let s = 0; + let shardCounter = 0; for (const shard of this.shards.values()) { const promises = [shard.respawn({ delay: respawnDelay, timeout })]; - if (++s < this.shards.size && shardDelay > 0) promises.push(sleep(shardDelay)); - await Promise.all(promises); // eslint-disable-line no-await-in-loop + if (++shardCounter < this.shards.size && shardDelay > 0) promises.push(sleep(shardDelay)); + await Promise.all(promises); } + return this.shards; } } diff --git a/packages/discord.js/src/structures/ActionRow.js b/packages/discord.js/src/structures/ActionRow.js index 12c0b382a041..9c508573ef9f 100644 --- a/packages/discord.js/src/structures/ActionRow.js +++ b/packages/discord.js/src/structures/ActionRow.js @@ -1,10 +1,11 @@ 'use strict'; -const { Component } = require('./Component.js'); const { createComponent } = require('../util/Components.js'); +const { Component } = require('./Component.js'); /** * Represents an action row + * * @extends {Component} */ class ActionRow extends Component { @@ -13,6 +14,7 @@ class ActionRow extends Component { /** * The components in this action row + * * @type {Component[]} * @readonly */ @@ -21,6 +23,7 @@ class ActionRow extends Component { /** * Returns the API-compatible JSON for this component + * * @returns {APIActionRowComponent} */ toJSON() { diff --git a/packages/discord.js/src/structures/AnnouncementChannel.js b/packages/discord.js/src/structures/AnnouncementChannel.js index e25dbe706ac0..0c1919b28bbf 100644 --- a/packages/discord.js/src/structures/AnnouncementChannel.js +++ b/packages/discord.js/src/structures/AnnouncementChannel.js @@ -4,11 +4,13 @@ const { BaseGuildTextChannel } = require('./BaseGuildTextChannel.js'); /** * Represents a guild announcement channel on Discord. + * * @extends {BaseGuildTextChannel} */ class AnnouncementChannel extends BaseGuildTextChannel { /** * Adds the target to this channel's followers. + * * @param {TextChannelResolvable} channel The channel where the webhook should be created * @param {string} [reason] Reason for creating the webhook * @returns {Promise} Returns the data for the followed channel diff --git a/packages/discord.js/src/structures/AnonymousGuild.js b/packages/discord.js/src/structures/AnonymousGuild.js index 79687a83a33d..3aae65f64874 100644 --- a/packages/discord.js/src/structures/AnonymousGuild.js +++ b/packages/discord.js/src/structures/AnonymousGuild.js @@ -4,6 +4,7 @@ const { BaseGuild } = require('./BaseGuild.js'); /** * Bundles common attributes and methods between {@link Guild} and {@link InviteGuild} + * * @extends {BaseGuild} * @abstract */ @@ -19,6 +20,7 @@ class AnonymousGuild extends BaseGuild { if ('splash' in data) { /** * The hash of the guild invite splash image + * * @type {?string} */ this.splash = data.splash; @@ -27,6 +29,7 @@ class AnonymousGuild extends BaseGuild { if ('banner' in data) { /** * The hash of the guild banner + * * @type {?string} */ this.banner = data.banner; @@ -35,6 +38,7 @@ class AnonymousGuild extends BaseGuild { if ('description' in data) { /** * The description of the guild, if any + * * @type {?string} */ this.description = data.description; @@ -43,6 +47,7 @@ class AnonymousGuild extends BaseGuild { if ('verification_level' in data) { /** * The verification level of the guild + * * @type {GuildVerificationLevel} */ this.verificationLevel = data.verification_level; @@ -51,6 +56,7 @@ class AnonymousGuild extends BaseGuild { if ('vanity_url_code' in data) { /** * The vanity invite code of the guild, if any + * * @type {?string} */ this.vanityURLCode = data.vanity_url_code; @@ -59,6 +65,7 @@ class AnonymousGuild extends BaseGuild { if ('nsfw_level' in data) { /** * The NSFW level of this guild + * * @type {GuildNSFWLevel} */ this.nsfwLevel = data.nsfw_level; @@ -67,6 +74,7 @@ class AnonymousGuild extends BaseGuild { if ('premium_subscription_count' in data) { /** * The total number of boosts for this server + * * @type {?number} */ this.premiumSubscriptionCount = data.premium_subscription_count; @@ -77,7 +85,8 @@ class AnonymousGuild extends BaseGuild { /** * The URL to this guild's banner. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ bannerURL(options = {}) { @@ -86,7 +95,8 @@ class AnonymousGuild extends BaseGuild { /** * The URL to this guild's invite splash image. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ splashURL(options = {}) { diff --git a/packages/discord.js/src/structures/ApplicationCommand.js b/packages/discord.js/src/structures/ApplicationCommand.js index 95ab6fff8ee0..e06d57461995 100644 --- a/packages/discord.js/src/structures/ApplicationCommand.js +++ b/packages/discord.js/src/structures/ApplicationCommand.js @@ -3,12 +3,13 @@ const { DiscordSnowflake } = require('@sapphire/snowflake'); const { ApplicationCommandOptionType } = require('discord-api-types/v10'); const isEqual = require('fast-deep-equal'); -const { Base } = require('./Base.js'); const { ApplicationCommandPermissionsManager } = require('../managers/ApplicationCommandPermissionsManager.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); +const { Base } = require('./Base.js'); /** * Represents an application command. + * * @extends {Base} */ class ApplicationCommand extends Base { @@ -17,18 +18,21 @@ class ApplicationCommand extends Base { /** * The command's id + * * @type {Snowflake} */ this.id = data.id; /** * The parent application's id + * * @type {Snowflake} */ this.applicationId = data.application_id; /** * The guild this command is part of + * * @type {?Guild} */ this.guild = guild ?? null; @@ -36,24 +40,28 @@ class ApplicationCommand extends Base { /** * The guild's id this command is part of, this may be non-null when `guild` is `null` if the command * was fetched from the `ApplicationCommandManager` + * * @type {?Snowflake} */ this.guildId = guild?.id ?? guildId ?? null; /** * The manager for permissions of this command on its guild or arbitrary guilds when the command is global + * * @type {ApplicationCommandPermissionsManager} */ this.permissions = new ApplicationCommandPermissionsManager(this); /** * The type of this application command + * * @type {ApplicationCommandType} */ this.type = data.type; /** * Whether this command is age-restricted (18+) + * * @type {boolean} */ this.nsfw = data.nsfw ?? false; @@ -65,6 +73,7 @@ class ApplicationCommand extends Base { if ('name' in data) { /** * The name of this command + * * @type {string} */ this.name = data.name; @@ -73,7 +82,8 @@ class ApplicationCommand extends Base { if ('name_localizations' in data) { /** * The name localizations for this command - * @type {?Object} + * + * @type {?Record} */ this.nameLocalizations = data.name_localizations; } else { @@ -83,6 +93,7 @@ class ApplicationCommand extends Base { if ('name_localized' in data) { /** * The localized name for this command + * * @type {?string} */ this.nameLocalized = data.name_localized; @@ -93,6 +104,7 @@ class ApplicationCommand extends Base { if ('description' in data) { /** * The description of this command + * * @type {string} */ this.description = data.description; @@ -101,7 +113,8 @@ class ApplicationCommand extends Base { if ('description_localizations' in data) { /** * The description localizations for this command - * @type {?Object} + * + * @type {?Record} */ this.descriptionLocalizations = data.description_localizations; } else { @@ -111,6 +124,7 @@ class ApplicationCommand extends Base { if ('description_localized' in data) { /** * The localized description for this command + * * @type {?string} */ this.descriptionLocalized = data.description_localized; @@ -121,6 +135,7 @@ class ApplicationCommand extends Base { if ('options' in data) { /** * The options of this command + * * @type {ApplicationCommandOption[]} */ this.options = data.options.map(option => this.constructor.transformOption(option, true)); @@ -131,6 +146,7 @@ class ApplicationCommand extends Base { if ('default_member_permissions' in data) { /** * The default bitfield used to determine whether this command be used in a guild + * * @type {?Readonly} */ this.defaultMemberPermissions = data.default_member_permissions @@ -144,6 +160,7 @@ class ApplicationCommand extends Base { /** * Installation context(s) where the command is available * Only for globally-scoped commands + * * @type {?ApplicationIntegrationType[]} */ this.integrationTypes = data.integration_types; @@ -155,6 +172,7 @@ class ApplicationCommand extends Base { /** * Interaction context(s) where the command can be used * Only for globally-scoped commands + * * @type {?InteractionContextType[]} */ this.contexts = data.contexts; @@ -167,6 +185,7 @@ class ApplicationCommand extends Base { * Determines whether the interaction is handled by the app's interactions handler or by Discord. * Only available for {@link ApplicationCommandType.PrimaryEntryPoint} commands on * applications with the {@link ApplicationFlags.Embedded} flag (i.e, those that have an Activity) + * * @type {?EntryPointCommandHandlerType} */ this.handler = data.handler; @@ -177,6 +196,7 @@ class ApplicationCommand extends Base { if ('version' in data) { /** * Autoincrementing version identifier updated during substantial record changes + * * @type {Snowflake} */ this.version = data.version; @@ -185,6 +205,7 @@ class ApplicationCommand extends Base { /** * The timestamp the command was created at + * * @type {number} * @readonly */ @@ -194,6 +215,7 @@ class ApplicationCommand extends Base { /** * The time the command was created at + * * @type {Date} * @readonly */ @@ -203,6 +225,7 @@ class ApplicationCommand extends Base { /** * The manager that this command belongs to + * * @type {ApplicationCommandManager} * @readonly */ @@ -212,14 +235,15 @@ class ApplicationCommand extends Base { /** * Data for creating or editing an application command. - * @typedef {Object} ApplicationCommandData + * + * @typedef {object} ApplicationCommandData * @property {string} name The name of the command, must be in all lowercase if type is * {@link ApplicationCommandType.ChatInput} - * @property {Object} [nameLocalizations] The localizations for the command name + * @property {Record} [nameLocalizations] The localizations for the command name * @property {string} description The description of the command, * if type is {@link ApplicationCommandType.ChatInput} or {@link ApplicationCommandType.PrimaryEntryPoint} * @property {boolean} [nsfw] Whether the command is age-restricted - * @property {Object} [descriptionLocalizations] The localizations for the command description, + * @property {Record} [descriptionLocalizations] The localizations for the command description, * if type is {@link ApplicationCommandType.ChatInput} or {@link ApplicationCommandType.PrimaryEntryPoint} * @property {ApplicationCommandType} [type=ApplicationCommandType.ChatInput] The type of the command * @property {ApplicationCommandOptionData[]} [options] Options for the command @@ -237,12 +261,13 @@ class ApplicationCommand extends Base { * API style `snake_case` properties can be used for compatibility with generators like `@discordjs/builders`. * Note that providing a value for the `camelCase` counterpart for any `snake_case` property * will discard the provided `snake_case` property. - * @typedef {Object} ApplicationCommandOptionData + * + * @typedef {object} ApplicationCommandOptionData * @property {ApplicationCommandOptionType} type The type of the option * @property {string} name The name of the option - * @property {Object} [nameLocalizations] The name localizations for the option + * @property {Record} [nameLocalizations] The name localizations for the option * @property {string} description The description of the option - * @property {Object} [descriptionLocalizations] The description localizations for the option + * @property {Record} [descriptionLocalizations] The description localizations for the option * @property {boolean} [autocomplete] Whether the autocomplete interaction is enabled for a * {@link ApplicationCommandOptionType.String}, {@link ApplicationCommandOptionType.Integer} or * {@link ApplicationCommandOptionType.Number} option @@ -262,14 +287,15 @@ class ApplicationCommand extends Base { */ /** - * @typedef {Object} ApplicationCommandOptionChoiceData + * @typedef {object} ApplicationCommandOptionChoiceData * @property {string} name The name of the choice - * @property {Object} [nameLocalizations] The localized names for this choice + * @property {Record} [nameLocalizations] The localized names for this choice * @property {string|number} value The value of the choice */ /** * Edits this application command. + * * @param {Partial} data The data to update the command with * @returns {Promise} * @example @@ -280,22 +306,24 @@ class ApplicationCommand extends Base { * .then(console.log) * .catch(console.error); */ - edit(data) { + async edit(data) { return this.manager.edit(this, data, this.guildId); } /** * Edits the name of this ApplicationCommand + * * @param {string} name The new name of the command * @returns {Promise} */ - setName(name) { + async setName(name) { return this.edit({ name }); } /** * Edits the localized names of this ApplicationCommand - * @param {Object} nameLocalizations The new localized names for the command + * + * @param {Record} nameLocalizations The new localized names for the command * @returns {Promise} * @example * // Edit the name localizations of this command @@ -306,22 +334,24 @@ class ApplicationCommand extends Base { * .then(console.log) * .catch(console.error) */ - setNameLocalizations(nameLocalizations) { + async setNameLocalizations(nameLocalizations) { return this.edit({ nameLocalizations }); } /** * Edits the description of this ApplicationCommand + * * @param {string} description The new description of the command * @returns {Promise} */ - setDescription(description) { + async setDescription(description) { return this.edit({ description }); } /** * Edits the localized descriptions of this ApplicationCommand - * @param {Object} descriptionLocalizations The new localized descriptions for the command + * + * @param {Record} descriptionLocalizations The new localized descriptions for the command * @returns {Promise} * @example * // Edit the description localizations of this command @@ -332,30 +362,33 @@ class ApplicationCommand extends Base { * .then(console.log) * .catch(console.error) */ - setDescriptionLocalizations(descriptionLocalizations) { + async setDescriptionLocalizations(descriptionLocalizations) { return this.edit({ descriptionLocalizations }); } /** * Edits the default member permissions of this ApplicationCommand + * * @param {?PermissionResolvable} defaultMemberPermissions The default member permissions required to run this command * @returns {Promise} */ - setDefaultMemberPermissions(defaultMemberPermissions) { + async setDefaultMemberPermissions(defaultMemberPermissions) { return this.edit({ defaultMemberPermissions }); } /** * Edits the options of this ApplicationCommand + * * @param {ApplicationCommandOptionData[]} options The options to set for this command * @returns {Promise} */ - setOptions(options) { + async setOptions(options) { return this.edit({ options }); } /** * Deletes this command. + * * @returns {Promise} * @example * // Delete this command @@ -363,7 +396,7 @@ class ApplicationCommand extends Base { * .then(console.log) * .catch(console.error); */ - delete() { + async delete() { return this.manager.delete(this, this.guildId); } @@ -371,8 +404,9 @@ class ApplicationCommand extends Base { * Whether this command equals another command. It compares all properties, so for most operations * it is advisable to just compare `command.id === command2.id` as it is much faster and is often * what most users need. + * * @param {ApplicationCommand|ApplicationCommandData|APIApplicationCommand} command The command to compare with - * @param {boolean} [enforceOptionOrder=false] Whether to strictly check that options and choices are in the same + * @param {boolean} [enforceOptionOrder] Whether to strictly check that options and choices are in the same * order in the array The client may not always respect this ordering! * @returns {boolean} */ @@ -390,9 +424,9 @@ class ApplicationCommand extends Base { if ('defaultMemberPermissions' in command) { defaultMemberPermissions = - command.defaultMemberPermissions !== null - ? new PermissionsBitField(command.defaultMemberPermissions).bitfield - : null; + command.defaultMemberPermissions === null + ? null + : new PermissionsBitField(command.defaultMemberPermissions).bitfield; } // Check top level parameters @@ -421,16 +455,18 @@ class ApplicationCommand extends Base { if (command.options) { return this.constructor.optionsEqual(this.options, command.options, enforceOptionOrder); } + return true; } /** * Recursively checks that all options for an {@link ApplicationCommand} are equal to the provided options. * In most cases it is better to compare using {@link ApplicationCommand#equals} + * * @param {ApplicationCommandOptionData[]} existing The options on the existing command, * should be {@link ApplicationCommand#options} * @param {ApplicationCommandOptionData[]|APIApplicationCommandOption[]} options The options to compare against - * @param {boolean} [enforceOptionOrder=false] Whether to strictly check that options and choices are in the same + * @param {boolean} [enforceOptionOrder] Whether to strictly check that options and choices are in the same * order in the array The client may not always respect this ordering! * @returns {boolean} */ @@ -439,21 +475,24 @@ class ApplicationCommand extends Base { if (enforceOptionOrder) { return existing.every((option, index) => this._optionEquals(option, options[index], enforceOptionOrder)); } + const newOptions = new Map(options.map(option => [option.name, option])); for (const option of existing) { const foundOption = newOptions.get(option.name); if (!foundOption || !this._optionEquals(option, foundOption)) return false; } + return true; } /** * Checks that an option for an {@link ApplicationCommand} is equal to the provided option * In most cases it is better to compare using {@link ApplicationCommand#equals} + * * @param {ApplicationCommandOptionData} existing The option on the existing command, * should be from {@link ApplicationCommand#options} * @param {ApplicationCommandOptionData|APIApplicationCommandOption} option The option to compare against - * @param {boolean} [enforceOptionOrder=false] Whether to strictly check that options or choices are in the same + * @param {boolean} [enforceOptionOrder] Whether to strictly check that options or choices are in the same * order in their array The client may not always respect this ordering! * @returns {boolean} * @private @@ -499,6 +538,7 @@ class ApplicationCommand extends Base { ) { return false; } + if (!enforceOptionOrder) { const newChoices = new Map(option.choices.map(choice => [choice.name, choice])); for (const choice of existing.choices) { @@ -518,18 +558,20 @@ class ApplicationCommand extends Base { if (existing.options) { return this.optionsEqual(existing.options, option.options, enforceOptionOrder); } + return true; } /** * An option for an application command or subcommand. - * @typedef {Object} ApplicationCommandOption + * + * @typedef {object} ApplicationCommandOption * @property {ApplicationCommandOptionType} type The type of the option * @property {string} name The name of the option - * @property {Object} [nameLocalizations] The localizations for the option name + * @property {Record} [nameLocalizations] The localizations for the option name * @property {string} [nameLocalized] The localized name for this option * @property {string} description The description of the option - * @property {Object} [descriptionLocalizations] The localizations for the option description + * @property {Record} [descriptionLocalizations] The localizations for the option description * @property {string} [descriptionLocalized] The localized description for this option * @property {boolean} [required] Whether the option is required * @property {boolean} [autocomplete] Whether the autocomplete interaction is enabled for a @@ -551,15 +593,17 @@ class ApplicationCommand extends Base { /** * A choice for an application command option. - * @typedef {Object} ApplicationCommandOptionChoice + * + * @typedef {object} ApplicationCommandOptionChoice * @property {string} name The name of the choice * @property {?string} nameLocalized The localized name of the choice in the provided locale, if any - * @property {?Object} [nameLocalizations] The localized names for this choice + * @property {?Record} [nameLocalizations] The localized names for this choice * @property {string|number} value The value of the choice */ /** * Transforms an {@link ApplicationCommandOptionData} object into something that can be used with the API. + * * @param {ApplicationCommandOptionData|ApplicationCommandOption} option The option to transform * @param {boolean} [received] Whether this option has been received from Discord * @returns {APIApplicationCommandOption} @@ -608,7 +652,6 @@ class ApplicationCommand extends Base { exports.ApplicationCommand = ApplicationCommand; -/* eslint-disable max-len */ /** * @external ApplicationCommandOptionAllowedChannelTypes * @see {@link https://discord.js.org/docs/packages/builders/stable/ApplicationCommandOptionAllowedChannelTypes:TypeAlias} diff --git a/packages/discord.js/src/structures/ApplicationEmoji.js b/packages/discord.js/src/structures/ApplicationEmoji.js index 9d46db85210e..8b47eb3190cc 100644 --- a/packages/discord.js/src/structures/ApplicationEmoji.js +++ b/packages/discord.js/src/structures/ApplicationEmoji.js @@ -4,6 +4,7 @@ const { Emoji } = require('./Emoji.js'); /** * Represents a custom emoji. + * * @extends {Emoji} */ class ApplicationEmoji extends Emoji { @@ -12,12 +13,14 @@ class ApplicationEmoji extends Emoji { /** * The application this emoji originates from + * * @type {ClientApplication} */ this.application = application; /** * The user who created this emoji + * * @type {?User} */ this.author = null; @@ -35,6 +38,7 @@ class ApplicationEmoji extends Emoji { if ('managed' in data) { /** * Whether this emoji is managed by an external service + * * @type {?boolean} */ this.managed = data.managed; @@ -43,6 +47,7 @@ class ApplicationEmoji extends Emoji { if ('require_colons' in data) { /** * Whether or not this emoji requires colons surrounding it + * * @type {?boolean} */ this.requiresColons = data.require_colons; @@ -51,20 +56,23 @@ class ApplicationEmoji extends Emoji { /** * Fetches the author for this emoji + * * @returns {Promise} */ - fetchAuthor() { + async fetchAuthor() { return this.application.emojis.fetchAuthor(this); } /** * Data for editing an emoji. - * @typedef {Object} ApplicationEmojiEditOptions + * + * @typedef {object} ApplicationEmojiEditOptions * @property {string} [name] The name of the emoji */ /** * Edits the emoji. + * * @param {ApplicationEmojiEditOptions} options The options to provide * @returns {Promise} * @example @@ -73,21 +81,23 @@ class ApplicationEmoji extends Emoji { * .then(emoji => console.log(`Edited emoji ${emoji}`)) * .catch(console.error); */ - edit(options) { + async edit(options) { return this.application.emojis.edit(this.id, options); } /** * Sets the name of the emoji. + * * @param {string} name The new name for the emoji * @returns {Promise} */ - setName(name) { + async setName(name) { return this.edit({ name }); } /** * Deletes the emoji. + * * @returns {Promise} */ async delete() { @@ -97,6 +107,7 @@ class ApplicationEmoji extends Emoji { /** * Whether this emoji is the same as another one. + * * @param {ApplicationEmoji|APIEmoji} other The emoji to compare it to * @returns {boolean} */ diff --git a/packages/discord.js/src/structures/ApplicationRoleConnectionMetadata.js b/packages/discord.js/src/structures/ApplicationRoleConnectionMetadata.js index 7ed9b33f318f..64ea3bb7c618 100644 --- a/packages/discord.js/src/structures/ApplicationRoleConnectionMetadata.js +++ b/packages/discord.js/src/structures/ApplicationRoleConnectionMetadata.js @@ -7,36 +7,42 @@ class ApplicationRoleConnectionMetadata { constructor(data) { /** * The name of this metadata field + * * @type {string} */ this.name = data.name; /** * The name localizations for this metadata field - * @type {?Object} + * + * @type {?Record} */ this.nameLocalizations = data.name_localizations ?? null; /** * The description of this metadata field + * * @type {string} */ this.description = data.description; /** * The description localizations for this metadata field - * @type {?Object} + * + * @type {?Record} */ this.descriptionLocalizations = data.description_localizations ?? null; /** * The dictionary key for this metadata field + * * @type {string} */ this.key = data.key; /** * The type of this metadata field + * * @type {ApplicationRoleConnectionMetadataType} */ this.type = data.type; diff --git a/packages/discord.js/src/structures/Attachment.js b/packages/discord.js/src/structures/Attachment.js index 06a3109f68c2..1bcd7cfa347a 100644 --- a/packages/discord.js/src/structures/Attachment.js +++ b/packages/discord.js/src/structures/Attachment.js @@ -4,7 +4,7 @@ const { AttachmentFlagsBitField } = require('../util/AttachmentFlagsBitField.js' const { basename, flatten } = require('../util/Util.js'); /** - * @typedef {Object} AttachmentPayload + * @typedef {object} AttachmentPayload * @property {?string} name The name of the attachment * @property {Stream|BufferResolvable} attachment The attachment in this payload * @property {?string} description The description of the attachment @@ -18,6 +18,7 @@ class Attachment { this.attachment = data.url; /** * The name of this attachment + * * @type {string} */ this.name = data.filename; @@ -27,6 +28,7 @@ class Attachment { _patch(data) { /** * The attachment's id + * * @type {Snowflake} */ this.id = data.id; @@ -34,6 +36,7 @@ class Attachment { if ('size' in data) { /** * The size of this attachment in bytes + * * @type {number} */ this.size = data.size; @@ -42,6 +45,7 @@ class Attachment { if ('url' in data) { /** * The URL to this attachment + * * @type {string} */ this.url = data.url; @@ -50,6 +54,7 @@ class Attachment { if ('proxy_url' in data) { /** * The Proxy URL to this attachment + * * @type {string} */ this.proxyURL = data.proxy_url; @@ -58,6 +63,7 @@ class Attachment { if ('height' in data) { /** * The height of this attachment (if an image or video) + * * @type {?number} */ this.height = data.height; @@ -68,6 +74,7 @@ class Attachment { if ('width' in data) { /** * The width of this attachment (if an image or video) + * * @type {?number} */ this.width = data.width; @@ -78,6 +85,7 @@ class Attachment { if ('content_type' in data) { /** * The media (MIME) type of this attachment + * * @type {?string} * @see {@link https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types} */ @@ -89,6 +97,7 @@ class Attachment { if ('description' in data) { /** * The description (alt text) of this attachment + * * @type {?string} */ this.description = data.description; @@ -98,6 +107,7 @@ class Attachment { /** * Whether this attachment is ephemeral + * * @type {boolean} */ this.ephemeral = data.ephemeral ?? false; @@ -106,6 +116,7 @@ class Attachment { /** * The duration of this attachment in seconds * This will only be available if the attachment is an audio file. + * * @type {?number} */ this.duration = data.duration_secs; @@ -117,6 +128,7 @@ class Attachment { /** * The base64 encoded byte array representing a sampled waveform * This will only be available if the attachment is an audio file. + * * @type {?string} */ this.waveform = data.waveform; @@ -127,6 +139,7 @@ class Attachment { if ('flags' in data) { /** * The flags of this attachment + * * @type {Readonly} */ this.flags = new AttachmentFlagsBitField(data.flags).freeze(); @@ -138,6 +151,7 @@ class Attachment { /** * The title of this attachment * This will only be available if the attachment name contains special characters. + * * @type {?string} */ this.title = data.title; @@ -148,6 +162,7 @@ class Attachment { /** * Whether or not this attachment has been marked as a spoiler + * * @type {boolean} * @readonly */ diff --git a/packages/discord.js/src/structures/AttachmentBuilder.js b/packages/discord.js/src/structures/AttachmentBuilder.js index ebffe2e85f81..1ff35601792a 100644 --- a/packages/discord.js/src/structures/AttachmentBuilder.js +++ b/packages/discord.js/src/structures/AttachmentBuilder.js @@ -13,16 +13,19 @@ class AttachmentBuilder { constructor(attachment, data = {}) { /** * The file associated with this attachment. + * * @type {BufferResolvable|Stream} */ this.attachment = attachment; /** * The name of this attachment + * * @type {?string} */ this.name = data.name; /** * The description of the attachment + * * @type {?string} */ this.description = data.description; @@ -30,6 +33,7 @@ class AttachmentBuilder { /** * Sets the description of this attachment. + * * @param {string} description The description of the file * @returns {AttachmentBuilder} This attachment */ @@ -40,6 +44,7 @@ class AttachmentBuilder { /** * Sets the file of this attachment. + * * @param {BufferResolvable|Stream} attachment The file * @returns {AttachmentBuilder} This attachment */ @@ -50,6 +55,7 @@ class AttachmentBuilder { /** * Sets the name of this attachment. + * * @param {string} name The name of the file * @returns {AttachmentBuilder} This attachment */ @@ -60,7 +66,8 @@ class AttachmentBuilder { /** * Sets whether this attachment is a spoiler - * @param {boolean} [spoiler=true] Whether the attachment should be marked as a spoiler + * + * @param {boolean} [spoiler] Whether the attachment should be marked as a spoiler * @returns {AttachmentBuilder} This attachment */ setSpoiler(spoiler = true) { @@ -70,14 +77,17 @@ class AttachmentBuilder { while (this.spoiler) { this.name = this.name.slice('SPOILER_'.length); } + return this; } + this.name = `SPOILER_${this.name}`; return this; } /** * Whether or not this attachment has been marked as a spoiler + * * @type {boolean} * @readonly */ @@ -91,6 +101,7 @@ class AttachmentBuilder { /** * Makes a new builder instance from a preexisting attachment structure. + * * @param {AttachmentBuilder|Attachment|AttachmentPayload} other The builder to construct a new instance from * @returns {AttachmentBuilder} */ @@ -105,7 +116,7 @@ class AttachmentBuilder { exports.AttachmentBuilder = AttachmentBuilder; /** - * @typedef {Object} AttachmentData + * @typedef {object} AttachmentData * @property {string} [name] The name of the attachment * @property {string} [description] The description of the attachment */ diff --git a/packages/discord.js/src/structures/AutoModerationActionExecution.js b/packages/discord.js/src/structures/AutoModerationActionExecution.js index f03f032e710d..ada571c51cc5 100644 --- a/packages/discord.js/src/structures/AutoModerationActionExecution.js +++ b/packages/discord.js/src/structures/AutoModerationActionExecution.js @@ -9,36 +9,42 @@ class AutoModerationActionExecution { constructor(data, guild) { /** * The guild where this action was executed from. + * * @type {Guild} */ this.guild = guild; /** * The action that was executed. + * * @type {AutoModerationAction} */ this.action = _transformAPIAutoModerationAction(data.action); /** * The id of the auto moderation rule this action belongs to. + * * @type {Snowflake} */ this.ruleId = data.rule_id; /** * The trigger type of the auto moderation rule which was triggered. + * * @type {AutoModerationRuleTriggerType} */ this.ruleTriggerType = data.rule_trigger_type; /** * The id of the user that triggered this action. + * * @type {Snowflake} */ this.userId = data.user_id; /** * The id of the channel where this action was triggered from. + * * @type {?Snowflake} */ this.channelId = data.channel_id ?? null; @@ -46,12 +52,14 @@ class AutoModerationActionExecution { /** * The id of the message that triggered this action. * This will not be present if the message was blocked or the content was not part of any message. + * * @type {?Snowflake} */ this.messageId = data.message_id ?? null; /** * The id of any system auto moderation messages posted as a result of this action. + * * @type {?Snowflake} */ this.alertSystemMessageId = data.alert_system_message_id ?? null; @@ -59,18 +67,21 @@ class AutoModerationActionExecution { /** * The content that triggered this action. * This property requires the {@link GatewayIntentBits.MessageContent} privileged gateway intent. + * * @type {string} */ this.content = data.content; /** * The word or phrase configured in the rule that triggered this action. + * * @type {?string} */ this.matchedKeyword = data.matched_keyword ?? null; /** * The substring in content that triggered this action. + * * @type {?string} */ this.matchedContent = data.matched_content ?? null; @@ -78,6 +89,7 @@ class AutoModerationActionExecution { /** * The auto moderation rule this action belongs to. + * * @type {?AutoModerationRule} * @readonly */ @@ -87,6 +99,7 @@ class AutoModerationActionExecution { /** * The channel where this action was triggered from. + * * @type {?(GuildTextBasedChannel|ForumChannel|MediaChannel)} * @readonly */ @@ -96,6 +109,7 @@ class AutoModerationActionExecution { /** * The user that triggered this action. + * * @type {?User} * @readonly */ @@ -105,6 +119,7 @@ class AutoModerationActionExecution { /** * The guild member that triggered this action. + * * @type {?GuildMember} * @readonly */ diff --git a/packages/discord.js/src/structures/AutoModerationRule.js b/packages/discord.js/src/structures/AutoModerationRule.js index 585eb6ad9e4a..ec12bcf2de2d 100644 --- a/packages/discord.js/src/structures/AutoModerationRule.js +++ b/packages/discord.js/src/structures/AutoModerationRule.js @@ -1,11 +1,12 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); -const { Base } = require('./Base.js'); const { _transformAPIAutoModerationAction } = require('../util/Transformers.js'); +const { Base } = require('./Base.js'); /** * Represents an auto moderation rule. + * * @extends {Base} */ class AutoModerationRule extends Base { @@ -14,24 +15,28 @@ class AutoModerationRule extends Base { /** * The id of this auto moderation rule. + * * @type {Snowflake} */ this.id = data.id; /** * The guild this auto moderation rule is for. + * * @type {Guild} */ this.guild = guild; /** * The user that created this auto moderation rule. + * * @type {Snowflake} */ this.creatorId = data.creator_id; /** * The trigger type of this auto moderation rule. + * * @type {AutoModerationRuleTriggerType} */ this.triggerType = data.trigger_type; @@ -43,6 +48,7 @@ class AutoModerationRule extends Base { if ('name' in data) { /** * The name of this auto moderation rule. + * * @type {string} */ this.name = data.name; @@ -51,6 +57,7 @@ class AutoModerationRule extends Base { if ('event_type' in data) { /** * The event type of this auto moderation rule. + * * @type {AutoModerationRuleEventType} */ this.eventType = data.event_type; @@ -59,7 +66,8 @@ class AutoModerationRule extends Base { if ('trigger_metadata' in data) { /** * Additional data used to determine whether an auto moderation rule should be triggered. - * @typedef {Object} AutoModerationTriggerMetadata + * + * @typedef {object} AutoModerationTriggerMetadata * @property {string[]} keywordFilter The substrings that will be searched for in the content * @property {string[]} regexPatterns The regular expression patterns which will be matched against the content * Only Rust-flavored regular expressions are supported. @@ -75,6 +83,7 @@ class AutoModerationRule extends Base { /** * The trigger metadata of the rule. + * * @type {AutoModerationTriggerMetadata} */ this.triggerMetadata = { @@ -90,14 +99,16 @@ class AutoModerationRule extends Base { if ('actions' in data) { /** * An object containing information about an auto moderation rule action. - * @typedef {Object} AutoModerationAction + * + * @typedef {object} AutoModerationAction * @property {AutoModerationActionType} type The type of this auto moderation rule action * @property {AutoModerationActionMetadata} metadata Additional metadata needed during execution */ /** * Additional data used when an auto moderation rule is executed. - * @typedef {Object} AutoModerationActionMetadata + * + * @typedef {object} AutoModerationActionMetadata * @property {?Snowflake} channelId The id of the channel to which content will be logged * @property {?number} durationSeconds The timeout duration in seconds * @property {?string} customMessage The custom message that is shown whenever a message is blocked @@ -105,6 +116,7 @@ class AutoModerationRule extends Base { /** * The actions of this auto moderation rule. + * * @type {AutoModerationAction[]} */ this.actions = data.actions.map(action => _transformAPIAutoModerationAction(action)); @@ -113,6 +125,7 @@ class AutoModerationRule extends Base { if ('enabled' in data) { /** * Whether this auto moderation rule is enabled. + * * @type {boolean} */ this.enabled = data.enabled; @@ -121,6 +134,7 @@ class AutoModerationRule extends Base { if ('exempt_roles' in data) { /** * The roles exempt by this auto moderation rule. + * * @type {Collection} */ this.exemptRoles = new Collection( @@ -131,6 +145,7 @@ class AutoModerationRule extends Base { if ('exempt_channels' in data) { /** * The channels exempt by this auto moderation rule. + * * @type {Collection} */ this.exemptChannels = new Collection( @@ -141,75 +156,83 @@ class AutoModerationRule extends Base { /** * Edits this auto moderation rule. + * * @param {AutoModerationRuleEditOptions} options Options for editing this auto moderation rule * @returns {Promise} */ - edit(options) { + async edit(options) { return this.guild.autoModerationRules.edit(this.id, options); } /** * Deletes this auto moderation rule. + * * @param {string} [reason] The reason for deleting this auto moderation rule * @returns {Promise} */ - delete(reason) { + async delete(reason) { return this.guild.autoModerationRules.delete(this.id, reason); } /** * Sets the name for this auto moderation rule. + * * @param {string} name The name of this auto moderation rule * @param {string} [reason] The reason for changing the name of this auto moderation rule * @returns {Promise} */ - setName(name, reason) { + async setName(name, reason) { return this.edit({ name, reason }); } /** * Sets the event type for this auto moderation rule. + * * @param {AutoModerationRuleEventType} eventType The event type of this auto moderation rule * @param {string} [reason] The reason for changing the event type of this auto moderation rule * @returns {Promise} */ - setEventType(eventType, reason) { + async setEventType(eventType, reason) { return this.edit({ eventType, reason }); } /** * Sets the keyword filter for this auto moderation rule. + * * @param {string[]} keywordFilter The keyword filter of this auto moderation rule * @param {string} [reason] The reason for changing the keyword filter of this auto moderation rule * @returns {Promise} */ - setKeywordFilter(keywordFilter, reason) { + async setKeywordFilter(keywordFilter, reason) { return this.edit({ triggerMetadata: { ...this.triggerMetadata, keywordFilter }, reason }); } /** * Sets the regular expression patterns for this auto moderation rule. + * * @param {string[]} regexPatterns The regular expression patterns of this auto moderation rule * Only Rust-flavored regular expressions are supported. * @param {string} [reason] The reason for changing the regular expression patterns of this auto moderation rule * @returns {Promise} */ - setRegexPatterns(regexPatterns, reason) { + async setRegexPatterns(regexPatterns, reason) { return this.edit({ triggerMetadata: { ...this.triggerMetadata, regexPatterns }, reason }); } /** * Sets the presets for this auto moderation rule. + * * @param {AutoModerationRuleKeywordPresetType[]} presets The presets of this auto moderation rule * @param {string} [reason] The reason for changing the presets of this auto moderation rule * @returns {Promise} */ - setPresets(presets, reason) { + async setPresets(presets, reason) { return this.edit({ triggerMetadata: { ...this.triggerMetadata, presets }, reason }); } /** * Sets the allow list for this auto moderation rule. + * * @param {string[]} allowList The substrings that will be exempt from triggering * {@link AutoModerationRuleTriggerType.Keyword}, * {@link AutoModerationRuleTriggerType.KeywordPreset}, @@ -217,70 +240,76 @@ class AutoModerationRule extends Base { * @param {string} [reason] The reason for changing the allow list of this auto moderation rule * @returns {Promise} */ - setAllowList(allowList, reason) { + async setAllowList(allowList, reason) { return this.edit({ triggerMetadata: { ...this.triggerMetadata, allowList }, reason }); } /** * Sets the mention total limit for this auto moderation rule. + * * @param {number} mentionTotalLimit The total number of unique role and user mentions allowed per message * @param {string} [reason] The reason for changing the mention total limit of this auto moderation rule * @returns {Promise} */ - setMentionTotalLimit(mentionTotalLimit, reason) { + async setMentionTotalLimit(mentionTotalLimit, reason) { return this.edit({ triggerMetadata: { ...this.triggerMetadata, mentionTotalLimit }, reason }); } /** * Sets whether to enable mention raid protection for this auto moderation rule. + * * @param {boolean} mentionRaidProtectionEnabled * Whether to enable mention raid protection for this auto moderation rule * @param {string} [reason] The reason for changing the mention raid protection of this auto moderation rule * @returns {Promise} */ - setMentionRaidProtectionEnabled(mentionRaidProtectionEnabled, reason) { + async setMentionRaidProtectionEnabled(mentionRaidProtectionEnabled, reason) { return this.edit({ triggerMetadata: { ...this.triggerMetadata, mentionRaidProtectionEnabled }, reason }); } /** * Sets the actions for this auto moderation rule. + * * @param {AutoModerationActionOptions[]} actions The actions of this auto moderation rule * @param {string} [reason] The reason for changing the actions of this auto moderation rule * @returns {Promise} */ - setActions(actions, reason) { + async setActions(actions, reason) { return this.edit({ actions, reason }); } /** * Sets whether this auto moderation rule should be enabled. - * @param {boolean} [enabled=true] Whether to enable this auto moderation rule + * + * @param {boolean} [enabled] Whether to enable this auto moderation rule * @param {string} [reason] The reason for enabling or disabling this auto moderation rule * @returns {Promise} */ - setEnabled(enabled = true, reason) { + async setEnabled(enabled = true, reason = undefined) { return this.edit({ enabled, reason }); } /** * Sets the exempt roles for this auto moderation rule. + * * @param {Collection|RoleResolvable[]} [exemptRoles] * The roles that should not be affected by the auto moderation rule * @param {string} [reason] The reason for changing the exempt roles of this auto moderation rule * @returns {Promise} */ - setExemptRoles(exemptRoles, reason) { + async setExemptRoles(exemptRoles, reason) { return this.edit({ exemptRoles, reason }); } /** * Sets the exempt channels for this auto moderation rule. + * * @param {Collection|GuildChannelResolvable[]} [exemptChannels] * The channels that should not be affected by the auto moderation rule * @param {string} [reason] The reason for changing the exempt channels of this auto moderation rule * @returns {Promise} */ - setExemptChannels(exemptChannels, reason) { + async setExemptChannels(exemptChannels, reason) { return this.edit({ exemptChannels, reason }); } } diff --git a/packages/discord.js/src/structures/AutocompleteInteraction.js b/packages/discord.js/src/structures/AutocompleteInteraction.js index 2a8faeb29657..83ec425d56c6 100644 --- a/packages/discord.js/src/structures/AutocompleteInteraction.js +++ b/packages/discord.js/src/structures/AutocompleteInteraction.js @@ -1,12 +1,13 @@ 'use strict'; const { InteractionResponseType, Routes } = require('discord-api-types/v10'); +const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { BaseInteraction } = require('./BaseInteraction.js'); const { CommandInteractionOptionResolver } = require('./CommandInteractionOptionResolver.js'); -const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); /** * Represents an autocomplete interaction. + * * @extends {BaseInteraction} */ class AutocompleteInteraction extends BaseInteraction { @@ -15,42 +16,49 @@ class AutocompleteInteraction extends BaseInteraction { /** * The id of the channel this interaction was sent in + * * @type {Snowflake} * @name AutocompleteInteraction#channelId */ /** * The invoked application command's id + * * @type {Snowflake} */ this.commandId = data.data.id; /** * The invoked application command's name + * * @type {string} */ this.commandName = data.data.name; /** * The invoked application command's type + * * @type {ApplicationCommandType} */ this.commandType = data.data.type; /** * The id of the guild the invoked application command is registered to + * * @type {?Snowflake} */ this.commandGuildId = data.data.guild_id ?? null; /** * Whether this interaction has already received a response + * * @type {boolean} */ this.responded = false; /** * The options passed to the command + * * @type {CommandInteractionOptionResolver} */ this.options = new CommandInteractionOptionResolver(this.client, data.data.options ?? []); @@ -58,6 +66,7 @@ class AutocompleteInteraction extends BaseInteraction { /** * The invoked application command, if it was fetched before + * * @type {?ApplicationCommand} */ get command() { @@ -67,6 +76,7 @@ class AutocompleteInteraction extends BaseInteraction { /** * Sends results for the autocomplete of this interaction. + * * @param {ApplicationCommandOptionChoiceData[]} options The options for the autocomplete * @returns {Promise} * @example diff --git a/packages/discord.js/src/structures/Base.js b/packages/discord.js/src/structures/Base.js index 61e0de36787a..430fb8329ff7 100644 --- a/packages/discord.js/src/structures/Base.js +++ b/packages/discord.js/src/structures/Base.js @@ -4,12 +4,14 @@ const { flatten } = require('../util/Util.js'); /** * Represents a data model that is identifiable by a Snowflake (i.e. Discord API data models). + * * @abstract */ class Base { constructor(client) { /** * The client that instantiated this + * * @name Base#client * @type {Client} * @readonly diff --git a/packages/discord.js/src/structures/BaseChannel.js b/packages/discord.js/src/structures/BaseChannel.js index f1a1562ba9ae..d71680efe7a9 100644 --- a/packages/discord.js/src/structures/BaseChannel.js +++ b/packages/discord.js/src/structures/BaseChannel.js @@ -3,12 +3,13 @@ const { channelLink, channelMention } = require('@discordjs/formatters'); const { DiscordSnowflake } = require('@sapphire/snowflake'); const { ChannelType, Routes } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); const { ChannelFlagsBitField } = require('../util/ChannelFlagsBitField.js'); const { ThreadChannelTypes } = require('../util/Constants.js'); +const { Base } = require('./Base.js'); /** * Represents any channel on Discord. + * * @extends {Base} * @abstract */ @@ -18,6 +19,7 @@ class BaseChannel extends Base { /** * The type of the channel + * * @type {ChannelType} */ this.type = data.type; @@ -30,6 +32,7 @@ class BaseChannel extends Base { /** * The flags that are applied to the channel. * This is only `null` in a {@link PartialGroupDMChannel}. In all other cases, it is not `null`. + * * @type {?Readonly} */ this.flags = new ChannelFlagsBitField(data.flags).freeze(); @@ -39,6 +42,7 @@ class BaseChannel extends Base { /** * The channel's id + * * @type {Snowflake} */ this.id = data.id; @@ -46,6 +50,7 @@ class BaseChannel extends Base { /** * The timestamp the channel was created at + * * @type {number} * @readonly */ @@ -55,6 +60,7 @@ class BaseChannel extends Base { /** * The time the channel was created at + * * @type {Date} * @readonly */ @@ -64,6 +70,7 @@ class BaseChannel extends Base { /** * The URL to the channel + * * @type {string} * @readonly */ @@ -74,6 +81,7 @@ class BaseChannel extends Base { /** * Whether this Channel is a partial * This is always false outside of DM channels. + * * @type {boolean} * @readonly */ @@ -83,6 +91,7 @@ class BaseChannel extends Base { /** * When concatenated with a string, this automatically returns the channel's mention instead of the Channel object. + * * @returns {string} * @example * // Logs: Hello from <#123456789012345678>! @@ -94,6 +103,7 @@ class BaseChannel extends Base { /** * Deletes this channel. + * * @returns {Promise} * @example * // Delete the channel @@ -108,15 +118,17 @@ class BaseChannel extends Base { /** * Fetches this channel. - * @param {boolean} [force=true] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - fetch(force = true) { + async fetch(force = true) { return this.client.channels.fetch(this.id, { force }); } /** * Indicates whether this channel is a {@link ThreadChannel}. + * * @returns {boolean} */ isThread() { @@ -125,6 +137,7 @@ class BaseChannel extends Base { /** * Indicates whether this channel is {@link TextBasedChannels text-based}. + * * @returns {boolean} */ isTextBased() { @@ -133,6 +146,7 @@ class BaseChannel extends Base { /** * Indicates whether this channel is DM-based (either a {@link DMChannel} or a {@link PartialGroupDMChannel}). + * * @returns {boolean} */ isDMBased() { @@ -141,6 +155,7 @@ class BaseChannel extends Base { /** * Indicates whether this channel is {@link BaseGuildVoiceChannel voice-based}. + * * @returns {boolean} */ isVoiceBased() { @@ -149,6 +164,7 @@ class BaseChannel extends Base { /** * Indicates whether this channel is {@link ThreadOnlyChannel thread-only}. + * * @returns {boolean} */ isThreadOnly() { @@ -157,6 +173,7 @@ class BaseChannel extends Base { /** * Indicates whether this channel is sendable. + * * @returns {boolean} */ isSendable() { diff --git a/packages/discord.js/src/structures/BaseGuild.js b/packages/discord.js/src/structures/BaseGuild.js index e68a364d52eb..b07415c8cbb5 100644 --- a/packages/discord.js/src/structures/BaseGuild.js +++ b/packages/discord.js/src/structures/BaseGuild.js @@ -7,6 +7,7 @@ const { Base } = require('./Base.js'); /** * The base class for {@link Guild}, {@link OAuth2Guild} and {@link InviteGuild}. + * * @extends {Base} * @abstract */ @@ -16,24 +17,28 @@ class BaseGuild extends Base { /** * The guild's id + * * @type {Snowflake} */ this.id = data.id; /** * The name of this guild + * * @type {string} */ this.name = data.name; /** * The icon hash of this guild + * * @type {?string} */ this.icon = data.icon; /** * An array of features available to this guild + * * @type {GuildFeature[]} */ this.features = data.features; @@ -41,6 +46,7 @@ class BaseGuild extends Base { /** * The timestamp this guild was created at + * * @type {number} * @readonly */ @@ -50,6 +56,7 @@ class BaseGuild extends Base { /** * The time this guild was created at + * * @type {Date} * @readonly */ @@ -59,18 +66,20 @@ class BaseGuild extends Base { /** * The acronym that shows up in place of a guild icon + * * @type {string} * @readonly */ get nameAcronym() { return this.name - .replace(/'s /g, ' ') - .replace(/\w+/g, e => e[0]) - .replace(/\s/g, ''); + .replaceAll("'s ", ' ') + .replaceAll(/\w+/g, word => word[0]) + .replaceAll(/\s/g, ''); } /** * Whether this guild is partnered + * * @type {boolean} * @readonly */ @@ -80,6 +89,7 @@ class BaseGuild extends Base { /** * Whether this guild is verified + * * @type {boolean} * @readonly */ @@ -89,7 +99,8 @@ class BaseGuild extends Base { /** * The URL to this guild's icon. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ iconURL(options = {}) { @@ -98,6 +109,7 @@ class BaseGuild extends Base { /** * Fetches this guild. + * * @returns {Promise} */ async fetch() { @@ -109,6 +121,7 @@ class BaseGuild extends Base { /** * When concatenated with a string, this automatically returns the guild's name instead of the Guild object. + * * @returns {string} */ toString() { diff --git a/packages/discord.js/src/structures/BaseGuildEmoji.js b/packages/discord.js/src/structures/BaseGuildEmoji.js index bb4e8d005e2e..d1ede7d063bc 100644 --- a/packages/discord.js/src/structures/BaseGuildEmoji.js +++ b/packages/discord.js/src/structures/BaseGuildEmoji.js @@ -4,6 +4,7 @@ const { Emoji } = require('./Emoji.js'); /** * Parent class for {@link GuildEmoji} and {@link GuildPreviewEmoji}. + * * @extends {Emoji} * @abstract */ @@ -13,6 +14,7 @@ class BaseGuildEmoji extends Emoji { /** * The guild this emoji is a part of + * * @type {Guild|GuildPreview} */ this.guild = guild; @@ -30,6 +32,7 @@ class BaseGuildEmoji extends Emoji { if ('require_colons' in data) { /** * Whether or not this emoji requires colons surrounding it + * * @type {?boolean} */ this.requiresColons = data.require_colons; @@ -38,6 +41,7 @@ class BaseGuildEmoji extends Emoji { if ('managed' in data) { /** * Whether this emoji is managed by an external service + * * @type {?boolean} */ this.managed = data.managed; @@ -46,6 +50,7 @@ class BaseGuildEmoji extends Emoji { if ('available' in data) { /** * Whether this emoji is available + * * @type {?boolean} */ this.available = data.available; @@ -55,6 +60,7 @@ class BaseGuildEmoji extends Emoji { /** * Returns a URL for the emoji. + * * @method imageURL * @memberof BaseGuildEmoji * @instance diff --git a/packages/discord.js/src/structures/BaseGuildTextChannel.js b/packages/discord.js/src/structures/BaseGuildTextChannel.js index 980fb86a294f..9cf80ac84a98 100644 --- a/packages/discord.js/src/structures/BaseGuildTextChannel.js +++ b/packages/discord.js/src/structures/BaseGuildTextChannel.js @@ -1,12 +1,13 @@ 'use strict'; -const { GuildChannel } = require('./GuildChannel.js'); -const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); const { GuildMessageManager } = require('../managers/GuildMessageManager.js'); const { GuildTextThreadManager } = require('../managers/GuildTextThreadManager.js'); +const { GuildChannel } = require('./GuildChannel.js'); +const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); /** * Represents a text-based guild channel on Discord. + * * @extends {GuildChannel} * @implements {TextBasedChannel} */ @@ -16,18 +17,21 @@ class BaseGuildTextChannel extends GuildChannel { /** * A manager of the messages sent to this channel + * * @type {GuildMessageManager} */ this.messages = new GuildMessageManager(this); /** * A manager of the threads belonging to this channel + * * @type {GuildTextThreadManager} */ this.threads = new GuildTextThreadManager(this); /** * If the guild considers this channel NSFW + * * @type {boolean} */ this.nsfw = Boolean(data.nsfw); @@ -41,6 +45,7 @@ class BaseGuildTextChannel extends GuildChannel { if ('topic' in data) { /** * The topic of the text channel + * * @type {?string} */ this.topic = data.topic; @@ -53,6 +58,7 @@ class BaseGuildTextChannel extends GuildChannel { if ('last_message_id' in data) { /** * The last message id sent in the channel, if one was sent + * * @type {?Snowflake} */ this.lastMessageId = data.last_message_id; @@ -61,6 +67,7 @@ class BaseGuildTextChannel extends GuildChannel { if ('last_pin_timestamp' in data) { /** * The timestamp when the last pinned message was pinned, if there was one + * * @type {?number} */ this.lastPinTimestamp = data.last_pin_timestamp ? Date.parse(data.last_pin_timestamp) : null; @@ -69,6 +76,7 @@ class BaseGuildTextChannel extends GuildChannel { if ('default_auto_archive_duration' in data) { /** * The default auto archive duration for newly created threads in this channel + * * @type {?ThreadAutoArchiveDuration} */ this.defaultAutoArchiveDuration = data.default_auto_archive_duration; @@ -77,6 +85,7 @@ class BaseGuildTextChannel extends GuildChannel { if ('default_thread_rate_limit_per_user' in data) { /** * The initial rate limit per user (slowmode) to set on newly created threads in a channel. + * * @type {?number} */ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user; @@ -91,27 +100,30 @@ class BaseGuildTextChannel extends GuildChannel { /** * Sets the default auto archive duration for all newly created threads in this channel. + * * @param {ThreadAutoArchiveDuration} defaultAutoArchiveDuration The new default auto archive duration * @param {string} [reason] Reason for changing the channel's default auto archive duration * @returns {Promise} */ - setDefaultAutoArchiveDuration(defaultAutoArchiveDuration, reason) { + async setDefaultAutoArchiveDuration(defaultAutoArchiveDuration, reason) { return this.edit({ defaultAutoArchiveDuration, reason }); } /** * Sets the type of this channel. * Only conversion between {@link TextChannel} and {@link AnnouncementChannel} is supported. + * * @param {ChannelType.GuildText|ChannelType.GuildAnnouncement} type The new channel type * @param {string} [reason] Reason for changing the channel's type * @returns {Promise} */ - setType(type, reason) { + async setType(type, reason) { return this.edit({ type, reason }); } /** * Sets a new topic for the guild channel. + * * @param {?string} topic The new topic for the guild channel * @param {string} [reason] Reason for changing the guild channel's topic * @returns {Promise} @@ -121,21 +133,23 @@ class BaseGuildTextChannel extends GuildChannel { * .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`)) * .catch(console.error); */ - setTopic(topic, reason) { + async setTopic(topic, reason) { return this.edit({ topic, reason }); } /** * Data that can be resolved to an Application. This can be: - * * An Application - * * An Activity with associated Application - * * A Snowflake + * An Application + * An Activity with associated Application + * A Snowflake + * * @typedef {Application|Snowflake} ApplicationResolvable */ /** * Options used to create an invite to a guild channel. - * @typedef {Object} InviteCreateOptions + * + * @typedef {object} InviteCreateOptions * @property {boolean} [temporary] Whether members that joined via the invite should be automatically * kicked after 24 hours if they have not yet received a role * @property {number} [maxAge] How long the invite should last (in seconds, 0 for forever) @@ -152,7 +166,8 @@ class BaseGuildTextChannel extends GuildChannel { /** * Creates an invite to this guild channel. - * @param {InviteCreateOptions} [options={}] The options for creating the invite + * + * @param {InviteCreateOptions} [options] The options for creating the invite * @returns {Promise} * @example * // Create an invite to a channel @@ -160,34 +175,47 @@ class BaseGuildTextChannel extends GuildChannel { * .then(invite => console.log(`Created an invite with a code of ${invite.code}`)) * .catch(console.error); */ - createInvite(options) { + async createInvite(options) { return this.guild.invites.create(this.id, options); } /** * Fetches a collection of invites to this guild channel. * Resolves with a collection mapping invites by their codes. - * @param {boolean} [cache=true] Whether or not to cache the fetched invites + * + * @param {boolean} [cache] Whether or not to cache the fetched invites * @returns {Promise>} */ - fetchInvites(cache = true) { + async fetchInvites(cache = true) { return this.guild.invites.fetch({ channelId: this.id, cache }); } // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ + get lastMessage() {} + get lastPinAt() {} + send() {} + sendTyping() {} + createMessageCollector() {} + awaitMessages() {} + createMessageComponentCollector() {} + awaitMessageComponent() {} + bulkDelete() {} + fetchWebhooks() {} + createWebhook() {} + setRateLimitPerUser() {} + setNSFW() {} } diff --git a/packages/discord.js/src/structures/BaseGuildVoiceChannel.js b/packages/discord.js/src/structures/BaseGuildVoiceChannel.js index c42df6476c3d..eabc1b4708f9 100644 --- a/packages/discord.js/src/structures/BaseGuildVoiceChannel.js +++ b/packages/discord.js/src/structures/BaseGuildVoiceChannel.js @@ -2,12 +2,13 @@ const { Collection } = require('@discordjs/collection'); const { PermissionFlagsBits } = require('discord-api-types/v10'); +const { GuildMessageManager } = require('../managers/GuildMessageManager.js'); const { GuildChannel } = require('./GuildChannel.js'); const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); -const { GuildMessageManager } = require('../managers/GuildMessageManager.js'); /** * Represents a voice-based guild channel on Discord. + * * @extends {GuildChannel} * @implements {TextBasedChannel} */ @@ -16,12 +17,14 @@ class BaseGuildVoiceChannel extends GuildChannel { super(guild, data, client, false); /** * A manager of the messages sent to this channel + * * @type {GuildMessageManager} */ this.messages = new GuildMessageManager(this); /** * If the guild considers this channel NSFW + * * @type {boolean} */ this.nsfw = Boolean(data.nsfw); @@ -35,6 +38,7 @@ class BaseGuildVoiceChannel extends GuildChannel { if ('rtc_region' in data) { /** * The RTC region for this voice-based channel. This region is automatically selected if `null`. + * * @type {?string} */ this.rtcRegion = data.rtc_region; @@ -43,6 +47,7 @@ class BaseGuildVoiceChannel extends GuildChannel { if ('bitrate' in data) { /** * The bitrate of this voice-based channel + * * @type {number} */ this.bitrate = data.bitrate; @@ -51,6 +56,7 @@ class BaseGuildVoiceChannel extends GuildChannel { if ('user_limit' in data) { /** * The maximum amount of users allowed in this channel. + * * @type {number} */ this.userLimit = data.user_limit; @@ -59,6 +65,7 @@ class BaseGuildVoiceChannel extends GuildChannel { if ('video_quality_mode' in data) { /** * The camera video quality mode of the channel. + * * @type {?VideoQualityMode} */ this.videoQualityMode = data.video_quality_mode; @@ -69,6 +76,7 @@ class BaseGuildVoiceChannel extends GuildChannel { if ('last_message_id' in data) { /** * The last message id sent in the channel, if one was sent + * * @type {?Snowflake} */ this.lastMessageId = data.last_message_id; @@ -81,6 +89,7 @@ class BaseGuildVoiceChannel extends GuildChannel { if ('rate_limit_per_user' in data) { /** * The rate limit per user (slowmode) for this channel in seconds + * * @type {number} */ this.rateLimitPerUser = data.rate_limit_per_user; @@ -93,6 +102,7 @@ class BaseGuildVoiceChannel extends GuildChannel { /** * The members in this voice-based channel + * * @type {Collection} * @readonly */ @@ -103,11 +113,13 @@ class BaseGuildVoiceChannel extends GuildChannel { coll.set(state.id, state.member); } } + return coll; } /** * Checks if the voice-based channel is full + * * @type {boolean} * @readonly */ @@ -117,6 +129,7 @@ class BaseGuildVoiceChannel extends GuildChannel { /** * Whether the channel is joinable by the client user + * * @type {boolean} * @readonly */ @@ -136,7 +149,8 @@ class BaseGuildVoiceChannel extends GuildChannel { /** * Creates an invite to this guild channel. - * @param {InviteCreateOptions} [options={}] The options for creating the invite + * + * @param {InviteCreateOptions} [options] The options for creating the invite * @returns {Promise} * @example * // Create an invite to a channel @@ -144,21 +158,23 @@ class BaseGuildVoiceChannel extends GuildChannel { * .then(invite => console.log(`Created an invite with a code of ${invite.code}`)) * .catch(console.error); */ - createInvite(options) { + async createInvite(options) { return this.guild.invites.create(this.id, options); } /** * Fetches a collection of invites to this guild channel. - * @param {boolean} [cache=true] Whether to cache the fetched invites + * + * @param {boolean} [cache] Whether to cache the fetched invites * @returns {Promise>} */ - fetchInvites(cache = true) { + async fetchInvites(cache = true) { return this.guild.invites.fetch({ channelId: this.id, cache }); } /** * Sets the bitrate of the channel. + * * @param {number} bitrate The new bitrate * @param {string} [reason] Reason for changing the channel's bitrate * @returns {Promise} @@ -168,12 +184,13 @@ class BaseGuildVoiceChannel extends GuildChannel { * .then(channel => console.log(`Set bitrate to ${channel.bitrate}bps for ${channel.name}`)) * .catch(console.error); */ - setBitrate(bitrate, reason) { + async setBitrate(bitrate, reason) { return this.edit({ bitrate, reason }); } /** * Sets the RTC region of the channel. + * * @param {?string} rtcRegion The new region of the channel. Set to `null` to remove a specific region for the channel * @param {string} [reason] The reason for modifying this region. * @returns {Promise} @@ -184,12 +201,13 @@ class BaseGuildVoiceChannel extends GuildChannel { * // Remove a fixed region for this channel - let Discord decide automatically * channel.setRTCRegion(null, 'We want to let Discord decide.'); */ - setRTCRegion(rtcRegion, reason) { + async setRTCRegion(rtcRegion, reason) { return this.edit({ rtcRegion, reason }); } /** * Sets the user limit of the channel. + * * @param {number} userLimit The new user limit * @param {string} [reason] Reason for changing the user limit * @returns {Promise} @@ -199,33 +217,45 @@ class BaseGuildVoiceChannel extends GuildChannel { * .then(channel => console.log(`Set user limit to ${channel.userLimit} for ${channel.name}`)) * .catch(console.error); */ - setUserLimit(userLimit, reason) { + async setUserLimit(userLimit, reason) { return this.edit({ userLimit, reason }); } /** * Sets the camera video quality mode of the channel. + * * @param {VideoQualityMode} videoQualityMode The new camera video quality mode. * @param {string} [reason] Reason for changing the camera video quality mode. * @returns {Promise} */ - setVideoQualityMode(videoQualityMode, reason) { + async setVideoQualityMode(videoQualityMode, reason) { return this.edit({ videoQualityMode, reason }); } // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ + get lastMessage() {} + send() {} + sendTyping() {} + createMessageCollector() {} + awaitMessages() {} + createMessageComponentCollector() {} + awaitMessageComponent() {} + bulkDelete() {} + fetchWebhooks() {} + createWebhook() {} + setRateLimitPerUser() {} + setNSFW() {} } diff --git a/packages/discord.js/src/structures/BaseInteraction.js b/packages/discord.js/src/structures/BaseInteraction.js index 410ac36aadb5..49bc765199c3 100644 --- a/packages/discord.js/src/structures/BaseInteraction.js +++ b/packages/discord.js/src/structures/BaseInteraction.js @@ -3,12 +3,13 @@ const { Collection } = require('@discordjs/collection'); const { DiscordSnowflake } = require('@sapphire/snowflake'); const { InteractionType, ApplicationCommandType, ComponentType } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); const { SelectMenuTypes } = require('../util/Constants.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); +const { Base } = require('./Base.js'); /** * Represents an interaction. + * * @extends {Base} * @abstract */ @@ -18,18 +19,21 @@ class BaseInteraction extends Base { /** * The interaction's type + * * @type {InteractionType} */ this.type = data.type; /** * The interaction's id + * * @type {Snowflake} */ this.id = data.id; /** * The interaction's token + * * @type {string} * @name BaseInteraction#token * @readonly @@ -38,48 +42,56 @@ class BaseInteraction extends Base { /** * The application's id + * * @type {Snowflake} */ this.applicationId = data.application_id; /** * The id of the channel this interaction was sent in + * * @type {?Snowflake} */ this.channelId = data.channel?.id ?? null; /** * The id of the guild this interaction was sent in + * * @type {?Snowflake} */ this.guildId = data.guild_id ?? null; /** * The user who created this interaction + * * @type {User} */ this.user = this.client.users._add(data.user ?? data.member.user); /** * If this interaction was sent in a guild, the member which sent it + * * @type {?(GuildMember|APIInteractionGuildMember)} */ this.member = data.member ? (this.guild?.members._add(data.member) ?? data.member) : null; /** * The version + * * @type {number} */ this.version = data.version; /** * Set of permissions the application or bot has within the channel the interaction was sent from + * * @type {Readonly} */ this.appPermissions = new PermissionsBitField(data.app_permissions).freeze(); /** * The permissions of the member, if one exists, in the channel this interaction was executed in + * * @type {?Readonly} */ this.memberPermissions = data.member?.permissions @@ -88,18 +100,21 @@ class BaseInteraction extends Base { /** * The locale of the user who invoked this interaction + * * @type {Locale} */ this.locale = data.locale; /** * The preferred locale from the guild this interaction was sent in + * * @type {?Locale} */ this.guildLocale = data.guild_locale ?? null; /** * The entitlements for the invoking user, representing access to premium SKUs + * * @type {Collection} */ this.entitlements = data.entitlements.reduce( @@ -107,23 +122,24 @@ class BaseInteraction extends Base { new Collection(), ); - /* eslint-disable max-len */ /** * Mapping of installation contexts that the interaction was authorized for the related user or guild ids + * * @type {APIAuthorizingIntegrationOwnersMap} * @see {@link https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object-authorizing-integration-owners-object} */ this.authorizingIntegrationOwners = data.authorizing_integration_owners; - /* eslint-enable max-len */ /** * Context where the interaction was triggered from + * * @type {?InteractionContextType} */ this.context = data.context ?? null; /** * Attachment size limit in bytes + * * @type {number} */ this.attachmentSizeLimit = data.attachment_size_limit; @@ -131,6 +147,7 @@ class BaseInteraction extends Base { /** * The timestamp the interaction was created at + * * @type {number} * @readonly */ @@ -140,6 +157,7 @@ class BaseInteraction extends Base { /** * The time the interaction was created at + * * @type {Date} * @readonly */ @@ -149,6 +167,7 @@ class BaseInteraction extends Base { /** * The channel this interaction was sent in + * * @type {?TextBasedChannels} * @readonly */ @@ -158,6 +177,7 @@ class BaseInteraction extends Base { /** * The guild this interaction was sent in + * * @type {?Guild} * @readonly */ @@ -167,6 +187,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is received from a guild. + * * @returns {boolean} */ inGuild() { @@ -175,6 +196,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is received from a cached guild. + * * @returns {boolean} */ inCachedGuild() { @@ -183,6 +205,7 @@ class BaseInteraction extends Base { /** * Indicates whether or not this interaction is received from an uncached guild. + * * @returns {boolean} */ inRawGuild() { @@ -191,6 +214,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is an {@link AutocompleteInteraction} + * * @returns {boolean} */ isAutocomplete() { @@ -199,6 +223,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link CommandInteraction} + * * @returns {boolean} */ isCommand() { @@ -207,6 +232,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link ChatInputCommandInteraction}. + * * @returns {boolean} */ isChatInputCommand() { @@ -215,6 +241,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link ContextMenuCommandInteraction} + * * @returns {boolean} */ isContextMenuCommand() { @@ -226,6 +253,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link PrimaryEntryPointCommandInteraction} + * * @returns {boolean} */ isPrimaryEntryPointCommand() { @@ -236,6 +264,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link MessageComponentInteraction} + * * @returns {boolean} */ isMessageComponent() { @@ -244,6 +273,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link ModalSubmitInteraction} + * * @returns {boolean} */ isModalSubmit() { @@ -252,6 +282,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link UserContextMenuCommandInteraction} + * * @returns {boolean} */ isUserContextMenuCommand() { @@ -260,6 +291,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link MessageContextMenuCommandInteraction} + * * @returns {boolean} */ isMessageContextMenuCommand() { @@ -268,6 +300,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link ButtonInteraction}. + * * @returns {boolean} */ isButton() { @@ -276,6 +309,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a select menu of any known type. + * * @returns {boolean} */ isSelectMenu() { @@ -284,6 +318,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link StringSelectMenuInteraction}. + * * @returns {boolean} */ isStringSelectMenu() { @@ -292,6 +327,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link UserSelectMenuInteraction} + * * @returns {boolean} */ isUserSelectMenu() { @@ -300,6 +336,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link RoleSelectMenuInteraction} + * * @returns {boolean} */ isRoleSelectMenu() { @@ -308,6 +345,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link ChannelSelectMenuInteraction} + * * @returns {boolean} */ isChannelSelectMenu() { @@ -316,6 +354,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction is a {@link MentionableSelectMenuInteraction} + * * @returns {boolean} */ isMentionableSelectMenu() { @@ -324,6 +363,7 @@ class BaseInteraction extends Base { /** * Indicates whether this interaction can be replied to. + * * @returns {boolean} */ isRepliable() { diff --git a/packages/discord.js/src/structures/BaseSelectMenuComponent.js b/packages/discord.js/src/structures/BaseSelectMenuComponent.js index 8785373d6ec1..ecd8b806bfd0 100644 --- a/packages/discord.js/src/structures/BaseSelectMenuComponent.js +++ b/packages/discord.js/src/structures/BaseSelectMenuComponent.js @@ -4,11 +4,13 @@ const { Component } = require('./Component.js'); /** * Represents a select menu component + * * @extends {Component} */ class BaseSelectMenuComponent extends Component { /** * The placeholder for this select menu + * * @type {?string} * @readonly */ @@ -18,6 +20,7 @@ class BaseSelectMenuComponent extends Component { /** * The maximum amount of options that can be selected + * * @type {?number} * @readonly */ @@ -27,6 +30,7 @@ class BaseSelectMenuComponent extends Component { /** * The minimum amount of options that must be selected + * * @type {?number} * @readonly */ @@ -36,6 +40,7 @@ class BaseSelectMenuComponent extends Component { /** * The custom id of this select menu + * * @type {string} * @readonly */ @@ -45,6 +50,7 @@ class BaseSelectMenuComponent extends Component { /** * Whether this select menu is disabled + * * @type {boolean} * @readonly */ diff --git a/packages/discord.js/src/structures/ButtonComponent.js b/packages/discord.js/src/structures/ButtonComponent.js index ab71c3bd529f..b0380c5d2c66 100644 --- a/packages/discord.js/src/structures/ButtonComponent.js +++ b/packages/discord.js/src/structures/ButtonComponent.js @@ -4,11 +4,13 @@ const { Component } = require('./Component.js'); /** * Represents a button component + * * @extends {Component} */ class ButtonComponent extends Component { /** * The style of this button + * * @type {ButtonStyle} * @readonly */ @@ -18,6 +20,7 @@ class ButtonComponent extends Component { /** * The label of this button + * * @type {?string} * @readonly */ @@ -27,6 +30,7 @@ class ButtonComponent extends Component { /** * The emoji used in this button + * * @type {?APIMessageComponentEmoji} * @readonly */ @@ -36,6 +40,7 @@ class ButtonComponent extends Component { /** * Whether this button is disabled + * * @type {boolean} * @readonly */ @@ -45,6 +50,7 @@ class ButtonComponent extends Component { /** * The custom id of this button (only defined on non-link buttons) + * * @type {?string} * @readonly */ @@ -54,6 +60,7 @@ class ButtonComponent extends Component { /** * The URL of this button (only defined on link buttons) + * * @type {?string} * @readonly */ diff --git a/packages/discord.js/src/structures/ButtonInteraction.js b/packages/discord.js/src/structures/ButtonInteraction.js index 157346e9452c..f29bf3967e1b 100644 --- a/packages/discord.js/src/structures/ButtonInteraction.js +++ b/packages/discord.js/src/structures/ButtonInteraction.js @@ -4,6 +4,7 @@ const { MessageComponentInteraction } = require('./MessageComponentInteraction.j /** * Represents a button interaction. + * * @extends {MessageComponentInteraction} */ class ButtonInteraction extends MessageComponentInteraction {} diff --git a/packages/discord.js/src/structures/CategoryChannel.js b/packages/discord.js/src/structures/CategoryChannel.js index 83a51c934b86..68c96f6ac877 100644 --- a/packages/discord.js/src/structures/CategoryChannel.js +++ b/packages/discord.js/src/structures/CategoryChannel.js @@ -1,21 +1,24 @@ 'use strict'; -const { GuildChannel } = require('./GuildChannel.js'); const { CategoryChannelChildManager } = require('../managers/CategoryChannelChildManager.js'); +const { GuildChannel } = require('./GuildChannel.js'); /** * Represents a guild category channel on Discord. + * * @extends {GuildChannel} */ class CategoryChannel extends GuildChannel { /** * The id of the parent of this channel. + * * @name CategoryChannel#parentId * @type {null} */ /** * The parent of this channel. + * * @name CategoryChannel#parent * @type {null} * @readonly @@ -24,6 +27,7 @@ class CategoryChannel extends GuildChannel { /** * Sets the category parent of this channel. * It is not possible to set the parent of a CategoryChannel. + * * @method setParent * @memberof CategoryChannel * @instance @@ -34,6 +38,7 @@ class CategoryChannel extends GuildChannel { /** * A manager of the channels belonging to this category + * * @type {CategoryChannelChildManager} * @readonly */ diff --git a/packages/discord.js/src/structures/ChannelSelectMenuComponent.js b/packages/discord.js/src/structures/ChannelSelectMenuComponent.js index 9c2547d68b86..54ed53f752ca 100644 --- a/packages/discord.js/src/structures/ChannelSelectMenuComponent.js +++ b/packages/discord.js/src/structures/ChannelSelectMenuComponent.js @@ -4,11 +4,13 @@ const { BaseSelectMenuComponent } = require('./BaseSelectMenuComponent.js'); /** * Represents a channel select menu component + * * @extends {BaseSelectMenuComponent} */ class ChannelSelectMenuComponent extends BaseSelectMenuComponent { /** * The options in this select menu + * * @type {?(ChannelType[])} * @readonly */ diff --git a/packages/discord.js/src/structures/ChannelSelectMenuInteraction.js b/packages/discord.js/src/structures/ChannelSelectMenuInteraction.js index a9b33f3e7f6c..ed5c4a6c3269 100644 --- a/packages/discord.js/src/structures/ChannelSelectMenuInteraction.js +++ b/packages/discord.js/src/structures/ChannelSelectMenuInteraction.js @@ -5,6 +5,7 @@ const { MessageComponentInteraction } = require('./MessageComponentInteraction.j /** * Represents a {@link ComponentType.ChannelSelect} select menu interaction. + * * @extends {MessageComponentInteraction} */ class ChannelSelectMenuInteraction extends MessageComponentInteraction { @@ -14,12 +15,14 @@ class ChannelSelectMenuInteraction extends MessageComponentInteraction { /** * An array of the selected channel ids + * * @type {Snowflake[]} */ this.values = values ?? []; /** * Collection of the selected channels + * * @type {Collection} */ this.channels = new Collection(); diff --git a/packages/discord.js/src/structures/ChatInputCommandInteraction.js b/packages/discord.js/src/structures/ChatInputCommandInteraction.js index 0ff8c34d36a1..5368320c386e 100644 --- a/packages/discord.js/src/structures/ChatInputCommandInteraction.js +++ b/packages/discord.js/src/structures/ChatInputCommandInteraction.js @@ -1,11 +1,12 @@ 'use strict'; +const { transformResolved } = require('../util/Util.js'); const { CommandInteraction } = require('./CommandInteraction.js'); const { CommandInteractionOptionResolver } = require('./CommandInteractionOptionResolver.js'); -const { transformResolved } = require('../util/Util.js'); /** * Represents a command interaction. + * * @extends {CommandInteraction} */ class ChatInputCommandInteraction extends CommandInteraction { @@ -14,6 +15,7 @@ class ChatInputCommandInteraction extends CommandInteraction { /** * The options passed to the command. + * * @type {CommandInteractionOptionResolver} */ this.options = new CommandInteractionOptionResolver( @@ -26,6 +28,7 @@ class ChatInputCommandInteraction extends CommandInteraction { /** * Returns a string representation of the command interaction. * This can then be copied by a user and executed again in a new command while keeping the option order. + * * @returns {string} */ toString() { diff --git a/packages/discord.js/src/structures/ClientApplication.js b/packages/discord.js/src/structures/ClientApplication.js index c02f451a85c8..9f7dd4ae1c4e 100644 --- a/packages/discord.js/src/structures/ClientApplication.js +++ b/packages/discord.js/src/structures/ClientApplication.js @@ -2,10 +2,6 @@ const { Collection } = require('@discordjs/collection'); const { Routes } = require('discord-api-types/v10'); -const { ApplicationRoleConnectionMetadata } = require('./ApplicationRoleConnectionMetadata.js'); -const { SKU } = require('./SKU.js'); -const { Team } = require('./Team.js'); -const { Application } = require('./interfaces/Application.js'); const { ApplicationCommandManager } = require('../managers/ApplicationCommandManager.js'); const { ApplicationEmojiManager } = require('../managers/ApplicationEmojiManager.js'); const { EntitlementManager } = require('../managers/EntitlementManager.js'); @@ -13,15 +9,20 @@ const { SubscriptionManager } = require('../managers/SubscriptionManager.js'); const { ApplicationFlagsBitField } = require('../util/ApplicationFlagsBitField.js'); const { resolveImage } = require('../util/DataResolver.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); +const { ApplicationRoleConnectionMetadata } = require('./ApplicationRoleConnectionMetadata.js'); +const { SKU } = require('./SKU.js'); +const { Team } = require('./Team.js'); +const { Application } = require('./interfaces/Application.js'); /** - * @typedef {Object} ClientApplicationInstallParams + * @typedef {object} ClientApplicationInstallParams * @property {OAuth2Scopes[]} scopes Scopes that will be set upon adding this application * @property {Readonly} permissions Permissions that will be requested for the integrated role */ /** * Represents a client application. + * * @extends {Application} */ class ClientApplication extends Application { @@ -30,24 +31,28 @@ class ClientApplication extends Application { /** * The application command manager for this application + * * @type {ApplicationCommandManager} */ this.commands = new ApplicationCommandManager(this.client); /** * The application emoji manager for this application + * * @type {ApplicationEmojiManager} */ this.emojis = new ApplicationEmojiManager(this); /** * The entitlement manager for this application + * * @type {EntitlementManager} */ this.entitlements = new EntitlementManager(this.client); /** * The subscription manager for this application + * * @type {SubscriptionManager} */ this.subscriptions = new SubscriptionManager(this.client); @@ -58,6 +63,7 @@ class ClientApplication extends Application { /** * The tags this application has (max of 5) + * * @type {string[]} */ this.tags = data.tags ?? []; @@ -65,6 +71,7 @@ class ClientApplication extends Application { if ('install_params' in data) { /** * Settings for this application's default in-app authorization + * * @type {?ClientApplicationInstallParams} */ this.installParams = { @@ -77,21 +84,24 @@ class ClientApplication extends Application { /** * OAuth2 installation parameters. - * @typedef {Object} IntegrationTypesConfigurationParameters + * + * @typedef {object} IntegrationTypesConfigurationParameters * @property {OAuth2Scopes[]} scopes Scopes that will be set upon adding this application * @property {Readonly} permissions Permissions that will be requested for the integrated role */ /** * The application's supported installation context data. - * @typedef {Object} IntegrationTypesConfigurationContext + * + * @typedef {object} IntegrationTypesConfigurationContext * @property {?IntegrationTypesConfigurationParameters} oauth2InstallParams * Scopes and permissions regarding the installation context */ /** * The application's supported installation context data. - * @typedef {Object} IntegrationTypesConfiguration + * + * @typedef {object} IntegrationTypesConfiguration * @property {IntegrationTypesConfigurationContext} [0] Scopes and permissions * regarding the guild-installation context * @property {IntegrationTypesConfigurationContext} [1] Scopes and permissions @@ -102,6 +112,7 @@ class ClientApplication extends Application { /** * Default scopes and permissions for each supported installation context. * The keys are stringified variants of {@link ApplicationIntegrationType}. + * * @type {?IntegrationTypesConfiguration} */ this.integrationTypesConfig = Object.fromEntries( @@ -128,6 +139,7 @@ class ClientApplication extends Application { if ('custom_install_url' in data) { /** * This application's custom installation URL + * * @type {?string} */ this.customInstallURL = data.custom_install_url; @@ -138,6 +150,7 @@ class ClientApplication extends Application { if ('flags' in data) { /** * The flags this application has + * * @type {ApplicationFlagsBitField} */ this.flags = new ApplicationFlagsBitField(data.flags).freeze(); @@ -146,6 +159,7 @@ class ClientApplication extends Application { if ('approximate_guild_count' in data) { /** * An approximate amount of guilds this application is in. + * * @type {?number} */ this.approximateGuildCount = data.approximate_guild_count; @@ -156,6 +170,7 @@ class ClientApplication extends Application { if ('approximate_user_install_count' in data) { /** * An approximate amount of users that have installed this application. + * * @type {?number} */ this.approximateUserInstallCount = data.approximate_user_install_count; @@ -166,6 +181,7 @@ class ClientApplication extends Application { if ('guild_id' in data) { /** * The id of the guild associated with this application. + * * @type {?Snowflake} */ this.guildId = data.guild_id; @@ -176,6 +192,7 @@ class ClientApplication extends Application { if ('bot_require_code_grant' in data) { /** * If this application's bot requires a code grant when using the OAuth2 flow + * * @type {?boolean} */ this.botRequireCodeGrant = data.bot_require_code_grant; @@ -186,6 +203,7 @@ class ClientApplication extends Application { if ('bot' in data) { /** * The bot associated with this application. + * * @type {?User} */ this.bot = this.client.users._add(data.bot); @@ -196,6 +214,7 @@ class ClientApplication extends Application { if ('bot_public' in data) { /** * If this application's bot is public + * * @type {?boolean} */ this.botPublic = data.bot_public; @@ -206,6 +225,7 @@ class ClientApplication extends Application { if ('interactions_endpoint_url' in data) { /** * This application's interaction endpoint URL. + * * @type {?string} */ this.interactionsEndpointURL = data.interactions_endpoint_url; @@ -216,6 +236,7 @@ class ClientApplication extends Application { if ('role_connections_verification_url' in data) { /** * This application's role connection verification entry point URL + * * @type {?string} */ this.roleConnectionsVerificationURL = data.role_connections_verification_url; @@ -226,6 +247,7 @@ class ClientApplication extends Application { if ('event_webhooks_url' in data) { /** * This application's URL to receive event webhooks + * * @type {?string} */ this.eventWebhooksURL = data.event_webhooks_url; @@ -236,6 +258,7 @@ class ClientApplication extends Application { if ('event_webhooks_status' in data) { /** * This application's event webhooks status + * * @type {?ApplicationWebhookEventStatus} */ this.eventWebhooksStatus = data.event_webhooks_status; @@ -246,6 +269,7 @@ class ClientApplication extends Application { if ('event_webhooks_types' in data) { /** * List of event webhooks types this application subscribes to + * * @type {?ApplicationWebhookEventType[]} */ this.eventWebhooksTypes = data.event_webhooks_types; @@ -255,6 +279,7 @@ class ClientApplication extends Application { /** * The owner of this OAuth application + * * @type {?(User|Team)} */ this.owner = data.team @@ -266,6 +291,7 @@ class ClientApplication extends Application { /** * The guild associated with this application. + * * @type {?Guild} * @readonly */ @@ -275,6 +301,7 @@ class ClientApplication extends Application { /** * Whether this application is partial + * * @type {boolean} * @readonly */ @@ -284,7 +311,8 @@ class ClientApplication extends Application { /** * Options used for editing an application. - * @typedef {Object} ClientApplicationEditOptions + * + * @typedef {object} ClientApplicationEditOptions * @property {string} [customInstallURL] The application's custom installation URL * @property {string} [description] The application's description * @property {string} [roleConnectionsVerificationURL] The application's role connection verification URL @@ -303,6 +331,7 @@ class ClientApplication extends Application { /** * Edits this application. + * * @param {ClientApplicationEditOptions} [options] The options for editing this application * @returns {Promise} */ @@ -343,6 +372,7 @@ class ClientApplication extends Application { /** * Obtains this application from Discord. + * * @returns {Promise} */ async fetch() { @@ -353,6 +383,7 @@ class ClientApplication extends Application { /** * Gets this application's role connection metadata records + * * @returns {Promise} */ async fetchRoleConnectionMetadataRecords() { @@ -362,17 +393,19 @@ class ClientApplication extends Application { /** * Data for creating or editing an application role connection metadata. - * @typedef {Object} ApplicationRoleConnectionMetadataEditOptions + * + * @typedef {object} ApplicationRoleConnectionMetadataEditOptions * @property {string} name The name of the metadata field - * @property {?Object} [nameLocalizations] The name localizations for the metadata field + * @property {?Record} [nameLocalizations] The name localizations for the metadata field * @property {string} description The description of the metadata field - * @property {?Object} [descriptionLocalizations] The description localizations for the metadata field + * @property {?Record} [descriptionLocalizations] The description localizations for the metadata field * @property {string} key The dictionary key of the metadata field * @property {ApplicationRoleConnectionMetadataType} type The type of the metadata field */ /** * Updates this application's role connection metadata records + * * @param {ApplicationRoleConnectionMetadataEditOptions[]} records The new role connection metadata records * @returns {Promise} */ @@ -393,6 +426,7 @@ class ClientApplication extends Application { /** * Gets this application's SKUs + * * @returns {Promise>} */ async fetchSKUs() { diff --git a/packages/discord.js/src/structures/ClientPresence.js b/packages/discord.js/src/structures/ClientPresence.js index bc2e9b9d555e..3c92cdb8b26a 100644 --- a/packages/discord.js/src/structures/ClientPresence.js +++ b/packages/discord.js/src/structures/ClientPresence.js @@ -1,11 +1,13 @@ +/* eslint-disable id-length */ 'use strict'; const { GatewayOpcodes, ActivityType } = require('discord-api-types/v10'); -const { Presence } = require('./Presence.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); +const { Presence } = require('./Presence.js'); /** * Represents the client's presence. + * * @extends {Presence} */ class ClientPresence extends Presence { @@ -15,6 +17,7 @@ class ClientPresence extends Presence { /** * Sets the client's presence + * * @param {PresenceData} presence The data to set the presence to * @returns {Promise} */ @@ -30,11 +33,13 @@ class ClientPresence extends Presence { } else { await this.client.ws.send(presence.shardId, { op: GatewayOpcodes.PresenceUpdate, d: packet }); } + return this; } /** * Parses presence data into a packet ready to be sent to Discord + * * @param {PresenceData} presence The data to parse * @returns {GatewayPresenceUpdateData} * @private diff --git a/packages/discord.js/src/structures/ClientUser.js b/packages/discord.js/src/structures/ClientUser.js index 24b85c3553e1..83d38852997e 100644 --- a/packages/discord.js/src/structures/ClientUser.js +++ b/packages/discord.js/src/structures/ClientUser.js @@ -1,11 +1,12 @@ 'use strict'; const { Routes } = require('discord-api-types/v10'); -const { User } = require('./User.js'); const { resolveImage } = require('../util/DataResolver.js'); +const { User } = require('./User.js'); /** * Represents the logged in client's Discord user. + * * @extends {User} */ class ClientUser extends User { @@ -15,6 +16,7 @@ class ClientUser extends User { if ('verified' in data) { /** * Whether or not this account has been verified + * * @type {boolean} */ this.verified = data.verified; @@ -23,6 +25,7 @@ class ClientUser extends User { if ('mfa_enabled' in data) { /** * If the bot's {@link ClientApplication#owner Owner} has MFA enabled on their account + * * @type {?boolean} */ this.mfaEnabled = typeof data.mfa_enabled === 'boolean' ? data.mfa_enabled : null; @@ -35,6 +38,7 @@ class ClientUser extends User { /** * Represents the client user's presence + * * @type {ClientPresence} * @readonly */ @@ -44,7 +48,8 @@ class ClientUser extends User { /** * Data used to edit the logged in client - * @typedef {Object} ClientUserEditOptions + * + * @typedef {object} ClientUserEditOptions * @property {string} [username] The new username * @property {?(BufferResolvable|Base64Resolvable)} [avatar] The new avatar * @property {?(BufferResolvable|Base64Resolvable)} [banner] The new banner @@ -52,6 +57,7 @@ class ClientUser extends User { /** * Edits the logged in client. + * * @param {ClientUserEditOptions} options The options to provide * @returns {Promise} */ @@ -74,6 +80,7 @@ class ClientUser extends User { * Sets the username of the logged in client. * Changing usernames in Discord is heavily rate limited, with only 2 requests * every hour. Use this sparingly! + * * @param {string} username The new username * @returns {Promise} * @example @@ -82,12 +89,13 @@ class ClientUser extends User { * .then(user => console.log(`My new username is ${user.username}`)) * .catch(console.error); */ - setUsername(username) { + async setUsername(username) { return this.edit({ username }); } /** * Sets the avatar of the logged in client. + * * @param {?(BufferResolvable|Base64Resolvable)} avatar The new avatar * @returns {Promise} * @example @@ -96,12 +104,13 @@ class ClientUser extends User { * .then(user => console.log(`New avatar set!`)) * .catch(console.error); */ - setAvatar(avatar) { + async setAvatar(avatar) { return this.edit({ avatar }); } /** * Sets the banner of the logged in client. + * * @param {?(BufferResolvable|Base64Resolvable)} banner The new banner * @returns {Promise} * @example @@ -110,13 +119,14 @@ class ClientUser extends User { * .then(user => console.log(`New banner set!`)) * .catch(console.error); */ - setBanner(banner) { + async setBanner(banner) { return this.edit({ banner }); } /** * Options for setting activities - * @typedef {Object} ActivitiesOptions + * + * @typedef {object} ActivitiesOptions * @property {string} name Name of the activity * @property {string} [state] State of the activity * @property {ActivityType} [type] Type of the activity @@ -125,7 +135,8 @@ class ClientUser extends User { /** * Data resembling a raw Discord presence. - * @typedef {Object} PresenceData + * + * @typedef {object} PresenceData * @property {PresenceStatusData} [status] Status of the user * @property {boolean} [afk] Whether the user is AFK * @property {ActivitiesOptions[]} [activities] Activity the user is playing @@ -134,27 +145,30 @@ class ClientUser extends User { /** * Sets the full presence of the client user. + * * @param {PresenceData} data Data for the presence * @returns {Promise} * @example * // Set the client user's presence * client.user.setPresence({ activities: [{ name: 'with discord.js' }], status: 'idle' }); */ - setPresence(data) { + async setPresence(data) { return this.client.presence.set(data); } /** * A user's status. Must be one of: - * * `online` - * * `idle` - * * `invisible` - * * `dnd` (do not disturb) + * `online` + * `idle` + * `invisible` + * `dnd` (do not disturb) + * * @typedef {string} PresenceStatusData */ /** * Sets the status of the client user. + * * @param {PresenceStatusData} status Status to change to * @param {number|number[]} [shardId] Shard id(s) to have the activity set on * @returns {Promise} @@ -162,13 +176,14 @@ class ClientUser extends User { * // Set the client user's status * client.user.setStatus('idle'); */ - setStatus(status, shardId) { + async setStatus(status, shardId) { return this.setPresence({ status, shardId }); } /** * Options for setting an activity. - * @typedef {Object} ActivityOptions + * + * @typedef {object} ActivityOptions * @property {string} name Name of the activity * @property {string} [state] State of the activity * @property {string} [url] Twitch / YouTube stream URL @@ -178,6 +193,7 @@ class ClientUser extends User { /** * Sets the activity the client user is playing. + * * @param {string|ActivityOptions} name Activity being played, or options for setting the activity * @param {ActivityOptions} [options] Options for setting the activity * @returns {Promise} @@ -185,20 +201,21 @@ class ClientUser extends User { * // Set the client user's activity * client.user.setActivity('discord.js', { type: ActivityType.Watching }); */ - setActivity(name, options = {}) { + async setActivity(name, options = {}) { if (!name) return this.setPresence({ activities: [], shardId: options.shardId }); - const activity = Object.assign({}, options, typeof name === 'object' ? name : { name }); + const activity = { ...options, ...(typeof name === 'object' ? name : { name }) }; return this.setPresence({ activities: [activity], shardId: activity.shardId }); } /** * Sets/removes the AFK flag for the client user. - * @param {boolean} [afk=true] Whether or not the user is AFK + * + * @param {boolean} [afk] Whether or not the user is AFK * @param {number|number[]} [shardId] Shard Id(s) to have the AFK flag set on * @returns {Promise} */ - setAFK(afk = true, shardId) { + async setAFK(afk = true, shardId = undefined) { return this.setPresence({ afk, shardId }); } } diff --git a/packages/discord.js/src/structures/CommandInteraction.js b/packages/discord.js/src/structures/CommandInteraction.js index 05a90422f692..fa920cbe9f50 100644 --- a/packages/discord.js/src/structures/CommandInteraction.js +++ b/packages/discord.js/src/structures/CommandInteraction.js @@ -7,6 +7,7 @@ const { InteractionResponses } = require('./interfaces/InteractionResponses.js') /** * Represents a command interaction. + * * @extends {BaseInteraction} * @implements {InteractionResponses} * @abstract @@ -17,54 +18,63 @@ class CommandInteraction extends BaseInteraction { /** * The id of the channel this interaction was sent in + * * @type {Snowflake} * @name CommandInteraction#channelId */ /** * The invoked application command's id + * * @type {Snowflake} */ this.commandId = data.data.id; /** * The invoked application command's name + * * @type {string} */ this.commandName = data.data.name; /** * The invoked application command's type + * * @type {ApplicationCommandType} */ this.commandType = data.data.type; /** * The id of the guild the invoked application command is registered to + * * @type {?Snowflake} */ this.commandGuildId = data.data.guild_id ?? null; /** * Whether the reply to this interaction has been deferred + * * @type {boolean} */ this.deferred = false; /** * Whether this interaction has already been replied to + * * @type {boolean} */ this.replied = false; /** * Whether the reply to this interaction is ephemeral + * * @type {?boolean} */ this.ephemeral = null; /** * An associated interaction webhook, can be used to further interact with this interaction + * * @type {InteractionWebhook} */ this.webhook = new InteractionWebhook(this.client, this.applicationId, this.token); @@ -72,6 +82,7 @@ class CommandInteraction extends BaseInteraction { /** * The invoked application command, if it was fetched before + * * @type {?ApplicationCommand} */ get command() { @@ -81,7 +92,8 @@ class CommandInteraction extends BaseInteraction { /** * Represents the resolved data of a received command interaction. - * @typedef {Object} CommandInteractionResolvedData + * + * @typedef {object} CommandInteractionResolvedData * @property {Collection} [users] The resolved users * @property {Collection} [members] The resolved guild members * @property {Collection} [roles] The resolved roles @@ -92,7 +104,8 @@ class CommandInteraction extends BaseInteraction { /** * Represents an option of a received command interaction. - * @typedef {Object} CommandInteractionOption + * + * @typedef {object} CommandInteractionOption * @property {string} name The name of the option * @property {ApplicationCommandOptionType} type The type of the option * @property {boolean} [autocomplete] Whether the autocomplete interaction is enabled for a @@ -110,6 +123,7 @@ class CommandInteraction extends BaseInteraction { /** * Transforms an option received from the API. + * * @param {APIApplicationCommandOption} option The received option * @param {APIInteractionDataResolved} resolved The resolved interaction data * @returns {CommandInteractionOption} @@ -145,15 +159,23 @@ class CommandInteraction extends BaseInteraction { } // These are here only for documentation purposes - they are implemented by InteractionResponses - /* eslint-disable no-empty-function */ + deferReply() {} + reply() {} + fetchReply() {} + editReply() {} + deleteReply() {} + followUp() {} + launchActivity() {} + showModal() {} + awaitModalSubmit() {} } diff --git a/packages/discord.js/src/structures/CommandInteractionOptionResolver.js b/packages/discord.js/src/structures/CommandInteractionOptionResolver.js index d5728d5664db..79252454fded 100644 --- a/packages/discord.js/src/structures/CommandInteractionOptionResolver.js +++ b/packages/discord.js/src/structures/CommandInteractionOptionResolver.js @@ -10,6 +10,7 @@ class CommandInteractionOptionResolver { constructor(client, options, resolved) { /** * The client that instantiated this. + * * @name CommandInteractionOptionResolver#client * @type {Client} * @readonly @@ -18,6 +19,7 @@ class CommandInteractionOptionResolver { /** * The name of the subcommand group. + * * @type {?string} * @private */ @@ -25,6 +27,7 @@ class CommandInteractionOptionResolver { /** * The name of the subcommand. + * * @type {?string} * @private */ @@ -33,6 +36,7 @@ class CommandInteractionOptionResolver { /** * The bottom-level options for the interaction. * If there is a subcommand (or subcommand and group), this is the options for the subcommand. + * * @type {CommandInteractionOption[]} * @private */ @@ -43,6 +47,7 @@ class CommandInteractionOptionResolver { this._group = this._hoistedOptions[0].name; this._hoistedOptions = this._hoistedOptions[0].options ?? []; } + // Hoist subcommand if present if (this._hoistedOptions[0]?.type === ApplicationCommandOptionType.Subcommand) { this._subcommand = this._hoistedOptions[0].name; @@ -51,6 +56,7 @@ class CommandInteractionOptionResolver { /** * The interaction options array. + * * @name CommandInteractionOptionResolver#data * @type {ReadonlyArray} * @readonly @@ -59,6 +65,7 @@ class CommandInteractionOptionResolver { /** * The interaction resolved data + * * @name CommandInteractionOptionResolver#resolved * @type {?Readonly} */ @@ -67,8 +74,9 @@ class CommandInteractionOptionResolver { /** * Gets an option by its name. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?CommandInteractionOption} The option, if found. */ get(name, required = false) { @@ -77,13 +85,16 @@ class CommandInteractionOptionResolver { if (required) { throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNotFound, name); } + return null; } + return option; } /** * Gets an option by name and property and checks its type. + * * @param {string} name The name of the option. * @param {ApplicationCommandOptionType[]} allowedTypes The allowed types of the option. * @param {string[]} properties The properties to check for for `required`. @@ -100,37 +111,43 @@ class CommandInteractionOptionResolver { } else if (required && properties.every(prop => option[prop] === null || option[prop] === undefined)) { throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionEmpty, name, option.type); } + return option; } /** * Gets the selected subcommand. - * @param {boolean} [required=true] Whether to throw an error if there is no subcommand. + * + * @param {boolean} [required] Whether to throw an error if there is no subcommand. * @returns {?string} The name of the selected subcommand, or null if not set and not required. */ getSubcommand(required = true) { if (required && !this._subcommand) { throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNoSubcommand); } + return this._subcommand; } /** * Gets the selected subcommand group. - * @param {boolean} [required=false] Whether to throw an error if there is no subcommand group. + * + * @param {boolean} [required] Whether to throw an error if there is no subcommand group. * @returns {?string} The name of the selected subcommand group, or null if not set and not required. */ getSubcommandGroup(required = false) { if (required && !this._group) { throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNoSubcommandGroup); } + return this._group; } /** * Gets a boolean option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?boolean} The value of the option, or null if not set and not required. */ getBoolean(name, required = false) { @@ -140,9 +157,10 @@ class CommandInteractionOptionResolver { /** * Gets a channel option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. - * @param {ChannelType[]} [channelTypes=[]] The allowed types of channels. If empty, all channel types are allowed. + * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {ChannelType[]} [channelTypes] The allowed types of channels. If empty, all channel types are allowed. * @returns {?(GuildChannel|ThreadChannel|APIChannel)} * The value of the option, or null if not set and not required. */ @@ -164,8 +182,9 @@ class CommandInteractionOptionResolver { /** * Gets a string option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?string} The value of the option, or null if not set and not required. */ getString(name, required = false) { @@ -175,8 +194,9 @@ class CommandInteractionOptionResolver { /** * Gets an integer option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?number} The value of the option, or null if not set and not required. */ getInteger(name, required = false) { @@ -186,8 +206,9 @@ class CommandInteractionOptionResolver { /** * Gets a number option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?number} The value of the option, or null if not set and not required. */ getNumber(name, required = false) { @@ -197,8 +218,9 @@ class CommandInteractionOptionResolver { /** * Gets a user option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?User} The value of the option, or null if not set and not required. */ getUser(name, required = false) { @@ -213,6 +235,7 @@ class CommandInteractionOptionResolver { /** * Gets a member option. + * * @param {string} name The name of the option. * @returns {?(GuildMember|APIGuildMember)} * The value of the option, or null if the user is not present in the guild or the option is not set. @@ -229,8 +252,9 @@ class CommandInteractionOptionResolver { /** * Gets a role option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?(Role|APIRole)} The value of the option, or null if not set and not required. */ getRole(name, required = false) { @@ -245,8 +269,9 @@ class CommandInteractionOptionResolver { /** * Gets an attachment option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?Attachment} The value of the option, or null if not set and not required. */ getAttachment(name, required = false) { @@ -256,8 +281,9 @@ class CommandInteractionOptionResolver { /** * Gets a mentionable option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?(User|GuildMember|APIGuildMember|Role|APIRole)} * The value of the option, or null if not set and not required. */ @@ -273,8 +299,9 @@ class CommandInteractionOptionResolver { /** * Gets a message option. + * * @param {string} name The name of the option. - * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {boolean} [required] Whether to throw an error if the option is not found. * @returns {?Message} * The value of the option, or null if not set and not required. */ @@ -285,7 +312,8 @@ class CommandInteractionOptionResolver { /** * The full autocomplete option object. - * @typedef {Object} AutocompleteFocusedOption + * + * @typedef {object} AutocompleteFocusedOption * @property {string} name The name of the option * @property {ApplicationCommandOptionType} type The type of the application command option * @property {string} value The value of the option @@ -294,6 +322,7 @@ class CommandInteractionOptionResolver { /** * Gets the focused option. + * * @returns {AutocompleteFocusedOption} * The whole object of the option that is focused */ diff --git a/packages/discord.js/src/structures/Component.js b/packages/discord.js/src/structures/Component.js index fbe464f76278..94c28bf3d834 100644 --- a/packages/discord.js/src/structures/Component.js +++ b/packages/discord.js/src/structures/Component.js @@ -9,6 +9,7 @@ class Component { constructor(data) { /** * The API data associated with this component + * * @type {APIMessageComponent} */ this.data = data; @@ -16,6 +17,7 @@ class Component { /** * The type of the component + * * @type {ComponentType} * @readonly */ @@ -25,6 +27,7 @@ class Component { /** * Whether or not the given components are equal + * * @param {Component|APIMessageComponent} other The component to compare against * @returns {boolean} */ @@ -32,11 +35,13 @@ class Component { if (other instanceof Component) { return isEqual(other.data, this.data); } + return isEqual(other, this.data); } /** * Returns the API-compatible JSON for this component + * * @returns {APIMessageComponent} */ toJSON() { diff --git a/packages/discord.js/src/structures/ContextMenuCommandInteraction.js b/packages/discord.js/src/structures/ContextMenuCommandInteraction.js index d4f05eeea01a..52c8bae84df2 100644 --- a/packages/discord.js/src/structures/ContextMenuCommandInteraction.js +++ b/packages/discord.js/src/structures/ContextMenuCommandInteraction.js @@ -2,14 +2,15 @@ const { lazy } = require('@discordjs/util'); const { ApplicationCommandOptionType } = require('discord-api-types/v10'); +const { transformResolved } = require('../util/Util.js'); const { CommandInteraction } = require('./CommandInteraction.js'); const { CommandInteractionOptionResolver } = require('./CommandInteractionOptionResolver.js'); -const { transformResolved } = require('../util/Util.js'); const getMessage = lazy(() => require('./Message.js').Message); /** * Represents a context menu interaction. + * * @extends {CommandInteraction} */ class ContextMenuCommandInteraction extends CommandInteraction { @@ -17,6 +18,7 @@ class ContextMenuCommandInteraction extends CommandInteraction { super(client, data); /** * The target of the interaction, parsed into options + * * @type {CommandInteractionOptionResolver} */ this.options = new CommandInteractionOptionResolver( @@ -27,6 +29,7 @@ class ContextMenuCommandInteraction extends CommandInteraction { /** * The id of the target of this interaction + * * @type {Snowflake} */ this.targetId = data.data.target_id; @@ -34,6 +37,7 @@ class ContextMenuCommandInteraction extends CommandInteraction { /** * Resolves and transforms options received from the API for a context menu interaction. + * * @param {APIApplicationCommandInteractionData} data The interaction data * @returns {CommandInteractionOption[]} * @private diff --git a/packages/discord.js/src/structures/DMChannel.js b/packages/discord.js/src/structures/DMChannel.js index a77d56f917d2..d568070e8df1 100644 --- a/packages/discord.js/src/structures/DMChannel.js +++ b/packages/discord.js/src/structures/DMChannel.js @@ -2,13 +2,14 @@ const { userMention } = require('@discordjs/formatters'); const { ChannelType } = require('discord-api-types/v10'); -const { BaseChannel } = require('./BaseChannel.js'); -const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); const { DMMessageManager } = require('../managers/DMMessageManager.js'); const { Partials } = require('../util/Partials.js'); +const { BaseChannel } = require('./BaseChannel.js'); +const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); /** * Represents a direct message channel between two users. + * * @extends {BaseChannel} * @implements {TextBasedChannel} */ @@ -21,6 +22,7 @@ class DMChannel extends BaseChannel { /** * A manager of the messages belonging to this channel + * * @type {DMMessageManager} */ this.messages = new DMMessageManager(this); @@ -34,6 +36,7 @@ class DMChannel extends BaseChannel { /** * The recipient's id + * * @type {Snowflake} */ this.recipientId = recipient.id; @@ -46,6 +49,7 @@ class DMChannel extends BaseChannel { if ('last_message_id' in data) { /** * The channel's last message id, if one was sent + * * @type {?Snowflake} */ this.lastMessageId = data.last_message_id; @@ -54,6 +58,7 @@ class DMChannel extends BaseChannel { if ('last_pin_timestamp' in data) { /** * The timestamp when the last pinned message was pinned, if there was one + * * @type {?number} */ this.lastPinTimestamp = Date.parse(data.last_pin_timestamp); @@ -64,6 +69,7 @@ class DMChannel extends BaseChannel { /** * Whether this DMChannel is a partial + * * @type {boolean} * @readonly */ @@ -73,6 +79,7 @@ class DMChannel extends BaseChannel { /** * The recipient on the other end of the DM + * * @type {?User} * @readonly */ @@ -82,16 +89,18 @@ class DMChannel extends BaseChannel { /** * Fetch this DMChannel. - * @param {boolean} [force=true] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - fetch(force = true) { + async fetch(force = true) { return this.client.users.createDM(this.recipientId, { force }); } /** * When concatenated with a string, this automatically returns the recipient's mention instead of the * DMChannel object. + * * @returns {string} * @example * // Logs: Hello from <@123456789012345678>! @@ -102,14 +111,21 @@ class DMChannel extends BaseChannel { } // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ + get lastMessage() {} + get lastPinAt() {} + send() {} + sendTyping() {} + createMessageCollector() {} + awaitMessages() {} + createMessageComponentCollector() {} + awaitMessageComponent() {} // Doesn't work on DM channels; bulkDelete() {} // Doesn't work on DM channels; fetchWebhooks() {} diff --git a/packages/discord.js/src/structures/DirectoryChannel.js b/packages/discord.js/src/structures/DirectoryChannel.js index b1cb3c61013f..12c7a054c248 100644 --- a/packages/discord.js/src/structures/DirectoryChannel.js +++ b/packages/discord.js/src/structures/DirectoryChannel.js @@ -4,6 +4,7 @@ const { BaseChannel } = require('./BaseChannel.js'); /** * Represents a channel that displays a directory of guilds. + * * @extends {BaseChannel} */ class DirectoryChannel extends BaseChannel { @@ -12,12 +13,14 @@ class DirectoryChannel extends BaseChannel { /** * The guild the channel is in + * * @type {InviteGuild} */ this.guild = guild; /** * The id of the guild the channel is in + * * @type {Snowflake} */ this.guildId = guild.id; @@ -27,6 +30,7 @@ class DirectoryChannel extends BaseChannel { super._patch(data); /** * The channel's name + * * @type {string} */ this.name = data.name; diff --git a/packages/discord.js/src/structures/Embed.js b/packages/discord.js/src/structures/Embed.js index 3021493339b9..517958d50c19 100644 --- a/packages/discord.js/src/structures/Embed.js +++ b/packages/discord.js/src/structures/Embed.js @@ -10,6 +10,7 @@ class Embed { constructor(data) { /** * The API embed data. + * * @type {APIEmbed} * @readonly */ @@ -18,6 +19,7 @@ class Embed { /** * An array of fields of this embed. + * * @type {Array} * @readonly */ @@ -27,6 +29,7 @@ class Embed { /** * The title of this embed. + * * @type {?string} * @readonly */ @@ -36,6 +39,7 @@ class Embed { /** * The description of this embed. + * * @type {?string} * @readonly */ @@ -45,6 +49,7 @@ class Embed { /** * The URL of this embed. + * * @type {?string} * @readonly */ @@ -54,6 +59,7 @@ class Embed { /** * The color of this embed. + * * @type {?number} * @readonly */ @@ -63,6 +69,7 @@ class Embed { /** * The timestamp of this embed. This is in an ISO 8601 format. + * * @type {?string} * @readonly */ @@ -71,7 +78,7 @@ class Embed { } /** - * @typedef {Object} EmbedAssetData + * @typedef {object} EmbedAssetData * @property {?string} url The URL of the image * @property {?string} proxyURL The proxy URL of the image * @property {?number} height The height of the image @@ -80,6 +87,7 @@ class Embed { /** * The thumbnail of this embed. + * * @type {?EmbedAssetData} * @readonly */ @@ -95,6 +103,7 @@ class Embed { /** * The image of this embed. + * * @type {?EmbedAssetData} * @readonly */ @@ -110,6 +119,7 @@ class Embed { /** * The video of this embed. + * * @type {?EmbedAssetData} * @readonly */ @@ -124,7 +134,7 @@ class Embed { } /** - * @typedef {Object} EmbedAuthorData + * @typedef {object} EmbedAuthorData * @property {string} name The name of the author * @property {?string} url The URL of the author * @property {?string} iconURL The icon URL of the author @@ -133,6 +143,7 @@ class Embed { /** * The author of this embed. + * * @type {?EmbedAuthorData} * @readonly */ @@ -148,6 +159,7 @@ class Embed { /** * The provider of this embed. + * * @type {?APIEmbedProvider} * @readonly */ @@ -156,7 +168,7 @@ class Embed { } /** - * @typedef {Object} EmbedFooterData + * @typedef {object} EmbedFooterData * @property {string} text The text of the footer * @property {?string} iconURL The URL of the icon * @property {?string} proxyIconURL The proxy URL of the icon @@ -164,6 +176,7 @@ class Embed { /** * The footer of this embed. + * * @type {?EmbedFooterData} * @readonly */ @@ -178,6 +191,7 @@ class Embed { /** * The accumulated length for the embed title, description, fields, footer text, and author name. + * * @type {number} * @readonly */ @@ -187,6 +201,7 @@ class Embed { /** * The hex color of this embed. + * * @type {?string} * @readonly */ @@ -198,6 +213,7 @@ class Embed { /** * Returns the API-compatible JSON for this embed. + * * @returns {APIEmbed} */ toJSON() { @@ -206,6 +222,7 @@ class Embed { /** * Whether the given embeds are equal. + * * @param {Embed|APIEmbed} other The embed to compare against * @returns {boolean} */ diff --git a/packages/discord.js/src/structures/Emoji.js b/packages/discord.js/src/structures/Emoji.js index 8ce73fb045a0..f410773fde88 100644 --- a/packages/discord.js/src/structures/Emoji.js +++ b/packages/discord.js/src/structures/Emoji.js @@ -6,6 +6,7 @@ const { Base } = require('./Base.js'); /** * Represents an emoji, see {@link ApplicationEmoji}, {@link GuildEmoji} and {@link ReactionEmoji}. + * * @extends {Base} */ class Emoji extends Base { @@ -13,18 +14,21 @@ class Emoji extends Base { super(client); /** * Whether or not the emoji is animated + * * @type {?boolean} */ this.animated = emoji.animated ?? null; /** * The emoji's name + * * @type {?string} */ this.name = emoji.name ?? null; /** * The emoji's id + * * @type {?Snowflake} */ this.id = emoji.id ?? null; @@ -32,6 +36,7 @@ class Emoji extends Base { /** * The identifier of this emoji, used for message reactions + * * @type {string} * @readonly */ @@ -42,7 +47,8 @@ class Emoji extends Base { /** * Returns a URL for the emoji or `null` if this is not a custom emoji. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ imageURL(options = {}) { @@ -51,6 +57,7 @@ class Emoji extends Base { /** * The timestamp the emoji was created at, or null if unicode + * * @type {?number} * @readonly */ @@ -60,6 +67,7 @@ class Emoji extends Base { /** * The time the emoji was created at, or null if unicode + * * @type {?Date} * @readonly */ @@ -70,6 +78,7 @@ class Emoji extends Base { /** * When concatenated with a string, this automatically returns the text required to form a graphical emoji on Discord * instead of the Emoji object. + * * @returns {string} * @example * // Send a custom emoji from a guild: diff --git a/packages/discord.js/src/structures/Entitlement.js b/packages/discord.js/src/structures/Entitlement.js index 890afe88df44..92db4b111768 100644 --- a/packages/discord.js/src/structures/Entitlement.js +++ b/packages/discord.js/src/structures/Entitlement.js @@ -4,6 +4,7 @@ const { Base } = require('./Base.js'); /** * Represents an Entitlement + * * @extends {Base} */ class Entitlement extends Base { @@ -12,6 +13,7 @@ class Entitlement extends Base { /** * The id of the entitlement + * * @type {Snowflake} */ this.id = data.id; @@ -23,6 +25,7 @@ class Entitlement extends Base { if ('sku_id' in data) { /** * The id of the associated SKU + * * @type {Snowflake} */ this.skuId = data.sku_id; @@ -31,6 +34,7 @@ class Entitlement extends Base { if ('user_id' in data) { /** * The id of the user that is granted access to this entitlement's SKU + * * @type {Snowflake} */ this.userId = data.user_id; @@ -39,6 +43,7 @@ class Entitlement extends Base { if ('guild_id' in data) { /** * The id of the guild that is granted access to this entitlement's SKU + * * @type {?Snowflake} */ this.guildId = data.guild_id; @@ -49,6 +54,7 @@ class Entitlement extends Base { if ('application_id' in data) { /** * The id of the parent application + * * @type {Snowflake} */ this.applicationId = data.application_id; @@ -57,6 +63,7 @@ class Entitlement extends Base { if ('type' in data) { /** * The type of this entitlement + * * @type {EntitlementType} */ this.type = data.type; @@ -65,6 +72,7 @@ class Entitlement extends Base { if ('deleted' in data) { /** * Whether this entitlement was deleted + * * @type {boolean} */ this.deleted = data.deleted; @@ -73,6 +81,7 @@ class Entitlement extends Base { if ('starts_at' in data) { /** * The timestamp at which this entitlement is valid + * * @type {?number} */ this.startsTimestamp = data.starts_at ? Date.parse(data.starts_at) : null; @@ -83,6 +92,7 @@ class Entitlement extends Base { if ('ends_at' in data) { /** * The timestamp at which this entitlement is no longer valid + * * @type {?number} */ this.endsTimestamp = data.ends_at ? Date.parse(data.ends_at) : null; @@ -93,6 +103,7 @@ class Entitlement extends Base { if ('consumed' in data) { /** * Whether this entitlement has been consumed + * * @type {boolean} */ this.consumed = data.consumed; @@ -103,6 +114,7 @@ class Entitlement extends Base { /** * The guild that is granted access to this entitlement's SKU + * * @type {?Guild} */ get guild() { @@ -112,6 +124,7 @@ class Entitlement extends Base { /** * The start date at which this entitlement is valid + * * @type {?Date} */ get startsAt() { @@ -120,6 +133,7 @@ class Entitlement extends Base { /** * The end date at which this entitlement is no longer valid + * * @type {?Date} */ get endsAt() { @@ -128,6 +142,7 @@ class Entitlement extends Base { /** * Indicates whether this entitlement is active + * * @returns {boolean} */ isActive() { @@ -136,6 +151,7 @@ class Entitlement extends Base { /** * Indicates whether this entitlement is a test entitlement + * * @returns {boolean} */ isTest() { @@ -144,6 +160,7 @@ class Entitlement extends Base { /** * Indicates whether this entitlement is a user subscription + * * @returns {boolean} */ isUserSubscription() { @@ -152,6 +169,7 @@ class Entitlement extends Base { /** * Indicates whether this entitlement is a guild subscription + * * @returns {boolean} */ isGuildSubscription() { @@ -160,15 +178,17 @@ class Entitlement extends Base { /** * Fetches the user that is granted access to this entitlement's SKU + * * @returns {Promise} */ - fetchUser() { + async fetchUser() { return this.client.users.fetch(this.userId); } /** * Marks this entitlement as consumed * Only available for One-Time Purchase consumable SKUs. + * * @returns {Promise} */ async consume() { diff --git a/packages/discord.js/src/structures/ForumChannel.js b/packages/discord.js/src/structures/ForumChannel.js index b18d9c7d5bb1..4d41927e2f83 100644 --- a/packages/discord.js/src/structures/ForumChannel.js +++ b/packages/discord.js/src/structures/ForumChannel.js @@ -4,6 +4,7 @@ const { ThreadOnlyChannel } = require('./ThreadOnlyChannel.js'); /** * Represents a forum channel. + * * @extends {ThreadOnlyChannel} */ class ForumChannel extends ThreadOnlyChannel { @@ -12,6 +13,7 @@ class ForumChannel extends ThreadOnlyChannel { /** * The default layout type used to display posts + * * @type {ForumLayoutType} */ this.defaultForumLayout = data.default_forum_layout; @@ -19,11 +21,12 @@ class ForumChannel extends ThreadOnlyChannel { /** * Sets the default forum layout type used to display posts + * * @param {ForumLayoutType} defaultForumLayout The default forum layout type to set on this channel * @param {string} [reason] Reason for changing the default forum layout * @returns {Promise} */ - setDefaultForumLayout(defaultForumLayout, reason) { + async setDefaultForumLayout(defaultForumLayout, reason) { return this.edit({ defaultForumLayout, reason }); } } diff --git a/packages/discord.js/src/structures/Guild.js b/packages/discord.js/src/structures/Guild.js index 8c971bb660e9..636c2e0384fd 100644 --- a/packages/discord.js/src/structures/Guild.js +++ b/packages/discord.js/src/structures/Guild.js @@ -4,14 +4,6 @@ const { Collection } = require('@discordjs/collection'); const { makeURLSearchParams } = require('@discordjs/rest'); const { DiscordSnowflake } = require('@sapphire/snowflake'); const { ChannelType, GuildPremiumTier, Routes, GuildFeature } = require('discord-api-types/v10'); -const { AnonymousGuild } = require('./AnonymousGuild.js'); -const { GuildAuditLogs } = require('./GuildAuditLogs.js'); -const { GuildOnboarding } = require('./GuildOnboarding.js'); -const { GuildPreview } = require('./GuildPreview.js'); -const { GuildTemplate } = require('./GuildTemplate.js'); -const { Integration } = require('./Integration.js'); -const { Webhook } = require('./Webhook.js'); -const { WelcomeScreen } = require('./WelcomeScreen.js'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { AutoModerationRuleManager } = require('../managers/AutoModerationRuleManager.js'); const { GuildApplicationCommandManager } = require('../managers/GuildApplicationCommandManager.js'); @@ -31,11 +23,20 @@ const { resolveImage } = require('../util/DataResolver.js'); const { SystemChannelFlagsBitField } = require('../util/SystemChannelFlagsBitField.js'); const { _transformAPIIncidentsData } = require('../util/Transformers.js'); const { discordSort, getSortableGroupTypes, resolvePartialEmoji } = require('../util/Util.js'); +const { AnonymousGuild } = require('./AnonymousGuild.js'); +const { GuildAuditLogs } = require('./GuildAuditLogs.js'); +const { GuildOnboarding } = require('./GuildOnboarding.js'); +const { GuildPreview } = require('./GuildPreview.js'); +const { GuildTemplate } = require('./GuildTemplate.js'); +const { Integration } = require('./Integration.js'); +const { Webhook } = require('./Webhook.js'); +const { WelcomeScreen } = require('./WelcomeScreen.js'); /** * Represents a guild (or a server) on Discord. * It's recommended to see if a guild is available before performing operations or reading data from it. You can * check this with {@link Guild#available}. + * * @extends {AnonymousGuild} */ class Guild extends AnonymousGuild { @@ -44,72 +45,84 @@ class Guild extends AnonymousGuild { /** * A manager of the application commands belonging to this guild + * * @type {GuildApplicationCommandManager} */ this.commands = new GuildApplicationCommandManager(this); /** * A manager of the members belonging to this guild + * * @type {GuildMemberManager} */ this.members = new GuildMemberManager(this); /** * A manager of the channels belonging to this guild + * * @type {GuildChannelManager} */ this.channels = new GuildChannelManager(this); /** * A manager of the bans belonging to this guild + * * @type {GuildBanManager} */ this.bans = new GuildBanManager(this); /** * A manager of the roles belonging to this guild + * * @type {RoleManager} */ this.roles = new RoleManager(this); /** * A manager of the presences belonging to this guild + * * @type {PresenceManager} */ this.presences = new PresenceManager(this.client); /** * A manager of the voice states of this guild + * * @type {VoiceStateManager} */ this.voiceStates = new VoiceStateManager(this); /** * A manager of the stage instances of this guild + * * @type {StageInstanceManager} */ this.stageInstances = new StageInstanceManager(this); /** * A manager of the invites of this guild + * * @type {GuildInviteManager} */ this.invites = new GuildInviteManager(this); /** * A manager of the scheduled events of this guild + * * @type {GuildScheduledEventManager} */ this.scheduledEvents = new GuildScheduledEventManager(this); /** * A manager of the auto moderation rules of this guild. + * * @type {AutoModerationRuleManager} */ this.autoModerationRules = new AutoModerationRuleManager(this); /** * A manager of the soundboard sounds of this guild. + * * @type {GuildSoundboardSoundManager} */ this.soundboardSounds = new GuildSoundboardSoundManager(this); @@ -118,6 +131,7 @@ class Guild extends AnonymousGuild { if (data.unavailable) { /** * Whether the guild is available to access. If it is not available, it indicates a server outage + * * @type {boolean} */ this.available = false; @@ -128,6 +142,7 @@ class Guild extends AnonymousGuild { /** * The id of the shard this Guild belongs to. + * * @type {number} */ this.shardId = data.shardId; @@ -147,6 +162,7 @@ class Guild extends AnonymousGuild { if ('discovery_splash' in data) { /** * The hash of the guild discovery splash image + * * @type {?string} */ this.discoverySplash = data.discovery_splash; @@ -155,6 +171,7 @@ class Guild extends AnonymousGuild { if ('member_count' in data) { /** * The full amount of members in this guild + * * @type {number} */ this.memberCount = data.member_count; @@ -163,6 +180,7 @@ class Guild extends AnonymousGuild { if ('large' in data) { /** * Whether the guild is "large" (has more than {@link WebSocketOptions large_threshold} members, 50 by default) + * * @type {boolean} */ this.large = Boolean(data.large); @@ -171,6 +189,7 @@ class Guild extends AnonymousGuild { if ('premium_progress_bar_enabled' in data) { /** * Whether this guild has its premium (boost) progress bar enabled + * * @type {boolean} */ this.premiumProgressBarEnabled = data.premium_progress_bar_enabled; @@ -179,6 +198,7 @@ class Guild extends AnonymousGuild { if ('application_id' in data) { /** * The id of the application that created this guild (if applicable) + * * @type {?Snowflake} */ this.applicationId = data.application_id; @@ -187,6 +207,7 @@ class Guild extends AnonymousGuild { if ('afk_timeout' in data) { /** * The time in seconds before a user is counted as "away from keyboard" + * * @type {?number} */ this.afkTimeout = data.afk_timeout; @@ -195,6 +216,7 @@ class Guild extends AnonymousGuild { if ('afk_channel_id' in data) { /** * The id of the voice channel where AFK members are moved + * * @type {?Snowflake} */ this.afkChannelId = data.afk_channel_id; @@ -203,6 +225,7 @@ class Guild extends AnonymousGuild { if ('system_channel_id' in data) { /** * The system channel's id + * * @type {?Snowflake} */ this.systemChannelId = data.system_channel_id; @@ -211,6 +234,7 @@ class Guild extends AnonymousGuild { if ('premium_tier' in data) { /** * The premium tier of this guild + * * @type {GuildPremiumTier} */ this.premiumTier = data.premium_tier; @@ -219,6 +243,7 @@ class Guild extends AnonymousGuild { if ('widget_enabled' in data) { /** * Whether widget images are enabled on this guild + * * @type {?boolean} */ this.widgetEnabled = data.widget_enabled; @@ -229,6 +254,7 @@ class Guild extends AnonymousGuild { if ('widget_channel_id' in data) { /** * The widget channel's id, if enabled + * * @type {?string} */ this.widgetChannelId = data.widget_channel_id; @@ -239,6 +265,7 @@ class Guild extends AnonymousGuild { if ('explicit_content_filter' in data) { /** * The explicit content filter level of the guild + * * @type {GuildExplicitContentFilter} */ this.explicitContentFilter = data.explicit_content_filter; @@ -247,6 +274,7 @@ class Guild extends AnonymousGuild { if ('mfa_level' in data) { /** * The required MFA level for this guild + * * @type {GuildMFALevel} */ this.mfaLevel = data.mfa_level; @@ -255,6 +283,7 @@ class Guild extends AnonymousGuild { if ('joined_at' in data) { /** * The timestamp the client user joined the guild at + * * @type {number} */ this.joinedTimestamp = Date.parse(data.joined_at); @@ -263,6 +292,7 @@ class Guild extends AnonymousGuild { if ('default_message_notifications' in data) { /** * The default message notification level of the guild + * * @type {GuildDefaultMessageNotifications} */ this.defaultMessageNotifications = data.default_message_notifications; @@ -271,6 +301,7 @@ class Guild extends AnonymousGuild { if ('system_channel_flags' in data) { /** * The value set for the guild's system channel flags + * * @type {Readonly} */ this.systemChannelFlags = new SystemChannelFlagsBitField(data.system_channel_flags).freeze(); @@ -279,6 +310,7 @@ class Guild extends AnonymousGuild { if ('max_members' in data) { /** * The maximum amount of members the guild can have + * * @type {?number} */ this.maximumMembers = data.max_members; @@ -291,6 +323,7 @@ class Guild extends AnonymousGuild { * The maximum amount of presences the guild can have (this is `null` for all but the largest of guilds) * You will need to fetch the guild using {@link BaseGuild#fetch} if you want to receive * this parameter + * * @type {?number} */ this.maximumPresences = data.max_presences; @@ -301,6 +334,7 @@ class Guild extends AnonymousGuild { if ('max_video_channel_users' in data) { /** * The maximum amount of users allowed in a video channel. + * * @type {?number} */ this.maxVideoChannelUsers = data.max_video_channel_users; @@ -311,6 +345,7 @@ class Guild extends AnonymousGuild { if ('max_stage_video_channel_users' in data) { /** * The maximum amount of users allowed in a stage video channel. + * * @type {?number} */ this.maxStageVideoChannelUsers = data.max_stage_video_channel_users; @@ -323,6 +358,7 @@ class Guild extends AnonymousGuild { * The approximate amount of members the guild has * You will need to fetch the guild using {@link BaseGuild#fetch} if you want to receive * this parameter + * * @type {?number} */ this.approximateMemberCount = data.approximate_member_count; @@ -335,6 +371,7 @@ class Guild extends AnonymousGuild { * The approximate amount of presences the guild has * You will need to fetch the guild using {@link BaseGuild#fetch} if you want to receive * this parameter + * * @type {?number} */ this.approximatePresenceCount = data.approximate_presence_count; @@ -345,6 +382,7 @@ class Guild extends AnonymousGuild { /** * The use count of the vanity URL code of the guild, if any * You will need to fetch this parameter using {@link Guild#fetchVanityData} if you want to receive it + * * @type {?number} */ this.vanityURLUses ??= null; @@ -352,6 +390,7 @@ class Guild extends AnonymousGuild { if ('rules_channel_id' in data) { /** * The rules channel's id for the guild + * * @type {?Snowflake} */ this.rulesChannelId = data.rules_channel_id; @@ -360,6 +399,7 @@ class Guild extends AnonymousGuild { if ('public_updates_channel_id' in data) { /** * The community updates channel's id for the guild + * * @type {?Snowflake} */ this.publicUpdatesChannelId = data.public_updates_channel_id; @@ -368,6 +408,7 @@ class Guild extends AnonymousGuild { if ('preferred_locale' in data) { /** * The preferred locale of the guild, defaults to `en-US` + * * @type {Locale} */ this.preferredLocale = data.preferred_locale; @@ -376,6 +417,7 @@ class Guild extends AnonymousGuild { if ('safety_alerts_channel_id' in data) { /** * The safety alerts channel's id for the guild + * * @type {?Snowflake} */ this.safetyAlertsChannelId = data.safety_alerts_channel_id; @@ -409,6 +451,7 @@ class Guild extends AnonymousGuild { if ('owner_id' in data) { /** * The user id of this guild's owner + * * @type {Snowflake} */ this.ownerId = data.owner_id; @@ -444,6 +487,7 @@ class Guild extends AnonymousGuild { if (!this.emojis) { /** * A manager of the emojis belonging to this guild + * * @type {GuildEmojiManager} */ this.emojis = new GuildEmojiManager(this); @@ -458,6 +502,7 @@ class Guild extends AnonymousGuild { if (!this.stickers) { /** * A manager of the stickers belonging to this guild + * * @type {GuildStickerManager} */ this.stickers = new GuildStickerManager(this); @@ -472,7 +517,8 @@ class Guild extends AnonymousGuild { if ('incidents_data' in data) { /** * Incident actions of a guild. - * @typedef {Object} IncidentActions + * + * @typedef {object} IncidentActions * @property {?Date} invitesDisabledUntil When invites would be enabled again * @property {?Date} dmsDisabledUntil When direct messages would be enabled again * @property {?Date} dmSpamDetectedAt When direct message spam was detected @@ -483,6 +529,7 @@ class Guild extends AnonymousGuild { * The incidents data of this guild. * You will need to fetch the guild using {@link BaseGuild#fetch} if you want to receive * this property. + * * @type {?IncidentActions} */ this.incidentsData = data.incidents_data && _transformAPIIncidentsData(data.incidents_data); @@ -493,6 +540,7 @@ class Guild extends AnonymousGuild { /** * The time the client user joined the guild + * * @type {Date} * @readonly */ @@ -502,7 +550,8 @@ class Guild extends AnonymousGuild { /** * The URL to this guild's discovery splash image. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ discoverySplashURL(options = {}) { @@ -512,6 +561,7 @@ class Guild extends AnonymousGuild { /** * Fetches the owner of the guild. * If the member object isn't needed, use {@link Guild#ownerId} instead. + * * @param {BaseFetchOptions} [options] The options for fetching the member * @returns {Promise} */ @@ -519,12 +569,13 @@ class Guild extends AnonymousGuild { if (!this.ownerId) { throw new DiscordjsError(ErrorCodes.FetchOwnerId, 'guild'); } - const member = await this.members.fetch({ ...options, user: this.ownerId }); - return member; + + return this.members.fetch({ ...options, user: this.ownerId }); } /** * AFK voice channel for this guild + * * @type {?VoiceChannel} * @readonly */ @@ -534,6 +585,7 @@ class Guild extends AnonymousGuild { /** * System channel for this guild + * * @type {?TextChannel} * @readonly */ @@ -543,6 +595,7 @@ class Guild extends AnonymousGuild { /** * Widget channel for this guild + * * @type {?(TextChannel|AnnouncementChannel|VoiceChannel|StageChannel|ForumChannel|MediaChannel)} * @readonly */ @@ -552,6 +605,7 @@ class Guild extends AnonymousGuild { /** * Rules channel for this guild + * * @type {?TextChannel} * @readonly */ @@ -561,6 +615,7 @@ class Guild extends AnonymousGuild { /** * Public updates channel for this guild + * * @type {?TextChannel} * @readonly */ @@ -570,6 +625,7 @@ class Guild extends AnonymousGuild { /** * Safety alerts channel for this guild + * * @type {?TextChannel} * @readonly */ @@ -579,6 +635,7 @@ class Guild extends AnonymousGuild { /** * The maximum bitrate available for this guild + * * @type {number} * @readonly */ @@ -587,6 +644,7 @@ class Guild extends AnonymousGuild { return 384_000; } + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check switch (this.premiumTier) { case GuildPremiumTier.Tier1: return 128_000; @@ -602,6 +660,7 @@ class Guild extends AnonymousGuild { /** * Fetches a collection of integrations to this guild. * Resolves with a collection mapping integrations by their ids. + * * @returns {Promise>} * @example * // Fetch integrations @@ -620,6 +679,7 @@ class Guild extends AnonymousGuild { /** * Fetches a collection of templates from this guild. * Resolves with a collection mapping templates by their codes. + * * @returns {Promise>} */ async fetchTemplates() { @@ -629,6 +689,7 @@ class Guild extends AnonymousGuild { /** * Fetches the welcome screen for this guild. + * * @returns {Promise} */ async fetchWelcomeScreen() { @@ -638,6 +699,7 @@ class Guild extends AnonymousGuild { /** * Creates a template for the guild. + * * @param {string} name The name for the template * @param {string} [description] The description for the template * @returns {Promise} @@ -649,6 +711,7 @@ class Guild extends AnonymousGuild { /** * Obtains a guild preview for this guild from Discord. + * * @returns {Promise} */ async fetchPreview() { @@ -658,7 +721,8 @@ class Guild extends AnonymousGuild { /** * An object containing information about a guild's vanity invite. - * @typedef {Object} Vanity + * + * @typedef {object} Vanity * @property {?string} code Vanity invite code * @property {number} uses How many times this invite has been used */ @@ -666,6 +730,7 @@ class Guild extends AnonymousGuild { /** * Fetches the vanity URL invite object to this guild. * Resolves with an object containing the vanity URL invite code and the use count + * * @returns {Promise} * @example * // Fetch invite data @@ -685,6 +750,7 @@ class Guild extends AnonymousGuild { /** * Fetches all webhooks for the guild. + * * @returns {Promise>} * @example * // Fetch webhooks @@ -701,6 +767,7 @@ class Guild extends AnonymousGuild { /** * Fetches the guild widget data, requires the widget to be enabled. + * * @returns {Promise} * @example * // Fetches the guild widget data @@ -708,13 +775,14 @@ class Guild extends AnonymousGuild { * .then(widget => console.log(`The widget shows ${widget.channels.size} channels`)) * .catch(console.error); */ - fetchWidget() { + async fetchWidget() { return this.client.fetchGuildWidget(this.id); } /** * Data for the Guild Widget Settings object - * @typedef {Object} GuildWidgetSettings + * + * @typedef {object} GuildWidgetSettings * @property {boolean} enabled Whether the widget is enabled * @property {?(TextChannel|AnnouncementChannel|VoiceChannel|StageChannel|ForumChannel|MediaChannel)} channel * The widget invite channel @@ -722,7 +790,8 @@ class Guild extends AnonymousGuild { /** * The Guild Widget Settings object - * @typedef {Object} GuildWidgetSettingsData + * + * @typedef {object} GuildWidgetSettingsData * @property {boolean} enabled Whether the widget is enabled * @property {?(TextChannel|AnnouncementChannel|VoiceChannel|StageChannel|ForumChannel| * MediaChannel|Snowflake)} channel The widget invite channel @@ -730,6 +799,7 @@ class Guild extends AnonymousGuild { /** * Fetches the guild widget settings. + * * @returns {Promise} * @example * // Fetches the guild widget settings @@ -749,6 +819,7 @@ class Guild extends AnonymousGuild { /** * Returns a URL for the PNG widget of the guild. + * * @param {GuildWidgetStyle} [style] The style for the widget image * @returns {string} */ @@ -758,7 +829,8 @@ class Guild extends AnonymousGuild { /** * Options used to fetch audit logs. - * @typedef {Object} GuildAuditLogsFetchOptions + * + * @typedef {object} GuildAuditLogsFetchOptions * @property {Snowflake|GuildAuditLogsEntry} [before] Consider only entries before this entry * @property {Snowflake|GuildAuditLogsEntry} [after] Consider only entries after this entry * @property {number} [limit] The number of entries to return @@ -768,7 +840,8 @@ class Guild extends AnonymousGuild { /** * Fetches audit logs for this guild. - * @param {GuildAuditLogsFetchOptions} [options={}] Options for fetching audit logs + * + * @param {GuildAuditLogsFetchOptions} [options] Options for fetching audit logs * @returns {Promise} * @example * // Output audit log entries @@ -796,6 +869,7 @@ class Guild extends AnonymousGuild { /** * Fetches the guild onboarding data for this guild. + * * @returns {Promise} */ async fetchOnboarding() { @@ -805,7 +879,8 @@ class Guild extends AnonymousGuild { /** * The data for editing a guild. - * @typedef {Object} GuildEditOptions + * + * @typedef {object} GuildEditOptions * @property {string} [name] The name of the guild * @property {?GuildVerificationLevel} [verificationLevel] The verification level of the guild * @property {?GuildDefaultMessageNotifications} [defaultMessageNotifications] The default message @@ -832,20 +907,23 @@ class Guild extends AnonymousGuild { /** * Data that can be resolved to a Text Channel object. This can be: - * * A TextChannel - * * A Snowflake + * A TextChannel + * A Snowflake + * * @typedef {TextChannel|Snowflake} TextChannelResolvable */ /** * Data that can be resolved to a Voice Channel object. This can be: - * * A VoiceChannel - * * A Snowflake + * A VoiceChannel + * A Snowflake + * * @typedef {VoiceChannel|Snowflake} VoiceChannelResolvable */ /** * Updates the guild with new information - e.g. a new name. + * * @param {GuildEditOptions} options The options to provide * @returns {Promise} * @example @@ -906,7 +984,8 @@ class Guild extends AnonymousGuild { /** * Options used to edit the guild onboarding. - * @typedef {Object} GuildOnboardingEditOptions + * + * @typedef {object} GuildOnboardingEditOptions * @property {GuildOnboardingPromptData[]|Collection} [prompts] * The prompts shown during onboarding and in customize community * @property {ChannelResolvable[]|Collection} [defaultChannels] @@ -918,7 +997,8 @@ class Guild extends AnonymousGuild { /** * Data for editing a guild onboarding prompt. - * @typedef {Object} GuildOnboardingPromptData + * + * @typedef {object} GuildOnboardingPromptData * @property {Snowflake} [id] The id of the prompt * @property {string} title The title for the prompt * @property {boolean} [singleSelect] Whether users are limited to selecting one option for the prompt @@ -931,7 +1011,8 @@ class Guild extends AnonymousGuild { /** * Data for editing a guild onboarding prompt option. - * @typedef {Object} GuildOnboardingPromptOptionData + * + * @typedef {object} GuildOnboardingPromptOptionData * @property {?Snowflake} [id] The id of the option * @property {ChannelResolvable[]|Collection} [channels] * The channels a member is added to when the option is selected @@ -944,6 +1025,7 @@ class Guild extends AnonymousGuild { /** * Edits the guild onboarding data for this guild. + * * @param {GuildOnboardingEditOptions} options The options to provide * @returns {Promise} */ @@ -985,7 +1067,8 @@ class Guild extends AnonymousGuild { /** * Welcome channel data - * @typedef {Object} WelcomeChannelData + * + * @typedef {object} WelcomeChannelData * @property {string} description The description to show for this welcome channel * @property {TextChannel|AnnouncementChannel|ForumChannel|MediaChannel|Snowflake} channel * The channel to link for this welcome channel @@ -994,7 +1077,8 @@ class Guild extends AnonymousGuild { /** * Welcome screen edit data - * @typedef {Object} WelcomeScreenEditOptions + * + * @typedef {object} WelcomeScreenEditOptions * @property {boolean} [enabled] Whether the welcome screen is enabled * @property {string} [description] The description for the welcome screen * @property {WelcomeChannelData[]} [welcomeChannels] The welcome channel data for the welcome screen @@ -1002,22 +1086,25 @@ class Guild extends AnonymousGuild { /** * Data that can be resolved to a GuildTextChannel object. This can be: - * * A TextChannel - * * A AnnouncementChannel - * * A Snowflake + * A TextChannel + * A AnnouncementChannel + * A Snowflake + * * @typedef {TextChannel|AnnouncementChannel|Snowflake} GuildTextChannelResolvable */ /** * Data that can be resolved to a GuildVoiceChannel object. This can be: - * * A VoiceChannel - * * A StageChannel - * * A Snowflake + * A VoiceChannel + * A StageChannel + * A Snowflake + * * @typedef {VoiceChannel|StageChannel|Snowflake} GuildVoiceChannelResolvable */ /** * Updates the guild's welcome screen + * * @param {WelcomeScreenEditOptions} options The options to provide * @returns {Promise} * @example @@ -1056,37 +1143,41 @@ class Guild extends AnonymousGuild { /** * Edits the level of the explicit content filter. + * * @param {?GuildExplicitContentFilter} explicitContentFilter The new level of the explicit content filter * @param {string} [reason] Reason for changing the level of the guild's explicit content filter * @returns {Promise} */ - setExplicitContentFilter(explicitContentFilter, reason) { + async setExplicitContentFilter(explicitContentFilter, reason) { return this.edit({ explicitContentFilter, reason }); } /** * Edits the setting of the default message notifications of the guild. + * * @param {?GuildDefaultMessageNotifications} defaultMessageNotifications * The new default message notification level of the guild * @param {string} [reason] Reason for changing the setting of the default message notifications * @returns {Promise} */ - setDefaultMessageNotifications(defaultMessageNotifications, reason) { + async setDefaultMessageNotifications(defaultMessageNotifications, reason) { return this.edit({ defaultMessageNotifications, reason }); } /** * Edits the flags of the default message notifications of the guild. + * * @param {SystemChannelFlagsResolvable} systemChannelFlags The new flags for the default message notifications * @param {string} [reason] Reason for changing the flags of the default message notifications * @returns {Promise} */ - setSystemChannelFlags(systemChannelFlags, reason) { + async setSystemChannelFlags(systemChannelFlags, reason) { return this.edit({ systemChannelFlags, reason }); } /** * Edits the name of the guild. + * * @param {string} name The new name of the guild * @param {string} [reason] Reason for changing the guild's name * @returns {Promise} @@ -1096,12 +1187,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild name to ${updated.name}`)) * .catch(console.error); */ - setName(name, reason) { + async setName(name, reason) { return this.edit({ name, reason }); } /** * Edits the verification level of the guild. + * * @param {?GuildVerificationLevel} verificationLevel The new verification level of the guild * @param {string} [reason] Reason for changing the guild's verification level * @returns {Promise} @@ -1111,12 +1203,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild verification level to ${guild.verificationLevel}`)) * .catch(console.error); */ - setVerificationLevel(verificationLevel, reason) { + async setVerificationLevel(verificationLevel, reason) { return this.edit({ verificationLevel, reason }); } /** * Edits the AFK channel of the guild. + * * @param {?VoiceChannelResolvable} afkChannel The new AFK channel * @param {string} [reason] Reason for changing the guild's AFK channel * @returns {Promise} @@ -1126,12 +1219,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild AFK channel to ${guild.afkChannel.name}`)) * .catch(console.error); */ - setAFKChannel(afkChannel, reason) { + async setAFKChannel(afkChannel, reason) { return this.edit({ afkChannel, reason }); } /** * Edits the system channel of the guild. + * * @param {?TextChannelResolvable} systemChannel The new system channel * @param {string} [reason] Reason for changing the guild's system channel * @returns {Promise} @@ -1141,12 +1235,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild system channel to ${guild.systemChannel.name}`)) * .catch(console.error); */ - setSystemChannel(systemChannel, reason) { + async setSystemChannel(systemChannel, reason) { return this.edit({ systemChannel, reason }); } /** * Edits the AFK timeout of the guild. + * * @param {number} afkTimeout The time in seconds that a user must be idle to be considered AFK * @param {string} [reason] Reason for changing the guild's AFK timeout * @returns {Promise} @@ -1156,12 +1251,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild AFK timeout to ${guild.afkTimeout}`)) * .catch(console.error); */ - setAFKTimeout(afkTimeout, reason) { + async setAFKTimeout(afkTimeout, reason) { return this.edit({ afkTimeout, reason }); } /** * Sets a new guild icon. + * * @param {?(Base64Resolvable|BufferResolvable)} icon The new icon of the guild * @param {string} [reason] Reason for changing the guild's icon * @returns {Promise} @@ -1171,12 +1267,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log('Updated the guild icon')) * .catch(console.error); */ - setIcon(icon, reason) { + async setIcon(icon, reason) { return this.edit({ icon, reason }); } /** * Sets a new owner of the guild. + * * @param {UserResolvable} owner The new owner of the guild * @param {string} [reason] Reason for setting the new owner * @returns {Promise} @@ -1187,12 +1284,13 @@ class Guild extends AnonymousGuild { * .then(owner => console.log(`Updated the guild owner to ${owner.displayName}`)) * .catch(console.error); */ - setOwner(owner, reason) { + async setOwner(owner, reason) { return this.edit({ owner, reason }); } /** * Sets a new guild invite splash image. + * * @param {?(Base64Resolvable|BufferResolvable)} splash The new invite splash image of the guild * @param {string} [reason] Reason for changing the guild's invite splash image * @returns {Promise} @@ -1202,12 +1300,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log('Updated the guild splash')) * .catch(console.error); */ - setSplash(splash, reason) { + async setSplash(splash, reason) { return this.edit({ splash, reason }); } /** * Sets a new guild discovery splash image. + * * @param {?(Base64Resolvable|BufferResolvable)} discoverySplash The new discovery splash image of the guild * @param {string} [reason] Reason for changing the guild's discovery splash image * @returns {Promise} @@ -1217,12 +1316,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log('Updated the guild discovery splash')) * .catch(console.error); */ - setDiscoverySplash(discoverySplash, reason) { + async setDiscoverySplash(discoverySplash, reason) { return this.edit({ discoverySplash, reason }); } /** * Sets a new guild banner. + * * @param {?(Base64Resolvable|BufferResolvable)} banner The new banner of the guild * @param {string} [reason] Reason for changing the guild's banner * @returns {Promise} @@ -1231,12 +1331,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log('Updated the guild banner')) * .catch(console.error); */ - setBanner(banner, reason) { + async setBanner(banner, reason) { return this.edit({ banner, reason }); } /** * Edits the rules channel of the guild. + * * @param {?TextChannelResolvable} rulesChannel The new rules channel * @param {string} [reason] Reason for changing the guild's rules channel * @returns {Promise} @@ -1246,12 +1347,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild rules channel to ${guild.rulesChannel.name}`)) * .catch(console.error); */ - setRulesChannel(rulesChannel, reason) { + async setRulesChannel(rulesChannel, reason) { return this.edit({ rulesChannel, reason }); } /** * Edits the community updates channel of the guild. + * * @param {?TextChannelResolvable} publicUpdatesChannel The new community updates channel * @param {string} [reason] Reason for changing the guild's community updates channel * @returns {Promise} @@ -1261,12 +1363,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild community updates channel to ${guild.publicUpdatesChannel.name}`)) * .catch(console.error); */ - setPublicUpdatesChannel(publicUpdatesChannel, reason) { + async setPublicUpdatesChannel(publicUpdatesChannel, reason) { return this.edit({ publicUpdatesChannel, reason }); } /** * Edits the preferred locale of the guild. + * * @param {?Locale} preferredLocale The new preferred locale of the guild * @param {string} [reason] Reason for changing the guild's preferred locale * @returns {Promise} @@ -1276,22 +1379,24 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild preferred locale to ${guild.preferredLocale}`)) * .catch(console.error); */ - setPreferredLocale(preferredLocale, reason) { + async setPreferredLocale(preferredLocale, reason) { return this.edit({ preferredLocale, reason }); } /** * Edits the enabled state of the guild's premium progress bar - * @param {boolean} [enabled=true] The new enabled state of the guild's premium progress bar + * + * @param {boolean} [enabled] The new enabled state of the guild's premium progress bar * @param {string} [reason] Reason for changing the state of the guild's premium progress bar * @returns {Promise} */ - setPremiumProgressBarEnabled(enabled = true, reason) { + async setPremiumProgressBarEnabled(enabled = true, reason = undefined) { return this.edit({ premiumProgressBarEnabled: enabled, reason }); } /** * Edits the safety alerts channel of the guild. + * * @param {?TextChannelResolvable} safetyAlertsChannel The new safety alerts channel * @param {string} [reason] Reason for changing the guild's safety alerts channel * @returns {Promise} @@ -1301,12 +1406,13 @@ class Guild extends AnonymousGuild { * .then(updated => console.log(`Updated guild safety alerts channel to ${updated.safetyAlertsChannel.name}`)) * .catch(console.error); */ - setSafetyAlertsChannel(safetyAlertsChannel, reason) { + async setSafetyAlertsChannel(safetyAlertsChannel, reason) { return this.edit({ safetyAlertsChannel, reason }); } /** * Edits the guild's widget settings. + * * @param {GuildWidgetSettingsData} settings The widget settings for the guild * @param {string} [reason] Reason for changing the guild's widget settings * @returns {Promise} @@ -1325,6 +1431,7 @@ class Guild extends AnonymousGuild { /** * Sets the guild's MFA level * An elevated MFA level requires guild moderators to have 2FA enabled. + * * @param {GuildMFALevel} level The MFA level * @param {string} [reason] Reason for changing the guild's MFA level * @returns {Promise} @@ -1346,6 +1453,7 @@ class Guild extends AnonymousGuild { /** * Leaves the guild. + * * @returns {Promise} * @example * // Leave a guild @@ -1361,6 +1469,7 @@ class Guild extends AnonymousGuild { /** * Deletes the guild. + * * @returns {Promise} * @example * // Delete a guild @@ -1375,7 +1484,8 @@ class Guild extends AnonymousGuild { /** * Sets whether this guild's invites are disabled. - * @param {boolean} [disabled=true] Whether the invites are disabled + * + * @param {boolean} [disabled] Whether the invites are disabled * @returns {Promise} */ async disableInvites(disabled = true) { @@ -1386,6 +1496,7 @@ class Guild extends AnonymousGuild { /** * Sets the incident actions for a guild. + * * @param {IncidentActionsEditOptions} incidentActions The incident actions to set * @returns {Promise} */ @@ -1397,6 +1508,7 @@ class Guild extends AnonymousGuild { * Whether this guild equals another guild. It compares all properties, so for most operations * it is advisable to just compare `guild.id === guild2.id` as it is much faster and is often * what most users need. + * * @param {Guild} guild The guild to compare with * @returns {boolean} */ @@ -1416,7 +1528,7 @@ class Guild extends AnonymousGuild { this.verificationLevel === guild.verificationLevel && (this.features === guild.features || (this.features.length === guild.features.length && - this.features.every((feat, i) => feat === guild.features[i]))) + this.features.every((feat, index) => feat === guild.features[index]))) ); } @@ -1438,6 +1550,7 @@ class Guild extends AnonymousGuild { /** * The voice state adapter for this guild that can be used with `@discordjs/voice` to play audio in voice * and stage channels. + * * @type {Function} * @readonly */ @@ -1458,6 +1571,7 @@ class Guild extends AnonymousGuild { /** * Creates a collection of this guild's roles, sorted by their position and ids. + * * @returns {Collection} * @private */ @@ -1467,6 +1581,7 @@ class Guild extends AnonymousGuild { /** * Creates a collection of this guild's or a specific category's channels, sorted by their position and ids. + * * @param {GuildChannel} [channel] Category to get the channels of * @returns {Collection} * @private diff --git a/packages/discord.js/src/structures/GuildAuditLogs.js b/packages/discord.js/src/structures/GuildAuditLogs.js index fd7af914cc50..d91ec6e75065 100644 --- a/packages/discord.js/src/structures/GuildAuditLogs.js +++ b/packages/discord.js/src/structures/GuildAuditLogs.js @@ -1,11 +1,11 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); +const { flatten } = require('../util/Util.js'); const { ApplicationCommand } = require('./ApplicationCommand.js'); const { GuildAuditLogsEntry } = require('./GuildAuditLogsEntry.js'); const { Integration } = require('./Integration.js'); const { Webhook } = require('./Webhook.js'); -const { flatten } = require('../util/Util.js'); /** * Audit logs entries are held in this class. @@ -16,6 +16,7 @@ class GuildAuditLogs { if (data.threads) for (const thread of data.threads) guild.client.channels._add(thread, guild); /** * Cached webhooks + * * @type {Collection} * @private */ @@ -28,6 +29,7 @@ class GuildAuditLogs { /** * Cached integrations + * * @type {Collection} * @private */ @@ -40,6 +42,7 @@ class GuildAuditLogs { /** * Cached {@link GuildScheduledEvent}s. + * * @type {Collection} * @private */ @@ -51,6 +54,7 @@ class GuildAuditLogs { /** * Cached application commands, includes application commands from other applications + * * @type {Collection} * @private */ @@ -63,6 +67,7 @@ class GuildAuditLogs { /** * Cached auto moderation rules. + * * @type {Collection} * @private */ @@ -74,6 +79,7 @@ class GuildAuditLogs { /** * The entries for this guild's audit logs + * * @type {Collection} */ this.entries = new Collection(); diff --git a/packages/discord.js/src/structures/GuildAuditLogsEntry.js b/packages/discord.js/src/structures/GuildAuditLogsEntry.js index cf88c016930a..e19c2ca35355 100644 --- a/packages/discord.js/src/structures/GuildAuditLogsEntry.js +++ b/packages/discord.js/src/structures/GuildAuditLogsEntry.js @@ -2,6 +2,8 @@ const { DiscordSnowflake } = require('@sapphire/snowflake'); const { AuditLogOptionsType, AuditLogEvent } = require('discord-api-types/v10'); +const { Partials } = require('../util/Partials.js'); +const { flatten } = require('../util/Util.js'); const { AutoModerationRule } = require('./AutoModerationRule.js'); const { GuildOnboardingPrompt } = require('./GuildOnboardingPrompt.js'); const { GuildScheduledEvent } = require('./GuildScheduledEvent.js'); @@ -10,8 +12,6 @@ const { Invite } = require('./Invite.js'); const { StageInstance } = require('./StageInstance.js'); const { Sticker } = require('./Sticker.js'); const { Webhook } = require('./Webhook.js'); -const { Partials } = require('../util/Partials.js'); -const { flatten } = require('../util/Util.js'); const Targets = { Guild: 'Guild', @@ -36,65 +36,69 @@ const Targets = { /** * The target of a guild audit log entry. It can be one of: - * * A guild - * * A channel - * * A user - * * A role - * * An invite - * * A webhook - * * A guild emoji - * * An integration - * * A stage instance - * * A sticker - * * A guild scheduled event - * * A thread - * * An application command - * * An auto moderation rule - * * A guild onboarding prompt - * * A soundboard sound - * * An object with an id key if target was deleted or fake entity - * * An object where the keys represent either the new value or the old value - * @typedef {?(Object|Guild|BaseChannel|User|Role|Invite|Webhook|GuildEmoji|Integration|StageInstance|Sticker| + * A guild + * A channel + * A user + * A role + * An invite + * A webhook + * A guild emoji + * An integration + * A stage instance + * A sticker + * A guild scheduled event + * A thread + * An application command + * An auto moderation rule + * A guild onboarding prompt + * A soundboard sound + * An object with an id key if target was deleted or fake entity + * An object where the keys represent either the new value or the old value + * + * @typedef {?(object|Guild|BaseChannel|User|Role|Invite|Webhook|GuildEmoji|Integration|StageInstance|Sticker| * GuildScheduledEvent|ApplicationCommand|AutoModerationRule|GuildOnboardingPrompt|SoundboardSound)} AuditLogEntryTarget */ /** * The action type of an entry, e.g. `Create`. Here are the available types: - * * Create - * * Delete - * * Update - * * All + * Create + * Delete + * Update + * All + * * @typedef {string} AuditLogActionType */ /** * The target type of an entry. Here are the available types: - * * Guild - * * Channel - * * User - * * Role - * * Invite - * * Webhook - * * Emoji - * * Message - * * Integration - * * StageInstance - * * Sticker - * * Thread - * * GuildScheduledEvent - * * ApplicationCommand - * * GuildOnboardingPrompt - * * SoundboardSound - * * AutoModeration - * * Unknown + * Guild + * Channel + * User + * Role + * Invite + * Webhook + * Emoji + * Message + * Integration + * StageInstance + * Sticker + * Thread + * GuildScheduledEvent + * ApplicationCommand + * GuildOnboardingPrompt + * SoundboardSound + * AutoModeration + * Unknown + * * @typedef {string} AuditLogTargetType */ /** * Constructs an object of known properties for a structure from an array of changes. + * * @param {AuditLogChange[]} changes The array of changes - * @param {Object} [initialData={}] The initial data passed to the function - * @returns {Object} + * @param {object} [initialData] The initial data passed to the function + * @returns {object} * @ignore */ function changesReduce(changes, initialData = {}) { @@ -110,7 +114,8 @@ function changesReduce(changes, initialData = {}) { class GuildAuditLogsEntry { /** * Key mirror of all available audit log targets. - * @type {Object} + * + * @type {Record} * @memberof GuildAuditLogsEntry */ static Targets = Targets; @@ -118,6 +123,7 @@ class GuildAuditLogsEntry { constructor(guild, data, logs) { /** * The target type of this entry + * * @type {AuditLogTargetType} */ this.targetType = GuildAuditLogsEntry.targetType(data.action_type); @@ -125,30 +131,35 @@ class GuildAuditLogsEntry { /** * The action type of this entry + * * @type {AuditLogActionType} */ this.actionType = GuildAuditLogsEntry.actionType(data.action_type); /** * The type of action that occurred. + * * @type {AuditLogEvent} */ this.action = data.action_type; /** * The reason of this entry + * * @type {?string} */ this.reason = data.reason ?? null; /** * The id of the user that executed this entry + * * @type {?Snowflake} */ this.executorId = data.user_id; /** * The user that executed this entry + * * @type {?User} */ this.executor = data.user_id @@ -159,7 +170,8 @@ class GuildAuditLogsEntry { /** * An entry in the audit log representing a specific change. - * @typedef {Object} AuditLogChange + * + * @typedef {object} AuditLogChange * @property {string} key The property that was changed, e.g. `nick` for nickname changes * For application command permissions updates the key is the id of the user, channel, * role, or a permission constant that was updated instead of an actual property name @@ -169,6 +181,7 @@ class GuildAuditLogsEntry { /** * Specific property changes + * * @type {AuditLogChange[]} */ this.changes = @@ -180,13 +193,15 @@ class GuildAuditLogsEntry { /** * The entry's id + * * @type {Snowflake} */ this.id = data.id; /** * Any extra data from the entry - * @type {?(Object|Role|GuildMember)} + * + * @type {?(object | Role | GuildMember)} */ this.extra = null; switch (data.action_type) { @@ -223,6 +238,7 @@ class GuildAuditLogsEntry { case AuditLogEvent.ChannelOverwriteCreate: case AuditLogEvent.ChannelOverwriteUpdate: case AuditLogEvent.ChannelOverwriteDelete: + // eslint-disable-next-line sonarjs/no-nested-switch switch (data.options.type) { case AuditLogOptionsType.Role: this.extra = guild.roles.cache.get(data.options.id) ?? { @@ -242,6 +258,7 @@ class GuildAuditLogsEntry { default: break; } + break; case AuditLogEvent.StageInstanceCreate: @@ -275,6 +292,7 @@ class GuildAuditLogsEntry { integrationType: data.integration_type, }; } + break; } @@ -284,12 +302,14 @@ class GuildAuditLogsEntry { /** * The id of the target of this entry + * * @type {?Snowflake} */ this.targetId = data.target_id; /** * The target of this entry + * * @type {?AuditLogEntryTarget} */ this.target = null; @@ -378,6 +398,7 @@ class GuildAuditLogsEntry { /** * Finds the target type of a guild audit log entry. + * * @param {AuditLogEvent} target The action target * @returns {AuditLogTargetType} */ @@ -405,6 +426,7 @@ class GuildAuditLogsEntry { /** * Finds the action type from the guild audit log entry action. + * * @param {AuditLogEvent} action The action target * @returns {AuditLogActionType} */ @@ -495,6 +517,7 @@ class GuildAuditLogsEntry { /** * The timestamp this entry was created at + * * @type {number} * @readonly */ @@ -504,6 +527,7 @@ class GuildAuditLogsEntry { /** * The time this entry was created at + * * @type {Date} * @readonly */ @@ -513,6 +537,7 @@ class GuildAuditLogsEntry { /** * Checks whether this GuildAuditLogsEntry is of the specified {@link AuditLogEvent} type. + * * @param {AuditLogEvent} action The type to check for * @returns {boolean} */ diff --git a/packages/discord.js/src/structures/GuildBan.js b/packages/discord.js/src/structures/GuildBan.js index 92b844180bbf..3a0636ae2b85 100644 --- a/packages/discord.js/src/structures/GuildBan.js +++ b/packages/discord.js/src/structures/GuildBan.js @@ -4,6 +4,7 @@ const { Base } = require('./Base.js'); /** * Represents a ban in a guild on Discord. + * * @extends {Base} */ class GuildBan extends Base { @@ -12,6 +13,7 @@ class GuildBan extends Base { /** * The guild in which the ban is + * * @type {Guild} */ this.guild = guild; @@ -23,6 +25,7 @@ class GuildBan extends Base { if ('user' in data) { /** * The user this ban applies to + * * @type {User} */ this.user = this.client.users._add(data.user, true); @@ -31,6 +34,7 @@ class GuildBan extends Base { if ('reason' in data) { /** * The reason for the ban + * * @type {?string} */ this.reason = data.reason; @@ -39,6 +43,7 @@ class GuildBan extends Base { /** * Whether this GuildBan is partial. If the reason is not provided the value is null + * * @type {boolean} * @readonly */ @@ -48,10 +53,11 @@ class GuildBan extends Base { /** * Fetches this GuildBan. - * @param {boolean} [force=true] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - fetch(force = true) { + async fetch(force = true) { return this.guild.bans.fetch({ user: this.user, cache: true, force }); } } diff --git a/packages/discord.js/src/structures/GuildChannel.js b/packages/discord.js/src/structures/GuildChannel.js index 5ef409e89d2a..857d27508772 100644 --- a/packages/discord.js/src/structures/GuildChannel.js +++ b/packages/discord.js/src/structures/GuildChannel.js @@ -2,12 +2,12 @@ const { Snowflake } = require('@sapphire/snowflake'); const { PermissionFlagsBits, ChannelType } = require('discord-api-types/v10'); -const { BaseChannel } = require('./BaseChannel.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { PermissionOverwriteManager } = require('../managers/PermissionOverwriteManager.js'); const { VoiceBasedChannelTypes } = require('../util/Constants.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); const { getSortableGroupTypes } = require('../util/Util.js'); +const { BaseChannel } = require('./BaseChannel.js'); /** * Represents a guild channel from any of the following: @@ -18,6 +18,7 @@ const { getSortableGroupTypes } = require('../util/Util.js'); * - {@link StageChannel} * - {@link ForumChannel} * - {@link MediaChannel} + * * @extends {BaseChannel} * @abstract */ @@ -27,17 +28,20 @@ class GuildChannel extends BaseChannel { /** * The guild the channel is in + * * @type {Guild} */ this.guild = guild; /** * The id of the guild the channel is in + * * @type {Snowflake} */ this.guildId = guild?.id ?? data.guild_id; /** * A manager of permission overwrites that belong to this channel + * * @type {PermissionOverwriteManager} */ this.permissionOverwrites = new PermissionOverwriteManager(this); @@ -51,6 +55,7 @@ class GuildChannel extends BaseChannel { if ('name' in data) { /** * The name of the guild channel + * * @type {string} */ this.name = data.name; @@ -59,6 +64,7 @@ class GuildChannel extends BaseChannel { if ('position' in data) { /** * The raw position of the channel from Discord + * * @type {number} */ this.rawPosition = data.position; @@ -71,6 +77,7 @@ class GuildChannel extends BaseChannel { if ('parent_id' in data) { /** * The id of the category parent of this channel + * * @type {?Snowflake} */ this.parentId = data.parent_id; @@ -94,6 +101,7 @@ class GuildChannel extends BaseChannel { /** * The category parent of this channel + * * @type {?CategoryChannel} * @readonly */ @@ -103,6 +111,7 @@ class GuildChannel extends BaseChannel { /** * If the permissionOverwrites match the parent channel, null if no parent + * * @type {?boolean} * @readonly */ @@ -144,6 +153,7 @@ class GuildChannel extends BaseChannel { /** * The position of the channel + * * @type {number} * @readonly */ @@ -167,8 +177,9 @@ class GuildChannel extends BaseChannel { /** * Gets the overall set of permissions for a member or role in this channel, taking into account channel overwrites. + * * @param {UserResolvable|RoleResolvable} memberOrRole The member or role to obtain the overall permissions for - * @param {boolean} [checkAdmin=true] Whether having the {@link PermissionFlagsBits.Administrator} permission + * @param {boolean} [checkAdmin] Whether having the {@link PermissionFlagsBits.Administrator} permission * will return all permissions * @returns {?Readonly} */ @@ -207,6 +218,7 @@ class GuildChannel extends BaseChannel { /** * Gets the overall set of permissions for a member in this channel, taking into account channel overwrites. + * * @param {GuildMember} member The member to obtain the overall permissions for * @param {boolean} checkAdmin Whether having the {@link PermissionFlagsBits.Administrator} permission * will return all permissions @@ -239,6 +251,7 @@ class GuildChannel extends BaseChannel { /** * Gets the overall set of permissions for a role in this channel, taking into account channel overwrites. + * * @param {Role} role The role to obtain the overall permissions for * @param {boolean} checkAdmin Whether having the {@link PermissionFlagsBits.Administrator} permission * will return all permissions @@ -263,6 +276,7 @@ class GuildChannel extends BaseChannel { /** * Locks in the permission overwrites from the parent channel. + * * @returns {Promise} */ async lockPermissions() { @@ -275,6 +289,7 @@ class GuildChannel extends BaseChannel { * A collection of cached members of this channel, mapped by their ids. * Members that can view this channel, if the channel is text-based. * Members in the channel, if the channel is voice-based. + * * @type {Collection} * @readonly */ @@ -286,6 +301,7 @@ class GuildChannel extends BaseChannel { /** * Edits the channel. + * * @param {GuildChannelEditOptions} options The options to provide * @returns {Promise} * @example @@ -294,12 +310,13 @@ class GuildChannel extends BaseChannel { * .then(console.log) * .catch(console.error); */ - edit(options) { + async edit(options) { return this.guild.channels.edit(this, options); } /** * Sets a new name for the guild channel. + * * @param {string} name The new name for the guild channel * @param {string} [reason] Reason for changing the guild channel's name * @returns {Promise} @@ -309,21 +326,23 @@ class GuildChannel extends BaseChannel { * .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`)) * .catch(console.error); */ - setName(name, reason) { + async setName(name, reason) { return this.edit({ name, reason }); } /** * Options used to set the parent of a channel. - * @typedef {Object} SetParentOptions + * + * @typedef {object} SetParentOptions * @property {boolean} [lockPermissions=false] Whether to lock the permissions to what the parent's permissions are * @property {string} [reason] The reason for modifying the parent of the channel */ /** * Sets the parent of this channel. + * * @param {?CategoryChannelResolvable} channel The category channel to set as the parent - * @param {SetParentOptions} [options={}] The options for setting the parent + * @param {SetParentOptions} [options] The options for setting the parent * @returns {Promise} * @example * // Add a parent to a channel @@ -336,7 +355,7 @@ class GuildChannel extends BaseChannel { * .then(channel => console.log(`Moved ${message.channel.name} to ${channel.parent.name}`)) * .catch(console.error); */ - setParent(channel, { lockPermissions = false, reason } = {}) { + async setParent(channel, { lockPermissions = false, reason } = {}) { return this.edit({ parent: channel ?? null, lockPermissions, @@ -346,13 +365,15 @@ class GuildChannel extends BaseChannel { /** * Options used to set the position of a channel. - * @typedef {Object} SetChannelPositionOptions + * + * @typedef {object} SetChannelPositionOptions * @property {boolean} [relative=false] Whether or not to change the position relative to its current value * @property {string} [reason] The reason for changing the position */ /** * Sets a new position for the guild channel. + * * @param {number} position The new position for the guild channel * @param {SetChannelPositionOptions} [options] Options for setting position * @returns {Promise} @@ -362,22 +383,24 @@ class GuildChannel extends BaseChannel { * .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`)) * .catch(console.error); */ - setPosition(position, options = {}) { + async setPosition(position, options = {}) { return this.guild.channels.setPosition(this, position, options); } /** * Options used to clone a guild channel. + * * @typedef {GuildChannelCreateOptions} GuildChannelCloneOptions * @property {string} [name=this.name] Name of the new channel */ /** * Clones this channel. + * * @param {GuildChannelCloneOptions} [options] The options for cloning this channel * @returns {Promise} */ - clone(options = {}) { + async clone(options = {}) { return this.guild.channels.create({ name: options.name ?? this.name, permissionOverwrites: this.permissionOverwrites.cache, @@ -397,6 +420,7 @@ class GuildChannel extends BaseChannel { /** * Checks if this channel has the same type, topic, position, name, overwrites, and id as another channel. * In most cases, a simple `channel.id === channel2.id` will do, and is much faster too. + * * @param {GuildChannel} channel Channel to compare with * @returns {boolean} */ @@ -422,6 +446,7 @@ class GuildChannel extends BaseChannel { /** * Whether the channel is deletable by the client user + * * @type {boolean} * @readonly */ @@ -431,6 +456,7 @@ class GuildChannel extends BaseChannel { /** * Whether the channel is manageable by the client user + * * @type {boolean} * @readonly */ @@ -451,6 +477,7 @@ class GuildChannel extends BaseChannel { /** * Whether the channel is viewable by the client user + * * @type {boolean} * @readonly */ @@ -463,6 +490,7 @@ class GuildChannel extends BaseChannel { /** * Deletes this channel. + * * @param {string} [reason] Reason for deleting this channel * @returns {Promise} * @example diff --git a/packages/discord.js/src/structures/GuildEmoji.js b/packages/discord.js/src/structures/GuildEmoji.js index a0f0629501f2..d20241c9f95b 100644 --- a/packages/discord.js/src/structures/GuildEmoji.js +++ b/packages/discord.js/src/structures/GuildEmoji.js @@ -1,12 +1,13 @@ 'use strict'; const { PermissionFlagsBits } = require('discord-api-types/v10'); -const { BaseGuildEmoji } = require('./BaseGuildEmoji.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { GuildEmojiRoleManager } = require('../managers/GuildEmojiRoleManager.js'); +const { BaseGuildEmoji } = require('./BaseGuildEmoji.js'); /** * Represents a custom emoji. + * * @extends {BaseGuildEmoji} */ class GuildEmoji extends BaseGuildEmoji { @@ -15,12 +16,14 @@ class GuildEmoji extends BaseGuildEmoji { /** * The user who created this emoji + * * @type {?User} */ this.author = null; /** * Array of role ids this emoji is active for + * * @name GuildEmoji#_roles * @type {Snowflake[]} * @private @@ -32,6 +35,7 @@ class GuildEmoji extends BaseGuildEmoji { /** * The guild this emoji is part of + * * @type {Guild} * @name GuildEmoji#guild */ @@ -51,6 +55,7 @@ class GuildEmoji extends BaseGuildEmoji { /** * Whether the emoji is deletable by the client user + * * @type {boolean} * @readonly */ @@ -61,6 +66,7 @@ class GuildEmoji extends BaseGuildEmoji { /** * A manager for roles this emoji is active for. + * * @type {GuildEmojiRoleManager} * @readonly */ @@ -70,15 +76,17 @@ class GuildEmoji extends BaseGuildEmoji { /** * Fetches the author for this emoji + * * @returns {Promise} */ - fetchAuthor() { + async fetchAuthor() { return this.guild.emojis.fetchAuthor(this); } /** * Data for editing an emoji. - * @typedef {Object} GuildEmojiEditOptions + * + * @typedef {object} GuildEmojiEditOptions * @property {string} [name] The name of the emoji * @property {Collection|RoleResolvable[]} [roles] Roles to restrict emoji to * @property {string} [reason] Reason for editing this emoji @@ -86,6 +94,7 @@ class GuildEmoji extends BaseGuildEmoji { /** * Edits the emoji. + * * @param {GuildEmojiEditOptions} options The options to provide * @returns {Promise} * @example @@ -94,22 +103,24 @@ class GuildEmoji extends BaseGuildEmoji { * .then(emoji => console.log(`Edited emoji ${emoji}`)) * .catch(console.error); */ - edit(options) { + async edit(options) { return this.guild.emojis.edit(this.id, options); } /** * Sets the name of the emoji. + * * @param {string} name The new name for the emoji * @param {string} [reason] Reason for changing the emoji's name * @returns {Promise} */ - setName(name, reason) { + async setName(name, reason) { return this.edit({ name, reason }); } /** * Deletes the emoji. + * * @param {string} [reason] Reason for deleting the emoji * @returns {Promise} */ @@ -120,6 +131,7 @@ class GuildEmoji extends BaseGuildEmoji { /** * Whether this emoji is the same as another one. + * * @param {GuildEmoji|APIEmoji} other The emoji to compare it to * @returns {boolean} */ diff --git a/packages/discord.js/src/structures/GuildMember.js b/packages/discord.js/src/structures/GuildMember.js index 015dd3b61521..c8e933721bcb 100644 --- a/packages/discord.js/src/structures/GuildMember.js +++ b/packages/discord.js/src/structures/GuildMember.js @@ -1,15 +1,16 @@ 'use strict'; const { PermissionFlagsBits } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); -const { VoiceState } = require('./VoiceState.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { GuildMemberRoleManager } = require('../managers/GuildMemberRoleManager.js'); const { GuildMemberFlagsBitField } = require('../util/GuildMemberFlagsBitField.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); +const { Base } = require('./Base.js'); +const { VoiceState } = require('./VoiceState.js'); /** * Represents a member of a guild on Discord. + * * @extends {Base} */ class GuildMember extends Base { @@ -18,42 +19,49 @@ class GuildMember extends Base { /** * The guild that this member is part of + * * @type {Guild} */ this.guild = guild; /** * The timestamp the member joined the guild at + * * @type {?number} */ this.joinedTimestamp = null; /** * The last timestamp this member started boosting the guild + * * @type {?number} */ this.premiumSinceTimestamp = null; /** * The nickname of this member, if they have one + * * @type {?string} */ this.nickname = null; /** * Whether this member has yet to pass the guild's membership gate + * * @type {?boolean} */ this.pending = null; /** * The timestamp this member's timeout will be removed + * * @type {?number} */ this.communicationDisabledUntilTimestamp = null; /** * The role ids of the member + * * @name GuildMember#_roles * @type {Snowflake[]} * @private @@ -67,6 +75,7 @@ class GuildMember extends Base { if ('user' in data) { /** * The user that this guild member instance represents + * * @type {?User} */ this.user = this.client.users._add(data.user, true); @@ -76,6 +85,7 @@ class GuildMember extends Base { if ('avatar' in data) { /** * The guild member's avatar hash + * * @type {?string} */ this.avatar = data.avatar; @@ -86,6 +96,7 @@ class GuildMember extends Base { if ('banner' in data) { /** * The guild member's banner hash. + * * @type {?string} */ this.banner = data.banner; @@ -97,6 +108,7 @@ class GuildMember extends Base { if ('premium_since' in data) { this.premiumSinceTimestamp = data.premium_since ? Date.parse(data.premium_since) : null; } + if ('roles' in data) this._roles = data.roles; if ('pending' in data) { @@ -114,6 +126,7 @@ class GuildMember extends Base { if ('flags' in data) { /** * The flags of this member + * * @type {Readonly} */ this.flags = new GuildMemberFlagsBitField(data.flags).freeze(); @@ -130,6 +143,7 @@ class GuildMember extends Base { /** * Whether this GuildMember is a partial + * * @type {boolean} * @readonly */ @@ -139,6 +153,7 @@ class GuildMember extends Base { /** * A manager for the roles belonging to this member + * * @type {GuildMemberRoleManager} * @readonly */ @@ -148,6 +163,7 @@ class GuildMember extends Base { /** * The voice state of this member + * * @type {VoiceState} * @readonly */ @@ -157,7 +173,8 @@ class GuildMember extends Base { /** * A link to the member's guild avatar. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ avatarURL(options = {}) { @@ -166,7 +183,8 @@ class GuildMember extends Base { /** * A link to the member's banner. - * @param {ImageURLOptions} [options={}] Options for the banner URL + * + * @param {ImageURLOptions} [options] Options for the banner URL * @returns {?string} */ bannerURL(options = {}) { @@ -176,7 +194,8 @@ class GuildMember extends Base { /** * A link to the member's guild avatar if they have one. * Otherwise, a link to their {@link User#displayAvatarURL} will be returned. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {string} */ displayAvatarURL(options) { @@ -186,7 +205,8 @@ class GuildMember extends Base { /** * A link to the member's guild banner if they have one. * Otherwise, a link to their {@link User#bannerURL} will be returned. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ displayBannerURL(options) { @@ -195,6 +215,7 @@ class GuildMember extends Base { /** * The time this member joined the guild + * * @type {?Date} * @readonly */ @@ -204,6 +225,7 @@ class GuildMember extends Base { /** * The time this member's timeout will be removed + * * @type {?Date} * @readonly */ @@ -213,6 +235,7 @@ class GuildMember extends Base { /** * The last time this member started boosting the guild + * * @type {?Date} * @readonly */ @@ -222,6 +245,7 @@ class GuildMember extends Base { /** * The presence of this guild member + * * @type {?Presence} * @readonly */ @@ -231,6 +255,7 @@ class GuildMember extends Base { /** * The displayed role color of this member in base 10 + * * @type {number} * @readonly */ @@ -240,6 +265,7 @@ class GuildMember extends Base { /** * The displayed role color of this member in hexadecimal + * * @type {string} * @readonly */ @@ -249,6 +275,7 @@ class GuildMember extends Base { /** * The member's id + * * @type {Snowflake} * @readonly */ @@ -258,6 +285,7 @@ class GuildMember extends Base { /** * The DM between the client's user and this member + * * @type {?DMChannel} * @readonly */ @@ -267,6 +295,7 @@ class GuildMember extends Base { /** * The nickname of this member, or their user display name if they don't have one + * * @type {?string} * @readonly */ @@ -276,6 +305,7 @@ class GuildMember extends Base { /** * The overall set of permissions for this member, taking only roles and owner status into account + * * @type {Readonly} * @readonly */ @@ -287,6 +317,7 @@ class GuildMember extends Base { /** * Whether the client user is above this user in the hierarchy, according to role position and guild ownership. * This is a prerequisite for many moderative actions. + * * @type {boolean} * @readonly */ @@ -300,6 +331,7 @@ class GuildMember extends Base { /** * Whether this member is kickable by the client user + * * @type {boolean} * @readonly */ @@ -310,6 +342,7 @@ class GuildMember extends Base { /** * Whether this member is bannable by the client user + * * @type {boolean} * @readonly */ @@ -320,6 +353,7 @@ class GuildMember extends Base { /** * Whether this member is moderatable by the client user + * * @type {boolean} * @readonly */ @@ -333,6 +367,7 @@ class GuildMember extends Base { /** * Whether this member is currently timed out + * * @returns {boolean} */ isCommunicationDisabled() { @@ -342,6 +377,7 @@ class GuildMember extends Base { /** * Returns `channel.permissionsFor(guildMember)`. Returns permissions for a member in a guild channel, * taking into account roles and permission overwrites. + * * @param {GuildChannelResolvable} channel The guild channel to use as context * @returns {Readonly} */ @@ -353,25 +389,28 @@ class GuildMember extends Base { /** * Edits this member. + * * @param {GuildMemberEditOptions} options The options to provide * @returns {Promise} */ - edit(options) { + async edit(options) { return this.guild.members.edit(this, options); } /** * Sets the flags for this member. + * * @param {GuildMemberFlagsResolvable} flags The flags to set * @param {string} [reason] Reason for setting the flags * @returns {Promise} */ - setFlags(flags, reason) { + async setFlags(flags, reason) { return this.edit({ flags, reason }); } /** * Sets the nickname for this member. + * * @param {?string} nick The nickname for the guild member, or `null` if you want to reset their nickname * @param {string} [reason] Reason for setting the nickname * @returns {Promise} @@ -386,29 +425,32 @@ class GuildMember extends Base { * .then(member => console.log(`Removed nickname for ${member.user.username}`)) * .catch(console.error); */ - setNickname(nick, reason) { + async setNickname(nick, reason) { return this.edit({ nick, reason }); } /** * Creates a DM channel between the client and this member. - * @param {boolean} [force=false] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - createDM(force = false) { + async createDM(force = false) { return this.user.createDM(force); } /** * Deletes any DMs with this member. + * * @returns {Promise} */ - deleteDM() { + async deleteDM() { return this.user.deleteDM(); } /** * Kicks this member from the guild. + * * @param {string} [reason] Reason for kicking user * @returns {Promise} */ @@ -418,6 +460,7 @@ class GuildMember extends Base { /** * Bans this guild member. + * * @param {BanOptions} [options] Options for the ban * @returns {Promise} * @example @@ -430,6 +473,7 @@ class GuildMember extends Base { /** * Times this guild member out. + * * @param {?DateResolvable} communicationDisabledUntil The date or timestamp * for the member's communication to be disabled until. Provide `null` to remove the timeout. * @param {string} [reason] The reason for this timeout. @@ -445,12 +489,13 @@ class GuildMember extends Base { * .then(member => console.log(`Removed timeout for ${member.displayName}`)) * .catch(console.error); */ - disableCommunicationUntil(communicationDisabledUntil, reason) { + async disableCommunicationUntil(communicationDisabledUntil, reason) { return this.edit({ communicationDisabledUntil, reason }); } /** * Times this guild member out. + * * @param {?number} timeout The duration in milliseconds * for the member's communication to be disabled. Provide `null` to remove the timeout. * @param {string} [reason] The reason for this timeout. @@ -461,21 +506,23 @@ class GuildMember extends Base { * .then(console.log) * .catch(console.error); */ - timeout(timeout, reason) { + async timeout(timeout, reason) { return this.disableCommunicationUntil(timeout && Date.now() + timeout, reason); } /** * Fetches this GuildMember. - * @param {boolean} [force=true] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - fetch(force = true) { + async fetch(force = true) { return this.guild.members.fetch({ user: this.id, cache: true, force }); } /** * Sends a message to this user. + * * @param {string|MessagePayload|MessageCreateOptions} options The options to provide * @returns {Promise} * @example @@ -494,6 +541,7 @@ class GuildMember extends Base { * Whether this guild member equals another guild member. It compares all properties, so for most * comparison it is advisable to just compare `member.id === member2.id` as it is significantly faster * and is often what most users need. + * * @param {GuildMember} member The member to compare with * @returns {boolean} */ @@ -511,12 +559,14 @@ class GuildMember extends Base { this.communicationDisabledUntilTimestamp === member.communicationDisabledUntilTimestamp && this.flags.bitfield === member.flags.bitfield && (this._roles === member._roles || - (this._roles.length === member._roles.length && this._roles.every((role, i) => role === member._roles[i]))) + (this._roles.length === member._roles.length && + this._roles.every((role, index) => role === member._roles[index]))) ); } /** * When concatenated with a string, this automatically returns the user's mention instead of the GuildMember object. + * * @returns {string} * @example * // Logs: Hello from <@123456789012345678>! diff --git a/packages/discord.js/src/structures/GuildOnboarding.js b/packages/discord.js/src/structures/GuildOnboarding.js index 546d22c75c54..fd3bbfdf5396 100644 --- a/packages/discord.js/src/structures/GuildOnboarding.js +++ b/packages/discord.js/src/structures/GuildOnboarding.js @@ -6,6 +6,7 @@ const { GuildOnboardingPrompt } = require('./GuildOnboardingPrompt.js'); /** * Represents the onboarding data of a guild. + * * @extends {Base} */ class GuildOnboarding extends Base { @@ -14,6 +15,7 @@ class GuildOnboarding extends Base { /** * The id of the guild this onboarding data is for + * * @type {Snowflake} */ this.guildId = data.guild_id; @@ -22,6 +24,7 @@ class GuildOnboarding extends Base { /** * The prompts shown during onboarding and in customize community + * * @type {Collection} */ this.prompts = data.prompts.reduce( @@ -31,6 +34,7 @@ class GuildOnboarding extends Base { /** * The ids of the channels that new members get opted into automatically + * * @type {Collection} */ this.defaultChannels = data.default_channel_ids.reduce( @@ -40,12 +44,14 @@ class GuildOnboarding extends Base { /** * Whether onboarding is enabled + * * @type {boolean} */ this.enabled = data.enabled; /** * The mode of this onboarding + * * @type {GuildOnboardingMode} */ this.mode = data.mode; @@ -53,6 +59,7 @@ class GuildOnboarding extends Base { /** * The guild this onboarding is from + * * @type {Guild} * @readonly */ diff --git a/packages/discord.js/src/structures/GuildOnboardingPrompt.js b/packages/discord.js/src/structures/GuildOnboardingPrompt.js index 2cd192707352..836b5bf7865b 100644 --- a/packages/discord.js/src/structures/GuildOnboardingPrompt.js +++ b/packages/discord.js/src/structures/GuildOnboardingPrompt.js @@ -6,6 +6,7 @@ const { GuildOnboardingPromptOption } = require('./GuildOnboardingPromptOption.j /** * Represents the data of a prompt of a guilds onboarding. + * * @extends {Base} */ class GuildOnboardingPrompt extends Base { @@ -14,18 +15,21 @@ class GuildOnboardingPrompt extends Base { /** * The id of the guild this onboarding prompt is from + * * @type {Snowflake} */ this.guildId = guildId; /** * The id of the prompt + * * @type {Snowflake} */ this.id = data.id; /** * The options available within the prompt + * * @type {Collection} */ this.options = data.options.reduce( @@ -35,18 +39,21 @@ class GuildOnboardingPrompt extends Base { /** * The title of the prompt + * * @type {string} */ this.title = data.title; /** * Whether users are limited to selecting one option for the prompt + * * @type {boolean} */ this.singleSelect = data.single_select; /** * Whether the prompt is required before a user completes the onboarding flow + * * @type {boolean} */ this.required = data.required; @@ -54,12 +61,14 @@ class GuildOnboardingPrompt extends Base { /** * Whether the prompt is present in the onboarding flow. * If `false`, the prompt will only appear in the Channels & Roles tab + * * @type {boolean} */ this.inOnboarding = data.in_onboarding; /** * The type of the prompt + * * @type {GuildOnboardingPromptType} */ this.type = data.type; @@ -67,6 +76,7 @@ class GuildOnboardingPrompt extends Base { /** * The guild this onboarding prompt is from + * * @type {Guild} * @readonly */ diff --git a/packages/discord.js/src/structures/GuildOnboardingPromptOption.js b/packages/discord.js/src/structures/GuildOnboardingPromptOption.js index 503c1d9a7461..7c78f51a096c 100644 --- a/packages/discord.js/src/structures/GuildOnboardingPromptOption.js +++ b/packages/discord.js/src/structures/GuildOnboardingPromptOption.js @@ -6,6 +6,7 @@ const { Emoji } = require('./Emoji.js'); /** * Represents the data of an option from a prompt of a guilds onboarding. + * * @extends {Base} */ class GuildOnboardingPromptOption extends Base { @@ -14,6 +15,7 @@ class GuildOnboardingPromptOption extends Base { /** * The id of the guild this onboarding prompt option is from + * * @type {Snowflake} */ this.guildId = guildId; @@ -22,12 +24,14 @@ class GuildOnboardingPromptOption extends Base { /** * The id of the option + * * @type {Snowflake} */ this.id = data.id; /** * The channels a member is added to when the option is selected + * * @type {Collection} */ this.channels = data.channel_ids.reduce( @@ -37,6 +41,7 @@ class GuildOnboardingPromptOption extends Base { /** * The roles assigned to a member when the option is selected + * * @type {Collection} */ this.roles = data.role_ids.reduce( @@ -46,6 +51,7 @@ class GuildOnboardingPromptOption extends Base { /** * The raw emoji of the option + * * @type {APIPartialEmoji} * @private */ @@ -53,12 +59,14 @@ class GuildOnboardingPromptOption extends Base { /** * The title of the option + * * @type {string} */ this.title = data.title; /** * The description of the option + * * @type {?string} */ this.description = data.description; @@ -66,6 +74,7 @@ class GuildOnboardingPromptOption extends Base { /** * The guild this onboarding prompt option is from + * * @type {Guild} * @readonly */ @@ -75,6 +84,7 @@ class GuildOnboardingPromptOption extends Base { /** * The emoji of this onboarding prompt option + * * @type {?(GuildEmoji|Emoji)} */ get emoji() { diff --git a/packages/discord.js/src/structures/GuildPreview.js b/packages/discord.js/src/structures/GuildPreview.js index 888b62784b4b..87f6163e46d8 100644 --- a/packages/discord.js/src/structures/GuildPreview.js +++ b/packages/discord.js/src/structures/GuildPreview.js @@ -9,6 +9,7 @@ const { Sticker } = require('./Sticker.js'); /** * Represents the data about the guild any bot can preview, connected to the specified guild. + * * @extends {Base} */ class GuildPreview extends Base { @@ -23,6 +24,7 @@ class GuildPreview extends Base { _patch(data) { /** * The id of this guild + * * @type {string} */ this.id = data.id; @@ -30,6 +32,7 @@ class GuildPreview extends Base { if ('name' in data) { /** * The name of this guild + * * @type {string} */ this.name = data.name; @@ -38,6 +41,7 @@ class GuildPreview extends Base { if ('icon' in data) { /** * The icon of this guild + * * @type {?string} */ this.icon = data.icon; @@ -46,6 +50,7 @@ class GuildPreview extends Base { if ('splash' in data) { /** * The splash icon of this guild + * * @type {?string} */ this.splash = data.splash; @@ -54,6 +59,7 @@ class GuildPreview extends Base { if ('discovery_splash' in data) { /** * The discovery splash icon of this guild + * * @type {?string} */ this.discoverySplash = data.discovery_splash; @@ -62,6 +68,7 @@ class GuildPreview extends Base { if ('features' in data) { /** * An array of enabled guild features + * * @type {GuildFeature[]} */ this.features = data.features; @@ -70,6 +77,7 @@ class GuildPreview extends Base { if ('approximate_member_count' in data) { /** * The approximate count of members in this guild + * * @type {number} */ this.approximateMemberCount = data.approximate_member_count; @@ -78,6 +86,7 @@ class GuildPreview extends Base { if ('approximate_presence_count' in data) { /** * The approximate count of online members in this guild + * * @type {number} */ this.approximatePresenceCount = data.approximate_presence_count; @@ -86,6 +95,7 @@ class GuildPreview extends Base { if ('description' in data) { /** * The description for this guild + * * @type {?string} */ this.description = data.description; @@ -93,21 +103,24 @@ class GuildPreview extends Base { this.description ??= null; } - if (!this.emojis) { + if (this.emojis) { + this.emojis.clear(); + } else { /** * Collection of emojis belonging to this guild + * * @type {Collection} */ this.emojis = new Collection(); - } else { - this.emojis.clear(); } + for (const emoji of data.emojis) { this.emojis.set(emoji.id, new GuildPreviewEmoji(this.client, emoji, this)); } /** * Collection of stickers belonging to this guild + * * @type {Collection} */ this.stickers = data.stickers.reduce( @@ -118,6 +131,7 @@ class GuildPreview extends Base { /** * The timestamp this guild was created at + * * @type {number} * @readonly */ @@ -127,6 +141,7 @@ class GuildPreview extends Base { /** * The time this guild was created at + * * @type {Date} * @readonly */ @@ -136,7 +151,8 @@ class GuildPreview extends Base { /** * The URL to this guild's splash. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ splashURL(options = {}) { @@ -145,7 +161,8 @@ class GuildPreview extends Base { /** * The URL to this guild's discovery splash. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ discoverySplashURL(options = {}) { @@ -154,7 +171,8 @@ class GuildPreview extends Base { /** * The URL to this guild's icon. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ iconURL(options = {}) { @@ -163,6 +181,7 @@ class GuildPreview extends Base { /** * Fetches this guild. + * * @returns {Promise} */ async fetch() { @@ -173,6 +192,7 @@ class GuildPreview extends Base { /** * When concatenated with a string, this automatically returns the guild's name instead of the Guild object. + * * @returns {string} * @example * // Logs: Hello from My Guild! diff --git a/packages/discord.js/src/structures/GuildPreviewEmoji.js b/packages/discord.js/src/structures/GuildPreviewEmoji.js index a500118b4282..884e125c787f 100644 --- a/packages/discord.js/src/structures/GuildPreviewEmoji.js +++ b/packages/discord.js/src/structures/GuildPreviewEmoji.js @@ -4,11 +4,13 @@ const { BaseGuildEmoji } = require('./BaseGuildEmoji.js'); /** * Represents an instance of an emoji belonging to a public guild obtained through Discord's preview endpoint. + * * @extends {BaseGuildEmoji} */ class GuildPreviewEmoji extends BaseGuildEmoji { /** * The public guild this emoji is part of + * * @type {GuildPreview} * @name GuildPreviewEmoji#guild */ @@ -18,6 +20,7 @@ class GuildPreviewEmoji extends BaseGuildEmoji { /** * The roles this emoji is active for + * * @type {Snowflake[]} */ this.roles = data.roles; diff --git a/packages/discord.js/src/structures/GuildScheduledEvent.js b/packages/discord.js/src/structures/GuildScheduledEvent.js index 81304794e064..f01befd7a3b4 100644 --- a/packages/discord.js/src/structures/GuildScheduledEvent.js +++ b/packages/discord.js/src/structures/GuildScheduledEvent.js @@ -2,11 +2,12 @@ const { DiscordSnowflake } = require('@sapphire/snowflake'); const { GuildScheduledEventStatus, GuildScheduledEventEntityType, RouteBases } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); +const { Base } = require('./Base.js'); /** * Represents a scheduled event in a {@link Guild}. + * * @extends {Base} */ class GuildScheduledEvent extends Base { @@ -15,12 +16,14 @@ class GuildScheduledEvent extends Base { /** * The id of the guild scheduled event + * * @type {Snowflake} */ this.id = data.id; /** * The id of the guild this guild scheduled event belongs to + * * @type {Snowflake} */ this.guildId = data.guild_id; @@ -33,6 +36,7 @@ class GuildScheduledEvent extends Base { /** * The channel id in which the scheduled event will be hosted, * or `null` if entity type is {@link GuildScheduledEventEntityType.External} + * * @type {?Snowflake} */ this.channelId = data.channel_id; @@ -43,6 +47,7 @@ class GuildScheduledEvent extends Base { if ('creator_id' in data) { /** * The id of the user that created this guild scheduled event + * * @type {?Snowflake} */ this.creatorId = data.creator_id; @@ -53,6 +58,7 @@ class GuildScheduledEvent extends Base { if ('name' in data) { /** * The name of the guild scheduled event + * * @type {?string} */ this.name = data.name; @@ -64,6 +70,7 @@ class GuildScheduledEvent extends Base { if ('description' in data) { /** * The description of the guild scheduled event + * * @type {?string} */ this.description = data.description; @@ -74,6 +81,7 @@ class GuildScheduledEvent extends Base { if ('scheduled_start_time' in data) { /** * The timestamp the guild scheduled event will start at + * * @type {?number} */ this.scheduledStartTimestamp = Date.parse(data.scheduled_start_time); @@ -85,6 +93,7 @@ class GuildScheduledEvent extends Base { /** * The timestamp the guild scheduled event will end at * or `null` if the event does not have a scheduled time to end + * * @type {?number} */ this.scheduledEndTimestamp = data.scheduled_end_time ? Date.parse(data.scheduled_end_time) : null; @@ -95,6 +104,7 @@ class GuildScheduledEvent extends Base { if ('privacy_level' in data) { /** * The privacy level of the guild scheduled event + * * @type {?GuildScheduledEventPrivacyLevel} */ this.privacyLevel = data.privacy_level; @@ -106,6 +116,7 @@ class GuildScheduledEvent extends Base { if ('status' in data) { /** * The status of the guild scheduled event + * * @type {?GuildScheduledEventStatus} */ this.status = data.status; @@ -117,6 +128,7 @@ class GuildScheduledEvent extends Base { if ('entity_type' in data) { /** * The type of hosting entity associated with the scheduled event + * * @type {?GuildScheduledEventEntityType} */ this.entityType = data.entity_type; @@ -128,6 +140,7 @@ class GuildScheduledEvent extends Base { if ('entity_id' in data) { /** * The id of the hosting entity associated with the scheduled event + * * @type {?Snowflake} */ this.entityId = data.entity_id; @@ -138,6 +151,7 @@ class GuildScheduledEvent extends Base { if ('user_count' in data) { /** * The number of users who are subscribed to this guild scheduled event + * * @type {?number} */ this.userCount = data.user_count; @@ -148,6 +162,7 @@ class GuildScheduledEvent extends Base { if ('creator' in data) { /** * The user that created this guild scheduled event + * * @type {?User} */ this.creator = this.client.users._add(data.creator); @@ -155,19 +170,19 @@ class GuildScheduledEvent extends Base { this.creator ??= this.client.users.resolve(this.creatorId); } - /* eslint-disable max-len */ /** * Represents the additional metadata for a {@link GuildScheduledEvent} + * * @see {@link https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-entity-metadata} - * @typedef {Object} GuildScheduledEventEntityMetadata + * @typedef {object} GuildScheduledEventEntityMetadata * @property {?string} location The location of the guild scheduled event */ - /* eslint-enable max-len */ if ('entity_metadata' in data) { if (data.entity_metadata) { /** * Additional metadata + * * @type {?GuildScheduledEventEntityMetadata} */ this.entityMetadata = { @@ -183,6 +198,7 @@ class GuildScheduledEvent extends Base { if ('image' in data) { /** * The cover image hash for this scheduled event + * * @type {?string} */ this.image = data.image; @@ -192,7 +208,8 @@ class GuildScheduledEvent extends Base { /** * Represents the recurrence rule for a {@link GuildScheduledEvent}. - * @typedef {Object} GuildScheduledEventRecurrenceRule + * + * @typedef {object} GuildScheduledEventRecurrenceRule * @property {number} startTimestamp The timestamp the recurrence rule interval starts at * @property {Date} startAt The time the recurrence rule interval starts at * @property {?number} endTimestamp The timestamp the recurrence rule interval ends at @@ -208,7 +225,7 @@ class GuildScheduledEvent extends Base { */ /** - * @typedef {Object} GuildScheduledEventRecurrenceRuleNWeekday + * @typedef {object} GuildScheduledEventRecurrenceRuleNWeekday * @property {number} n The week to recur on * @property {GuildScheduledEventRecurrenceRuleWeekday} day The day within the week to recur on */ @@ -216,6 +233,7 @@ class GuildScheduledEvent extends Base { if ('recurrence_rule' in data) { /** * The recurrence rule for this scheduled event + * * @type {?GuildScheduledEventRecurrenceRule} */ this.recurrenceRule = data.recurrence_rule && { @@ -243,6 +261,7 @@ class GuildScheduledEvent extends Base { /** * Whether this guild scheduled event is partial. + * * @type {boolean} * @readonly */ @@ -252,7 +271,8 @@ class GuildScheduledEvent extends Base { /** * The URL of this scheduled event's cover image - * @param {BaseImageURLOptions} [options={}] Options for image URL + * + * @param {BaseImageURLOptions} [options] Options for image URL * @returns {?string} */ coverImageURL(options = {}) { @@ -261,6 +281,7 @@ class GuildScheduledEvent extends Base { /** * The timestamp the guild scheduled event was created at + * * @type {number} * @readonly */ @@ -270,6 +291,7 @@ class GuildScheduledEvent extends Base { /** * The time the guild scheduled event was created at + * * @type {Date} * @readonly */ @@ -280,6 +302,7 @@ class GuildScheduledEvent extends Base { /** * The time the guild scheduled event will start at * This can be potentially `null` only when it's an {@link GuildAuditLogsEntry#target} + * * @type {?Date} * @readonly */ @@ -290,6 +313,7 @@ class GuildScheduledEvent extends Base { /** * The time the guild scheduled event will end at, * or `null` if the event does not have a scheduled time to end + * * @type {?Date} * @readonly */ @@ -299,6 +323,7 @@ class GuildScheduledEvent extends Base { /** * The channel associated with this scheduled event + * * @type {?(VoiceChannel|StageChannel)} * @readonly */ @@ -308,6 +333,7 @@ class GuildScheduledEvent extends Base { /** * The guild this scheduled event belongs to + * * @type {?Guild} * @readonly */ @@ -317,6 +343,7 @@ class GuildScheduledEvent extends Base { /** * The URL to the guild scheduled event + * * @type {string} * @readonly */ @@ -326,6 +353,7 @@ class GuildScheduledEvent extends Base { /** * Options used to create an invite URL to a {@link GuildScheduledEvent} + * * @typedef {InviteCreateOptions} GuildScheduledEventInviteURLCreateOptions * @property {GuildInvitableChannelResolvable} [channel] The channel to create the invite in. * This is required when the `entityType` of `GuildScheduledEvent` is @@ -334,6 +362,7 @@ class GuildScheduledEvent extends Base { /** * Creates an invite URL to this guild scheduled event. + * * @param {GuildScheduledEventInviteURLCreateOptions} [options] The options to create the invite * @returns {Promise} */ @@ -344,12 +373,14 @@ class GuildScheduledEvent extends Base { channelId = this.guild.channels.resolveId(options.channel); if (!channelId) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); } + const invite = await this.guild.invites.create(channelId, options); return `${RouteBases.invite}/${invite.code}?event=${this.id}`; } /** * Edits this guild scheduled event. + * * @param {GuildScheduledEventEditOptions} options The options to edit the guild scheduled event * @returns {Promise} * @example @@ -358,21 +389,23 @@ class GuildScheduledEvent extends Base { * .then(guildScheduledEvent => console.log(guildScheduledEvent)) * .catch(console.error); */ - edit(options) { + async edit(options) { return this.guild.scheduledEvents.edit(this.id, options); } /** * Fetches this guild scheduled event. - * @param {boolean} [force=true] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - fetch(force = true) { + async fetch(force = true) { return this.guild.scheduledEvents.fetch({ guildScheduledEvent: this.id, force }); } /** * Deletes this guild scheduled event. + * * @returns {Promise} * @example * // Delete a guild scheduled event @@ -387,6 +420,7 @@ class GuildScheduledEvent extends Base { /** * Sets a new name for the guild scheduled event. + * * @param {string} name The new name of the guild scheduled event * @param {string} [reason] The reason for changing the name * @returns {Promise} @@ -396,12 +430,13 @@ class GuildScheduledEvent extends Base { * .then(guildScheduledEvent => console.log(`Set the name to: ${guildScheduledEvent.name}`)) * .catch(console.error); */ - setName(name, reason) { + async setName(name, reason) { return this.edit({ name, reason }); } /** * Sets a new time to schedule the event at. + * * @param {DateResolvable} scheduledStartTime The time to schedule the event at * @param {string} [reason] The reason for changing the scheduled start time * @returns {Promise} @@ -411,13 +446,14 @@ class GuildScheduledEvent extends Base { * .then(guildScheduledEvent => console.log(`Set the start time to: ${guildScheduledEvent.scheduledStartTime}`)) * .catch(console.error); */ - setScheduledStartTime(scheduledStartTime, reason) { + async setScheduledStartTime(scheduledStartTime, reason) { return this.edit({ scheduledStartTime, reason }); } // TODO: scheduledEndTime gets reset on passing null but it hasn't been documented /** * Sets a new time to end the event at. + * * @param {DateResolvable} scheduledEndTime The time to end the event at * @param {string} [reason] The reason for changing the scheduled end time * @returns {Promise} @@ -427,12 +463,13 @@ class GuildScheduledEvent extends Base { * .then(guildScheduledEvent => console.log(`Set the end time to: ${guildScheduledEvent.scheduledEndTime}`)) * .catch(console.error); */ - setScheduledEndTime(scheduledEndTime, reason) { + async setScheduledEndTime(scheduledEndTime, reason) { return this.edit({ scheduledEndTime, reason }); } /** * Sets the new description of the guild scheduled event. + * * @param {string} description The description of the guild scheduled event * @param {string} [reason] The reason for changing the description * @returns {Promise} @@ -442,7 +479,7 @@ class GuildScheduledEvent extends Base { * .then(guildScheduledEvent => console.log(`Set the description to: ${guildScheduledEvent.description}`)) * .catch(console.error); */ - setDescription(description, reason) { + async setDescription(description, reason) { return this.edit({ description, reason }); } @@ -450,6 +487,7 @@ class GuildScheduledEvent extends Base { * Sets the new status of the guild scheduled event. * If you're working with TypeScript, use this method in conjunction with status type-guards * like {@link GuildScheduledEvent#isScheduled} to get only valid status as suggestion + * * @param {GuildScheduledEventStatus} status The status of the guild scheduled event * @param {string} [reason] The reason for changing the status * @returns {Promise} @@ -459,12 +497,13 @@ class GuildScheduledEvent extends Base { * .then(guildScheduledEvent => console.log(`Set the status to: ${guildScheduledEvent.status}`)) * .catch(console.error); */ - setStatus(status, reason) { + async setStatus(status, reason) { return this.edit({ status, reason }); } /** * Sets the new location of the guild scheduled event. + * * @param {string} location The location of the guild scheduled event * @param {string} [reason] The reason for changing the location * @returns {Promise} @@ -474,21 +513,23 @@ class GuildScheduledEvent extends Base { * .then(guildScheduledEvent => console.log(`Set the location to: ${guildScheduledEvent.entityMetadata.location}`)) * .catch(console.error); */ - setLocation(location, reason) { + async setLocation(location, reason) { return this.edit({ entityMetadata: { location }, reason }); } /** * Fetches subscribers of this guild scheduled event. + * * @param {FetchGuildScheduledEventSubscribersOptions} [options] Options for fetching the subscribers * @returns {Promise>} */ - fetchSubscribers(options) { + async fetchSubscribers(options) { return this.guild.scheduledEvents.fetchSubscribers(this.id, options); } /** * When concatenated with a string, this automatically concatenates the event's URL instead of the object. + * * @returns {string} * @example * // Logs: Event: https://discord.com/events/412345678901234567/499876543211234567 @@ -500,6 +541,7 @@ class GuildScheduledEvent extends Base { /** * Indicates whether this guild scheduled event has an {@link GuildScheduledEventStatus.Active} status. + * * @returns {boolean} */ isActive() { @@ -508,6 +550,7 @@ class GuildScheduledEvent extends Base { /** * Indicates whether this guild scheduled event has a {@link GuildScheduledEventStatus.Canceled} status. + * * @returns {boolean} */ isCanceled() { @@ -516,6 +559,7 @@ class GuildScheduledEvent extends Base { /** * Indicates whether this guild scheduled event has a {@link GuildScheduledEventStatus.Completed} status. + * * @returns {boolean} */ isCompleted() { @@ -524,6 +568,7 @@ class GuildScheduledEvent extends Base { /** * Indicates whether this guild scheduled event has a {@link GuildScheduledEventStatus.Scheduled} status. + * * @returns {boolean} */ isScheduled() { diff --git a/packages/discord.js/src/structures/GuildTemplate.js b/packages/discord.js/src/structures/GuildTemplate.js index 8c219ea4bca0..d022039d2002 100644 --- a/packages/discord.js/src/structures/GuildTemplate.js +++ b/packages/discord.js/src/structures/GuildTemplate.js @@ -2,18 +2,20 @@ const { setTimeout, clearTimeout } = require('node:timers'); const { RouteBases, Routes } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); const { resolveImage } = require('../util/DataResolver.js'); const { Events } = require('../util/Events.js'); +const { Base } = require('./Base.js'); /** * Represents the template for a guild. + * * @extends {Base} */ class GuildTemplate extends Base { /** * A regular expression that matches guild template links. * The `code` group property is present on the `exec()` result of this expression. + * * @type {RegExp} * @memberof GuildTemplate */ @@ -28,6 +30,7 @@ class GuildTemplate extends Base { if ('code' in data) { /** * The unique code of this template + * * @type {string} */ this.code = data.code; @@ -36,6 +39,7 @@ class GuildTemplate extends Base { if ('name' in data) { /** * The name of this template + * * @type {string} */ this.name = data.name; @@ -44,6 +48,7 @@ class GuildTemplate extends Base { if ('description' in data) { /** * The description of this template + * * @type {?string} */ this.description = data.description; @@ -52,6 +57,7 @@ class GuildTemplate extends Base { if ('usage_count' in data) { /** * The amount of times this template has been used + * * @type {number} */ this.usageCount = data.usage_count; @@ -60,6 +66,7 @@ class GuildTemplate extends Base { if ('creator_id' in data) { /** * The id of the user that created this template + * * @type {Snowflake} */ this.creatorId = data.creator_id; @@ -68,6 +75,7 @@ class GuildTemplate extends Base { if ('creator' in data) { /** * The user that created this template + * * @type {User} */ this.creator = this.client.users._add(data.creator); @@ -76,6 +84,7 @@ class GuildTemplate extends Base { if ('created_at' in data) { /** * The timestamp of when this template was created at + * * @type {number} */ this.createdTimestamp = Date.parse(data.created_at); @@ -84,6 +93,7 @@ class GuildTemplate extends Base { if ('updated_at' in data) { /** * The timestamp of when this template was last synced to the guild + * * @type {number} */ this.updatedTimestamp = Date.parse(data.updated_at); @@ -92,6 +102,7 @@ class GuildTemplate extends Base { if ('source_guild_id' in data) { /** * The id of the guild that this template belongs to + * * @type {Snowflake} */ this.guildId = data.source_guild_id; @@ -100,6 +111,7 @@ class GuildTemplate extends Base { if ('serialized_source_guild' in data) { /** * The data of the guild that this template would create + * * @type {APIGuild} */ this.serializedGuild = data.serialized_source_guild; @@ -107,6 +119,7 @@ class GuildTemplate extends Base { /** * Whether this template has unsynced changes + * * @type {?boolean} */ this.unSynced = 'is_dirty' in data ? Boolean(data.is_dirty) : null; @@ -117,6 +130,7 @@ class GuildTemplate extends Base { /** * Creates a guild based on this template. * This is only available to bots in fewer than 10 guilds. + * * @param {string} name The name of the guild * @param {BufferResolvable|Base64Resolvable} [icon] The icon for the guild * @returns {Promise} @@ -134,6 +148,7 @@ class GuildTemplate extends Base { return new Promise(resolve => { const resolveGuild = guild => { + // eslint-disable-next-line @typescript-eslint/no-use-before-define client.off(Events.GuildCreate, handleGuild); client.decrementMaxListeners(); resolve(guild); @@ -141,6 +156,7 @@ class GuildTemplate extends Base { const handleGuild = guild => { if (guild.id === data.id) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(timeout); resolveGuild(guild); } @@ -155,13 +171,15 @@ class GuildTemplate extends Base { /** * Options used to edit a guild template. - * @typedef {Object} GuildTemplateEditOptions + * + * @typedef {object} GuildTemplateEditOptions * @property {string} [name] The name of this template * @property {string} [description] The description of this template */ /** * Updates the metadata of this template. + * * @param {GuildTemplateEditOptions} [options] Options for editing the template * @returns {Promise} */ @@ -174,6 +192,7 @@ class GuildTemplate extends Base { /** * Deletes this template. + * * @returns {Promise} */ async delete() { @@ -183,6 +202,7 @@ class GuildTemplate extends Base { /** * Syncs this template to the current state of the guild. + * * @returns {Promise} */ async sync() { @@ -192,6 +212,7 @@ class GuildTemplate extends Base { /** * The time when this template was created at + * * @type {Date} * @readonly */ @@ -201,6 +222,7 @@ class GuildTemplate extends Base { /** * The time when this template was last synced to the guild + * * @type {Date} * @readonly */ @@ -210,6 +232,7 @@ class GuildTemplate extends Base { /** * The guild that this template belongs to + * * @type {?Guild} * @readonly */ @@ -219,6 +242,7 @@ class GuildTemplate extends Base { /** * The URL of this template + * * @type {string} * @readonly */ @@ -228,6 +252,7 @@ class GuildTemplate extends Base { /** * When concatenated with a string, this automatically returns the template's code instead of the template object. + * * @returns {string} * @example * // Logs: Template: FKvmczH2HyUf diff --git a/packages/discord.js/src/structures/Integration.js b/packages/discord.js/src/structures/Integration.js index bfefc1834770..4706bda7c590 100644 --- a/packages/discord.js/src/structures/Integration.js +++ b/packages/discord.js/src/structures/Integration.js @@ -6,22 +6,25 @@ const { IntegrationApplication } = require('./IntegrationApplication.js'); /** * The information account for an integration - * @typedef {Object} IntegrationAccount + * + * @typedef {object} IntegrationAccount * @property {Snowflake|string} id The id of the account * @property {string} name The name of the account */ /** * The type of an {@link Integration}. This can be: - * * `twitch` - * * `youtube` - * * `discord` - * * `guild_subscription` + * `twitch` + * `youtube` + * `discord` + * `guild_subscription` + * * @typedef {string} IntegrationType */ /** * Represents a guild integration. + * * @extends {Base} */ class Integration extends Base { @@ -30,30 +33,35 @@ class Integration extends Base { /** * The guild this integration belongs to + * * @type {Guild} */ this.guild = guild; /** * The integration id + * * @type {Snowflake|string} */ this.id = data.id; /** * The integration name + * * @type {string} */ this.name = data.name; /** * The integration type + * * @type {IntegrationType} */ this.type = data.type; /** * Whether this integration is enabled + * * @type {?boolean} */ this.enabled = data.enabled ?? null; @@ -61,6 +69,7 @@ class Integration extends Base { if ('syncing' in data) { /** * Whether this integration is syncing + * * @type {?boolean} */ this.syncing = data.syncing; @@ -70,6 +79,7 @@ class Integration extends Base { /** * The role that this integration uses for subscribers + * * @type {?Role} */ this.role = this.guild.roles.resolve(data.role_id); @@ -77,6 +87,7 @@ class Integration extends Base { if ('enable_emoticons' in data) { /** * Whether emoticons should be synced for this integration (twitch only currently) + * * @type {?boolean} */ this.enableEmoticons = data.enable_emoticons; @@ -87,6 +98,7 @@ class Integration extends Base { if (data.user) { /** * The user for this integration + * * @type {?User} */ this.user = this.client.users._add(data.user); @@ -96,6 +108,7 @@ class Integration extends Base { /** * The account integration information + * * @type {IntegrationAccount} */ this.account = data.account; @@ -103,6 +116,7 @@ class Integration extends Base { if ('synced_at' in data) { /** * The timestamp at which this integration was last synced at + * * @type {?number} */ this.syncedTimestamp = Date.parse(data.synced_at); @@ -113,6 +127,7 @@ class Integration extends Base { if ('subscriber_count' in data) { /** * How many subscribers this integration has + * * @type {?number} */ this.subscriberCount = data.subscriber_count; @@ -123,6 +138,7 @@ class Integration extends Base { if ('revoked' in data) { /** * Whether this integration has been revoked + * * @type {?boolean} */ this.revoked = data.revoked; @@ -135,6 +151,7 @@ class Integration extends Base { /** * The date at which this integration was last synced at + * * @type {?Date} * @readonly */ @@ -144,6 +161,7 @@ class Integration extends Base { /** * All roles that are managed by this integration + * * @type {Collection} * @readonly */ @@ -156,6 +174,7 @@ class Integration extends Base { if ('expire_behavior' in data) { /** * The behavior of expiring subscribers + * * @type {?IntegrationExpireBehavior} */ this.expireBehavior = data.expire_behavior; @@ -166,6 +185,7 @@ class Integration extends Base { if ('expire_grace_period' in data) { /** * The grace period (in days) before expiring subscribers + * * @type {?number} */ this.expireGracePeriod = data.expire_grace_period; @@ -179,6 +199,7 @@ class Integration extends Base { } else { /** * The application for this integration + * * @type {?IntegrationApplication} */ this.application = new IntegrationApplication(this.client, data.application); @@ -190,6 +211,7 @@ class Integration extends Base { if ('scopes' in data) { /** * The scopes this application has been authorized for + * * @type {OAuth2Scopes[]} */ this.scopes = data.scopes; @@ -200,6 +222,7 @@ class Integration extends Base { /** * Deletes this integration. + * * @returns {Promise} * @param {string} [reason] Reason for deleting this integration */ diff --git a/packages/discord.js/src/structures/IntegrationApplication.js b/packages/discord.js/src/structures/IntegrationApplication.js index 5a847bbe214d..c204b41ca83a 100644 --- a/packages/discord.js/src/structures/IntegrationApplication.js +++ b/packages/discord.js/src/structures/IntegrationApplication.js @@ -4,6 +4,7 @@ const { Application } = require('./interfaces/Application.js'); /** * Represents an Integration's OAuth2 Application. + * * @extends {Application} */ class IntegrationApplication extends Application { @@ -13,6 +14,7 @@ class IntegrationApplication extends Application { if ('bot' in data) { /** * The bot user for this application + * * @type {?User} */ this.bot = this.client.users._add(data.bot); @@ -23,6 +25,7 @@ class IntegrationApplication extends Application { if ('terms_of_service_url' in data) { /** * The URL of the application's terms of service + * * @type {?string} */ this.termsOfServiceURL = data.terms_of_service_url; @@ -33,6 +36,7 @@ class IntegrationApplication extends Application { if ('privacy_policy_url' in data) { /** * The URL of the application's privacy policy + * * @type {?string} */ this.privacyPolicyURL = data.privacy_policy_url; @@ -43,6 +47,7 @@ class IntegrationApplication extends Application { if ('rpc_origins' in data) { /** * The Array of RPC origin URLs + * * @type {string[]} */ this.rpcOrigins = data.rpc_origins; @@ -53,6 +58,7 @@ class IntegrationApplication extends Application { if ('cover_image' in data) { /** * The hash of the application's cover image + * * @type {?string} */ this.cover = data.cover_image; @@ -63,6 +69,7 @@ class IntegrationApplication extends Application { if ('verify_key' in data) { /** * The hex-encoded key for verification in interactions and the GameSDK's GetTicket + * * @type {?string} */ this.verifyKey = data.verify_key; diff --git a/packages/discord.js/src/structures/InteractionCallback.js b/packages/discord.js/src/structures/InteractionCallback.js index 406e1ef707d8..665cb92a8a7c 100644 --- a/packages/discord.js/src/structures/InteractionCallback.js +++ b/packages/discord.js/src/structures/InteractionCallback.js @@ -9,6 +9,7 @@ class InteractionCallback { constructor(client, data) { /** * The client that instantiated this. + * * @name InteractionCallback#client * @type {Client} * @readonly @@ -17,36 +18,42 @@ class InteractionCallback { /** * The id of the original interaction response + * * @type {Snowflake} */ this.id = data.id; /** * The type of the original interaction + * * @type {InteractionType} */ this.type = data.type; /** * The instance id of the Activity if one was launched or joined + * * @type {?string} */ this.activityInstanceId = data.activity_instance_id ?? null; /** * The id of the message that was created by the interaction + * * @type {?Snowflake} */ this.responseMessageId = data.response_message_id ?? null; /** * Whether the message is in a loading state + * * @type {?boolean} */ this.responseMessageLoading = data.response_message_loading ?? null; /** * Whether the response message was ephemeral + * * @type {?boolean} */ this.responseMessageEphemeral = data.response_message_ephemeral ?? null; @@ -54,6 +61,7 @@ class InteractionCallback { /** * The timestamp the original interaction was created at + * * @type {number} * @readonly */ @@ -63,6 +71,7 @@ class InteractionCallback { /** * The time the original interaction was created at + * * @type {Date} * @readonly */ diff --git a/packages/discord.js/src/structures/InteractionCallbackResource.js b/packages/discord.js/src/structures/InteractionCallbackResource.js index eeed0b7aa9f4..65c7cb1a03e4 100644 --- a/packages/discord.js/src/structures/InteractionCallbackResource.js +++ b/packages/discord.js/src/structures/InteractionCallbackResource.js @@ -11,6 +11,7 @@ class InteractionCallbackResource { constructor(client, data) { /** * The client that instantiated this + * * @name InteractionCallbackResource#client * @type {Client} * @readonly @@ -19,18 +20,21 @@ class InteractionCallbackResource { /** * The interaction callback type + * * @type {InteractionResponseType} */ this.type = data.type; /** * The Activity launched by an interaction - * @typedef {Object} ActivityInstance + * + * @typedef {object} ActivityInstance * @property {string} id The instance id of the Activity */ /** * Represents the Activity launched by this interaction + * * @type {?ActivityInstance} */ this.activityInstance = data.activity_instance ?? null; @@ -38,6 +42,7 @@ class InteractionCallbackResource { if ('message' in data) { /** * The message created by the interaction + * * @type {?Message} */ this.message = diff --git a/packages/discord.js/src/structures/InteractionCallbackResponse.js b/packages/discord.js/src/structures/InteractionCallbackResponse.js index c6bf5920e26f..0c8b5d8e055a 100644 --- a/packages/discord.js/src/structures/InteractionCallbackResponse.js +++ b/packages/discord.js/src/structures/InteractionCallbackResponse.js @@ -10,6 +10,7 @@ class InteractionCallbackResponse { constructor(client, data) { /** * The client that instantiated this + * * @name InteractionCallbackResponse#client * @type {Client} * @readonly @@ -18,12 +19,14 @@ class InteractionCallbackResponse { /** * The interaction object associated with the interaction callback response + * * @type {InteractionCallback} */ this.interaction = new InteractionCallback(client, data.interaction); /** * The resource that was created by the interaction response + * * @type {?InteractionCallbackResource} */ this.resource = data.resource ? new InteractionCallbackResource(client, data.resource) : null; diff --git a/packages/discord.js/src/structures/InteractionCollector.js b/packages/discord.js/src/structures/InteractionCollector.js index 253f9eae168d..41eeb71d7534 100644 --- a/packages/discord.js/src/structures/InteractionCollector.js +++ b/packages/discord.js/src/structures/InteractionCollector.js @@ -1,8 +1,9 @@ +/* eslint-disable @typescript-eslint/unbound-method */ 'use strict'; const { Collection } = require('@discordjs/collection'); -const { Collector } = require('./interfaces/Collector.js'); const { Events } = require('../util/Events.js'); +const { Collector } = require('./interfaces/Collector.js'); /** * @typedef {CollectorOptions} InteractionCollectorOptions @@ -24,24 +25,27 @@ const { Events } = require('../util/Events.js'); * guild ({@link Client#event:guildDelete guildDelete}) is deleted. * Interaction collectors that do not specify `time` or `idle` may be prone to always running. * Ensure your interaction collectors end via either of these options or manual cancellation. + * * @extends {Collector} */ class InteractionCollector extends Collector { /** * @param {Client} client The client on which to collect interactions - * @param {InteractionCollectorOptions} [options={}] The options to apply to this collector + * @param {InteractionCollectorOptions} [options] The options to apply to this collector */ constructor(client, options = {}) { super(client, options); /** * The message from which to collect interactions, if provided + * * @type {?Snowflake} */ this.messageId = options.message?.id ?? null; /** * The channel from which to collect interactions, if provided + * * @type {?Snowflake} */ this.channelId = @@ -49,6 +53,7 @@ class InteractionCollector extends Collector { /** * The guild from which to collect interactions, if provided + * * @type {?Snowflake} */ this.guildId = @@ -59,24 +64,28 @@ class InteractionCollector extends Collector { /** * The type of interaction to collect + * * @type {?InteractionType} */ this.interactionType = options.interactionType ?? null; /** * The type of component to collect + * * @type {?ComponentType} */ this.componentType = options.componentType ?? null; /** * The users that have interacted with this collector + * * @type {Collection} */ this.users = new Collection(); /** * The total number of interactions collected + * * @type {number} */ this.total = 0; @@ -125,6 +134,7 @@ class InteractionCollector extends Collector { /** * Handles an incoming interaction for possible collection. + * * @param {BaseInteraction} interaction The interaction to possibly collect * @returns {?Snowflake} * @private @@ -132,6 +142,7 @@ class InteractionCollector extends Collector { collect(interaction) { /** * Emitted whenever an interaction is collected. + * * @event InteractionCollector#collect * @param {BaseInteraction} interaction The interaction that was collected */ @@ -147,12 +158,14 @@ class InteractionCollector extends Collector { /** * Handles an interaction for possible disposal. + * * @param {BaseInteraction} interaction The interaction that could be disposed of * @returns {?Snowflake} */ dispose(interaction) { /** * Emitted whenever an interaction is disposed of. + * * @event InteractionCollector#dispose * @param {BaseInteraction} interaction The interaction that was disposed of */ @@ -177,6 +190,7 @@ class InteractionCollector extends Collector { /** * The reason this collector has ended with, or null if it hasn't ended yet + * * @type {?string} * @readonly */ @@ -189,6 +203,7 @@ class InteractionCollector extends Collector { /** * Handles checking if the message has been deleted, and if so, stops the collector with the reason 'messageDelete'. + * * @private * @param {Message} message The message that was deleted * @returns {void} @@ -201,6 +216,7 @@ class InteractionCollector extends Collector { /** * Handles checking if the channel has been deleted, and if so, stops the collector with the reason 'channelDelete'. + * * @private * @param {GuildChannel} channel The channel that was deleted * @returns {void} @@ -213,6 +229,7 @@ class InteractionCollector extends Collector { /** * Handles checking if the thread has been deleted, and if so, stops the collector with the reason 'threadDelete'. + * * @private * @param {ThreadChannel} thread The thread that was deleted * @returns {void} @@ -225,6 +242,7 @@ class InteractionCollector extends Collector { /** * Handles checking if the guild has been deleted, and if so, stops the collector with the reason 'guildDelete'. + * * @private * @param {Guild} guild The guild that was deleted * @returns {void} diff --git a/packages/discord.js/src/structures/InteractionWebhook.js b/packages/discord.js/src/structures/InteractionWebhook.js index 48008339a0db..d633d3a9d9f3 100644 --- a/packages/discord.js/src/structures/InteractionWebhook.js +++ b/packages/discord.js/src/structures/InteractionWebhook.js @@ -4,6 +4,7 @@ const { Webhook } = require('./Webhook.js'); /** * Represents a webhook for an Interaction + * * @implements {Webhook} */ class InteractionWebhook { @@ -15,6 +16,7 @@ class InteractionWebhook { constructor(client, id, token) { /** * The client that instantiated the interaction webhook + * * @name InteractionWebhook#client * @type {Client} * @readonly @@ -25,32 +27,37 @@ class InteractionWebhook { } // These are here only for documentation purposes - they are implemented by Webhook - /* eslint-disable no-empty-function */ + /** * Sends a message with this webhook. + * * @param {string|MessagePayload|InteractionReplyOptions} options The content for the reply * @returns {Promise} */ - send() {} + async send() {} /** * Gets a message that was sent by this webhook. + * * @param {Snowflake|'@original'} message The id of the message to fetch * @returns {Promise} Returns the message sent by this webhook */ - fetchMessage() {} + async fetchMessage() {} /** * Edits a message that was sent by this webhook. + * * @param {MessageResolvable|'@original'} message The message to edit * @param {string|MessagePayload|WebhookMessageEditOptions} options The options to provide * @returns {Promise} Returns the message edited by this webhook */ - editMessage() {} + async editMessage() {} + deleteMessage() {} + get url() {} } diff --git a/packages/discord.js/src/structures/Invite.js b/packages/discord.js/src/structures/Invite.js index 3041d6c9a725..2e426a522303 100644 --- a/packages/discord.js/src/structures/Invite.js +++ b/packages/discord.js/src/structures/Invite.js @@ -1,19 +1,21 @@ 'use strict'; const { RouteBases, Routes, PermissionFlagsBits } = require('discord-api-types/v10'); +const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { Base } = require('./Base.js'); const { GuildScheduledEvent } = require('./GuildScheduledEvent.js'); const { IntegrationApplication } = require('./IntegrationApplication.js'); -const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); /** * Represents an invitation to a guild channel. + * * @extends {Base} */ class Invite extends Base { /** * A regular expression that matches Discord invite links. * The `code` group property is present on the `exec()` result of this expression. + * * @type {RegExp} * @memberof Invite */ @@ -24,6 +26,7 @@ class Invite extends Base { /** * The type of this invite + * * @type {InviteType} */ this.type = data.type; @@ -35,6 +38,7 @@ class Invite extends Base { const { InviteGuild } = require('./InviteGuild.js'); /** * The guild the invite is for including welcome screen data if present + * * @type {?(Guild|InviteGuild)} */ this.guild ??= null; @@ -45,6 +49,7 @@ class Invite extends Base { if ('code' in data) { /** * The code for this invite + * * @type {string} */ this.code = data.code; @@ -54,6 +59,7 @@ class Invite extends Base { /** * The approximate number of online members of the guild this invite is for * This is only available when the invite was fetched through {@link Client#fetchInvite}. + * * @type {?number} */ this.presenceCount = data.approximate_presence_count; @@ -65,6 +71,7 @@ class Invite extends Base { /** * The approximate total number of members of the guild this invite is for * This is only available when the invite was fetched through {@link Client#fetchInvite}. + * * @type {?number} */ this.memberCount = data.approximate_member_count; @@ -77,6 +84,7 @@ class Invite extends Base { * Whether or not this invite only grants temporary membership * This is only available when the invite was fetched through {@link GuildInviteManager#fetch} * or created through {@link GuildInviteManager#create}. + * * @type {?boolean} */ this.temporary = data.temporary ?? null; @@ -89,6 +97,7 @@ class Invite extends Base { * The maximum age of the invite, in seconds, 0 if never expires * This is only available when the invite was fetched through {@link GuildInviteManager#fetch} * or created through {@link GuildInviteManager#create}. + * * @type {?number} */ this.maxAge = data.max_age; @@ -101,6 +110,7 @@ class Invite extends Base { * How many times this invite has been used * This is only available when the invite was fetched through {@link GuildInviteManager#fetch} * or created through {@link GuildInviteManager#create}. + * * @type {?number} */ this.uses = data.uses; @@ -113,6 +123,7 @@ class Invite extends Base { * The maximum uses of this invite * This is only available when the invite was fetched through {@link GuildInviteManager#fetch} * or created through {@link GuildInviteManager#create}. + * * @type {?number} */ this.maxUses = data.max_uses; @@ -123,6 +134,7 @@ class Invite extends Base { if ('inviter_id' in data) { /** * The user's id who created this invite + * * @type {?Snowflake} */ this.inviterId = data.inviter_id; @@ -138,6 +150,7 @@ class Invite extends Base { if ('target_user' in data) { /** * The user whose stream to display for this voice channel stream invite + * * @type {?User} */ this.targetUser = this.client.users._add(data.target_user); @@ -148,6 +161,7 @@ class Invite extends Base { if ('target_application' in data) { /** * The embedded application to open for this voice channel embedded application invite + * * @type {?IntegrationApplication} */ this.targetApplication = new IntegrationApplication(this.client, data.target_application); @@ -158,6 +172,7 @@ class Invite extends Base { if ('target_type' in data) { /** * The target type + * * @type {?InviteTargetType} */ this.targetType = data.target_type; @@ -168,6 +183,7 @@ class Invite extends Base { if ('channel_id' in data) { /** * The id of the channel this invite is for + * * @type {?Snowflake} */ this.channelId = data.channel_id; @@ -176,6 +192,7 @@ class Invite extends Base { if ('channel' in data) { /** * The channel this invite is for + * * @type {?BaseChannel} */ this.channel = @@ -188,6 +205,7 @@ class Invite extends Base { if ('created_at' in data) { /** * The timestamp this invite was created at + * * @type {?number} */ this.createdTimestamp = Date.parse(data.created_at); @@ -204,6 +222,7 @@ class Invite extends Base { if ('guild_scheduled_event' in data) { /** * The guild scheduled event data if there is a {@link GuildScheduledEvent} in the channel this invite is for + * * @type {?GuildScheduledEvent} */ this.guildScheduledEvent = new GuildScheduledEvent(this.client, data.guild_scheduled_event); @@ -214,6 +233,7 @@ class Invite extends Base { /** * The time the invite was created at + * * @type {?Date} * @readonly */ @@ -223,6 +243,7 @@ class Invite extends Base { /** * Whether the invite is deletable by the client user + * * @type {boolean} * @readonly */ @@ -231,13 +252,14 @@ class Invite extends Base { if (!guild || !this.client.guilds.cache.has(guild.id)) return false; if (!guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); return Boolean( - this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) || + this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) ?? guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild), ); } /** * The timestamp the invite will expire at + * * @type {?number} * @readonly */ @@ -250,6 +272,7 @@ class Invite extends Base { /** * The time the invite will expire at + * * @type {?Date} * @readonly */ @@ -259,6 +282,7 @@ class Invite extends Base { /** * The user who created this invite + * * @type {?User} * @readonly */ @@ -268,6 +292,7 @@ class Invite extends Base { /** * The URL to the invite + * * @type {string} * @readonly */ @@ -277,6 +302,7 @@ class Invite extends Base { /** * Deletes this invite. + * * @param {string} [reason] Reason for deleting this invite * @returns {Promise} */ @@ -287,6 +313,7 @@ class Invite extends Base { /** * When concatenated with a string, this automatically concatenates the invite's URL instead of the object. + * * @returns {string} * @example * // Logs: Invite: https://discord.gg/A1b2C3 diff --git a/packages/discord.js/src/structures/InviteGuild.js b/packages/discord.js/src/structures/InviteGuild.js index 932e98214861..f70867816fe9 100644 --- a/packages/discord.js/src/structures/InviteGuild.js +++ b/packages/discord.js/src/structures/InviteGuild.js @@ -5,6 +5,7 @@ const { WelcomeScreen } = require('./WelcomeScreen.js'); /** * Represents a guild received from an invite, includes welcome screen data if available. + * * @extends {AnonymousGuild} */ class InviteGuild extends AnonymousGuild { @@ -13,9 +14,10 @@ class InviteGuild extends AnonymousGuild { /** * The welcome screen for this invite guild + * * @type {?WelcomeScreen} */ - this.welcomeScreen = data.welcome_screen !== undefined ? new WelcomeScreen(this, data.welcome_screen) : null; + this.welcomeScreen = data.welcome_screen === undefined ? null : new WelcomeScreen(this, data.welcome_screen); } } diff --git a/packages/discord.js/src/structures/MediaChannel.js b/packages/discord.js/src/structures/MediaChannel.js index 21cab7c48d71..bafb203b1b03 100644 --- a/packages/discord.js/src/structures/MediaChannel.js +++ b/packages/discord.js/src/structures/MediaChannel.js @@ -4,6 +4,7 @@ const { ThreadOnlyChannel } = require('./ThreadOnlyChannel.js'); /** * Represents a media channel. + * * @extends {ThreadOnlyChannel} */ class MediaChannel extends ThreadOnlyChannel {} diff --git a/packages/discord.js/src/structures/MentionableSelectMenuComponent.js b/packages/discord.js/src/structures/MentionableSelectMenuComponent.js index 12dbaebed3bf..8dba9517b1cf 100644 --- a/packages/discord.js/src/structures/MentionableSelectMenuComponent.js +++ b/packages/discord.js/src/structures/MentionableSelectMenuComponent.js @@ -4,6 +4,7 @@ const { BaseSelectMenuComponent } = require('./BaseSelectMenuComponent.js'); /** * Represents a mentionable select menu component + * * @extends {BaseSelectMenuComponent} */ class MentionableSelectMenuComponent extends BaseSelectMenuComponent {} diff --git a/packages/discord.js/src/structures/MentionableSelectMenuInteraction.js b/packages/discord.js/src/structures/MentionableSelectMenuInteraction.js index b7e6c4ef2653..db2a0a27754a 100644 --- a/packages/discord.js/src/structures/MentionableSelectMenuInteraction.js +++ b/packages/discord.js/src/structures/MentionableSelectMenuInteraction.js @@ -1,11 +1,12 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); -const { MessageComponentInteraction } = require('./MessageComponentInteraction.js'); const { Events } = require('../util/Events.js'); +const { MessageComponentInteraction } = require('./MessageComponentInteraction.js'); /** * Represents a {@link ComponentType.MentionableSelect} select menu interaction. + * * @extends {MessageComponentInteraction} */ class MentionableSelectMenuInteraction extends MessageComponentInteraction { @@ -16,24 +17,28 @@ class MentionableSelectMenuInteraction extends MessageComponentInteraction { /** * An array of the selected user and role ids + * * @type {Snowflake[]} */ this.values = values ?? []; /** * Collection of the selected users + * * @type {Collection} */ this.users = new Collection(); /** * Collection of the selected users + * * @type {Collection} */ this.members = new Collection(); /** * Collection of the selected roles + * * @type {Collection} */ this.roles = new Collection(); diff --git a/packages/discord.js/src/structures/Message.js b/packages/discord.js/src/structures/Message.js index 8a07ed612e80..27439c12c28b 100644 --- a/packages/discord.js/src/structures/Message.js +++ b/packages/discord.js/src/structures/Message.js @@ -11,6 +11,14 @@ const { MessageReferenceType, PermissionFlagsBits, } = require('discord-api-types/v10'); +const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); +const { ReactionManager } = require('../managers/ReactionManager.js'); +const { createComponent } = require('../util/Components.js'); +const { NonSystemMessageTypes, MaxBulkDeletableMessageAge, UndeletableMessageTypes } = require('../util/Constants.js'); +const { MessageFlagsBitField } = require('../util/MessageFlagsBitField.js'); +const { PermissionsBitField } = require('../util/PermissionsBitField.js'); +const { _transformAPIMessageInteractionMetadata } = require('../util/Transformers.js'); +const { cleanContent, resolvePartialEmoji, transformResolved } = require('../util/Util.js'); const { Attachment } = require('./Attachment.js'); const { Base } = require('./Base.js'); const { ClientApplication } = require('./ClientApplication.js'); @@ -21,17 +29,10 @@ const { MessagePayload } = require('./MessagePayload.js'); const { Poll } = require('./Poll.js'); const { ReactionCollector } = require('./ReactionCollector.js'); const { Sticker } = require('./Sticker.js'); -const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); -const { ReactionManager } = require('../managers/ReactionManager.js'); -const { createComponent } = require('../util/Components.js'); -const { NonSystemMessageTypes, MaxBulkDeletableMessageAge, UndeletableMessageTypes } = require('../util/Constants.js'); -const { MessageFlagsBitField } = require('../util/MessageFlagsBitField.js'); -const { PermissionsBitField } = require('../util/PermissionsBitField.js'); -const { _transformAPIMessageInteractionMetadata } = require('../util/Transformers.js'); -const { cleanContent, resolvePartialEmoji, transformResolved } = require('../util/Util.js'); /** * Represents a message on Discord. + * * @extends {Base} */ class Message extends Base { @@ -40,12 +41,14 @@ class Message extends Base { /** * The id of the channel the message was sent in + * * @type {Snowflake} */ this.channelId = data.channel_id; /** * The id of the guild the message was sent in, if any + * * @type {?Snowflake} */ this.guildId = data.guild_id ?? this.channel?.guild?.id ?? null; @@ -56,12 +59,14 @@ class Message extends Base { _patch(data) { /** * The message's id + * * @type {Snowflake} */ this.id = data.id; /** * The timestamp the message was sent at + * * @type {number} */ this.createdTimestamp = DiscordSnowflake.timestampFrom(this.id); @@ -69,12 +74,14 @@ class Message extends Base { if ('type' in data) { /** * The type of the message + * * @type {?MessageType} */ this.type = data.type; /** * Whether or not this message was sent by Discord, not actually a user (e.g. pin notifications) + * * @type {?boolean} */ this.system = !NonSystemMessageTypes.includes(this.type); @@ -88,6 +95,7 @@ class Message extends Base { * The content of the message. * This property requires the {@link GatewayIntentBits.MessageContent} privileged intent * in a guild for messages that do not mention the client. + * * @type {?string} */ this.content = data.content; @@ -98,6 +106,7 @@ class Message extends Base { if ('author' in data) { /** * The author of the message + * * @type {?User} */ this.author = this.client.users._add(data.author, !data.webhook_id); @@ -108,6 +117,7 @@ class Message extends Base { if ('pinned' in data) { /** * Whether or not this message is pinned + * * @type {?boolean} */ this.pinned = Boolean(data.pinned); @@ -118,6 +128,7 @@ class Message extends Base { if ('tts' in data) { /** * Whether or not the message was Text-To-Speech + * * @type {?boolean} */ this.tts = data.tts; @@ -130,6 +141,7 @@ class Message extends Base { * A random number or string used for checking message delivery * This is only received after the message was sent successfully, and * lost if re-fetched + * * @type {?string} */ this.nonce = data.nonce; @@ -142,6 +154,7 @@ class Message extends Base { * An array of embeds in the message - e.g. YouTube Player. * This property requires the {@link GatewayIntentBits.MessageContent} privileged intent * in a guild for messages that do not mention the client. + * * @type {Embed[]} */ this.embeds = data.embeds.map(embed => new Embed(embed)); @@ -154,6 +167,7 @@ class Message extends Base { * An array of action rows in the message. * This property requires the {@link GatewayIntentBits.MessageContent} privileged intent * in a guild for messages that do not mention the client. + * * @type {ActionRow[]} */ this.components = data.components.map(component => createComponent(component)); @@ -166,6 +180,7 @@ class Message extends Base { * A collection of attachments in the message - e.g. Pictures - mapped by their ids. * This property requires the {@link GatewayIntentBits.MessageContent} privileged intent * in a guild for messages that do not mention the client. + * * @type {Collection} */ this.attachments = new Collection(); @@ -181,6 +196,7 @@ class Message extends Base { if ('sticker_items' in data || 'stickers' in data) { /** * A collection of stickers in the message + * * @type {Collection} */ this.stickers = new Collection( @@ -194,6 +210,7 @@ class Message extends Base { /** * A generally increasing integer (there may be gaps or duplicates) that represents * the approximate position of the message in a thread. + * * @type {?number} */ this.position = data.position; @@ -204,7 +221,8 @@ class Message extends Base { if ('role_subscription_data' in data) { /** * Role subscription data found on {@link MessageType.RoleSubscriptionPurchase} messages. - * @typedef {Object} RoleSubscriptionData + * + * @typedef {object} RoleSubscriptionData * @property {Snowflake} roleSubscriptionListingId The id of the SKU and listing the user is subscribed to * @property {string} tierName The name of the tier the user is subscribed to * @property {number} totalMonthsSubscribed The total number of months the user has been subscribed for @@ -214,6 +232,7 @@ class Message extends Base { /** * The data of the role subscription purchase or renewal. * This is present on {@link MessageType.RoleSubscriptionPurchase} messages. + * * @type {?RoleSubscriptionData} */ this.roleSubscriptionData = { @@ -229,7 +248,14 @@ class Message extends Base { if ('resolved' in data) { /** * Resolved data from auto-populated select menus. - * @typedef {Object} CommandInteractionResolvedData + * + * @typedef {object} CommandInteractionResolvedData + * @property {Collection} attachments attachments + * @property {Collection} channels channels + * @property {Collection} members members + * @property {Collection} messages messages + * @property {Collection} roles roles + * @property {Collection} users users */ this.resolved = transformResolved( { client: this.client, guild: this.guild, channel: this.channel }, @@ -243,6 +269,7 @@ class Message extends Base { if (data.edited_timestamp) { /** * The timestamp the message was last edited at (if applicable) + * * @type {?number} */ this.editedTimestamp = Date.parse(data.edited_timestamp); @@ -253,6 +280,7 @@ class Message extends Base { if ('reactions' in data) { /** * A manager of the reactions belonging to this message + * * @type {ReactionManager} */ this.reactions = new ReactionManager(this); @@ -265,20 +293,12 @@ class Message extends Base { this.reactions ??= new ReactionManager(this); } - if (!this.mentions) { + if (this.mentions) { /** * All valid mentions that the message contains + * * @type {MessageMentions} */ - this.mentions = new MessageMentions( - this, - data.mentions, - data.mention_roles, - data.mention_everyone, - data.mention_channels, - data.referenced_message?.author, - ); - } else { this.mentions = new MessageMentions( this, data.mentions ?? this.mentions.users, @@ -287,11 +307,21 @@ class Message extends Base { data.mention_channels ?? this.mentions.crosspostedChannels, data.referenced_message?.author ?? this.mentions.repliedUser, ); + } else { + this.mentions = new MessageMentions( + this, + data.mentions, + data.mention_roles, + data.mention_everyone, + data.mention_channels, + data.referenced_message?.author, + ); } if ('webhook_id' in data) { /** * The id of the webhook that sent the message, if applicable + * * @type {?Snowflake} */ this.webhookId = data.webhook_id; @@ -302,6 +332,7 @@ class Message extends Base { if ('application' in data) { /** * Supplemental application information for group activities + * * @type {?ClientApplication} */ this.groupActivityApplication = new ClientApplication(this.client, data.application); @@ -312,6 +343,7 @@ class Message extends Base { if ('application_id' in data) { /** * The id of the application of the interaction that sent this message, if any + * * @type {?Snowflake} */ this.applicationId = data.application_id; @@ -322,6 +354,7 @@ class Message extends Base { if ('activity' in data) { /** * Group activity + * * @type {?MessageActivity} */ this.activity = { @@ -345,6 +378,7 @@ class Message extends Base { if ('flags' in data) { /** * Flags that are applied to the message + * * @type {Readonly} */ this.flags = new MessageFlagsBitField(data.flags).freeze(); @@ -355,13 +389,14 @@ class Message extends Base { /** * Reference data sent in a message that contains ids identifying the referenced message. * This can be present in the following types of message: - * * Crossposted messages (`MessageFlags.Crossposted`) - * * {@link MessageType.ChannelPinnedMessage} - * * {@link MessageType.ChannelFollowAdd} - * * {@link MessageType.Reply} - * * {@link MessageType.ThreadStarterMessage} + * Crossposted messages (`MessageFlags.Crossposted`) + * {@link MessageType.ChannelPinnedMessage} + * {@link MessageType.ChannelFollowAdd} + * {@link MessageType.Reply} + * {@link MessageType.ThreadStarterMessage} + * * @see {@link https://discord.com/developers/docs/resources/message#message-object-message-types} - * @typedef {Object} MessageReference + * @typedef {object} MessageReference * @property {Snowflake} channelId The channel id that was referenced * @property {Snowflake|undefined} guildId The guild id that was referenced * @property {Snowflake|undefined} messageId The message id that was referenced @@ -371,6 +406,7 @@ class Message extends Base { if ('message_reference' in data) { /** * Message reference data + * * @type {?MessageReference} */ this.reference = { @@ -390,7 +426,8 @@ class Message extends Base { if (data.interaction_metadata) { /** * Partial data of the interaction that a message is a result of - * @typedef {Object} MessageInteractionMetadata + * + * @typedef {object} MessageInteractionMetadata * @property {Snowflake} id The interaction's id * @property {InteractionType} type The type of the interaction * @property {User} user The user that invoked the interaction @@ -407,6 +444,7 @@ class Message extends Base { /** * Partial data of the interaction that this message is a result of + * * @type {?MessageInteractionMetadata} */ this.interactionMetadata = _transformAPIMessageInteractionMetadata(this.client, data.interaction_metadata); @@ -420,6 +458,7 @@ class Message extends Base { } else { /** * The poll that was sent with the message + * * @type {?Poll} */ this.poll = new Poll(this.client, data.poll, this, this.channel); @@ -431,6 +470,7 @@ class Message extends Base { if (data.message_snapshots) { /** * The message snapshots associated with the message reference + * * @type {Collection} */ this.messageSnapshots = data.message_snapshots.reduce((coll, snapshot) => { @@ -453,7 +493,8 @@ class Message extends Base { /** * A call associated with a message - * @typedef {Object} MessageCall + * + * @typedef {object} MessageCall * @property {Readonly} endedAt The time the call ended * @property {?number} endedTimestamp The timestamp the call ended * @property {Snowflake[]} participants The ids of the users that participated in the call @@ -462,6 +503,7 @@ class Message extends Base { if (data.call) { /** * The call associated with the message + * * @type {?MessageCall} */ this.call = { @@ -478,6 +520,7 @@ class Message extends Base { /** * The channel that the message was sent in + * * @type {TextBasedChannels} * @readonly */ @@ -487,6 +530,7 @@ class Message extends Base { /** * Whether or not this message is a partial + * * @type {boolean} * @readonly */ @@ -497,6 +541,7 @@ class Message extends Base { /** * Represents the author of the message as a guild member. * Only available if the message comes from a guild where the author is still a member + * * @type {?GuildMember} * @readonly */ @@ -506,6 +551,7 @@ class Message extends Base { /** * The time the message was sent at + * * @type {Date} * @readonly */ @@ -515,6 +561,7 @@ class Message extends Base { /** * The time the message was last edited at (if applicable) + * * @type {?Date} * @readonly */ @@ -524,6 +571,7 @@ class Message extends Base { /** * The guild the message was sent in (if in a guild channel) + * * @type {?Guild} * @readonly */ @@ -533,6 +581,7 @@ class Message extends Base { /** * Whether this message has a thread associated with it + * * @type {boolean} * @readonly */ @@ -544,6 +593,7 @@ class Message extends Base { * The thread started by this message * This property is not suitable for checking whether a message has a thread, * use {@link Message#hasThread} instead. + * * @type {?ThreadChannel} * @readonly */ @@ -553,6 +603,7 @@ class Message extends Base { /** * The URL to jump to this message + * * @type {string} * @readonly */ @@ -563,17 +614,19 @@ class Message extends Base { /** * The message contents with all mentions replaced by the equivalent text. * If mentions cannot be resolved to a name, the relevant mention in the message content will not be converted. + * * @type {?string} * @readonly */ get cleanContent() { - // eslint-disable-next-line eqeqeq + // eslint-disable-next-line eqeqeq, no-eq-null return this.content != null && this.channel ? cleanContent(this.content, this.channel) : null; } /** * Creates a reaction collector. - * @param {ReactionCollectorOptions} [options={}] Options to send to the collector + * + * @param {ReactionCollectorOptions} [options] Options to send to the collector * @returns {ReactionCollector} * @example * // Create a reaction collector @@ -588,6 +641,7 @@ class Message extends Base { /** * An object containing the same properties as CollectorOptions, but a few more: + * * @typedef {ReactionCollectorOptions} AwaitReactionsOptions * @property {string[]} [errors] Stop/end reasons that cause the promise to reject */ @@ -595,7 +649,8 @@ class Message extends Base { /** * Similar to createReactionCollector but in promise form. * Resolves with a collection of reactions that pass the specified filter. - * @param {AwaitReactionsOptions} [options={}] Optional options to pass to the internal collector + * + * @param {AwaitReactionsOptions} [options] Optional options to pass to the internal collector * @returns {Promise>} * @example * // Create a reaction collector @@ -604,7 +659,7 @@ class Message extends Base { * .then(collected => console.log(`Collected ${collected.size} reactions`)) * .catch(console.error); */ - awaitReactions(options = {}) { + async awaitReactions(options = {}) { return new Promise((resolve, reject) => { const collector = this.createReactionCollector(options); collector.once('end', (reactions, reason) => { @@ -624,7 +679,8 @@ class Message extends Base { /** * Creates a message component interaction collector. - * @param {MessageComponentCollectorOptions} [options={}] Options to send to the collector + * + * @param {MessageComponentCollectorOptions} [options] Options to send to the collector * @returns {InteractionCollector} * @example * // Create a message component interaction collector @@ -643,7 +699,8 @@ class Message extends Base { /** * An object containing the same properties as CollectorOptions, but a few more: - * @typedef {Object} AwaitMessageComponentOptions + * + * @typedef {object} AwaitMessageComponentOptions * @property {CollectorFilter} [filter] The filter applied to this collector * @property {number} [time] Time to wait for an interaction before rejecting * @property {ComponentType} [componentType] The type of component interaction to collect @@ -654,7 +711,8 @@ class Message extends Base { /** * Collects a single component interaction that passes the filter. * The Promise will reject if the time expires. - * @param {AwaitMessageComponentOptions} [options={}] Options to pass to the internal collector + * + * @param {AwaitMessageComponentOptions} [options] Options to pass to the internal collector * @returns {Promise} * @example * // Collect a message component interaction @@ -663,7 +721,7 @@ class Message extends Base { * .then(interaction => console.log(`${interaction.customId} was clicked!`)) * .catch(console.error); */ - awaitMessageComponent(options = {}) { + async awaitMessageComponent(options = {}) { const _options = { ...options, max: 1 }; return new Promise((resolve, reject) => { const collector = this.createMessageComponentCollector(_options); @@ -677,6 +735,7 @@ class Message extends Base { /** * Whether the message is editable by the client user + * * @type {boolean} * @readonly */ @@ -702,6 +761,7 @@ class Message extends Base { /** * Whether the message is deletable by the client user + * * @type {boolean} * @readonly */ @@ -711,6 +771,7 @@ class Message extends Base { if (!this.guild) { return this.author.id === this.client.user.id; } + // DMChannel does not have viewable property, so check viewable after proved that message is on a guild. if (!this.channel?.viewable) { return false; @@ -730,6 +791,7 @@ class Message extends Base { /** * Whether the message is bulk deletable by the client user + * * @type {boolean} * @readonly * @example @@ -748,6 +810,7 @@ class Message extends Base { /** * Whether the message is pinnable by the client user + * * @type {boolean} * @readonly */ @@ -763,6 +826,7 @@ class Message extends Base { /** * Fetches the Message this crosspost/reply/pin-add references, if available to the client + * * @returns {Promise} */ async fetchReference() { @@ -771,12 +835,12 @@ class Message extends Base { if (!messageId) throw new DiscordjsError(ErrorCodes.MessageReferenceMissing); const channel = this.client.channels.resolve(channelId); if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); - const message = await channel.messages.fetch(messageId); - return message; + return await channel.messages.fetch(messageId); } /** * Whether the message is crosspostable by the client user + * * @type {boolean} * @readonly */ @@ -798,6 +862,7 @@ class Message extends Base { /** * Edits the content of the message. + * * @param {string|MessagePayload|MessageEditOptions} options The options to provide * @returns {Promise} * @example @@ -813,6 +878,7 @@ class Message extends Base { /** * Publishes a message in an announcement channel to all channels following it. + * * @returns {Promise} * @example * // Crosspost a message @@ -829,6 +895,7 @@ class Message extends Base { /** * Pins this message to the channel's pinned messages. + * * @param {string} [reason] Reason for pinning * @returns {Promise} * @example @@ -845,6 +912,7 @@ class Message extends Base { /** * Unpins this message from the channel's pinned messages. + * * @param {string} [reason] Reason for unpinning * @returns {Promise} * @example @@ -861,6 +929,7 @@ class Message extends Base { /** * Adds a reaction to the message. + * * @param {EmojiIdentifierResolvable} emoji The emoji to react with * @returns {Promise} * @example @@ -891,6 +960,7 @@ class Message extends Base { /** * Deletes the message. + * * @returns {Promise} * @example * // Delete a message @@ -906,6 +976,7 @@ class Message extends Base { /** * Options provided when sending a message as an inline reply. + * * @typedef {BaseMessageCreateOptions} MessageReplyOptions * @property {boolean} [failIfNotExists=this.client.options.failIfNotExists] Whether to error if the referenced * message does not exist (creates a standard message in this case when false) @@ -913,6 +984,7 @@ class Message extends Base { /** * Send an inline reply to this message. + * * @param {string|MessagePayload|MessageReplyOptions} options The options to provide * @returns {Promise} * @example @@ -921,7 +993,7 @@ class Message extends Base { * .then(() => console.log(`Replied to message "${message.content}"`)) * .catch(console.error); */ - reply(options) { + async reply(options) { let data; if (options instanceof MessagePayload) { @@ -937,15 +1009,17 @@ class Message extends Base { }, }); } + return this.client.channels.createMessage(this.channelId, data); } /** * Forwards this message. + * * @param {TextChannelResolvable} channel The channel to forward this message to. * @returns {Promise} */ - forward(channel) { + async forward(channel) { return this.client.channels.createMessage(channel, { messageReference: { messageId: this.id, @@ -958,7 +1032,8 @@ class Message extends Base { /** * Options for starting a thread on a message. - * @typedef {Object} StartThreadOptions + * + * @typedef {object} StartThreadOptions * @property {string} name The name of the new thread * @property {ThreadAutoArchiveDuration} [autoArchiveDuration=this.channel.defaultAutoArchiveDuration] The amount of * time after which the thread should automatically archive in case of no recent activity @@ -968,6 +1043,7 @@ class Message extends Base { /** * Create a new public thread from this message + * * @see GuildTextThreadManager#create * @param {StartThreadOptions} [options] Options for starting a thread on this message * @returns {Promise} @@ -977,13 +1053,15 @@ class Message extends Base { if (![ChannelType.GuildText, ChannelType.GuildAnnouncement].includes(this.channel.type)) { throw new DiscordjsError(ErrorCodes.MessageThreadParent); } + if (this.hasThread) throw new DiscordjsError(ErrorCodes.MessageExistingThread); return this.channel.threads.create({ ...options, startMessage: this }); } /** * Fetch this message. - * @param {boolean} [force=true] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { @@ -993,6 +1071,7 @@ class Message extends Base { /** * Fetches the webhook used to create this message. + * * @returns {Promise} */ async fetchWebhook() { @@ -1003,10 +1082,11 @@ class Message extends Base { /** * Suppresses or unsuppresses embeds on a message. - * @param {boolean} [suppress=true] If the embeds should be suppressed or not + * + * @param {boolean} [suppress] If the embeds should be suppressed or not * @returns {Promise} */ - suppressEmbeds(suppress = true) { + async suppressEmbeds(suppress = true) { const flags = new MessageFlagsBitField(this.flags.bitfield); if (suppress) { @@ -1020,14 +1100,16 @@ class Message extends Base { /** * Removes the attachments from this message. + * * @returns {Promise} */ - removeAttachments() { + async removeAttachments() { return this.edit({ attachments: [] }); } /** * Resolves a component by a custom id. + * * @param {string} customId The custom id to resolve against * @returns {?MessageActionRowComponent} */ @@ -1039,6 +1121,7 @@ class Message extends Base { * Used mainly internally. Whether two messages are identical in properties. If you want to compare messages * without checking all the properties, use `message.id === message2.id`, which is much more efficient. This * method allows you to see if there are differences in content, embeds, attachments, nonce and tts properties. + * * @param {Message} message The message to compare it to * @param {APIMessage} rawData Raw data passed through the WebSocket about this message * @returns {boolean} @@ -1071,6 +1154,7 @@ class Message extends Base { /** * Whether this message is from a guild. + * * @returns {boolean} */ inGuild() { @@ -1079,6 +1163,7 @@ class Message extends Base { /** * When concatenated with a string, this automatically concatenates the message's content instead of the object. + * * @returns {string} * @example * // Logs: Message: This is a message! diff --git a/packages/discord.js/src/structures/MessageCollector.js b/packages/discord.js/src/structures/MessageCollector.js index 7c3b0d7f106a..998e7bb87e66 100644 --- a/packages/discord.js/src/structures/MessageCollector.js +++ b/packages/discord.js/src/structures/MessageCollector.js @@ -1,7 +1,8 @@ +/* eslint-disable @typescript-eslint/unbound-method */ 'use strict'; -const { Collector } = require('./interfaces/Collector.js'); const { Events } = require('../util/Events.js'); +const { Collector } = require('./interfaces/Collector.js'); /** * @typedef {CollectorOptions} MessageCollectorOptions @@ -14,6 +15,7 @@ const { Events } = require('../util/Events.js'); * Will automatically stop if the channel ({@link Client#event:channelDelete channelDelete}), * thread ({@link Client#event:threadDelete threadDelete}), or * guild ({@link Client#event:guildDelete guildDelete}) is deleted. + * * @extends {Collector} */ class MessageCollector extends Collector { @@ -27,18 +29,20 @@ class MessageCollector extends Collector { /** * The channel + * * @type {TextBasedChannels} */ this.channel = channel; /** * Total number of messages that were received in the channel during message collection + * * @type {number} */ this.received = 0; - const bulkDeleteListener = messages => { - for (const message of messages.values()) this.handleDispose(message); + const bulkDeleteListener = async messages => { + for (const message of messages.values()) await this.handleDispose(message); }; this._handleChannelDeletion = this._handleChannelDeletion.bind(this); @@ -66,6 +70,7 @@ class MessageCollector extends Collector { /** * Handles a message for possible collection. + * * @param {Message} message The message that could be collected * @returns {?Snowflake} * @private @@ -73,6 +78,7 @@ class MessageCollector extends Collector { collect(message) { /** * Emitted whenever a message is collected. + * * @event MessageCollector#collect * @param {Message} message The message that was collected */ @@ -83,12 +89,14 @@ class MessageCollector extends Collector { /** * Handles a message for possible disposal. + * * @param {Message} message The message that could be disposed of * @returns {?Snowflake} */ dispose(message) { /** * Emitted whenever a message is disposed of. + * * @event MessageCollector#dispose * @param {Message} message The message that was disposed of */ @@ -97,6 +105,7 @@ class MessageCollector extends Collector { /** * The reason this collector has ended with, or null if it hasn't ended yet + * * @type {?string} * @readonly */ @@ -108,6 +117,7 @@ class MessageCollector extends Collector { /** * Handles checking if the channel has been deleted, and if so, stops the collector with the reason 'channelDelete'. + * * @private * @param {GuildChannel} channel The channel that was deleted * @returns {void} @@ -120,6 +130,7 @@ class MessageCollector extends Collector { /** * Handles checking if the thread has been deleted, and if so, stops the collector with the reason 'threadDelete'. + * * @private * @param {ThreadChannel} thread The thread that was deleted * @returns {void} @@ -132,6 +143,7 @@ class MessageCollector extends Collector { /** * Handles checking if the guild has been deleted, and if so, stops the collector with the reason 'guildDelete'. + * * @private * @param {Guild} guild The guild that was deleted * @returns {void} diff --git a/packages/discord.js/src/structures/MessageComponentInteraction.js b/packages/discord.js/src/structures/MessageComponentInteraction.js index 296451d84259..23b41b316441 100644 --- a/packages/discord.js/src/structures/MessageComponentInteraction.js +++ b/packages/discord.js/src/structures/MessageComponentInteraction.js @@ -9,6 +9,7 @@ const getMessage = lazy(() => require('./Message.js').Message); /** * Represents a message component interaction. + * * @extends {BaseInteraction} * @implements {InteractionResponses} */ @@ -18,48 +19,56 @@ class MessageComponentInteraction extends BaseInteraction { /** * The id of the channel this interaction was sent in + * * @type {Snowflake} * @name MessageComponentInteraction#channelId */ /** * The message to which the component was attached + * * @type {Message} */ this.message = this.channel?.messages._add(data.message) ?? new (getMessage())(client, data.message); /** * The custom id of the component which was interacted with + * * @type {string} */ this.customId = data.data.custom_id; /** * The type of component which was interacted with + * * @type {ComponentType} */ this.componentType = data.data.component_type; /** * Whether the reply to this interaction has been deferred + * * @type {boolean} */ this.deferred = false; /** * Whether the reply to this interaction is ephemeral + * * @type {?boolean} */ this.ephemeral = null; /** * Whether this interaction has already been replied to + * * @type {boolean} */ this.replied = false; /** * An associated interaction webhook, can be used to further interact with this interaction + * * @type {InteractionWebhook} */ this.webhook = new InteractionWebhook(this.client, this.applicationId, this.token); @@ -67,18 +76,20 @@ class MessageComponentInteraction extends BaseInteraction { /** * Components that can be placed in an action row for messages. - * * ButtonComponent - * * StringSelectMenuComponent - * * UserSelectMenuComponent - * * RoleSelectMenuComponent - * * MentionableSelectMenuComponent - * * ChannelSelectMenuComponent + * ButtonComponent + * StringSelectMenuComponent + * UserSelectMenuComponent + * RoleSelectMenuComponent + * MentionableSelectMenuComponent + * ChannelSelectMenuComponent + * * @typedef {ButtonComponent|StringSelectMenuComponent|UserSelectMenuComponent| * RoleSelectMenuComponent|MentionableSelectMenuComponent|ChannelSelectMenuComponent} MessageActionRowComponent */ /** * The component which was interacted with + * * @type {MessageActionRowComponent|APIMessageActionRowComponent} * @readonly */ @@ -89,17 +100,27 @@ class MessageComponentInteraction extends BaseInteraction { } // These are here only for documentation purposes - they are implemented by InteractionResponses - /* eslint-disable no-empty-function */ + deferReply() {} + reply() {} + fetchReply() {} + editReply() {} + deleteReply() {} + followUp() {} + deferUpdate() {} + update() {} + launchActivity() {} + showModal() {} + awaitModalSubmit() {} } diff --git a/packages/discord.js/src/structures/MessageContextMenuCommandInteraction.js b/packages/discord.js/src/structures/MessageContextMenuCommandInteraction.js index 7efbfa77d152..ab9dd290068c 100644 --- a/packages/discord.js/src/structures/MessageContextMenuCommandInteraction.js +++ b/packages/discord.js/src/structures/MessageContextMenuCommandInteraction.js @@ -4,11 +4,13 @@ const { ContextMenuCommandInteraction } = require('./ContextMenuCommandInteracti /** * Represents a message context menu interaction. + * * @extends {ContextMenuCommandInteraction} */ class MessageContextMenuCommandInteraction extends ContextMenuCommandInteraction { /** * The message this interaction was sent from + * * @type {Message|APIMessage} * @readonly */ diff --git a/packages/discord.js/src/structures/MessageMentions.js b/packages/discord.js/src/structures/MessageMentions.js index 5df93a75c472..ff215abf3dc8 100644 --- a/packages/discord.js/src/structures/MessageMentions.js +++ b/packages/discord.js/src/structures/MessageMentions.js @@ -11,6 +11,7 @@ class MessageMentions { /** * A regular expression that matches `@everyone` and `@here`. * The `mention` group property is present on the `exec` result of this expression. + * * @type {RegExp} * @memberof MessageMentions */ @@ -19,6 +20,7 @@ class MessageMentions { /** * A regular expression that matches user mentions like `<@81440962496172032>`. * The `id` group property is present on the `exec` result of this expression. + * * @type {RegExp} * @memberof MessageMentions */ @@ -27,6 +29,7 @@ class MessageMentions { /** * A regular expression that matches role mentions like `<@&297577916114403338>`. * The `id` group property is present on the `exec` result of this expression. + * * @type {RegExp} * @memberof MessageMentions */ @@ -35,6 +38,7 @@ class MessageMentions { /** * A regular expression that matches channel mentions like `<#222079895583457280>`. * The `id` group property is present on the `exec` result of this expression. + * * @type {RegExp} * @memberof MessageMentions */ @@ -42,6 +46,7 @@ class MessageMentions { /** * A global regular expression variant of {@link MessageMentions.ChannelsPattern}. + * * @type {RegExp} * @memberof MessageMentions * @private @@ -50,6 +55,7 @@ class MessageMentions { /** * A global regular expression variant of {@link MessageMentions.UsersPattern}. + * * @type {RegExp} * @memberof MessageMentions * @private @@ -59,6 +65,7 @@ class MessageMentions { constructor(message, users, roles, everyone, crosspostedChannels, repliedUser) { /** * The client the message is from + * * @type {Client} * @readonly */ @@ -66,6 +73,7 @@ class MessageMentions { /** * The guild the message is in + * * @type {?Guild} * @readonly */ @@ -73,6 +81,7 @@ class MessageMentions { /** * The initial message content + * * @type {string} * @readonly * @private @@ -81,6 +90,7 @@ class MessageMentions { /** * Whether `@everyone` or `@here` were mentioned + * * @type {boolean} */ this.everyone = Boolean(everyone); @@ -90,6 +100,7 @@ class MessageMentions { /** * Any users that were mentioned * Order as received from the API, not as they appear in the message content + * * @type {Collection} */ this.users = new Collection(users); @@ -99,6 +110,7 @@ class MessageMentions { if (mention.member && message.guild) { message.guild.members._add(Object.assign(mention.member, { user: mention })); } + const user = message.client.users._add(mention); this.users.set(user.id, user); } @@ -111,6 +123,7 @@ class MessageMentions { /** * Any roles that were mentioned * Order as received from the API, not as they appear in the message content + * * @type {Collection} */ this.roles = new Collection(roles); @@ -129,6 +142,7 @@ class MessageMentions { /** * Cached members for {@link MessageMentions#members} + * * @type {?Collection} * @private */ @@ -136,6 +150,7 @@ class MessageMentions { /** * Cached channels for {@link MessageMentions#channels} + * * @type {?Collection} * @private */ @@ -143,6 +158,7 @@ class MessageMentions { /** * Cached users for {@link MessageMentions#parsedUsers} + * * @type {?Collection} * @private */ @@ -150,7 +166,8 @@ class MessageMentions { /** * Crossposted channel data. - * @typedef {Object} CrosspostedChannel + * + * @typedef {object} CrosspostedChannel * @property {Snowflake} channelId The mentioned channel's id * @property {Snowflake} guildId The id of the guild that has the channel * @property {ChannelType} type The channel's type @@ -162,6 +179,7 @@ class MessageMentions { /** * A collection of crossposted channels * Order as received from the API, not as they appear in the message content + * * @type {Collection} */ this.crosspostedChannels = new Collection(crosspostedChannels); @@ -182,6 +200,7 @@ class MessageMentions { /** * The author of the message that this message is a reply to + * * @type {?User} */ this.repliedUser = repliedUser ? this.client.users._add(repliedUser) : null; @@ -190,6 +209,7 @@ class MessageMentions { /** * Any members that were mentioned (only in {@link Guild}s) * Order as received from the API, not as they appear in the message content + * * @type {?Collection} * @readonly */ @@ -207,6 +227,7 @@ class MessageMentions { /** * Any channels that were mentioned * Order as they appear first in the message content + * * @type {Collection} * @readonly */ @@ -226,6 +247,7 @@ class MessageMentions { /** * Any user mentions that were included in the message content * Order as they appear first in the message content + * * @type {Collection} * @readonly */ @@ -237,12 +259,14 @@ class MessageMentions { const user = this.client.users.cache.get(matches[1]); if (user) this._parsedUsers.set(user.id, user); } + return this._parsedUsers; } /** * Options used to check for a mention. - * @typedef {Object} MessageMentionsHasOptions + * + * @typedef {object} MessageMentionsHasOptions * @property {boolean} [ignoreDirect=false] Whether to ignore direct mentions to the item * @property {boolean} [ignoreRoles=false] Whether to ignore role mentions to a guild member * @property {boolean} [ignoreRepliedUser=false] Whether to ignore replied user mention to an user @@ -253,6 +277,7 @@ class MessageMentions { * Checks if a user, guild member, thread member, role, or channel is mentioned. * Takes into account user mentions, role mentions, channel mentions, * replied user mention, and `@everyone`/`@here` mentions. + * * @param {UserResolvable|RoleResolvable|ChannelResolvable} data The User/Role/Channel to check for * @param {MessageMentionsHasOptions} [options] The options for the check * @returns {boolean} diff --git a/packages/discord.js/src/structures/MessagePayload.js b/packages/discord.js/src/structures/MessagePayload.js index bf07b026b743..86b8628f8c95 100644 --- a/packages/discord.js/src/structures/MessagePayload.js +++ b/packages/discord.js/src/structures/MessagePayload.js @@ -19,24 +19,28 @@ class MessagePayload { constructor(target, options) { /** * The target for this message to be sent to + * * @type {MessageTarget} */ this.target = target; /** * The payload of this message. + * * @type {MessagePayloadOption} */ this.options = options; /** * Body sendable to the API + * * @type {?APIMessage} */ this.body = null; /** * Files sendable to the API + * * @type {?RawFile[]} */ this.files = null; @@ -44,6 +48,7 @@ class MessagePayload { /** * Whether or not the target is a {@link Webhook} or a {@link WebhookClient} + * * @type {boolean} * @readonly */ @@ -55,6 +60,7 @@ class MessagePayload { /** * Whether or not the target is a {@link User} + * * @type {boolean} * @readonly */ @@ -66,6 +72,7 @@ class MessagePayload { /** * Whether or not the target is a {@link Message} + * * @type {boolean} * @readonly */ @@ -76,6 +83,7 @@ class MessagePayload { /** * Whether or not the target is a {@link MessageManager} + * * @type {boolean} * @readonly */ @@ -86,6 +94,7 @@ class MessagePayload { /** * Makes the content of this message. + * * @returns {?string} */ makeContent() { @@ -101,6 +110,7 @@ class MessagePayload { /** * Resolves the body. + * * @returns {MessagePayload} */ resolveBody() { @@ -148,7 +158,7 @@ class MessagePayload { let flags; if ( - // eslint-disable-next-line eqeqeq + // eslint-disable-next-line eqeqeq, no-eq-null this.options.flags != null ) { flags = new MessageFlagsBitField(this.options.flags).bitfield; @@ -231,6 +241,7 @@ class MessagePayload { /** * Resolves files. + * * @returns {Promise} */ async resolveFiles() { @@ -242,6 +253,7 @@ class MessagePayload { /** * Resolves a single file into an object sendable to the API. + * * @param {AttachmentPayload|BufferResolvable|Stream} fileLike Something that could be resolved to a file * @returns {Promise} */ @@ -277,9 +289,10 @@ class MessagePayload { /** * Creates a {@link MessagePayload} from user-level arguments. + * * @param {MessageTarget} target Target to send to * @param {string|MessagePayloadOption} options Options or content to use - * @param {MessagePayloadOption} [extra={}] Extra options to add onto specified options + * @param {MessagePayloadOption} [extra] Extra options to add onto specified options * @returns {MessagePayload} */ static create(target, options, extra = {}) { @@ -294,12 +307,14 @@ exports.MessagePayload = MessagePayload; /** * A target for a message. + * * @typedef {TextBasedChannels|ChannelManager|Webhook|WebhookClient|BaseInteraction|InteractionWebhook| * Message|MessageManager} MessageTarget */ /** * A possible payload option. + * * @typedef {MessageCreateOptions|MessageEditOptions|WebhookMessageCreateOptions|WebhookMessageEditOptions| * InteractionReplyOptions|InteractionUpdateOptions} MessagePayloadOption */ diff --git a/packages/discord.js/src/structures/MessageReaction.js b/packages/discord.js/src/structures/MessageReaction.js index 334b0dffa42f..bfe910ec7e41 100644 --- a/packages/discord.js/src/structures/MessageReaction.js +++ b/packages/discord.js/src/structures/MessageReaction.js @@ -1,11 +1,11 @@ 'use strict'; const { Routes } = require('discord-api-types/v10'); +const { ReactionUserManager } = require('../managers/ReactionUserManager.js'); +const { flatten, resolveGuildEmoji } = require('../util/Util.js'); const { ApplicationEmoji } = require('./ApplicationEmoji.js'); const { GuildEmoji } = require('./GuildEmoji.js'); const { ReactionEmoji } = require('./ReactionEmoji.js'); -const { ReactionUserManager } = require('../managers/ReactionUserManager.js'); -const { flatten, resolveGuildEmoji } = require('../util/Util.js'); /** * Represents a reaction to a message. @@ -14,6 +14,7 @@ class MessageReaction { constructor(client, data, message) { /** * The client that instantiated this message reaction + * * @name MessageReaction#client * @type {Client} * @readonly @@ -22,24 +23,28 @@ class MessageReaction { /** * The message that this reaction refers to + * * @type {Message} */ this.message = message; /** * Whether the client has given this reaction + * * @type {boolean} */ this.me = data.me; /** * Whether the client has super-reacted using this emoji + * * @type {boolean} */ this.meBurst = Boolean(data.me_burst); /** * A manager of the users that have given this reaction + * * @type {ReactionUserManager} */ this.users = new ReactionUserManager(this, this.me ? [client.user] : []); @@ -55,6 +60,7 @@ class MessageReaction { if (data.burst_colors) { /** * Hexadecimal colors used for this super reaction + * * @type {?string[]} */ this.burstColors = data.burst_colors; @@ -63,6 +69,7 @@ class MessageReaction { if ('count' in data) { /** * The number of people that have given the same reaction + * * @type {?number} */ this.count ??= data.count; @@ -71,13 +78,15 @@ class MessageReaction { if ('count_details' in data) { /** * The reaction count details object contains information about super and normal reaction counts. - * @typedef {Object} ReactionCountDetailsData + * + * @typedef {object} ReactionCountDetailsData * @property {number} burst Count of super reactions * @property {number} normal Count of normal reactions */ /** * The reaction count details object contains information about super and normal reaction counts. + * * @type {ReactionCountDetailsData} */ this.countDetails = { @@ -91,14 +100,16 @@ class MessageReaction { /** * Makes the client user react with this reaction + * * @returns {Promise} */ - react() { + async react() { return this.message.react(this.emoji); } /** * Removes all users from this reaction. + * * @returns {Promise} */ async remove() { @@ -113,6 +124,7 @@ class MessageReaction { * {@link ApplicationEmoji} for application emojis, or a {@link ReactionEmoji} object * which has fewer properties. Whatever the prototype of the emoji, it will still have * `name`, `id`, `identifier` and `toString()` + * * @type {GuildEmoji|ReactionEmoji|ApplicationEmoji} * @readonly */ @@ -128,12 +140,14 @@ class MessageReaction { return emoji; } } + const emoji = resolveGuildEmoji(this.client, this._emoji.id); return emoji ?? this._emoji; } /** * Whether or not this reaction is a partial + * * @type {boolean} * @readonly */ @@ -143,6 +157,7 @@ class MessageReaction { /** * Fetch this reaction. + * * @returns {Promise} */ async fetch() { @@ -169,11 +184,13 @@ class MessageReaction { if (burst) this.countDetails.burst++; else this.countDetails.normal++; } + if (user.id === this.message.client.user.id) { if (burst) this.meBurst = true; else this.me = true; } } + _remove(user, burst) { if (this.partial) return; this.users.cache.delete(user.id); @@ -182,10 +199,12 @@ class MessageReaction { if (burst) this.countDetails.burst--; else this.countDetails.normal--; } + if (user.id === this.message.client.user.id) { if (burst) this.meBurst = false; else this.me = false; } + if (this.count <= 0 && this.users.cache.size === 0) { this.message.reactions.cache.delete(this.emoji.id ?? this.emoji.name); } diff --git a/packages/discord.js/src/structures/ModalSubmitFields.js b/packages/discord.js/src/structures/ModalSubmitFields.js index 4a0d846f1e44..e2c4e12be08e 100644 --- a/packages/discord.js/src/structures/ModalSubmitFields.js +++ b/packages/discord.js/src/structures/ModalSubmitFields.js @@ -11,12 +11,14 @@ class ModalSubmitFields { constructor(components) { /** * The components within the modal + * * @type {ActionRowModalData[]} */ this.components = components; /** * The extracted fields from the modal + * * @type {Collection} */ this.fields = components.reduce((accumulator, next) => { @@ -27,6 +29,7 @@ class ModalSubmitFields { /** * Gets a field given a custom id from a component + * * @param {string} customId The custom id of the component * @param {ComponentType} [type] The type of the component * @returns {ModalData} @@ -44,6 +47,7 @@ class ModalSubmitFields { /** * Gets the value of a text input component given a custom id + * * @param {string} customId The custom id of the text input component * @returns {string} */ diff --git a/packages/discord.js/src/structures/ModalSubmitInteraction.js b/packages/discord.js/src/structures/ModalSubmitInteraction.js index 85ae1df1ce9b..485cdc0bde84 100644 --- a/packages/discord.js/src/structures/ModalSubmitInteraction.js +++ b/packages/discord.js/src/structures/ModalSubmitInteraction.js @@ -9,20 +9,21 @@ const { InteractionResponses } = require('./interfaces/InteractionResponses.js') const getMessage = lazy(() => require('./Message.js').Message); /** - * @typedef {Object} ModalData + * @typedef {object} ModalData * @property {string} value The value of the field * @property {ComponentType} type The component type of the field * @property {string} customId The custom id of the field */ /** - * @typedef {Object} ActionRowModalData + * @typedef {object} ActionRowModalData * @property {ModalData[]} components The components of this action row * @property {ComponentType} type The component type of the action row */ /** * Represents a modal interaction + * * @extends {BaseInteraction} * @implements {InteractionResponses} */ @@ -31,6 +32,7 @@ class ModalSubmitInteraction extends BaseInteraction { super(client, data); /** * The custom id of the modal. + * * @type {string} */ this.customId = data.data.custom_id; @@ -38,6 +40,7 @@ class ModalSubmitInteraction extends BaseInteraction { if ('message' in data) { /** * The message associated with this interaction + * * @type {?Message} */ this.message = this.channel?.messages._add(data.message) ?? new (getMessage())(this.client, data.message); @@ -47,36 +50,42 @@ class ModalSubmitInteraction extends BaseInteraction { /** * The components within the modal + * * @type {ActionRowModalData[]} */ this.components = data.data.components?.map(component => ModalSubmitInteraction.transformComponent(component)); /** * The fields within the modal + * * @type {ModalSubmitFields} */ this.fields = new ModalSubmitFields(this.components); /** * Whether the reply to this interaction has been deferred + * * @type {boolean} */ this.deferred = false; /** * Whether this interaction has already been replied to + * * @type {boolean} */ this.replied = false; /** * Whether the reply to this interaction is ephemeral + * * @type {?boolean} */ this.ephemeral = null; /** * An associated interaction webhook, can be used to further interact with this interaction + * * @type {InteractionWebhook} */ this.webhook = new InteractionWebhook(this.client, this.applicationId, this.token); @@ -84,6 +93,7 @@ class ModalSubmitInteraction extends BaseInteraction { /** * Transforms component data to discord.js-compatible data + * * @param {*} rawComponent The data to transform * @returns {ModalData[]} */ @@ -102,6 +112,7 @@ class ModalSubmitInteraction extends BaseInteraction { /** * Whether this is from a {@link MessageComponentInteraction}. + * * @returns {boolean} */ isFromMessage() { @@ -109,15 +120,23 @@ class ModalSubmitInteraction extends BaseInteraction { } // These are here only for documentation purposes - they are implemented by InteractionResponses - /* eslint-disable no-empty-function */ + deferReply() {} + reply() {} + fetchReply() {} + editReply() {} + deleteReply() {} + followUp() {} + deferUpdate() {} + update() {} + launchActivity() {} } diff --git a/packages/discord.js/src/structures/OAuth2Guild.js b/packages/discord.js/src/structures/OAuth2Guild.js index 96443a88bd7f..c4b4467d649c 100644 --- a/packages/discord.js/src/structures/OAuth2Guild.js +++ b/packages/discord.js/src/structures/OAuth2Guild.js @@ -1,10 +1,11 @@ 'use strict'; -const { BaseGuild } = require('./BaseGuild.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); +const { BaseGuild } = require('./BaseGuild.js'); /** * A partial guild received when using {@link GuildManager#fetch} to fetch multiple guilds. + * * @extends {BaseGuild} */ class OAuth2Guild extends BaseGuild { @@ -13,12 +14,14 @@ class OAuth2Guild extends BaseGuild { /** * Whether the client user is the owner of the guild + * * @type {boolean} */ this.owner = data.owner; /** * The permissions that the client user has in this guild + * * @type {Readonly} */ this.permissions = new PermissionsBitField(BigInt(data.permissions)).freeze(); diff --git a/packages/discord.js/src/structures/PartialGroupDMChannel.js b/packages/discord.js/src/structures/PartialGroupDMChannel.js index ceaf60217d59..8768e131f012 100644 --- a/packages/discord.js/src/structures/PartialGroupDMChannel.js +++ b/packages/discord.js/src/structures/PartialGroupDMChannel.js @@ -1,12 +1,13 @@ 'use strict'; -const { BaseChannel } = require('./BaseChannel.js'); -const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { PartialGroupDMMessageManager } = require('../managers/PartialGroupDMMessageManager.js'); +const { BaseChannel } = require('./BaseChannel.js'); +const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); /** * Represents a Partial Group DM Channel on Discord. + * * @extends {BaseChannel} * @implements {TextBasedChannel} */ @@ -19,30 +20,35 @@ class PartialGroupDMChannel extends BaseChannel { /** * The name of this Group DM Channel + * * @type {?string} */ this.name = data.name; /** * The hash of the channel icon + * * @type {?string} */ this.icon = data.icon; /** * Recipient data received in a {@link PartialGroupDMChannel}. - * @typedef {Object} PartialRecipient + * + * @typedef {object} PartialRecipient * @property {string} username The username of the recipient */ /** * The recipients of this Group DM Channel. + * * @type {PartialRecipient[]} */ this.recipients = data.recipients; /** * A manager of the messages belonging to this channel + * * @type {PartialGroupDMMessageManager} */ this.messages = new PartialGroupDMMessageManager(this); @@ -50,6 +56,7 @@ class PartialGroupDMChannel extends BaseChannel { if ('owner_id' in data) { /** * The user id of the owner of this Group DM Channel + * * @type {?Snowflake} */ this.ownerId = data.owner_id; @@ -60,6 +67,7 @@ class PartialGroupDMChannel extends BaseChannel { if ('last_message_id' in data) { /** * The channel's last message id, if one was sent + * * @type {?Snowflake} */ this.lastMessageId = data.last_message_id; @@ -70,6 +78,7 @@ class PartialGroupDMChannel extends BaseChannel { if ('last_pin_timestamp' in data) { /** * The timestamp when the last pinned message was pinned, if there was one + * * @type {?number} */ this.lastPinTimestamp = data.last_pin_timestamp ? Date.parse(data.last_pin_timestamp) : null; @@ -80,7 +89,8 @@ class PartialGroupDMChannel extends BaseChannel { /** * The URL to this channel's icon. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ iconURL(options = {}) { @@ -89,6 +99,7 @@ class PartialGroupDMChannel extends BaseChannel { /** * Fetches the owner of this Group DM Channel. + * * @param {BaseFetchOptions} [options] The options for fetching the user * @returns {Promise} */ @@ -109,10 +120,13 @@ class PartialGroupDMChannel extends BaseChannel { } // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ + get lastMessage() {} + get lastPinAt() {} + createMessageComponentCollector() {} + awaitMessageComponent() {} } diff --git a/packages/discord.js/src/structures/PermissionOverwrites.js b/packages/discord.js/src/structures/PermissionOverwrites.js index 86cc0b305d39..3dbc49ef49a1 100644 --- a/packages/discord.js/src/structures/PermissionOverwrites.js +++ b/packages/discord.js/src/structures/PermissionOverwrites.js @@ -1,13 +1,14 @@ 'use strict'; const { OverwriteType } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); -const { Role } = require('./Role.js'); const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); +const { Base } = require('./Base.js'); +const { Role } = require('./Role.js'); /** * Represents a permission overwrite for a role or member in a guild channel. + * * @extends {Base} */ class PermissionOverwrites extends Base { @@ -16,6 +17,7 @@ class PermissionOverwrites extends Base { /** * The GuildChannel this overwrite is for + * * @name PermissionOverwrites#channel * @type {GuildChannel} * @readonly @@ -28,6 +30,7 @@ class PermissionOverwrites extends Base { _patch(data) { /** * The overwrite's id, either a {@link User} or a {@link Role} id + * * @type {Snowflake} */ this.id = data.id; @@ -35,6 +38,7 @@ class PermissionOverwrites extends Base { if ('type' in data) { /** * The type of this overwrite + * * @type {OverwriteType} */ this.type = data.type; @@ -43,6 +47,7 @@ class PermissionOverwrites extends Base { if ('deny' in data) { /** * The permissions that are denied for the user or role. + * * @type {Readonly} */ this.deny = new PermissionsBitField(BigInt(data.deny)).freeze(); @@ -51,6 +56,7 @@ class PermissionOverwrites extends Base { if ('allow' in data) { /** * The permissions that are allowed for the user or role. + * * @type {Readonly} */ this.allow = new PermissionsBitField(BigInt(data.allow)).freeze(); @@ -59,6 +65,7 @@ class PermissionOverwrites extends Base { /** * Edits this Permission Overwrite. + * * @param {PermissionOverwriteOptions} options The options for the update * @param {string} [reason] Reason for creating/editing this overwrite * @returns {Promise} @@ -77,6 +84,7 @@ class PermissionOverwrites extends Base { /** * Deletes this Permission Overwrite. + * * @param {string} [reason] Reason for deleting this overwrite * @returns {Promise} */ @@ -98,22 +106,24 @@ class PermissionOverwrites extends Base { * An object mapping permission flags to `true` (enabled), `null` (unset) or `false` (disabled). * ```js * { - * 'SendMessages': true, - * 'EmbedLinks': null, - * 'AttachFiles': false, + * 'SendMessages': true, + * 'EmbedLinks': null, + * 'AttachFiles': false, * } * ``` - * @typedef {Object} PermissionOverwriteOptions + * + * @typedef {Record} PermissionOverwriteOptions */ /** - * @typedef {Object} ResolvedOverwriteOptions + * @typedef {object} ResolvedOverwriteOptions * @property {PermissionsBitField} allow The allowed permissions * @property {PermissionsBitField} deny The denied permissions */ /** * Resolves bitfield permissions overwrites from an object. + * * @param {PermissionOverwriteOptions} options The options for the update * @param {ResolvedOverwriteOptions} initialPermissions The initial permissions * @returns {ResolvedOverwriteOptions} @@ -140,7 +150,8 @@ class PermissionOverwrites extends Base { /** * The raw data for a permission overwrite - * @typedef {Object} RawOverwriteData + * + * @typedef {object} RawOverwriteData * @property {Snowflake} id The id of the {@link Role} or {@link User} this overwrite belongs to * @property {string} allow The permissions to allow * @property {string} deny The permissions to deny @@ -149,14 +160,16 @@ class PermissionOverwrites extends Base { /** * Data that can be resolved into {@link APIOverwrite}. This can be: - * * PermissionOverwrites - * * OverwriteData + * PermissionOverwrites + * OverwriteData + * * @typedef {PermissionOverwrites|OverwriteData} OverwriteResolvable */ /** * Data that can be used for a permission overwrite - * @typedef {Object} OverwriteData + * + * @typedef {object} OverwriteData * @property {UserResolvable|RoleResolvable} id Member or role this overwrite is for * @property {PermissionResolvable} [allow] The permissions to allow * @property {PermissionResolvable} [deny] The permissions to deny @@ -165,6 +178,7 @@ class PermissionOverwrites extends Base { /** * Resolves an overwrite into {@link APIOverwrite}. + * * @param {OverwriteResolvable} overwrite The overwrite-like data to resolve * @param {Guild} [guild] The guild to resolve from * @returns {RawOverwriteData} @@ -186,6 +200,7 @@ class PermissionOverwrites extends Base { if (overwrite.type === undefined) { throw new DiscordjsTypeError(ErrorCodes.PermissionOverwritesTypeMandatory); } + type = overwrite.type; } else { type = overwrite.id instanceof Role ? OverwriteType.Role : OverwriteType.Member; diff --git a/packages/discord.js/src/structures/Poll.js b/packages/discord.js/src/structures/Poll.js index 202c94ade2be..2d7b9e2eaf75 100644 --- a/packages/discord.js/src/structures/Poll.js +++ b/packages/discord.js/src/structures/Poll.js @@ -1,12 +1,13 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); +const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { Base } = require('./Base.js'); const { PollAnswer } = require('./PollAnswer.js'); -const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); /** * Represents a Poll + * * @extends {Base} */ class Poll extends Base { @@ -15,12 +16,14 @@ class Poll extends Base { /** * The id of the channel that this poll is in + * * @type {Snowflake} */ this.channelId = data.channel_id ?? channel.id; /** * The channel that this poll is in + * * @name Poll#channel * @type {TextBasedChannel} * @readonly @@ -30,12 +33,14 @@ class Poll extends Base { /** * The id of the message that started this poll + * * @type {Snowflake} */ this.messageId = data.message_id ?? message.id; /** * The message that started this poll + * * @name Poll#message * @type {Message} * @readonly @@ -45,6 +50,7 @@ class Poll extends Base { /** * The answers of this poll + * * @type {Collection} */ this.answers = new Collection(); @@ -67,6 +73,7 @@ class Poll extends Base { if (data.results) { /** * Whether this poll's results have been precisely counted + * * @type {boolean} */ this.resultsFinalized = data.results.is_finalized; @@ -82,6 +89,7 @@ class Poll extends Base { if ('allow_multiselect' in data) { /** * Whether this poll allows multiple answers + * * @type {boolean} */ this.allowMultiselect = data.allow_multiselect; @@ -92,6 +100,7 @@ class Poll extends Base { if ('layout_type' in data) { /** * The layout type of this poll + * * @type {PollLayoutType} */ this.layoutType = data.layout_type; @@ -102,6 +111,7 @@ class Poll extends Base { if ('expiry' in data) { /** * The timestamp when this poll expires + * * @type {?number} */ this.expiresTimestamp = data.expiry && Date.parse(data.expiry); @@ -112,12 +122,14 @@ class Poll extends Base { if (data.question) { /** * The media for a poll's question - * @typedef {Object} PollQuestionMedia + * + * @typedef {object} PollQuestionMedia * @property {?string} text The text of this question */ /** * The media for this poll's question + * * @type {PollQuestionMedia} */ this.question = { @@ -132,6 +144,7 @@ class Poll extends Base { /** * The date when this poll expires + * * @type {?Date} * @readonly */ @@ -141,6 +154,7 @@ class Poll extends Base { /** * Whether this poll is a partial + * * @type {boolean} * @readonly */ @@ -150,6 +164,7 @@ class Poll extends Base { /** * Fetches the message that started this poll, then updates the poll from the fetched message. + * * @returns {Promise} */ async fetch() { @@ -160,6 +175,7 @@ class Poll extends Base { /** * Ends this poll. + * * @returns {Promise} */ async end() { diff --git a/packages/discord.js/src/structures/PollAnswer.js b/packages/discord.js/src/structures/PollAnswer.js index 29cf5fe61612..b20e9568ee37 100644 --- a/packages/discord.js/src/structures/PollAnswer.js +++ b/packages/discord.js/src/structures/PollAnswer.js @@ -1,12 +1,13 @@ 'use strict'; -const { Base } = require('./Base.js'); -const { Emoji } = require('./Emoji.js'); const { PollAnswerVoterManager } = require('../managers/PollAnswerVoterManager.js'); const { resolveGuildEmoji } = require('../util/Util.js'); +const { Base } = require('./Base.js'); +const { Emoji } = require('./Emoji.js'); /** * Represents an answer to a {@link Poll} + * * @extends {Base} */ class PollAnswer extends Base { @@ -15,6 +16,7 @@ class PollAnswer extends Base { /** * The {@link Poll} this answer is part of + * * @name PollAnswer#poll * @type {Poll|PartialPoll} * @readonly @@ -23,18 +25,21 @@ class PollAnswer extends Base { /** * The id of this answer + * * @type {number} */ this.id = data.answer_id; /** * The manager of the voters for this answer + * * @type {PollAnswerVoterManager} */ this.voters = new PollAnswerVoterManager(this); /** * The raw emoji of this answer + * * @name PollAnswer#_emoji * @type {?APIPartialEmoji} * @private @@ -49,6 +54,7 @@ class PollAnswer extends Base { if ('count' in data) { /** * The amount of votes this answer has + * * @type {number} */ this.voteCount = data.count; @@ -58,6 +64,7 @@ class PollAnswer extends Base { /** * The text of this answer + * * @type {?string} */ this.text ??= data.poll_media?.text ?? null; @@ -69,6 +76,7 @@ class PollAnswer extends Base { /** * The emoji of this answer + * * @type {?(GuildEmoji|Emoji)} */ get emoji() { @@ -78,6 +86,7 @@ class PollAnswer extends Base { /** * Whether this poll answer is a partial. + * * @type {boolean} * @readonly */ @@ -87,18 +96,20 @@ class PollAnswer extends Base { /** * Options used for fetching voters of a poll answer. - * @typedef {Object} BaseFetchPollAnswerVotersOptions + * + * @typedef {object} BaseFetchPollAnswerVotersOptions * @property {number} [limit] The maximum number of voters to fetch * @property {Snowflake} [after] The user id to fetch voters after */ /** * Fetches the users that voted for this answer. - * @param {BaseFetchPollAnswerVotersOptions} [options={}] The options for fetching voters + * + * @param {BaseFetchPollAnswerVotersOptions} [options] The options for fetching voters * @returns {Promise>} * @deprecated Use {@link PollAnswerVoterManager#fetch} instead */ - fetchVoters({ after, limit } = {}) { + async fetchVoters({ after, limit } = {}) { return this.voters.fetch({ after, limit }); } } diff --git a/packages/discord.js/src/structures/Presence.js b/packages/discord.js/src/structures/Presence.js index a86d1f37c3ab..6495fb0abe98 100644 --- a/packages/discord.js/src/structures/Presence.js +++ b/packages/discord.js/src/structures/Presence.js @@ -1,36 +1,41 @@ +/* eslint-disable @typescript-eslint/no-use-before-define */ 'use strict'; -const { Base } = require('./Base.js'); -const { Emoji } = require('./Emoji.js'); const { ActivityFlagsBitField } = require('../util/ActivityFlagsBitField.js'); const { flatten } = require('../util/Util.js'); +const { Base } = require('./Base.js'); +const { Emoji } = require('./Emoji.js'); /** * Activity sent in a message. - * @typedef {Object} MessageActivity + * + * @typedef {object} MessageActivity * @property {string} [partyId] Id of the party represented in activity * @property {MessageActivityType} type Type of activity sent */ /** * The status of this presence: - * * **`online`** - user is online - * * **`idle`** - user is AFK - * * **`offline`** - user is offline or invisible - * * **`dnd`** - user is in Do Not Disturb + * **`online`** - user is online + * **`idle`** - user is AFK + * **`offline`** - user is offline or invisible + * **`dnd`** - user is in Do Not Disturb + * * @typedef {string} PresenceStatus */ /** * The status of this presence: - * * **`online`** - user is online - * * **`idle`** - user is AFK - * * **`dnd`** - user is in Do Not Disturb + * **`online`** - user is online + * **`idle`** - user is AFK + * **`dnd`** - user is in Do Not Disturb + * * @typedef {string} ClientPresenceStatus */ /** * Represents a user's presence. + * * @extends {Base} */ class Presence extends Base { @@ -39,12 +44,14 @@ class Presence extends Base { /** * The presence's user id + * * @type {Snowflake} */ this.userId = data.user.id; /** * The guild this presence is in + * * @type {?Guild} */ this.guild = data.guild ?? null; @@ -54,6 +61,7 @@ class Presence extends Base { /** * The user of this presence + * * @type {?User} * @readonly */ @@ -63,6 +71,7 @@ class Presence extends Base { /** * The member of this presence + * * @type {?GuildMember} * @readonly */ @@ -74,6 +83,7 @@ class Presence extends Base { if ('status' in data) { /** * The status of this presence + * * @type {PresenceStatus} */ this.status = data.status; @@ -84,6 +94,7 @@ class Presence extends Base { if ('activities' in data) { /** * The activities of this presence + * * @type {Activity[]} */ this.activities = data.activities.map(activity => new Activity(this, activity)); @@ -94,7 +105,8 @@ class Presence extends Base { if ('client_status' in data) { /** * The devices this presence is on - * @type {?Object} + * + * @type {?object} * @property {?ClientPresenceStatus} web The current presence in the web application * @property {?ClientPresenceStatus} mobile The current presence in the mobile application * @property {?ClientPresenceStatus} desktop The current presence in the desktop application @@ -115,6 +127,7 @@ class Presence extends Base { /** * Whether this presence is equal to another. + * * @param {Presence} presence The presence to compare with * @returns {boolean} */ @@ -143,6 +156,7 @@ class Activity { constructor(presence, data) { /** * The presence of the Activity + * * @type {Presence} * @readonly * @name Activity#presence @@ -151,49 +165,57 @@ class Activity { /** * The activity's name + * * @type {string} */ this.name = data.name; /** * The activity status's type + * * @type {ActivityType} */ this.type = data.type; /** * If the activity is being streamed, a link to the stream + * * @type {?string} */ this.url = data.url ?? null; /** * Details about the activity + * * @type {?string} */ this.details = data.details ?? null; /** * State of the activity + * * @type {?string} */ this.state = data.state ?? null; /** * The id of the application associated with this activity + * * @type {?Snowflake} */ this.applicationId = data.application_id ?? null; /** * Represents timestamps of an activity - * @typedef {Object} ActivityTimestamps + * + * @typedef {object} ActivityTimestamps * @property {?Date} start When the activity started * @property {?Date} end When the activity will end */ /** * Timestamps for the activity + * * @type {?ActivityTimestamps} */ this.timestamps = data.timestamps @@ -205,13 +227,15 @@ class Activity { /** * Represents a party of an activity - * @typedef {Object} ActivityParty + * + * @typedef {object} ActivityParty * @property {?string} id The party's id * @property {number[]} size Size of the party as `[current, max]` */ /** * Party of the activity + * * @type {?ActivityParty} */ this.party = data.party ?? null; @@ -219,36 +243,42 @@ class Activity { /** * The sync id of the activity * This property is not documented by Discord and represents the track id in spotify activities. + * * @type {?string} */ this.syncId = data.sync_id ?? null; /** * Assets for rich presence + * * @type {?RichPresenceAssets} */ this.assets = data.assets ? new RichPresenceAssets(this, data.assets) : null; /** * Flags that describe the activity + * * @type {Readonly} */ this.flags = new ActivityFlagsBitField(data.flags).freeze(); /** * Emoji for a custom activity + * * @type {?Emoji} */ this.emoji = data.emoji ? new Emoji(presence.client, data.emoji) : null; /** * The labels of the buttons of this rich presence + * * @type {string[]} */ this.buttons = data.buttons ?? []; /** * Creation date of the activity + * * @type {number} */ this.createdTimestamp = data.created_at; @@ -256,6 +286,7 @@ class Activity { /** * Whether this activity is equal to another activity. + * * @param {Activity} activity The activity to compare with * @returns {boolean} */ @@ -275,6 +306,7 @@ class Activity { /** * The time the activity was created at + * * @type {Date} * @readonly */ @@ -284,6 +316,7 @@ class Activity { /** * When concatenated with a string, this automatically returns the activity's name instead of the Activity object. + * * @returns {string} */ toString() { @@ -302,6 +335,7 @@ class RichPresenceAssets { constructor(activity, assets) { /** * The activity of the RichPresenceAssets + * * @type {Activity} * @readonly * @name RichPresenceAssets#activity @@ -310,24 +344,28 @@ class RichPresenceAssets { /** * Hover text for the large image + * * @type {?string} */ this.largeText = assets.large_text ?? null; /** * Hover text for the small image + * * @type {?string} */ this.smallText = assets.small_text ?? null; /** * The large image asset's id + * * @type {?Snowflake} */ this.largeImage = assets.large_image ?? null; /** * The small image asset's id + * * @type {?Snowflake} */ this.smallImage = assets.small_image ?? null; @@ -335,7 +373,8 @@ class RichPresenceAssets { /** * Gets the URL of the small image asset - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ smallImageURL(options = {}) { @@ -355,7 +394,8 @@ class RichPresenceAssets { /** * Gets the URL of the large image asset - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ largeImageURL(options = {}) { diff --git a/packages/discord.js/src/structures/PrimaryEntryPointCommandInteraction.js b/packages/discord.js/src/structures/PrimaryEntryPointCommandInteraction.js index e757e19c3b1a..b8539b441a1b 100644 --- a/packages/discord.js/src/structures/PrimaryEntryPointCommandInteraction.js +++ b/packages/discord.js/src/structures/PrimaryEntryPointCommandInteraction.js @@ -4,6 +4,7 @@ const { CommandInteraction } = require('./CommandInteraction.js'); /** * Represents a primary entry point command interaction. + * * @extends {CommandInteraction} */ class PrimaryEntryPointCommandInteraction extends CommandInteraction {} diff --git a/packages/discord.js/src/structures/ReactionCollector.js b/packages/discord.js/src/structures/ReactionCollector.js index 5ab31cfbce9c..b2ce65190f67 100644 --- a/packages/discord.js/src/structures/ReactionCollector.js +++ b/packages/discord.js/src/structures/ReactionCollector.js @@ -1,8 +1,9 @@ +/* eslint-disable @typescript-eslint/unbound-method */ 'use strict'; const { Collection } = require('@discordjs/collection'); -const { Collector } = require('./interfaces/Collector.js'); const { Events } = require('../util/Events.js'); +const { Collector } = require('./interfaces/Collector.js'); /** * @typedef {CollectorOptions} ReactionCollectorOptions @@ -18,30 +19,34 @@ const { Events } = require('../util/Events.js'); * channel ({@link Client#event:channelDelete channelDelete}), * thread ({@link Client#event:threadDelete threadDelete}), or * guild ({@link Client#event:guildDelete guildDelete}) is deleted. + * * @extends {Collector} */ class ReactionCollector extends Collector { /** * @param {Message} message The message upon which to collect reactions - * @param {ReactionCollectorOptions} [options={}] The options to apply to this collector + * @param {ReactionCollectorOptions} [options] The options to apply to this collector */ constructor(message, options = {}) { super(message.client, options); /** * The message upon which to collect reactions + * * @type {Message} */ this.message = message; /** * The users that have reacted to this message + * * @type {Collection} */ this.users = new Collection(); /** * The total number of reactions collected + * * @type {number} */ this.total = 0; @@ -83,6 +88,7 @@ class ReactionCollector extends Collector { * Emitted whenever a reaction is newly created on a message. Will emit only when a new reaction is * added to the message, as opposed to {@link Collector#event:collect} which will * be emitted even when a reaction has already been added to the message. + * * @event ReactionCollector#create * @param {MessageReaction} reaction The reaction that was added * @param {User} user The user that added the reaction @@ -90,6 +96,7 @@ class ReactionCollector extends Collector { if (reaction.count === 1) { this.emit('create', reaction, user); } + this.total++; this.users.set(user.id, user); }); @@ -102,14 +109,16 @@ class ReactionCollector extends Collector { /** * Handles an incoming reaction for possible collection. + * * @param {MessageReaction} reaction The reaction to possibly collect * @param {User} user The user that added the reaction * @returns {?(Snowflake|string)} * @private */ - collect(reaction) { + collect(reaction, user) { /** * Emitted whenever a reaction is collected. + * * @event ReactionCollector#collect * @param {MessageReaction} reaction The reaction that was collected * @param {User} user The user that added the reaction @@ -121,6 +130,7 @@ class ReactionCollector extends Collector { /** * Handles a reaction deletion for possible disposal. + * * @param {MessageReaction} reaction The reaction to possibly dispose of * @param {User} user The user that removed the reaction * @returns {?(Snowflake|string)} @@ -128,6 +138,7 @@ class ReactionCollector extends Collector { dispose(reaction, user) { /** * Emitted when the reaction had all the users removed and the `dispose` option is set to true. + * * @event ReactionCollector#dispose * @param {MessageReaction} reaction The reaction that was disposed of * @param {User} user The user that removed the reaction @@ -136,6 +147,7 @@ class ReactionCollector extends Collector { /** * Emitted when the reaction had one user removed and the `dispose` option is set to true. + * * @event ReactionCollector#remove * @param {MessageReaction} reaction The reaction that was removed * @param {User} user The user that removed the reaction @@ -143,6 +155,7 @@ class ReactionCollector extends Collector { if (this.collected.has(ReactionCollector.key(reaction)) && this.users.has(user.id)) { this.emit('remove', reaction, user); } + return reaction.count ? null : ReactionCollector.key(reaction); } @@ -158,6 +171,7 @@ class ReactionCollector extends Collector { /** * The reason this collector has ended with, or null if it hasn't ended yet + * * @type {?string} * @readonly */ @@ -170,6 +184,7 @@ class ReactionCollector extends Collector { /** * Handles checking if the message has been deleted, and if so, stops the collector with the reason 'messageDelete'. + * * @private * @param {Message} message The message that was deleted * @returns {void} @@ -182,6 +197,7 @@ class ReactionCollector extends Collector { /** * Handles checking if the channel has been deleted, and if so, stops the collector with the reason 'channelDelete'. + * * @private * @param {GuildChannel} channel The channel that was deleted * @returns {void} @@ -194,6 +210,7 @@ class ReactionCollector extends Collector { /** * Handles checking if the thread has been deleted, and if so, stops the collector with the reason 'threadDelete'. + * * @private * @param {ThreadChannel} thread The thread that was deleted * @returns {void} @@ -206,6 +223,7 @@ class ReactionCollector extends Collector { /** * Handles checking if the guild has been deleted, and if so, stops the collector with the reason 'guildDelete'. + * * @private * @param {Guild} guild The guild that was deleted * @returns {void} @@ -218,6 +236,7 @@ class ReactionCollector extends Collector { /** * Gets the collector key for a reaction. + * * @param {MessageReaction} reaction The message reaction to get the key for * @returns {Snowflake|string} */ diff --git a/packages/discord.js/src/structures/ReactionEmoji.js b/packages/discord.js/src/structures/ReactionEmoji.js index 5af48cd670f5..153822dee052 100644 --- a/packages/discord.js/src/structures/ReactionEmoji.js +++ b/packages/discord.js/src/structures/ReactionEmoji.js @@ -1,12 +1,13 @@ 'use strict'; -const { Emoji } = require('./Emoji.js'); const { flatten } = require('../util/Util.js'); +const { Emoji } = require('./Emoji.js'); /** * Represents a limited emoji set used for both custom and unicode emojis. Custom emojis * will use this class opposed to the Emoji class when the client doesn't know enough * information about them. + * * @extends {Emoji} */ class ReactionEmoji extends Emoji { @@ -14,6 +15,7 @@ class ReactionEmoji extends Emoji { super(reaction.message.client, emoji); /** * The message reaction this emoji refers to + * * @type {MessageReaction} */ this.reaction = reaction; diff --git a/packages/discord.js/src/structures/Role.js b/packages/discord.js/src/structures/Role.js index d58a0143b998..0d8bae75069f 100644 --- a/packages/discord.js/src/structures/Role.js +++ b/packages/discord.js/src/structures/Role.js @@ -3,13 +3,14 @@ const { roleMention } = require('@discordjs/formatters'); const { DiscordSnowflake } = require('@sapphire/snowflake'); const { PermissionFlagsBits } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { PermissionsBitField } = require('../util/PermissionsBitField.js'); const { RoleFlagsBitField } = require('../util/RoleFlagsBitField.js'); +const { Base } = require('./Base.js'); /** * Represents a role on Discord. + * * @extends {Base} */ class Role extends Base { @@ -18,18 +19,21 @@ class Role extends Base { /** * The guild that the role belongs to + * * @type {Guild} */ this.guild = guild; /** * The icon hash of the role + * * @type {?string} */ this.icon = null; /** * The unicode emoji for the role + * * @type {?string} */ this.unicodeEmoji = null; @@ -40,12 +44,14 @@ class Role extends Base { _patch(data) { /** * The role's id (unique to the guild it is part of) + * * @type {Snowflake} */ this.id = data.id; if ('name' in data) { /** * The name of the role + * * @type {string} */ this.name = data.name; @@ -54,6 +60,7 @@ class Role extends Base { if ('color' in data) { /** * The base 10 color of the role + * * @type {number} */ this.color = data.color; @@ -62,6 +69,7 @@ class Role extends Base { if ('hoist' in data) { /** * If true, users that are part of this role will appear in a separate category in the users list + * * @type {boolean} */ this.hoist = data.hoist; @@ -70,6 +78,7 @@ class Role extends Base { if ('position' in data) { /** * The raw position of the role from the API + * * @type {number} */ this.rawPosition = data.position; @@ -78,6 +87,7 @@ class Role extends Base { if ('permissions' in data) { /** * The permissions of the role + * * @type {Readonly} */ this.permissions = new PermissionsBitField(BigInt(data.permissions)).freeze(); @@ -86,6 +96,7 @@ class Role extends Base { if ('managed' in data) { /** * Whether or not the role is managed by an external service + * * @type {boolean} */ this.managed = data.managed; @@ -94,6 +105,7 @@ class Role extends Base { if ('mentionable' in data) { /** * Whether or not the role can be mentioned by anyone + * * @type {boolean} */ this.mentionable = data.mentionable; @@ -106,6 +118,7 @@ class Role extends Base { if ('flags' in data) { /** * The flags of this role + * * @type {Readonly} */ this.flags = new RoleFlagsBitField(data.flags).freeze(); @@ -115,7 +128,8 @@ class Role extends Base { /** * The tags this role has - * @type {?Object} + * + * @type {?object} * @property {Snowflake} [botId] The id of the bot this role belongs to * @property {Snowflake|string} [integrationId] The id of the integration this role belongs to * @property {true} [premiumSubscriberRole] Whether this is the guild's premium subscription role @@ -128,18 +142,23 @@ class Role extends Base { if ('bot_id' in data.tags) { this.tags.botId = data.tags.bot_id; } + if ('integration_id' in data.tags) { this.tags.integrationId = data.tags.integration_id; } + if ('premium_subscriber' in data.tags) { this.tags.premiumSubscriberRole = true; } + if ('subscription_listing_id' in data.tags) { this.tags.subscriptionListingId = data.tags.subscription_listing_id; } + if ('available_for_purchase' in data.tags) { this.tags.availableForPurchase = true; } + if ('guild_connections' in data.tags) { this.tags.guildConnections = true; } @@ -148,6 +167,7 @@ class Role extends Base { /** * The timestamp the role was created at + * * @type {number} * @readonly */ @@ -157,6 +177,7 @@ class Role extends Base { /** * The time the role was created at + * * @type {Date} * @readonly */ @@ -166,6 +187,7 @@ class Role extends Base { /** * The hexadecimal version of the role color, with a leading hashtag + * * @type {string} * @readonly */ @@ -175,6 +197,7 @@ class Role extends Base { /** * The cached guild members that have this role + * * @type {Collection} * @readonly */ @@ -186,6 +209,7 @@ class Role extends Base { /** * Whether the role is editable by the client user + * * @type {boolean} * @readonly */ @@ -198,6 +222,7 @@ class Role extends Base { /** * The position of the role in the role manager + * * @type {number} * @readonly */ @@ -214,6 +239,7 @@ class Role extends Base { /** * Compares this role's position to another role's. + * * @param {RoleResolvable} role Role to compare to this one * @returns {number} Negative number if this role's position is lower (other role's is higher), * positive number if this one is higher (other's is lower), 0 if equal @@ -228,7 +254,8 @@ class Role extends Base { /** * The data for a role. - * @typedef {Object} RoleData + * + * @typedef {object} RoleData * @property {string} [name] The name of the role * @property {ColorResolvable} [color] The color of the role, either a hex string or a base 10 number * @property {boolean} [hoist] Whether or not the role should be hoisted @@ -243,6 +270,7 @@ class Role extends Base { /** * Edits the role. + * * @param {RoleEditOptions} options The options to provide * @returns {Promise} * @example @@ -251,15 +279,16 @@ class Role extends Base { * .then(updated => console.log(`Edited role name to ${updated.name}`)) * .catch(console.error); */ - edit(options) { + async edit(options) { return this.guild.roles.edit(this, options); } /** * Returns `channel.permissionsFor(role)`. Returns permissions for a role in a guild channel, * taking into account permission overwrites. + * * @param {GuildChannel|Snowflake} channel The guild channel to use as context - * @param {boolean} [checkAdmin=true] Whether having the {@link PermissionFlagsBits.Administrator} permission + * @param {boolean} [checkAdmin] Whether having the {@link PermissionFlagsBits.Administrator} permission * will return all permissions * @returns {Readonly} */ @@ -271,6 +300,7 @@ class Role extends Base { /** * Sets a new name for the role. + * * @param {string} name The new name of the role * @param {string} [reason] Reason for changing the role's name * @returns {Promise} @@ -280,12 +310,13 @@ class Role extends Base { * .then(updated => console.log(`Updated role name to ${updated.name}`)) * .catch(console.error); */ - setName(name, reason) { + async setName(name, reason) { return this.edit({ name, reason }); } /** * Sets a new color for the role. + * * @param {ColorResolvable} color The color of the role * @param {string} [reason] Reason for changing the role's color * @returns {Promise} @@ -295,13 +326,14 @@ class Role extends Base { * .then(updated => console.log(`Set color of role to ${updated.color}`)) * .catch(console.error); */ - setColor(color, reason) { + async setColor(color, reason) { return this.edit({ color, reason }); } /** * Sets whether or not the role should be hoisted. - * @param {boolean} [hoist=true] Whether or not to hoist the role + * + * @param {boolean} [hoist] Whether or not to hoist the role * @param {string} [reason] Reason for setting whether or not the role should be hoisted * @returns {Promise} * @example @@ -310,12 +342,13 @@ class Role extends Base { * .then(updated => console.log(`Role hoisted: ${updated.hoist}`)) * .catch(console.error); */ - setHoist(hoist = true, reason) { + async setHoist(hoist = true, reason = undefined) { return this.edit({ hoist, reason }); } /** * Sets the permissions of the role. + * * @param {PermissionResolvable} permissions The permissions of the role * @param {string} [reason] Reason for changing the role's permissions * @returns {Promise} @@ -330,13 +363,14 @@ class Role extends Base { * .then(updated => console.log(`Updated permissions to ${updated.permissions.bitfield}`)) * .catch(console.error); */ - setPermissions(permissions, reason) { + async setPermissions(permissions, reason) { return this.edit({ permissions, reason }); } /** * Sets whether this role is mentionable. - * @param {boolean} [mentionable=true] Whether this role should be mentionable + * + * @param {boolean} [mentionable] Whether this role should be mentionable * @param {string} [reason] Reason for setting whether or not this role should be mentionable * @returns {Promise} * @example @@ -345,24 +379,26 @@ class Role extends Base { * .then(updated => console.log(`Role updated ${updated.name}`)) * .catch(console.error); */ - setMentionable(mentionable = true, reason) { + async setMentionable(mentionable = true, reason = undefined) { return this.edit({ mentionable, reason }); } /** * Sets a new icon for the role. + * * @param {?(BufferResolvable|Base64Resolvable|EmojiResolvable)} icon The icon for the role * The `EmojiResolvable` should belong to the same guild as the role. * If not, pass the emoji's URL directly * @param {string} [reason] Reason for changing the role's icon * @returns {Promise} */ - setIcon(icon, reason) { + async setIcon(icon, reason) { return this.edit({ icon, reason }); } /** * Sets a new unicode emoji for the role. + * * @param {?string} unicodeEmoji The new unicode emoji for the role * @param {string} [reason] Reason for changing the role's unicode emoji * @returns {Promise} @@ -372,19 +408,21 @@ class Role extends Base { * .then(updated => console.log(`Set unicode emoji for the role to ${updated.unicodeEmoji}`)) * .catch(console.error); */ - setUnicodeEmoji(unicodeEmoji, reason) { + async setUnicodeEmoji(unicodeEmoji, reason) { return this.edit({ unicodeEmoji, reason }); } /** * Options used to set the position of a role. - * @typedef {Object} SetRolePositionOptions + * + * @typedef {object} SetRolePositionOptions * @property {boolean} [relative=false] Whether to change the position relative to its current value or not * @property {string} [reason] The reason for changing the position */ /** * Sets the new position of the role. + * * @param {number} position The new position for the role * @param {SetRolePositionOptions} [options] Options for setting the position * @returns {Promise} @@ -394,12 +432,13 @@ class Role extends Base { * .then(updated => console.log(`Role position: ${updated.position}`)) * .catch(console.error); */ - setPosition(position, options = {}) { + async setPosition(position, options = {}) { return this.guild.roles.setPosition(this, position, options); } /** * Deletes the role. + * * @param {string} [reason] Reason for deleting this role * @returns {Promise} * @example @@ -415,7 +454,8 @@ class Role extends Base { /** * A link to the role's icon - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ iconURL(options = {}) { @@ -426,6 +466,7 @@ class Role extends Base { * Whether this role equals another role. It compares all properties, so for most operations * it is advisable to just compare `role.id === role2.id` as it is much faster and is often * what most users need. + * * @param {Role} role Role to compare with * @returns {boolean} */ @@ -446,6 +487,7 @@ class Role extends Base { /** * When concatenated with a string, this automatically returns the role's mention instead of the Role object. + * * @returns {string} * @example * // Logs: Role: <@&123456789012345678> diff --git a/packages/discord.js/src/structures/RoleSelectMenuComponent.js b/packages/discord.js/src/structures/RoleSelectMenuComponent.js index 85dfb439a8b8..f602afc02599 100644 --- a/packages/discord.js/src/structures/RoleSelectMenuComponent.js +++ b/packages/discord.js/src/structures/RoleSelectMenuComponent.js @@ -4,6 +4,7 @@ const { BaseSelectMenuComponent } = require('./BaseSelectMenuComponent.js'); /** * Represents a role select menu component + * * @extends {BaseSelectMenuComponent} */ class RoleSelectMenuComponent extends BaseSelectMenuComponent {} diff --git a/packages/discord.js/src/structures/RoleSelectMenuInteraction.js b/packages/discord.js/src/structures/RoleSelectMenuInteraction.js index 7706455f1bd7..add0a042aa9d 100644 --- a/packages/discord.js/src/structures/RoleSelectMenuInteraction.js +++ b/packages/discord.js/src/structures/RoleSelectMenuInteraction.js @@ -5,6 +5,7 @@ const { MessageComponentInteraction } = require('./MessageComponentInteraction.j /** * Represents a {@link ComponentType.RoleSelect} select menu interaction. + * * @extends {MessageComponentInteraction} */ class RoleSelectMenuInteraction extends MessageComponentInteraction { @@ -14,12 +15,14 @@ class RoleSelectMenuInteraction extends MessageComponentInteraction { /** * An array of the selected role ids + * * @type {Snowflake[]} */ this.values = values ?? []; /** * Collection of the selected roles + * * @type {Collection} */ this.roles = new Collection(); diff --git a/packages/discord.js/src/structures/SKU.js b/packages/discord.js/src/structures/SKU.js index b64aa078439c..b6db77af9f01 100644 --- a/packages/discord.js/src/structures/SKU.js +++ b/packages/discord.js/src/structures/SKU.js @@ -1,10 +1,11 @@ 'use strict'; -const { Base } = require('./Base.js'); const { SKUFlagsBitField } = require('../util/SKUFlagsBitField.js'); +const { Base } = require('./Base.js'); /** * Represents a premium application SKU. + * * @extends {Base} */ class SKU extends Base { @@ -13,36 +14,42 @@ class SKU extends Base { /** * The id of the SKU + * * @type {Snowflake} */ this.id = data.id; /** * The type of the SKU + * * @type {SKUType} */ this.type = data.type; /** * The id of the parent application + * * @type {Snowflake} */ this.applicationId = data.application_id; /** * The customer-facing name of the premium offering + * * @type {string} */ this.name = data.name; /** * The system-generated URL slug based on this SKU's name + * * @type {string} */ this.slug = data.slug; /** * Flags that describe the SKU + * * @type {Readonly} */ this.flags = new SKUFlagsBitField(data.flags).freeze(); diff --git a/packages/discord.js/src/structures/SoundboardSound.js b/packages/discord.js/src/structures/SoundboardSound.js index 2bfbae9ea3f6..20037218d287 100644 --- a/packages/discord.js/src/structures/SoundboardSound.js +++ b/packages/discord.js/src/structures/SoundboardSound.js @@ -1,12 +1,13 @@ 'use strict'; const { DiscordSnowflake } = require('@sapphire/snowflake'); +const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { Base } = require('./Base.js'); const { Emoji } = require('./Emoji.js'); -const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); /** * Represents a soundboard sound. + * * @extends {Base} */ class SoundboardSound extends Base { @@ -15,6 +16,7 @@ class SoundboardSound extends Base { /** * The id of this soundboard sound + * * @type {Snowflake|string} */ this.soundId = data.sound_id; @@ -26,6 +28,7 @@ class SoundboardSound extends Base { if ('available' in data) { /** * Whether this soundboard sound is available + * * @type {?boolean} */ this.available = data.available; @@ -36,6 +39,7 @@ class SoundboardSound extends Base { if ('name' in data) { /** * The name of this soundboard sound + * * @type {?string} */ this.name = data.name; @@ -46,6 +50,7 @@ class SoundboardSound extends Base { if ('volume' in data) { /** * The volume (a double) of this soundboard sound, from 0 to 1 + * * @type {?number} */ this.volume = data.volume; @@ -56,7 +61,8 @@ class SoundboardSound extends Base { if ('emoji_id' in data) { /** * The raw emoji data of this soundboard sound - * @type {?Object} + * + * @type {?object} * @private */ this._emoji = { @@ -70,6 +76,7 @@ class SoundboardSound extends Base { if ('guild_id' in data) { /** * The guild id of this soundboard sound + * * @type {?Snowflake} */ this.guildId = data.guild_id; @@ -80,6 +87,7 @@ class SoundboardSound extends Base { if ('user' in data) { /** * The user who created this soundboard sound + * * @type {?User} */ this.user = this.client.users._add(data.user); @@ -90,6 +98,7 @@ class SoundboardSound extends Base { /** * The timestamp this soundboard sound was created at + * * @type {number} * @readonly */ @@ -99,6 +108,7 @@ class SoundboardSound extends Base { /** * The time this soundboard sound was created at + * * @type {Date} * @readonly */ @@ -108,6 +118,7 @@ class SoundboardSound extends Base { /** * The emoji of this soundboard sound + * * @type {?Emoji} * @readonly */ @@ -119,6 +130,7 @@ class SoundboardSound extends Base { /** * The guild this soundboard sound is part of + * * @type {?Guild} * @readonly */ @@ -128,6 +140,7 @@ class SoundboardSound extends Base { /** * A link to this soundboard sound + * * @type {string} * @readonly */ @@ -137,6 +150,7 @@ class SoundboardSound extends Base { /** * Edits this soundboard sound. + * * @param {GuildSoundboardSoundEditOptions} options The options to provide * @returns {Promise} * @example @@ -153,6 +167,7 @@ class SoundboardSound extends Base { /** * Deletes this soundboard sound. + * * @param {string} [reason] Reason for deleting this soundboard sound * @returns {Promise} * @example @@ -171,6 +186,7 @@ class SoundboardSound extends Base { /** * Whether this soundboard sound is the same as another one. + * * @param {SoundboardSound|APISoundboardSound} other The soundboard sound to compare it to * @returns {boolean} */ diff --git a/packages/discord.js/src/structures/StageChannel.js b/packages/discord.js/src/structures/StageChannel.js index 1ad7fe4e9bfa..02f52f228eb5 100644 --- a/packages/discord.js/src/structures/StageChannel.js +++ b/packages/discord.js/src/structures/StageChannel.js @@ -4,6 +4,7 @@ const { BaseGuildVoiceChannel } = require('./BaseGuildVoiceChannel.js'); /** * Represents a guild stage channel on Discord. + * * @extends {BaseGuildVoiceChannel} */ class StageChannel extends BaseGuildVoiceChannel { @@ -13,6 +14,7 @@ class StageChannel extends BaseGuildVoiceChannel { if ('topic' in data) { /** * The topic of the stage channel + * * @type {?string} */ this.topic = data.topic; @@ -21,6 +23,7 @@ class StageChannel extends BaseGuildVoiceChannel { /** * The stage instance of this stage channel, if it exists + * * @type {?StageInstance} * @readonly */ @@ -30,15 +33,17 @@ class StageChannel extends BaseGuildVoiceChannel { /** * Creates a stage instance associated with this stage channel. + * * @param {StageInstanceCreateOptions} options The options to create the stage instance * @returns {Promise} */ - createStageInstance(options) { + async createStageInstance(options) { return this.guild.stageInstances.create(this.id, options); } /** * Sets a new topic for the guild channel. + * * @param {?string} topic The new topic for the guild channel * @param {string} [reason] Reason for changing the guild channel's topic * @returns {Promise} @@ -48,13 +53,14 @@ class StageChannel extends BaseGuildVoiceChannel { * .then(channel => console.log(`Channel's new topic is ${channel.topic}`)) * .catch(console.error); */ - setTopic(topic, reason) { + async setTopic(topic, reason) { return this.edit({ topic, reason }); } } /** * Sets the bitrate of the channel. + * * @method setBitrate * @memberof StageChannel * @instance @@ -70,6 +76,7 @@ class StageChannel extends BaseGuildVoiceChannel { /** * Sets the RTC region of the channel. + * * @method setRTCRegion * @memberof StageChannel * @instance @@ -86,6 +93,7 @@ class StageChannel extends BaseGuildVoiceChannel { /** * Sets the user limit of the channel. + * * @method setUserLimit * @memberof StageChannel * @instance @@ -101,6 +109,7 @@ class StageChannel extends BaseGuildVoiceChannel { /** * Sets the camera video quality mode of the channel. + * * @method setVideoQualityMode * @memberof StageChannel * @instance diff --git a/packages/discord.js/src/structures/StageInstance.js b/packages/discord.js/src/structures/StageInstance.js index 62bcbcadaec9..68a776ce54f1 100644 --- a/packages/discord.js/src/structures/StageInstance.js +++ b/packages/discord.js/src/structures/StageInstance.js @@ -5,6 +5,7 @@ const { Base } = require('./Base.js'); /** * Represents a stage instance. + * * @extends {Base} */ class StageInstance extends Base { @@ -13,6 +14,7 @@ class StageInstance extends Base { /** * The stage instance's id + * * @type {Snowflake} */ this.id = data.id; @@ -24,6 +26,7 @@ class StageInstance extends Base { if ('guild_id' in data) { /** * The id of the guild associated with the stage channel + * * @type {Snowflake} */ this.guildId = data.guild_id; @@ -32,6 +35,7 @@ class StageInstance extends Base { if ('channel_id' in data) { /** * The id of the channel associated with the stage channel + * * @type {Snowflake} */ this.channelId = data.channel_id; @@ -40,6 +44,7 @@ class StageInstance extends Base { if ('topic' in data) { /** * The topic of the stage instance + * * @type {string} */ this.topic = data.topic; @@ -48,6 +53,7 @@ class StageInstance extends Base { if ('privacy_level' in data) { /** * The privacy level of the stage instance + * * @type {StageInstancePrivacyLevel} */ this.privacyLevel = data.privacy_level; @@ -56,6 +62,7 @@ class StageInstance extends Base { if ('guild_scheduled_event_id' in data) { /** * The associated guild scheduled event id of this stage instance + * * @type {?Snowflake} */ this.guildScheduledEventId = data.guild_scheduled_event_id; @@ -66,6 +73,7 @@ class StageInstance extends Base { /** * The stage channel associated with this stage instance + * * @type {?StageChannel} * @readonly */ @@ -75,6 +83,7 @@ class StageInstance extends Base { /** * The guild this stage instance belongs to + * * @type {?Guild} * @readonly */ @@ -84,6 +93,7 @@ class StageInstance extends Base { /** * The associated guild scheduled event of this stage instance + * * @type {?GuildScheduledEvent} * @readonly */ @@ -93,6 +103,7 @@ class StageInstance extends Base { /** * Edits this stage instance. + * * @param {StageInstanceEditOptions} options The options to edit the stage instance * @returns {Promise} * @example @@ -101,12 +112,13 @@ class StageInstance extends Base { * .then(stageInstance => console.log(stageInstance)) * .catch(console.error) */ - edit(options) { + async edit(options) { return this.guild.stageInstances.edit(this.channelId, options); } /** * Deletes this stage instance. + * * @returns {Promise} * @example * // Delete a stage instance @@ -116,12 +128,12 @@ class StageInstance extends Base { */ async delete() { await this.guild.stageInstances.delete(this.channelId); - const clone = this._clone(); - return clone; + return this._clone(); } /** * Sets the topic of this stage instance. + * * @param {string} topic The topic for the stage instance * @returns {Promise} * @example @@ -130,12 +142,13 @@ class StageInstance extends Base { * .then(stageInstance => console.log(`Set the topic to: ${stageInstance.topic}`)) * .catch(console.error); */ - setTopic(topic) { + async setTopic(topic) { return this.guild.stageInstances.edit(this.channelId, { topic }); } /** * The timestamp this stage instances was created at + * * @type {number} * @readonly */ @@ -145,6 +158,7 @@ class StageInstance extends Base { /** * The time this stage instance was created at + * * @type {Date} * @readonly */ diff --git a/packages/discord.js/src/structures/Sticker.js b/packages/discord.js/src/structures/Sticker.js index 755f98e0e46f..5b3fa49a1780 100644 --- a/packages/discord.js/src/structures/Sticker.js +++ b/packages/discord.js/src/structures/Sticker.js @@ -2,12 +2,13 @@ const { DiscordSnowflake } = require('@sapphire/snowflake'); const { Routes } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { StickerFormatExtensionMap } = require('../util/Constants.js'); +const { Base } = require('./Base.js'); /** * Represents a Sticker. + * * @extends {Base} */ class Sticker extends Base { @@ -20,6 +21,7 @@ class Sticker extends Base { _patch(sticker) { /** * The sticker's id + * * @type {Snowflake} */ this.id = sticker.id; @@ -27,6 +29,7 @@ class Sticker extends Base { if ('description' in sticker) { /** * The description of the sticker + * * @type {?string} */ this.description = sticker.description; @@ -37,6 +40,7 @@ class Sticker extends Base { if ('type' in sticker) { /** * The type of the sticker + * * @type {?StickerType} */ this.type = sticker.type; @@ -47,6 +51,7 @@ class Sticker extends Base { if ('format_type' in sticker) { /** * The format of the sticker + * * @type {StickerFormatType} */ this.format = sticker.format_type; @@ -55,6 +60,7 @@ class Sticker extends Base { if ('name' in sticker) { /** * The name of the sticker + * * @type {string} */ this.name = sticker.name; @@ -63,6 +69,7 @@ class Sticker extends Base { if ('pack_id' in sticker) { /** * The id of the pack the sticker is from, for standard stickers + * * @type {?Snowflake} */ this.packId = sticker.pack_id; @@ -73,6 +80,7 @@ class Sticker extends Base { if ('tags' in sticker) { /** * Autocomplete/suggestions for the sticker + * * @type {?string} */ this.tags = sticker.tags; @@ -83,6 +91,7 @@ class Sticker extends Base { if ('available' in sticker) { /** * Whether or not the guild sticker is available + * * @type {?boolean} */ this.available = sticker.available; @@ -93,6 +102,7 @@ class Sticker extends Base { if ('guild_id' in sticker) { /** * The id of the guild that owns this sticker + * * @type {?Snowflake} */ this.guildId = sticker.guild_id; @@ -103,6 +113,7 @@ class Sticker extends Base { if ('user' in sticker) { /** * The user that uploaded the guild sticker + * * @type {?User} */ this.user = this.client.users._add(sticker.user); @@ -113,6 +124,7 @@ class Sticker extends Base { if ('sort_value' in sticker) { /** * The standard sticker's sort order within its pack + * * @type {?number} */ this.sortValue = sticker.sort_value; @@ -123,6 +135,7 @@ class Sticker extends Base { /** * The timestamp the sticker was created at + * * @type {number} * @readonly */ @@ -132,6 +145,7 @@ class Sticker extends Base { /** * The time the sticker was created at + * * @type {Date} * @readonly */ @@ -141,6 +155,7 @@ class Sticker extends Base { /** * Whether this sticker is partial + * * @type {boolean} * @readonly */ @@ -150,6 +165,7 @@ class Sticker extends Base { /** * The guild that owns this sticker + * * @type {?Guild} * @readonly */ @@ -161,6 +177,7 @@ class Sticker extends Base { * A link to the sticker * If the sticker's format is {@link StickerFormatType.Lottie}, it returns * the URL of the Lottie JSON file. + * * @type {string} * @readonly */ @@ -170,6 +187,7 @@ class Sticker extends Base { /** * Fetches this sticker. + * * @returns {Promise} */ async fetch() { @@ -180,6 +198,7 @@ class Sticker extends Base { /** * Fetches the pack that contains this sticker. + * * @returns {Promise} The sticker pack or `null` if this sticker does not belong to one. */ async fetchPack() { @@ -189,6 +208,7 @@ class Sticker extends Base { /** * Fetches the user who uploaded this sticker, if this is a guild sticker. + * * @returns {Promise} */ async fetchUser() { @@ -199,7 +219,8 @@ class Sticker extends Base { /** * Data for editing a sticker. - * @typedef {Object} GuildStickerEditOptions + * + * @typedef {object} GuildStickerEditOptions * @property {string} [name] The name of the sticker * @property {?string} [description] The description of the sticker * @property {string} [tags] The Discord name of a unicode emoji representing the sticker's expression @@ -208,6 +229,7 @@ class Sticker extends Base { /** * Edits the sticker. + * * @param {GuildStickerEditOptions} options The options to provide * @returns {Promise} * @example @@ -216,12 +238,13 @@ class Sticker extends Base { * .then(sticker => console.log(`Updated the name of the sticker to ${sticker.name}`)) * .catch(console.error); */ - edit(options) { + async edit(options) { return this.guild.stickers.edit(this, options); } /** * Deletes the sticker. + * * @returns {Promise} * @param {string} [reason] Reason for deleting this sticker * @example @@ -237,6 +260,7 @@ class Sticker extends Base { /** * Whether this sticker is the same as another one. + * * @param {Sticker|APISticker} other The sticker to compare it to * @returns {boolean} */ diff --git a/packages/discord.js/src/structures/StickerPack.js b/packages/discord.js/src/structures/StickerPack.js index 73a26855e97e..b9ec2d1c4250 100644 --- a/packages/discord.js/src/structures/StickerPack.js +++ b/packages/discord.js/src/structures/StickerPack.js @@ -7,6 +7,7 @@ const { Sticker } = require('./Sticker.js'); /** * Represents a pack of standard stickers. + * * @extends {Base} */ class StickerPack extends Base { @@ -14,42 +15,49 @@ class StickerPack extends Base { super(client); /** * The Sticker pack's id + * * @type {Snowflake} */ this.id = pack.id; /** * The stickers in the pack + * * @type {Collection} */ this.stickers = new Collection(pack.stickers.map(sticker => [sticker.id, new Sticker(client, sticker)])); /** * The name of the sticker pack + * * @type {string} */ this.name = pack.name; /** * The id of the pack's SKU + * * @type {Snowflake} */ this.skuId = pack.sku_id; /** * The id of a sticker in the pack which is shown as the pack's icon + * * @type {?Snowflake} */ this.coverStickerId = pack.cover_sticker_id ?? null; /** * The description of the sticker pack + * * @type {string} */ this.description = pack.description; /** * The id of the sticker pack's banner image + * * @type {?Snowflake} */ this.bannerId = pack.banner_asset_id ?? null; @@ -57,6 +65,7 @@ class StickerPack extends Base { /** * The timestamp the sticker was created at + * * @type {number} * @readonly */ @@ -66,6 +75,7 @@ class StickerPack extends Base { /** * The time the sticker was created at + * * @type {Date} * @readonly */ @@ -75,6 +85,7 @@ class StickerPack extends Base { /** * The sticker which is shown as the pack's icon + * * @type {?Sticker} * @readonly */ @@ -84,7 +95,8 @@ class StickerPack extends Base { /** * The URL to this sticker pack's banner. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ bannerURL(options = {}) { diff --git a/packages/discord.js/src/structures/StringSelectMenuComponent.js b/packages/discord.js/src/structures/StringSelectMenuComponent.js index 1eb317c19b81..86230a851ca8 100644 --- a/packages/discord.js/src/structures/StringSelectMenuComponent.js +++ b/packages/discord.js/src/structures/StringSelectMenuComponent.js @@ -4,11 +4,13 @@ const { BaseSelectMenuComponent } = require('./BaseSelectMenuComponent.js'); /** * Represents a string select menu component + * * @extends {BaseSelectMenuComponent} */ class StringSelectMenuComponent extends BaseSelectMenuComponent { /** * The options in this select menu + * * @type {APISelectMenuOption[]} * @readonly */ diff --git a/packages/discord.js/src/structures/StringSelectMenuInteraction.js b/packages/discord.js/src/structures/StringSelectMenuInteraction.js index 6671634df473..87602d125aab 100644 --- a/packages/discord.js/src/structures/StringSelectMenuInteraction.js +++ b/packages/discord.js/src/structures/StringSelectMenuInteraction.js @@ -4,6 +4,7 @@ const { MessageComponentInteraction } = require('./MessageComponentInteraction.j /** * Represents a {@link ComponentType.StringSelect} select menu interaction. + * * @extends {MessageComponentInteraction} */ class StringSelectMenuInteraction extends MessageComponentInteraction { @@ -12,6 +13,7 @@ class StringSelectMenuInteraction extends MessageComponentInteraction { /** * The values selected + * * @type {string[]} */ this.values = data.data.values ?? []; diff --git a/packages/discord.js/src/structures/Subscription.js b/packages/discord.js/src/structures/Subscription.js index b005cc3944d6..dbd1a01ae32c 100644 --- a/packages/discord.js/src/structures/Subscription.js +++ b/packages/discord.js/src/structures/Subscription.js @@ -4,6 +4,7 @@ const { Base } = require('./Base.js'); /** * Represents a Subscription + * * @extends {Base} */ class Subscription extends Base { @@ -12,12 +13,14 @@ class Subscription extends Base { /** * The id of the subscription + * * @type {Snowflake} */ this.id = data.id; /** * The id of the user who subscribed + * * @type {Snowflake} */ this.userId = data.user_id; @@ -28,30 +31,35 @@ class Subscription extends Base { _patch(data) { /** * The SKU ids subscribed to + * * @type {Snowflake[]} */ this.skuIds = data.sku_ids; /** * The entitlement ids granted for this subscription + * * @type {Snowflake[]} */ this.entitlementIds = data.entitlement_ids; /** * The timestamp the current subscription period will start at + * * @type {number} */ this.currentPeriodStartTimestamp = Date.parse(data.current_period_start); /** * The timestamp the current subscription period will end at + * * @type {number} */ this.currentPeriodEndTimestamp = Date.parse(data.current_period_end); /** * The current status of the subscription + * * @type {SubscriptionStatus} */ this.status = data.status; @@ -59,6 +67,7 @@ class Subscription extends Base { if ('renewal_sku_ids' in data) { /** * The SKU ids that this user will be subscribed to at renewal + * * @type {?Snowflake[]} */ this.renewalSkuIds = data.renewal_sku_ids; @@ -67,6 +76,7 @@ class Subscription extends Base { if ('canceled_at' in data) { /** * The timestamp of when the subscription was canceled + * * @type {?number} */ this.canceledTimestamp = data.canceled_at ? Date.parse(data.canceled_at) : null; @@ -78,6 +88,7 @@ class Subscription extends Base { /** * ISO 3166-1 alpha-2 country code of the payment source used to purchase the subscription. * Missing unless queried with a private OAuth scope. + * * @type {?string} */ this.country = data.country; @@ -88,6 +99,7 @@ class Subscription extends Base { /** * The time the subscription was canceled + * * @type {?Date} * @readonly */ @@ -97,6 +109,7 @@ class Subscription extends Base { /** * The time the current subscription period will start at + * * @type {Date} * @readonly */ @@ -106,6 +119,7 @@ class Subscription extends Base { /** * The time the current subscription period will end at + * * @type {Date} * @readonly */ diff --git a/packages/discord.js/src/structures/Team.js b/packages/discord.js/src/structures/Team.js index 95a4704e65e0..00fcac29f308 100644 --- a/packages/discord.js/src/structures/Team.js +++ b/packages/discord.js/src/structures/Team.js @@ -7,6 +7,7 @@ const { TeamMember } = require('./TeamMember.js'); /** * Represents a Client OAuth2 Application Team. + * * @extends {Base} */ class Team extends Base { @@ -18,6 +19,7 @@ class Team extends Base { _patch(data) { /** * The Team's id + * * @type {Snowflake} */ this.id = data.id; @@ -25,6 +27,7 @@ class Team extends Base { if ('name' in data) { /** * The name of the Team + * * @type {string} */ this.name = data.name; @@ -33,6 +36,7 @@ class Team extends Base { if ('icon' in data) { /** * The Team's icon hash + * * @type {?string} */ this.icon = data.icon; @@ -43,14 +47,17 @@ class Team extends Base { if ('owner_user_id' in data) { /** * The Team's owner id + * * @type {?Snowflake} */ this.ownerId = data.owner_user_id; } else { this.ownerId ??= null; } + /** * The Team's members + * * @type {Collection} */ this.members = new Collection(); @@ -63,6 +70,7 @@ class Team extends Base { /** * The owner of this team + * * @type {?TeamMember} * @readonly */ @@ -72,6 +80,7 @@ class Team extends Base { /** * The timestamp the team was created at + * * @type {number} * @readonly */ @@ -81,6 +90,7 @@ class Team extends Base { /** * The time the team was created at + * * @type {Date} * @readonly */ @@ -90,7 +100,8 @@ class Team extends Base { /** * A link to the team's icon. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ iconURL(options = {}) { @@ -100,6 +111,7 @@ class Team extends Base { /** * When concatenated with a string, this automatically returns the Team's name instead of the * Team object. + * * @returns {string} * @example * // Logs: Team name: My Team diff --git a/packages/discord.js/src/structures/TeamMember.js b/packages/discord.js/src/structures/TeamMember.js index 89bb54ee16d5..0163baf0819b 100644 --- a/packages/discord.js/src/structures/TeamMember.js +++ b/packages/discord.js/src/structures/TeamMember.js @@ -4,6 +4,7 @@ const { Base } = require('./Base.js'); /** * Represents a Client OAuth2 Application Team Member. + * * @extends {Base} */ class TeamMember extends Base { @@ -12,6 +13,7 @@ class TeamMember extends Base { /** * The Team this member is part of + * * @type {Team} */ this.team = team; @@ -23,6 +25,7 @@ class TeamMember extends Base { if ('membership_state' in data) { /** * The permissions this Team Member has with regard to the team + * * @type {TeamMemberMembershipState} */ this.membershipState = data.membership_state; @@ -31,6 +34,7 @@ class TeamMember extends Base { if ('user' in data) { /** * The user for this Team Member + * * @type {User} */ this.user = this.client.users._add(data.user); @@ -39,6 +43,7 @@ class TeamMember extends Base { if ('role' in data) { /** * The role of this Team Member + * * @type {TeamMemberRole} */ this.role = data.role; @@ -47,6 +52,7 @@ class TeamMember extends Base { /** * The Team Member's id + * * @type {Snowflake} * @readonly */ @@ -57,6 +63,7 @@ class TeamMember extends Base { /** * When concatenated with a string, this automatically returns the team member's mention instead of the * TeamMember object. + * * @returns {string} * @example * // Logs: Team Member's mention: <@123456789012345678> diff --git a/packages/discord.js/src/structures/TextChannel.js b/packages/discord.js/src/structures/TextChannel.js index 3978a7c53e21..6271196e5970 100644 --- a/packages/discord.js/src/structures/TextChannel.js +++ b/packages/discord.js/src/structures/TextChannel.js @@ -4,6 +4,7 @@ const { BaseGuildTextChannel } = require('./BaseGuildTextChannel.js'); /** * Represents a guild text channel on Discord. + * * @extends {BaseGuildTextChannel} */ class TextChannel extends BaseGuildTextChannel { @@ -13,6 +14,7 @@ class TextChannel extends BaseGuildTextChannel { if ('rate_limit_per_user' in data) { /** * The rate limit per user (slowmode) for this channel in seconds + * * @type {number} */ this.rateLimitPerUser = data.rate_limit_per_user; @@ -21,11 +23,12 @@ class TextChannel extends BaseGuildTextChannel { /** * Sets the rate limit per user (slowmode) for this channel. + * * @param {number} rateLimitPerUser The new rate limit in seconds * @param {string} [reason] Reason for changing the channel's rate limit * @returns {Promise} */ - setRateLimitPerUser(rateLimitPerUser, reason) { + async setRateLimitPerUser(rateLimitPerUser, reason) { return this.edit({ rateLimitPerUser, reason }); } } diff --git a/packages/discord.js/src/structures/TextInputComponent.js b/packages/discord.js/src/structures/TextInputComponent.js index d23d088ddf3b..57686584fafe 100644 --- a/packages/discord.js/src/structures/TextInputComponent.js +++ b/packages/discord.js/src/structures/TextInputComponent.js @@ -4,11 +4,13 @@ const { Component } = require('./Component.js'); /** * Represents a text input component. + * * @extends {Component} */ class TextInputComponent extends Component { /** * The custom id of this text input + * * @type {string} * @readonly */ @@ -18,6 +20,7 @@ class TextInputComponent extends Component { /** * The value for this text input + * * @type {string} * @readonly */ diff --git a/packages/discord.js/src/structures/ThreadChannel.js b/packages/discord.js/src/structures/ThreadChannel.js index 1467c1c03123..07c13771b309 100644 --- a/packages/discord.js/src/structures/ThreadChannel.js +++ b/packages/discord.js/src/structures/ThreadChannel.js @@ -2,16 +2,18 @@ const { lazy } = require('@discordjs/util'); const { ChannelFlags, ChannelType, PermissionFlagsBits, Routes } = require('discord-api-types/v10'); -const { BaseChannel } = require('./BaseChannel.js'); -const getThreadOnlyChannel = lazy(() => require('./ThreadOnlyChannel.js')); -const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); const { DiscordjsRangeError, ErrorCodes } = require('../errors/index.js'); const { GuildMessageManager } = require('../managers/GuildMessageManager.js'); const { ThreadMemberManager } = require('../managers/ThreadMemberManager.js'); const { ChannelFlagsBitField } = require('../util/ChannelFlagsBitField.js'); +const { BaseChannel } = require('./BaseChannel.js'); +const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); + +const getThreadOnlyChannel = lazy(() => require('./ThreadOnlyChannel.js')); /** * Represents a thread channel on Discord. + * * @extends {BaseChannel} * @implements {TextBasedChannel} */ @@ -21,30 +23,35 @@ class ThreadChannel extends BaseChannel { /** * The guild the thread is in + * * @type {Guild} */ this.guild = guild; /** * The id of the guild the channel is in + * * @type {Snowflake} */ this.guildId = guild?.id ?? data.guild_id; /** * The id of the member who created this thread + * * @type {Snowflake} */ this.ownerId = data.owner_id; /** * A manager of the messages sent to this thread + * * @type {GuildMessageManager} */ this.messages = new GuildMessageManager(this); /** * A manager of the members that are part of this thread + * * @type {ThreadMemberManager} */ this.members = new ThreadMemberManager(this); @@ -59,6 +66,7 @@ class ThreadChannel extends BaseChannel { if ('name' in data) { /** * The name of the thread + * * @type {string} */ this.name = data.name; @@ -71,6 +79,7 @@ class ThreadChannel extends BaseChannel { if ('parent_id' in data) { /** * The id of the parent channel of this thread + * * @type {?Snowflake} */ this.parentId = data.parent_id; @@ -81,6 +90,7 @@ class ThreadChannel extends BaseChannel { if ('thread_metadata' in data) { /** * Whether the thread is locked + * * @type {?boolean} */ this.locked = data.thread_metadata.locked ?? false; @@ -89,18 +99,21 @@ class ThreadChannel extends BaseChannel { * Whether members without the {@link PermissionFlagsBits.ManageThreads} permission * can invite other members to this thread. * This property is always `null` in public threads. + * * @type {?boolean} */ this.invitable = this.type === ChannelType.PrivateThread ? (data.thread_metadata.invitable ?? false) : null; /** * Whether the thread is archived + * * @type {?boolean} */ this.archived = data.thread_metadata.archived; /** * The amount of time (in minutes) after which the thread will automatically archive in case of no recent activity + * * @type {?ThreadAutoArchiveDuration} */ this.autoArchiveDuration = data.thread_metadata.auto_archive_duration; @@ -109,6 +122,7 @@ class ThreadChannel extends BaseChannel { * The timestamp when the thread's archive status was last changed * If the thread was never archived or unarchived, this is the timestamp at which the thread was * created + * * @type {?number} */ this.archiveTimestamp = Date.parse(data.thread_metadata.archive_timestamp); @@ -130,6 +144,7 @@ class ThreadChannel extends BaseChannel { if ('last_message_id' in data) { /** * The last message id sent in this thread, if one was sent + * * @type {?Snowflake} */ this.lastMessageId = data.last_message_id; @@ -140,6 +155,7 @@ class ThreadChannel extends BaseChannel { if ('last_pin_timestamp' in data) { /** * The timestamp when the last pinned message was pinned, if there was one + * * @type {?number} */ this.lastPinTimestamp = data.last_pin_timestamp ? Date.parse(data.last_pin_timestamp) : null; @@ -150,6 +166,7 @@ class ThreadChannel extends BaseChannel { if ('rate_limit_per_user' in data) { /** * The rate limit per user (slowmode) for this thread in seconds + * * @type {?number} */ this.rateLimitPerUser = data.rate_limit_per_user ?? 0; @@ -162,6 +179,7 @@ class ThreadChannel extends BaseChannel { * The approximate count of messages in this thread * Threads created before July 1, 2022 may have an inaccurate count. * If you need an approximate value higher than that, use `ThreadChannel#messages.cache.size` + * * @type {?number} */ this.messageCount = data.message_count; @@ -174,6 +192,7 @@ class ThreadChannel extends BaseChannel { * The approximate count of users in this thread * This stops counting at 50. If you need an approximate value higher than that, use * `ThreadChannel#members.cache.size` + * * @type {?number} */ this.memberCount = data.member_count; @@ -185,6 +204,7 @@ class ThreadChannel extends BaseChannel { /** * The number of messages ever sent in a thread, similar to {@link ThreadChannel#messageCount} except it * will not decrement whenever a message is deleted + * * @type {?number} */ this.totalMessageSent = data.total_message_sent; @@ -198,6 +218,7 @@ class ThreadChannel extends BaseChannel { if ('applied_tags' in data) { /** * The tags applied to this thread + * * @type {Snowflake[]} */ this.appliedTags = data.applied_tags; @@ -209,6 +230,7 @@ class ThreadChannel extends BaseChannel { /** * The timestamp when this thread was created. This isn't available for threads * created before 2022-01-09 + * * @type {?number} * @readonly */ @@ -218,6 +240,7 @@ class ThreadChannel extends BaseChannel { /** * A collection of associated guild member objects of this thread's members + * * @type {Collection} * @readonly */ @@ -228,6 +251,7 @@ class ThreadChannel extends BaseChannel { /** * The time at which this thread's archive status was last changed * If the thread was never archived or unarchived, this is the time at which the thread was created + * * @type {?Date} * @readonly */ @@ -237,6 +261,7 @@ class ThreadChannel extends BaseChannel { /** * The time the thread was created at + * * @type {?Date} * @readonly */ @@ -246,6 +271,7 @@ class ThreadChannel extends BaseChannel { /** * The parent channel of this thread + * * @type {?(AnnouncementChannel|TextChannel|ForumChannel|MediaChannel)} * @readonly */ @@ -255,6 +281,7 @@ class ThreadChannel extends BaseChannel { /** * Makes the client user join the thread. + * * @returns {Promise} */ async join() { @@ -264,6 +291,7 @@ class ThreadChannel extends BaseChannel { /** * Makes the client user leave the thread. + * * @returns {Promise} */ async leave() { @@ -274,8 +302,9 @@ class ThreadChannel extends BaseChannel { /** * Gets the overall set of permissions for a member or role in this thread's parent channel, taking overwrites into * account. + * * @param {UserResolvable|RoleResolvable} memberOrRole The member or role to obtain the overall permissions for - * @param {boolean} [checkAdmin=true] Whether having the {@link PermissionFlagsBits.Administrator} permission + * @param {boolean} [checkAdmin] Whether having the {@link PermissionFlagsBits.Administrator} permission * will return all permissions * @returns {?Readonly} */ @@ -285,6 +314,7 @@ class ThreadChannel extends BaseChannel { /** * Options used to fetch a thread owner. + * * @typedef {BaseFetchOptions} FetchThreadOwnerOptions * @property {boolean} [withMember] Whether to also return the guild member associated with this thread member */ @@ -292,12 +322,12 @@ class ThreadChannel extends BaseChannel { /** * Fetches the owner of this thread. If the thread member object isn't needed, * use {@link ThreadChannel#ownerId} instead. + * * @param {FetchThreadOwnerOptions} [options] Options for fetching the owner * @returns {Promise} */ async fetchOwner(options) { - const member = await this.members._fetchSingle({ ...options, member: this.ownerId }); - return member; + return this.members._fetchSingle({ ...options, member: this.ownerId }); } /** @@ -305,6 +335,7 @@ class ThreadChannel extends BaseChannel { * The `Promise` will reject if the original message in a forum post is deleted * or when the original message in the parent channel is deleted. * If you just need the id of that message, use {@link BaseChannel#id} instead. + * * @param {BaseFetchOptions} [options] Additional options for this fetch * @returns {Promise>} */ @@ -315,7 +346,8 @@ class ThreadChannel extends BaseChannel { /** * The options used to edit a thread channel - * @typedef {Object} ThreadEditOptions + * + * @typedef {object} ThreadEditOptions * @property {string} [name] The new name for the thread * @property {boolean} [archived] Whether the thread is archived * @property {ThreadAutoArchiveDuration} [autoArchiveDuration] The amount of time after which the thread @@ -331,6 +363,7 @@ class ThreadChannel extends BaseChannel { /** * Edits this thread. + * * @param {ThreadEditOptions} options The options to provide * @returns {Promise} * @example @@ -359,7 +392,8 @@ class ThreadChannel extends BaseChannel { /** * Sets whether the thread is archived. - * @param {boolean} [archived=true] Whether the thread is archived + * + * @param {boolean} [archived] Whether the thread is archived * @param {string} [reason] Reason for archiving or unarchiving * @returns {Promise} * @example @@ -368,12 +402,13 @@ class ThreadChannel extends BaseChannel { * .then(newThread => console.log(`Thread is now ${newThread.archived ? 'archived' : 'active'}`)) * .catch(console.error); */ - setArchived(archived = true, reason) { + async setArchived(archived = true, reason = undefined) { return this.edit({ archived, reason }); } /** * Sets the duration after which the thread will automatically archive in case of no recent activity. + * * @param {ThreadAutoArchiveDuration} autoArchiveDuration The amount of time after which the thread * should automatically archive in case of no recent activity * @param {string} [reason] Reason for changing the auto archive duration @@ -386,21 +421,23 @@ class ThreadChannel extends BaseChannel { * }); * .catch(console.error); */ - setAutoArchiveDuration(autoArchiveDuration, reason) { + async setAutoArchiveDuration(autoArchiveDuration, reason) { return this.edit({ autoArchiveDuration, reason }); } /** * Sets whether members without the {@link PermissionFlagsBits.ManageThreads} permission * can invite other members to this thread. - * @param {boolean} [invitable=true] Whether non-moderators can invite non-moderators to this thread + * + * @param {boolean} [invitable] Whether non-moderators can invite non-moderators to this thread * @param {string} [reason] Reason for changing invite * @returns {Promise} */ - async setInvitable(invitable = true, reason) { + async setInvitable(invitable = true, reason = undefined) { if (this.type !== ChannelType.PrivateThread) { throw new DiscordjsRangeError(ErrorCodes.ThreadInvitableType, this.type); } + return this.edit({ invitable, reason }); } @@ -408,7 +445,8 @@ class ThreadChannel extends BaseChannel { * Sets whether the thread can be **unarchived** by anyone with the * {@link PermissionFlagsBits.SendMessages} permission. When a thread is locked, only members with the * {@link PermissionFlagsBits.ManageThreads} permission can unarchive it. - * @param {boolean} [locked=true] Whether the thread is locked + * + * @param {boolean} [locked] Whether the thread is locked * @param {string} [reason] Reason for locking or unlocking the thread * @returns {Promise} * @example @@ -417,12 +455,13 @@ class ThreadChannel extends BaseChannel { * .then(newThread => console.log(`Thread is now ${newThread.locked ? 'locked' : 'unlocked'}`)) * .catch(console.error); */ - setLocked(locked = true, reason) { + async setLocked(locked = true, reason = undefined) { return this.edit({ locked, reason }); } /** * Sets a new name for this thread. + * * @param {string} name The new name for the thread * @param {string} [reason] Reason for changing the thread's name * @returns {Promise} @@ -432,50 +471,55 @@ class ThreadChannel extends BaseChannel { * .then(newThread => console.log(`Thread's new name is ${newThread.name}`)) * .catch(console.error); */ - setName(name, reason) { + async setName(name, reason) { return this.edit({ name, reason }); } /** * Sets the rate limit per user (slowmode) for this thread. + * * @param {number} rateLimitPerUser The new rate limit in seconds * @param {string} [reason] Reason for changing the thread's rate limit * @returns {Promise} */ - setRateLimitPerUser(rateLimitPerUser, reason) { + async setRateLimitPerUser(rateLimitPerUser, reason) { return this.edit({ rateLimitPerUser, reason }); } /** * Set the applied tags for this channel (only applicable to forum threads) + * * @param {Snowflake[]} appliedTags The tags to set for this channel * @param {string} [reason] Reason for changing the thread's applied tags * @returns {Promise} */ - setAppliedTags(appliedTags, reason) { + async setAppliedTags(appliedTags, reason) { return this.edit({ appliedTags, reason }); } /** * Pins this thread from the forum channel (only applicable to forum threads). + * * @param {string} [reason] Reason for pinning * @returns {Promise} */ - pin(reason) { + async pin(reason) { return this.edit({ flags: this.flags.add(ChannelFlags.Pinned), reason }); } /** * Unpins this thread from the forum channel (only applicable to forum threads). + * * @param {string} [reason] Reason for unpinning * @returns {Promise} */ - unpin(reason) { + async unpin(reason) { return this.edit({ flags: this.flags.remove(ChannelFlags.Pinned), reason }); } /** * Whether the client user is a member of the thread. + * * @type {boolean} * @readonly */ @@ -485,6 +529,7 @@ class ThreadChannel extends BaseChannel { /** * Whether the thread is editable by the client user (name, archived, autoArchiveDuration) + * * @type {boolean} * @readonly */ @@ -497,6 +542,7 @@ class ThreadChannel extends BaseChannel { /** * Whether the thread is joinable by the client user + * * @type {boolean} * @readonly */ @@ -513,6 +559,7 @@ class ThreadChannel extends BaseChannel { /** * Whether the thread is manageable by the client user, for deleting or editing rateLimitPerUser or locked. + * * @type {boolean} * @readonly */ @@ -530,6 +577,7 @@ class ThreadChannel extends BaseChannel { /** * Whether the thread is viewable by the client user + * * @type {boolean} * @readonly */ @@ -542,6 +590,7 @@ class ThreadChannel extends BaseChannel { /** * Whether the client user can send messages in this thread + * * @type {boolean} * @readonly */ @@ -561,6 +610,7 @@ class ThreadChannel extends BaseChannel { /** * Whether the thread is unarchivable by the client user + * * @type {boolean} * @readonly */ @@ -570,6 +620,7 @@ class ThreadChannel extends BaseChannel { /** * Deletes this thread. + * * @param {string} [reason] Reason for deleting this thread * @returns {Promise} * @example @@ -584,15 +635,23 @@ class ThreadChannel extends BaseChannel { } // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ + get lastMessage() {} + get lastPinAt() {} + send() {} + sendTyping() {} + createMessageCollector() {} + awaitMessages() {} + createMessageComponentCollector() {} + awaitMessageComponent() {} + bulkDelete() {} // Doesn't work on Thread channels; setRateLimitPerUser() {} // Doesn't work on Thread channels; setNSFW() {} diff --git a/packages/discord.js/src/structures/ThreadMember.js b/packages/discord.js/src/structures/ThreadMember.js index e308d821ac52..047ba212d345 100644 --- a/packages/discord.js/src/structures/ThreadMember.js +++ b/packages/discord.js/src/structures/ThreadMember.js @@ -1,10 +1,11 @@ 'use strict'; -const { Base } = require('./Base.js'); const { ThreadMemberFlagsBitField } = require('../util/ThreadMemberFlagsBitField.js'); +const { Base } = require('./Base.js'); /** * Represents a Member for a Thread. + * * @extends {Base} */ class ThreadMember extends Base { @@ -13,24 +14,28 @@ class ThreadMember extends Base { /** * The thread that this member is a part of + * * @type {ThreadChannel} */ this.thread = thread; /** * The timestamp the member last joined the thread at + * * @type {?number} */ this.joinedTimestamp = null; /** * The flags for this thread member. This will be `null` if partial. + * * @type {?ThreadMemberFlagsBitField} */ this.flags = null; /** * The id of the thread member + * * @type {Snowflake} */ this.id = data.user_id; @@ -45,6 +50,7 @@ class ThreadMember extends Base { if ('member' in data) { /** * The guild member associated with this thread member. + * * @type {?GuildMember} * @private */ @@ -56,6 +62,7 @@ class ThreadMember extends Base { /** * Whether this thread member is a partial + * * @type {boolean} * @readonly */ @@ -65,6 +72,7 @@ class ThreadMember extends Base { /** * The guild member associated with this thread member + * * @type {?GuildMember} * @readonly */ @@ -74,6 +82,7 @@ class ThreadMember extends Base { /** * The last time this member joined the thread + * * @type {?Date} * @readonly */ @@ -83,6 +92,7 @@ class ThreadMember extends Base { /** * The user associated with this thread member + * * @type {?User} * @readonly */ @@ -92,6 +102,7 @@ class ThreadMember extends Base { /** * Whether the client user can manage this thread member + * * @type {boolean} * @readonly */ @@ -101,6 +112,7 @@ class ThreadMember extends Base { /** * Removes this member from the thread. + * * @returns {Promise} */ async remove() { diff --git a/packages/discord.js/src/structures/ThreadOnlyChannel.js b/packages/discord.js/src/structures/ThreadOnlyChannel.js index e7bfbdb17333..6955ba7a845b 100644 --- a/packages/discord.js/src/structures/ThreadOnlyChannel.js +++ b/packages/discord.js/src/structures/ThreadOnlyChannel.js @@ -1,18 +1,18 @@ 'use strict'; -const { GuildChannel } = require('./GuildChannel.js'); -const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); const { GuildForumThreadManager } = require('../managers/GuildForumThreadManager.js'); const { transformAPIGuildForumTag, transformAPIGuildDefaultReaction } = require('../util/Channels.js'); +const { GuildChannel } = require('./GuildChannel.js'); +const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); /** - * @typedef {Object} GuildForumTagEmoji + * @typedef {object} GuildForumTagEmoji * @property {?Snowflake} id The id of a guild's custom emoji * @property {?string} name The unicode character of the emoji */ /** - * @typedef {Object} GuildForumTag + * @typedef {object} GuildForumTag * @property {Snowflake} id The id of the tag * @property {string} name The name of the tag * @property {boolean} moderated Whether this tag can only be added to or removed from threads @@ -21,7 +21,7 @@ const { transformAPIGuildForumTag, transformAPIGuildDefaultReaction } = require( */ /** - * @typedef {Object} GuildForumTagData + * @typedef {object} GuildForumTagData * @property {Snowflake} [id] The id of the tag * @property {string} name The name of the tag * @property {boolean} [moderated] Whether this tag can only be added to or removed from threads @@ -30,13 +30,14 @@ const { transformAPIGuildForumTag, transformAPIGuildDefaultReaction } = require( */ /** - * @typedef {Object} DefaultReactionEmoji + * @typedef {object} DefaultReactionEmoji * @property {?Snowflake} id The id of a guild's custom emoji * @property {?string} name The unicode character of the emoji */ /** * Represents symbols utilized by thread-only channels. + * * @extends {GuildChannel} * @implements {TextBasedChannel} * @abstract @@ -47,6 +48,7 @@ class ThreadOnlyChannel extends GuildChannel { /** * A manager of the threads belonging to this channel + * * @type {GuildForumThreadManager} */ this.threads = new GuildForumThreadManager(this); @@ -59,6 +61,7 @@ class ThreadOnlyChannel extends GuildChannel { if ('available_tags' in data) { /** * The set of tags that can be used in this channel. + * * @type {GuildForumTag[]} */ this.availableTags = data.available_tags.map(tag => transformAPIGuildForumTag(tag)); @@ -69,6 +72,7 @@ class ThreadOnlyChannel extends GuildChannel { if ('default_reaction_emoji' in data) { /** * The emoji to show in the add reaction button on a thread in a guild forum channel + * * @type {?DefaultReactionEmoji} */ this.defaultReactionEmoji = data.default_reaction_emoji @@ -81,6 +85,7 @@ class ThreadOnlyChannel extends GuildChannel { if ('default_thread_rate_limit_per_user' in data) { /** * The initial rate limit per user (slowmode) to set on newly created threads in a channel. + * * @type {?number} */ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user; @@ -91,6 +96,7 @@ class ThreadOnlyChannel extends GuildChannel { if ('rate_limit_per_user' in data) { /** * The rate limit per user (slowmode) for this channel. + * * @type {?number} */ this.rateLimitPerUser = data.rate_limit_per_user; @@ -101,6 +107,7 @@ class ThreadOnlyChannel extends GuildChannel { if ('default_auto_archive_duration' in data) { /** * The default auto archive duration for newly created threads in this channel. + * * @type {?ThreadAutoArchiveDuration} */ this.defaultAutoArchiveDuration = data.default_auto_archive_duration; @@ -111,6 +118,7 @@ class ThreadOnlyChannel extends GuildChannel { if ('nsfw' in data) { /** * If this channel is considered NSFW. + * * @type {boolean} */ this.nsfw = data.nsfw; @@ -121,6 +129,7 @@ class ThreadOnlyChannel extends GuildChannel { if ('topic' in data) { /** * The topic of this channel. + * * @type {?string} */ this.topic = data.topic; @@ -129,6 +138,7 @@ class ThreadOnlyChannel extends GuildChannel { if ('default_sort_order' in data) { /** * The default sort order mode used to order posts + * * @type {?SortOrderType} */ this.defaultSortOrder = data.default_sort_order; @@ -139,37 +149,41 @@ class ThreadOnlyChannel extends GuildChannel { /** * Sets the available tags for this forum channel + * * @param {GuildForumTagData[]} availableTags The tags to set as available in this channel * @param {string} [reason] Reason for changing the available tags * @returns {Promise} */ - setAvailableTags(availableTags, reason) { + async setAvailableTags(availableTags, reason) { return this.edit({ availableTags, reason }); } /** * Sets the default reaction emoji for this channel + * * @param {?DefaultReactionEmoji} defaultReactionEmoji The emoji to set as the default reaction emoji * @param {string} [reason] Reason for changing the default reaction emoji * @returns {Promise} */ - setDefaultReactionEmoji(defaultReactionEmoji, reason) { + async setDefaultReactionEmoji(defaultReactionEmoji, reason) { return this.edit({ defaultReactionEmoji, reason }); } /** * Sets the default rate limit per user (slowmode) for new threads in this channel + * * @param {number} defaultThreadRateLimitPerUser The rate limit to set on newly created threads in this channel * @param {string} [reason] Reason for changing the default rate limit * @returns {Promise} */ - setDefaultThreadRateLimitPerUser(defaultThreadRateLimitPerUser, reason) { + async setDefaultThreadRateLimitPerUser(defaultThreadRateLimitPerUser, reason) { return this.edit({ defaultThreadRateLimitPerUser, reason }); } /** * Creates an invite to this guild channel. - * @param {InviteCreateOptions} [options={}] The options for creating the invite + * + * @param {InviteCreateOptions} [options] The options for creating the invite * @returns {Promise} * @example * // Create an invite to a channel @@ -177,32 +191,35 @@ class ThreadOnlyChannel extends GuildChannel { * .then(invite => console.log(`Created an invite with a code of ${invite.code}`)) * .catch(console.error); */ - createInvite(options) { + async createInvite(options) { return this.guild.invites.create(this.id, options); } /** * Fetches a collection of invites to this guild channel. * Resolves with a collection mapping invites by their codes. - * @param {boolean} [cache=true] Whether to cache the fetched invites + * + * @param {boolean} [cache] Whether to cache the fetched invites * @returns {Promise>} */ - fetchInvites(cache) { + async fetchInvites(cache) { return this.guild.invites.fetch({ channelId: this.id, cache }); } /** * Sets the default auto archive duration for all newly created threads in this channel. + * * @param {ThreadAutoArchiveDuration} defaultAutoArchiveDuration The new default auto archive duration * @param {string} [reason] Reason for changing the channel's default auto archive duration * @returns {Promise} */ - setDefaultAutoArchiveDuration(defaultAutoArchiveDuration, reason) { + async setDefaultAutoArchiveDuration(defaultAutoArchiveDuration, reason) { return this.edit({ defaultAutoArchiveDuration, reason }); } /** * Sets a new topic for the guild channel. + * * @param {?string} topic The new topic for the guild channel * @param {string} [reason] Reason for changing the guild channel's topic * @returns {Promise} @@ -212,25 +229,29 @@ class ThreadOnlyChannel extends GuildChannel { * .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`)) * .catch(console.error); */ - setTopic(topic, reason) { + async setTopic(topic, reason) { return this.edit({ topic, reason }); } /** * Sets the default sort order mode used to order posts + * * @param {?SortOrderType} defaultSortOrder The default sort order mode to set on this channel * @param {string} [reason] Reason for changing the default sort order * @returns {Promise} */ - setDefaultSortOrder(defaultSortOrder, reason) { + async setDefaultSortOrder(defaultSortOrder, reason) { return this.edit({ defaultSortOrder, reason }); } // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ + createWebhook() {} + fetchWebhooks() {} + setNSFW() {} + setRateLimitPerUser() {} } diff --git a/packages/discord.js/src/structures/Typing.js b/packages/discord.js/src/structures/Typing.js index 6fdc0c865b11..c97c36060df4 100644 --- a/packages/discord.js/src/structures/Typing.js +++ b/packages/discord.js/src/structures/Typing.js @@ -4,6 +4,7 @@ const { Base } = require('./Base.js'); /** * Represents a typing state for a user in a channel. + * * @extends {Base} */ class Typing extends Base { @@ -12,12 +13,14 @@ class Typing extends Base { /** * The channel the status is from + * * @type {TextBasedChannels} */ this.channel = channel; /** * The user who is typing + * * @type {User} */ this.user = user; @@ -29,6 +32,7 @@ class Typing extends Base { if ('timestamp' in data) { /** * The UNIX timestamp in milliseconds the user started typing at + * * @type {number} */ this.startedTimestamp = data.timestamp * 1_000; @@ -37,6 +41,7 @@ class Typing extends Base { /** * Indicates whether the status is received from a guild. + * * @returns {boolean} */ inGuild() { @@ -45,6 +50,7 @@ class Typing extends Base { /** * The time the user started typing at + * * @type {Date} * @readonly */ @@ -54,6 +60,7 @@ class Typing extends Base { /** * The guild the status is from + * * @type {?Guild} * @readonly */ @@ -63,6 +70,7 @@ class Typing extends Base { /** * The member who is typing + * * @type {?GuildMember} * @readonly */ diff --git a/packages/discord.js/src/structures/User.js b/packages/discord.js/src/structures/User.js index 77be3c18f44d..4bcd228a63b1 100644 --- a/packages/discord.js/src/structures/User.js +++ b/packages/discord.js/src/structures/User.js @@ -3,11 +3,12 @@ const { userMention } = require('@discordjs/formatters'); const { calculateUserDefaultAvatarIndex } = require('@discordjs/rest'); const { DiscordSnowflake } = require('@sapphire/snowflake'); -const { Base } = require('./Base.js'); const { UserFlagsBitField } = require('../util/UserFlagsBitField.js'); +const { Base } = require('./Base.js'); /** * Represents a user on Discord. + * * @extends {Base} */ class User extends Base { @@ -16,6 +17,7 @@ class User extends Base { /** * The user's id + * * @type {Snowflake} */ this.id = data.id; @@ -33,6 +35,7 @@ class User extends Base { if ('username' in data) { /** * The username of the user + * * @type {?string} */ this.username = data.username; @@ -43,6 +46,7 @@ class User extends Base { if ('global_name' in data) { /** * The global name of this user + * * @type {?string} */ this.globalName = data.global_name; @@ -53,6 +57,7 @@ class User extends Base { if ('bot' in data) { /** * Whether or not the user is a bot + * * @type {?boolean} */ this.bot = Boolean(data.bot); @@ -64,6 +69,7 @@ class User extends Base { /** * The discriminator of this user * `'0'`, or a 4-digit stringified number if they're using the legacy username system + * * @type {?string} */ this.discriminator = data.discriminator; @@ -74,6 +80,7 @@ class User extends Base { if ('avatar' in data) { /** * The user avatar's hash + * * @type {?string} */ this.avatar = data.avatar; @@ -85,6 +92,7 @@ class User extends Base { /** * The user banner's hash * The user must be force fetched for this property to be present or be updated + * * @type {?string} */ this.banner = data.banner; @@ -96,6 +104,7 @@ class User extends Base { /** * The base 10 accent color of the user's banner * The user must be force fetched for this property to be present or be updated + * * @type {?number} */ this.accentColor = data.accent_color; @@ -106,6 +115,7 @@ class User extends Base { if ('system' in data) { /** * Whether the user is an Official Discord System user (part of the urgent message system) + * * @type {?boolean} */ this.system = Boolean(data.system); @@ -116,13 +126,14 @@ class User extends Base { if ('public_flags' in data) { /** * The flags for this user + * * @type {?UserFlagsBitField} */ this.flags = new UserFlagsBitField(data.public_flags); } /** - * @typedef {Object} AvatarDecorationData + * @typedef {object} AvatarDecorationData * @property {string} asset The avatar decoration hash * @property {Snowflake} skuId The id of the avatar decoration's SKU */ @@ -130,6 +141,7 @@ class User extends Base { if (data.avatar_decoration_data) { /** * The user avatar decoration's data + * * @type {?AvatarDecorationData} */ this.avatarDecorationData = { @@ -143,6 +155,7 @@ class User extends Base { /** * Whether this User is a partial + * * @type {boolean} * @readonly */ @@ -152,6 +165,7 @@ class User extends Base { /** * The timestamp the user was created at + * * @type {number} * @readonly */ @@ -161,6 +175,7 @@ class User extends Base { /** * The time the user was created at + * * @type {Date} * @readonly */ @@ -170,7 +185,8 @@ class User extends Base { /** * A link to the user's avatar. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ avatarURL(options = {}) { @@ -179,6 +195,7 @@ class User extends Base { /** * A link to the user's avatar decoration. + * * @returns {?string} */ avatarDecorationURL() { @@ -187,6 +204,7 @@ class User extends Base { /** * A link to the user's default avatar + * * @type {string} * @readonly */ @@ -198,7 +216,8 @@ class User extends Base { /** * A link to the user's avatar if they have one. * Otherwise a link to their default avatar will be returned. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {string} */ displayAvatarURL(options) { @@ -208,6 +227,7 @@ class User extends Base { /** * The hexadecimal version of the user accent color, with a leading hash * The user must be force fetched for this property to be present + * * @type {?string} * @readonly */ @@ -218,7 +238,8 @@ class User extends Base { /** * A link to the user's banner. See {@link User#banner} for more info - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ bannerURL(options = {}) { @@ -229,6 +250,7 @@ class User extends Base { * The tag of this user * This user's username, or their legacy tag (e.g. `hydrabolt#0001`) * if they're using the legacy username system + * * @type {?string} * @readonly */ @@ -242,6 +264,7 @@ class User extends Base { /** * The global name of this user, or their username if they don't have one + * * @type {?string} * @readonly */ @@ -251,6 +274,7 @@ class User extends Base { /** * The DM between the client's user and this user + * * @type {?DMChannel} * @readonly */ @@ -260,23 +284,26 @@ class User extends Base { /** * Creates a DM channel between the client and the user. - * @param {boolean} [force=false] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - createDM(force = false) { + async createDM(force = false) { return this.client.users.createDM(this.id, { force }); } /** * Deletes a DM channel (if one exists) between the client and the user. Resolves with the channel if successful. + * * @returns {Promise} */ - deleteDM() { + async deleteDM() { return this.client.users.deleteDM(this.id); } /** * Sends a message to this user. + * * @param {string|MessagePayload|MessageCreateOptions} options The options to provide * @returns {Promise} * @example @@ -295,6 +322,7 @@ class User extends Base { * Checks if the user is equal to another. * It compares id, username, discriminator, avatar, banner, accent color, and bot flags. * It is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties. + * * @param {User} user User to compare with * @returns {boolean} */ @@ -316,6 +344,7 @@ class User extends Base { /** * Compares the user with an API user object + * * @param {APIUser} user The API user object to compare * @returns {boolean} * @private @@ -340,15 +369,17 @@ class User extends Base { /** * Fetches this user. - * @param {boolean} [force=true] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - fetch(force = true) { + async fetch(force = true) { return this.client.users.fetch(this.id, { force }); } /** * When concatenated with a string, this automatically returns the user's mention instead of the User object. + * * @returns {string} * @example * // Logs: Hello from <@123456789012345678>! diff --git a/packages/discord.js/src/structures/UserContextMenuCommandInteraction.js b/packages/discord.js/src/structures/UserContextMenuCommandInteraction.js index a8a16d8863cb..bd1704b7e767 100644 --- a/packages/discord.js/src/structures/UserContextMenuCommandInteraction.js +++ b/packages/discord.js/src/structures/UserContextMenuCommandInteraction.js @@ -4,11 +4,13 @@ const { ContextMenuCommandInteraction } = require('./ContextMenuCommandInteracti /** * Represents a user context menu interaction. + * * @extends {ContextMenuCommandInteraction} */ class UserContextMenuCommandInteraction extends ContextMenuCommandInteraction { /** * The target user from this interaction + * * @type {User} * @readonly */ @@ -18,6 +20,7 @@ class UserContextMenuCommandInteraction extends ContextMenuCommandInteraction { /** * The target member from this interaction + * * @type {?(GuildMember|APIGuildMember)} * @readonly */ diff --git a/packages/discord.js/src/structures/UserSelectMenuComponent.js b/packages/discord.js/src/structures/UserSelectMenuComponent.js index 0a11d2b8ef0e..0bbf62ea0af8 100644 --- a/packages/discord.js/src/structures/UserSelectMenuComponent.js +++ b/packages/discord.js/src/structures/UserSelectMenuComponent.js @@ -4,6 +4,7 @@ const { BaseSelectMenuComponent } = require('./BaseSelectMenuComponent.js'); /** * Represents a user select menu component + * * @extends {BaseSelectMenuComponent} */ class UserSelectMenuComponent extends BaseSelectMenuComponent {} diff --git a/packages/discord.js/src/structures/UserSelectMenuInteraction.js b/packages/discord.js/src/structures/UserSelectMenuInteraction.js index 9b1d847a104c..a418c772982d 100644 --- a/packages/discord.js/src/structures/UserSelectMenuInteraction.js +++ b/packages/discord.js/src/structures/UserSelectMenuInteraction.js @@ -1,11 +1,12 @@ 'use strict'; const { Collection } = require('@discordjs/collection'); -const { MessageComponentInteraction } = require('./MessageComponentInteraction.js'); const { Events } = require('../util/Events.js'); +const { MessageComponentInteraction } = require('./MessageComponentInteraction.js'); /** * Represents a {@link ComponentType.UserSelect} select menu interaction. + * * @extends {MessageComponentInteraction} */ class UserSelectMenuInteraction extends MessageComponentInteraction { @@ -15,18 +16,21 @@ class UserSelectMenuInteraction extends MessageComponentInteraction { /** * An array of the selected user ids + * * @type {Snowflake[]} */ this.values = values ?? []; /** * Collection of the selected users + * * @type {Collection} */ this.users = new Collection(); /** * Collection of the selected members + * * @type {Collection} */ this.members = new Collection(); diff --git a/packages/discord.js/src/structures/VoiceChannel.js b/packages/discord.js/src/structures/VoiceChannel.js index 96f80ae3b79d..5b56a67e724c 100644 --- a/packages/discord.js/src/structures/VoiceChannel.js +++ b/packages/discord.js/src/structures/VoiceChannel.js @@ -5,22 +5,24 @@ const { BaseGuildVoiceChannel } = require('./BaseGuildVoiceChannel.js'); /** * Represents a guild voice channel on Discord. + * * @extends {BaseGuildVoiceChannel} */ class VoiceChannel extends BaseGuildVoiceChannel { /** * Whether the channel is joinable by the client user + * * @type {boolean} * @readonly */ get joinable() { if (!super.joinable) return false; - if (this.full && !this.permissionsFor(this.client.user).has(PermissionFlagsBits.MoveMembers, false)) return false; - return true; + return !this.full || this.permissionsFor(this.client.user).has(PermissionFlagsBits.MoveMembers, false); } /** * Checks if the client has permission to send audio to the voice channel + * * @type {boolean} * @readonly */ @@ -37,13 +39,14 @@ class VoiceChannel extends BaseGuildVoiceChannel { } /** - * @typedef {Object} SendSoundboardSoundOptions + * @typedef {object} SendSoundboardSoundOptions * @property {string} soundId The id of the soundboard sound to send * @property {string} [guildId] The id of the guild the soundboard sound is a part of */ /** * Send a soundboard sound to a voice channel the user is connected to. + * * @param {SoundboardSound|SendSoundboardSoundOptions} sound The sound to send * @returns {Promise} */ @@ -59,6 +62,7 @@ class VoiceChannel extends BaseGuildVoiceChannel { /** * Sets the bitrate of the channel. + * * @method setBitrate * @memberof VoiceChannel * @instance @@ -74,6 +78,7 @@ class VoiceChannel extends BaseGuildVoiceChannel { /** * Sets the RTC region of the channel. + * * @method setRTCRegion * @memberof VoiceChannel * @instance @@ -90,6 +95,7 @@ class VoiceChannel extends BaseGuildVoiceChannel { /** * Sets the user limit of the channel. + * * @method setUserLimit * @memberof VoiceChannel * @instance @@ -105,6 +111,7 @@ class VoiceChannel extends BaseGuildVoiceChannel { /** * Sets the camera video quality mode of the channel. + * * @method setVideoQualityMode * @memberof VoiceChannel * @instance diff --git a/packages/discord.js/src/structures/VoiceChannelEffect.js b/packages/discord.js/src/structures/VoiceChannelEffect.js index 3365ab5937fe..7c4ee8b816a5 100644 --- a/packages/discord.js/src/structures/VoiceChannelEffect.js +++ b/packages/discord.js/src/structures/VoiceChannelEffect.js @@ -9,48 +9,56 @@ class VoiceChannelEffect { constructor(data, guild) { /** * The guild where the effect was sent from. + * * @type {Guild} */ this.guild = guild; /** * The id of the channel the effect was sent in. + * * @type {Snowflake} */ this.channelId = data.channel_id; /** * The id of the user that sent the effect. + * * @type {Snowflake} */ this.userId = data.user_id; /** * The emoji of the effect. + * * @type {?Emoji} */ this.emoji = data.emoji ? new Emoji(guild.client, data.emoji) : null; /** * The animation type of the effect. + * * @type {?VoiceChannelEffectSendAnimationType} */ this.animationType = data.animation_type ?? null; /** * The animation id of the effect. + * * @type {?number} */ this.animationId = data.animation_id ?? null; /** * The id of the soundboard sound for soundboard effects. + * * @type {?(Snowflake|number)} */ this.soundId = data.sound_id ?? null; /** * The volume of the soundboard sound [0-1] for soundboard effects. + * * @type {?number} */ this.soundVolume = data.sound_volume ?? null; @@ -58,6 +66,7 @@ class VoiceChannelEffect { /** * The channel the effect was sent in. + * * @type {?VoiceChannel} * @readonly */ @@ -67,6 +76,7 @@ class VoiceChannelEffect { /** * The soundboard sound for soundboard effects. + * * @type {?SoundboardSound} * @readonly */ diff --git a/packages/discord.js/src/structures/VoiceRegion.js b/packages/discord.js/src/structures/VoiceRegion.js index dc50bcfd4ff6..79376f206f99 100644 --- a/packages/discord.js/src/structures/VoiceRegion.js +++ b/packages/discord.js/src/structures/VoiceRegion.js @@ -9,30 +9,35 @@ class VoiceRegion { constructor(data) { /** * The region's id + * * @type {string} */ this.id = data.id; /** * Name of the region + * * @type {string} */ this.name = data.name; /** * Whether the region is deprecated + * * @type {boolean} */ this.deprecated = data.deprecated; /** * Whether the region is optimal + * * @type {boolean} */ this.optimal = data.optimal; /** * Whether the region is custom + * * @type {boolean} */ this.custom = data.custom; diff --git a/packages/discord.js/src/structures/VoiceState.js b/packages/discord.js/src/structures/VoiceState.js index 31fc37b832b4..df41f69e14a4 100644 --- a/packages/discord.js/src/structures/VoiceState.js +++ b/packages/discord.js/src/structures/VoiceState.js @@ -1,11 +1,13 @@ +/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */ 'use strict'; const { ChannelType, Routes } = require('discord-api-types/v10'); -const { Base } = require('./Base.js'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); +const { Base } = require('./Base.js'); /** * Represents the voice state for a Guild Member. + * * @extends {Base} */ class VoiceState extends Base { @@ -13,11 +15,13 @@ class VoiceState extends Base { super(guild.client); /** * The guild of this voice state + * * @type {Guild} */ this.guild = guild; /** * The id of the member of this voice state + * * @type {Snowflake} */ this.id = data.user_id; @@ -28,6 +32,7 @@ class VoiceState extends Base { if ('deaf' in data) { /** * Whether this member is deafened server-wide + * * @type {?boolean} */ this.serverDeaf = data.deaf; @@ -38,6 +43,7 @@ class VoiceState extends Base { if ('mute' in data) { /** * Whether this member is muted server-wide + * * @type {?boolean} */ this.serverMute = data.mute; @@ -48,6 +54,7 @@ class VoiceState extends Base { if ('self_deaf' in data) { /** * Whether this member is self-deafened + * * @type {?boolean} */ this.selfDeaf = data.self_deaf; @@ -58,6 +65,7 @@ class VoiceState extends Base { if ('self_mute' in data) { /** * Whether this member is self-muted + * * @type {?boolean} */ this.selfMute = data.self_mute; @@ -68,6 +76,7 @@ class VoiceState extends Base { if ('self_video' in data) { /** * Whether this member's camera is enabled + * * @type {?boolean} */ this.selfVideo = data.self_video; @@ -78,6 +87,7 @@ class VoiceState extends Base { if ('session_id' in data) { /** * The session id for this member's connection + * * @type {?string} */ this.sessionId = data.session_id; @@ -90,6 +100,7 @@ class VoiceState extends Base { if ('self_video' in data) { /** * Whether this member is streaming using "Screen Share" + * * @type {?boolean} */ this.streaming = data.self_stream ?? false; @@ -100,6 +111,7 @@ class VoiceState extends Base { if ('channel_id' in data) { /** * The {@link VoiceChannel} or {@link StageChannel} id the member is in + * * @type {?Snowflake} */ this.channelId = data.channel_id; @@ -110,6 +122,7 @@ class VoiceState extends Base { if ('suppress' in data) { /** * Whether this member is suppressed from speaking. This property is specific to stage channels only. + * * @type {?boolean} */ this.suppress = data.suppress; @@ -120,6 +133,7 @@ class VoiceState extends Base { if ('request_to_speak_timestamp' in data) { /** * The time at which the member requested to speak. This property is specific to stage channels only. + * * @type {?number} */ this.requestToSpeakTimestamp = data.request_to_speak_timestamp && Date.parse(data.request_to_speak_timestamp); @@ -132,6 +146,7 @@ class VoiceState extends Base { /** * The member that this voice state belongs to + * * @type {?GuildMember} * @readonly */ @@ -141,6 +156,7 @@ class VoiceState extends Base { /** * The channel that the member is connected to + * * @type {?(VoiceChannel|StageChannel)} * @readonly */ @@ -150,6 +166,7 @@ class VoiceState extends Base { /** * Whether this member is either self-deafened or server-deafened + * * @type {?boolean} * @readonly */ @@ -159,6 +176,7 @@ class VoiceState extends Base { /** * Whether this member is either self-muted or server-muted + * * @type {?boolean} * @readonly */ @@ -168,47 +186,52 @@ class VoiceState extends Base { /** * Mutes/unmutes the member of this voice state. - * @param {boolean} [mute=true] Whether or not the member should be muted + * + * @param {boolean} [mute] Whether or not the member should be muted * @param {string} [reason] Reason for muting or unmuting * @returns {Promise} */ - setMute(mute = true, reason) { + async setMute(mute = true, reason = undefined) { return this.guild.members.edit(this.id, { mute, reason }); } /** * Deafens/undeafens the member of this voice state. - * @param {boolean} [deaf=true] Whether or not the member should be deafened + * + * @param {boolean} [deaf] Whether or not the member should be deafened * @param {string} [reason] Reason for deafening or undeafening * @returns {Promise} */ - setDeaf(deaf = true, reason) { + async setDeaf(deaf = true, reason = undefined) { return this.guild.members.edit(this.id, { deaf, reason }); } /** * Disconnects the member from the channel. + * * @param {string} [reason] Reason for disconnecting the member from the channel * @returns {Promise} */ - disconnect(reason) { + async disconnect(reason) { return this.setChannel(null, reason); } /** * Moves the member to a different channel, or disconnects them from the one they're in. + * * @param {?GuildVoiceChannelResolvable} channel Channel to move the member to, or `null` if you want to * disconnect them from voice. * @param {string} [reason] Reason for moving member to another channel or disconnecting * @returns {Promise} */ - setChannel(channel, reason) { + async setChannel(channel, reason) { return this.guild.members.edit(this.id, { channel, reason }); } /** * Data to edit the logged in user's own voice state with, when in a stage channel - * @typedef {Object} VoiceStateEditOptions + * + * @typedef {object} VoiceStateEditOptions * @property {boolean} [requestToSpeak] Whether or not the client is requesting to become a speaker. * Only available to the logged in user's own voice state. * @property {boolean} [suppressed] Whether or not the user should be suppressed. @@ -216,6 +239,7 @@ class VoiceState extends Base { /** * Edits this voice state. Currently only available when in a stage channel + * * @param {VoiceStateEditOptions} options The options to provide * @returns {Promise} */ @@ -252,17 +276,19 @@ class VoiceState extends Base { /** * Fetches this voice state. - * @param {boolean} [force=true] Whether to skip the cache check and request the API + * + * @param {boolean} [force] Whether to skip the cache check and request the API * @returns {Promise} */ - fetch(force = true) { + async fetch(force = true) { return this.guild.voiceStates.fetch(this.id, { force }); } /** * Toggles the request to speak in the channel. * Only applicable for stage channels and for the client's own voice state. - * @param {boolean} [requestToSpeak=true] Whether or not the client is requesting to become a speaker. + * + * @param {boolean} [requestToSpeak] Whether or not the client is requesting to become a speaker. * @example * // Making the client request to speak in a stage channel (raise its hand) * guild.members.me.voice.setRequestToSpeak(true); @@ -271,13 +297,14 @@ class VoiceState extends Base { * guild.members.me.voice.setRequestToSpeak(false); * @returns {Promise} */ - setRequestToSpeak(requestToSpeak = true) { + async setRequestToSpeak(requestToSpeak = true) { return this.edit({ requestToSpeak }); } /** * Suppress/unsuppress the user. Only applicable for stage channels. - * @param {boolean} [suppressed=true] Whether or not the user should be suppressed. + * + * @param {boolean} [suppressed] Whether or not the user should be suppressed. * @example * // Making the client a speaker * guild.members.me.voice.setSuppressed(false); @@ -292,7 +319,7 @@ class VoiceState extends Base { * voiceState.setSuppressed(true); * @returns {Promise} */ - setSuppressed(suppressed = true) { + async setSuppressed(suppressed = true) { return this.edit({ suppressed }); } diff --git a/packages/discord.js/src/structures/Webhook.js b/packages/discord.js/src/structures/Webhook.js index 299f7085060c..3debd06eddc9 100644 --- a/packages/discord.js/src/structures/Webhook.js +++ b/packages/discord.js/src/structures/Webhook.js @@ -4,9 +4,9 @@ const { makeURLSearchParams } = require('@discordjs/rest'); const { lazy } = require('@discordjs/util'); const { DiscordSnowflake } = require('@sapphire/snowflake'); const { Routes, WebhookType } = require('discord-api-types/v10'); -const { MessagePayload } = require('./MessagePayload.js'); const { DiscordjsError, ErrorCodes } = require('../errors/index.js'); const { resolveImage } = require('../util/DataResolver.js'); +const { MessagePayload } = require('./MessagePayload.js'); const getMessage = lazy(() => require('./Message.js').Message); @@ -17,6 +17,7 @@ class Webhook { constructor(client, data) { /** * The client that instantiated the webhook + * * @name Webhook#client * @type {Client} * @readonly @@ -29,6 +30,7 @@ class Webhook { if ('name' in data) { /** * The name of the webhook + * * @type {string} */ this.name = data.name; @@ -36,6 +38,7 @@ class Webhook { /** * The token for the webhook, unavailable for follower webhooks and webhooks owned by another application. + * * @name Webhook#token * @type {?string} */ @@ -48,6 +51,7 @@ class Webhook { if ('avatar' in data) { /** * The avatar for the webhook + * * @type {?string} */ this.avatar = data.avatar; @@ -55,6 +59,7 @@ class Webhook { /** * The webhook's id + * * @type {Snowflake} */ this.id = data.id; @@ -62,6 +67,7 @@ class Webhook { if ('type' in data) { /** * The type of the webhook + * * @type {WebhookType} */ this.type = data.type; @@ -70,6 +76,7 @@ class Webhook { if ('guild_id' in data) { /** * The guild the webhook belongs to + * * @type {Snowflake} */ this.guildId = data.guild_id; @@ -78,6 +85,7 @@ class Webhook { if ('channel_id' in data) { /** * The id of the channel the webhook belongs to + * * @type {Snowflake} */ this.channelId = data.channel_id; @@ -86,6 +94,7 @@ class Webhook { if ('user' in data) { /** * The owner of the webhook + * * @type {?(User|APIUser)} */ this.owner = this.client.users?._add(data.user) ?? data.user; @@ -96,6 +105,7 @@ class Webhook { if ('application_id' in data) { /** * The application that created this webhook + * * @type {?Snowflake} */ this.applicationId = data.application_id; @@ -106,6 +116,7 @@ class Webhook { if ('source_guild' in data) { /** * The source guild of the webhook + * * @type {?(Guild|APIGuild)} */ this.sourceGuild = this.client.guilds?.cache.get(data.source_guild.id) ?? data.source_guild; @@ -116,6 +127,7 @@ class Webhook { if ('source_channel' in data) { /** * The source channel of the webhook + * * @type {?(AnnouncementChannel|APIChannel)} */ this.sourceChannel = this.client.channels?.cache.get(data.source_channel?.id) ?? data.source_channel; @@ -126,6 +138,7 @@ class Webhook { /** * Options that can be passed into send. + * * @typedef {BaseMessageOptionsWithPoll} WebhookMessageCreateOptions * @property {boolean} [tts=false] Whether the message should be spoken aloud * @property {MessageFlags} [flags] Which flags to set for the message. @@ -143,6 +156,7 @@ class Webhook { /** * Options that can be passed into editMessage. + * * @typedef {MessageEditOptions} WebhookMessageEditOptions * @property {Snowflake} [threadId] The id of the thread this message belongs to * For interaction webhooks, this property is ignored @@ -152,6 +166,7 @@ class Webhook { /** * The channel the webhook belongs to + * * @type {?(TextChannel|VoiceChannel|StageChannel|AnnouncementChannel|ForumChannel|MediaChannel)} * @readonly */ @@ -161,6 +176,7 @@ class Webhook { /** * Sends a message with this webhook. + * * @param {string|MessagePayload|WebhookMessageCreateOptions} options The options to provide * @returns {Promise} * @example @@ -225,20 +241,23 @@ class Webhook { }); const { body, files } = await messagePayload.resolveFiles(); - const d = await this.client.rest.post(Routes.webhook(this.id, this.token), { + const data = await this.client.rest.post(Routes.webhook(this.id, this.token), { body, files, query, auth: false, }); - if (!this.client.channels) return d; - return this.client.channels.cache.get(d.channel_id)?.messages._add(d, false) ?? new (getMessage())(this.client, d); + if (!this.client.channels) return data; + return ( + this.client.channels.cache.get(d.channel_id)?.messages._add(data, false) ?? new (getMessage())(this.client, data) + ); } /** * Sends a raw slack message with this webhook. - * @param {Object} body The raw body to send + * + * @param {object} body The raw body to send * @returns {Promise} * @example * // Send a slack message @@ -267,7 +286,8 @@ class Webhook { /** * Options used to edit a {@link Webhook}. - * @typedef {Object} WebhookEditOptions + * + * @typedef {object} WebhookEditOptions * @property {string} [name=this.name] The new name for the webhook * @property {?(BufferResolvable)} [avatar] The new avatar for the webhook * @property {GuildTextChannelResolvable|VoiceChannel|StageChannel|ForumChannel|MediaChannel} [channel] @@ -277,6 +297,7 @@ class Webhook { /** * Edits this webhook. + * * @param {WebhookEditOptions} options Options for editing the webhook * @returns {Promise} */ @@ -285,6 +306,7 @@ class Webhook { if (avatar && !(typeof avatar === 'string' && avatar.startsWith('data:'))) { avatar = await resolveImage(avatar); } + const channel = newChannel?.id ?? newChannel; const data = await this.client.rest.patch(Routes.webhook(this.id, channel ? undefined : this.token), { body: { name, avatar, channel_id: channel }, @@ -300,6 +322,7 @@ class Webhook { /** * Options that can be passed into fetchMessage. + * * @typedef {options} WebhookFetchMessageOptions * @property {boolean} [cache=true] Whether to cache the message. * @property {Snowflake} [threadId] The id of the thread this message belongs to. @@ -308,8 +331,9 @@ class Webhook { /** * Gets a message that was sent by this webhook. + * * @param {Snowflake|'@original'} message The id of the message to fetch - * @param {WebhookFetchMessageOptions} [options={}] The options to provide to fetch the message. + * @param {WebhookFetchMessageOptions} [options] The options to provide to fetch the message. * @returns {Promise} Returns the message sent by this webhook */ async fetchMessage(message, { threadId } = {}) { @@ -329,6 +353,7 @@ class Webhook { /** * Edits a message that was sent by this webhook. + * * @param {MessageResolvable|'@original'} message The message to edit * @param {string|MessagePayload|WebhookMessageEditOptions} options The options to provide * @returns {Promise} Returns the message edited by this webhook @@ -348,7 +373,7 @@ class Webhook { with_components: messagePayload.options.withComponents, }); - const d = await this.client.rest.patch( + const data = await this.client.rest.patch( Routes.webhookMessage(this.id, this.token, typeof message === 'string' ? message : message.id), { body, @@ -359,30 +384,32 @@ class Webhook { ); const channelManager = this.client.channels; - if (!channelManager) return d; + if (!channelManager) return data; - const messageManager = channelManager.cache.get(d.channel_id)?.messages; - if (!messageManager) return new (getMessage())(this.client, d); + const messageManager = channelManager.cache.get(data.channel_id)?.messages; + if (!messageManager) return new (getMessage())(this.client, data); - const existing = messageManager.cache.get(d.id); - if (!existing) return messageManager._add(d); + const existing = messageManager.cache.get(data.id); + if (!existing) return messageManager._add(data); const clone = existing._clone(); - clone._patch(d); + clone._patch(data); return clone; } /** * Deletes the webhook. + * * @param {string} [reason] Reason for deleting this webhook * @returns {Promise} */ - delete(reason) { + async delete(reason) { return this.client.deleteWebhook(this.id, { token: this.token, reason }); } /** * Delete a message that was sent by this webhook. + * * @param {MessageResolvable|'@original'} message The message to delete * @param {Snowflake} [threadId] The id of the thread this message belongs to * @returns {Promise} @@ -401,6 +428,7 @@ class Webhook { /** * The timestamp the webhook was created at + * * @type {number} * @readonly */ @@ -410,6 +438,7 @@ class Webhook { /** * The time the webhook was created at + * * @type {Date} * @readonly */ @@ -419,6 +448,7 @@ class Webhook { /** * The URL of this webhook + * * @type {string} * @readonly */ @@ -428,7 +458,8 @@ class Webhook { /** * A link to the webhook's avatar. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ avatarURL(options = {}) { @@ -437,6 +468,7 @@ class Webhook { /** * Whether this webhook is created by a user. + * * @returns {boolean} */ isUserCreated() { @@ -445,6 +477,7 @@ class Webhook { /** * Whether this webhook is created by an application. + * * @returns {boolean} */ isApplicationCreated() { @@ -453,6 +486,7 @@ class Webhook { /** * Whether or not this webhook is a channel follower webhook. + * * @returns {boolean} */ isChannelFollower() { @@ -461,6 +495,7 @@ class Webhook { /** * Whether or not this webhook is an incoming webhook. + * * @returns {boolean} */ isIncoming() { diff --git a/packages/discord.js/src/structures/WelcomeChannel.js b/packages/discord.js/src/structures/WelcomeChannel.js index 86701dec8003..4caf536bf41f 100644 --- a/packages/discord.js/src/structures/WelcomeChannel.js +++ b/packages/discord.js/src/structures/WelcomeChannel.js @@ -5,6 +5,7 @@ const { Emoji } = require('./Emoji.js'); /** * Represents a channel link in a guild's welcome screen. + * * @extends {Base} */ class WelcomeChannel extends Base { @@ -13,19 +14,22 @@ class WelcomeChannel extends Base { /** * The guild for this welcome channel + * * @type {Guild|InviteGuild} */ this.guild = guild; /** * The description of this welcome channel + * * @type {string} */ this.description = data.description; /** * The raw emoji data - * @type {Object} + * + * @type {object} * @private */ this._emoji = { @@ -35,6 +39,7 @@ class WelcomeChannel extends Base { /** * The id of this welcome channel + * * @type {Snowflake} */ this.channelId = data.channel_id; @@ -42,6 +47,7 @@ class WelcomeChannel extends Base { /** * The channel of this welcome channel + * * @type {?(TextChannel|AnnouncementChannel|ForumChannel|MediaChannel)} */ get channel() { @@ -50,6 +56,7 @@ class WelcomeChannel extends Base { /** * The emoji of this welcome channel + * * @type {GuildEmoji|Emoji} */ get emoji() { diff --git a/packages/discord.js/src/structures/WelcomeScreen.js b/packages/discord.js/src/structures/WelcomeScreen.js index ece0ce00b64b..993d0af86cad 100644 --- a/packages/discord.js/src/structures/WelcomeScreen.js +++ b/packages/discord.js/src/structures/WelcomeScreen.js @@ -7,6 +7,7 @@ const { WelcomeChannel } = require('./WelcomeChannel.js'); /** * Represents a welcome screen. + * * @extends {Base} */ class WelcomeScreen extends Base { @@ -15,18 +16,21 @@ class WelcomeScreen extends Base { /** * The guild for this welcome screen + * * @type {Guild} */ this.guild = guild; /** * The description of this welcome screen + * * @type {?string} */ this.description = data.description ?? null; /** * Collection of welcome channels belonging to this welcome screen + * * @type {Collection} */ this.welcomeChannels = new Collection(); @@ -39,6 +43,7 @@ class WelcomeScreen extends Base { /** * Whether the welcome screen is enabled on the guild + * * @type {boolean} */ get enabled() { diff --git a/packages/discord.js/src/structures/Widget.js b/packages/discord.js/src/structures/Widget.js index e08e3aa82331..12fbadf80617 100644 --- a/packages/discord.js/src/structures/Widget.js +++ b/packages/discord.js/src/structures/Widget.js @@ -7,6 +7,7 @@ const { WidgetMember } = require('./WidgetMember.js'); /** * Represents a Widget. + * * @extends {Base} */ class Widget extends Base { @@ -17,7 +18,8 @@ class Widget extends Base { /** * Represents a channel in a Widget - * @typedef {Object} WidgetChannel + * + * @typedef {object} WidgetChannel * @property {Snowflake} id Id of the channel * @property {string} name Name of the channel * @property {number} position Position of the channel @@ -26,6 +28,7 @@ class Widget extends Base { _patch(data) { /** * The id of the guild. + * * @type {Snowflake} */ this.id = data.id; @@ -33,6 +36,7 @@ class Widget extends Base { if ('name' in data) { /** * The name of the guild. + * * @type {string} */ this.name = data.name; @@ -41,6 +45,7 @@ class Widget extends Base { if ('instant_invite' in data) { /** * The invite of the guild. + * * @type {?string} */ this.instantInvite = data.instant_invite; @@ -48,6 +53,7 @@ class Widget extends Base { /** * The list of channels in the guild. + * * @type {Collection} */ this.channels = new Collection(); @@ -58,6 +64,7 @@ class Widget extends Base { /** * The list of members in the guild. * These strings are just arbitrary numbers, they aren't Snowflakes. + * * @type {Collection} */ this.members = new Collection(); @@ -68,6 +75,7 @@ class Widget extends Base { if ('presence_count' in data) { /** * The number of members online. + * * @type {number} */ this.presenceCount = data.presence_count; @@ -76,6 +84,7 @@ class Widget extends Base { /** * Update the Widget. + * * @returns {Promise} */ async fetch() { @@ -86,6 +95,7 @@ class Widget extends Base { /** * Returns a URL for the PNG widget of the guild. + * * @param {GuildWidgetStyle} [style] The style for the widget image * @returns {string} */ diff --git a/packages/discord.js/src/structures/WidgetMember.js b/packages/discord.js/src/structures/WidgetMember.js index 3ada3de1e323..6df17a8460fd 100644 --- a/packages/discord.js/src/structures/WidgetMember.js +++ b/packages/discord.js/src/structures/WidgetMember.js @@ -4,12 +4,14 @@ const { Base } = require('./Base.js'); /** * Represents a WidgetMember. + * * @extends {Base} */ class WidgetMember extends Base { /** * Activity sent in a {@link WidgetMember}. - * @typedef {Object} WidgetActivity + * + * @typedef {object} WidgetActivity * @property {string} name The name of the activity */ @@ -18,78 +20,91 @@ class WidgetMember extends Base { /** * The id of the user. It's an arbitrary number. + * * @type {string} */ this.id = data.id; /** * The username of the member. + * * @type {string} */ this.username = data.username; /** * The discriminator of the member. + * * @type {string} */ this.discriminator = data.discriminator; /** * The avatar of the member. + * * @type {?string} */ this.avatar = data.avatar; /** * The status of the member. + * * @type {PresenceStatus} */ this.status = data.status; /** * If the member is server deafened + * * @type {?boolean} */ this.deaf = data.deaf ?? null; /** * If the member is server muted + * * @type {?boolean} */ this.mute = data.mute ?? null; /** * If the member is self deafened + * * @type {?boolean} */ this.selfDeaf = data.self_deaf ?? null; /** * If the member is self muted + * * @type {?boolean} */ this.selfMute = data.self_mute ?? null; /** * If the member is suppressed + * * @type {?boolean} */ this.suppress = data.suppress ?? null; /** * The id of the voice channel the member is in, if any + * * @type {?Snowflake} */ this.channelId = data.channel_id ?? null; /** * The avatar URL of the member. + * * @type {string} */ this.avatarURL = data.avatar_url; /** * The activity of the member. + * * @type {?WidgetActivity} */ this.activity = data.activity ?? null; diff --git a/packages/discord.js/src/structures/interfaces/Application.js b/packages/discord.js/src/structures/interfaces/Application.js index b36bcf0626b2..f11afd0d71db 100644 --- a/packages/discord.js/src/structures/interfaces/Application.js +++ b/packages/discord.js/src/structures/interfaces/Application.js @@ -5,6 +5,7 @@ const { Base } = require('../Base.js'); /** * Represents an OAuth2 Application. + * * @extends {Base} * @abstract */ @@ -17,6 +18,7 @@ class Application extends Base { _patch(data) { /** * The application's id + * * @type {Snowflake} */ this.id = data.id; @@ -24,6 +26,7 @@ class Application extends Base { if ('name' in data) { /** * The name of the application + * * @type {?string} */ this.name = data.name; @@ -34,6 +37,7 @@ class Application extends Base { if ('description' in data) { /** * The application's description + * * @type {?string} */ this.description = data.description; @@ -44,6 +48,7 @@ class Application extends Base { if ('icon' in data) { /** * The application's icon hash + * * @type {?string} */ this.icon = data.icon; @@ -54,6 +59,7 @@ class Application extends Base { if ('terms_of_service_url' in data) { /** * The URL of the application's terms of service + * * @type {?string} */ this.termsOfServiceURL = data.terms_of_service_url; @@ -64,6 +70,7 @@ class Application extends Base { if ('privacy_policy_url' in data) { /** * The URL of the application's privacy policy + * * @type {?string} */ this.privacyPolicyURL = data.privacy_policy_url; @@ -74,6 +81,7 @@ class Application extends Base { if ('rpc_origins' in data) { /** * The application's RPC origins, if enabled + * * @type {string[]} */ this.rpcOrigins = data.rpc_origins; @@ -84,6 +92,7 @@ class Application extends Base { if ('cover_image' in data) { /** * The hash of the application's cover image + * * @type {?string} */ this.cover = data.cover_image; @@ -94,6 +103,7 @@ class Application extends Base { if ('verify_key' in data) { /** * The hex-encoded key for verification in interactions and the GameSDK's GetTicket + * * @type {?string} */ this.verifyKey = data.verify_key; @@ -104,6 +114,7 @@ class Application extends Base { /** * The timestamp the application was created at + * * @type {number} * @readonly */ @@ -113,6 +124,7 @@ class Application extends Base { /** * The time the application was created at + * * @type {Date} * @readonly */ @@ -122,7 +134,8 @@ class Application extends Base { /** * A link to the application's icon. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ iconURL(options = {}) { @@ -131,7 +144,8 @@ class Application extends Base { /** * A link to this application's cover image. - * @param {ImageURLOptions} [options={}] Options for the image URL + * + * @param {ImageURLOptions} [options] Options for the image URL * @returns {?string} */ coverURL(options = {}) { @@ -141,6 +155,7 @@ class Application extends Base { /** * When concatenated with a string, this automatically returns the application's name instead of the * Application object. + * * @returns {?string} * @example * // Logs: Application name: My App diff --git a/packages/discord.js/src/structures/interfaces/Collector.js b/packages/discord.js/src/structures/interfaces/Collector.js index 143e7104548b..8c49c09b8836 100644 --- a/packages/discord.js/src/structures/interfaces/Collector.js +++ b/packages/discord.js/src/structures/interfaces/Collector.js @@ -8,6 +8,7 @@ const { flatten } = require('../../util/Util.js'); /** * Filter to be applied to the collector. + * * @typedef {Function} CollectorFilter * @param {...*} args Any arguments received by the listener * @param {Collection} collection The items collected by this collector @@ -16,7 +17,8 @@ const { flatten } = require('../../util/Util.js'); /** * Options to be applied to the collector. - * @typedef {Object} CollectorOptions + * + * @typedef {object} CollectorOptions * @property {CollectorFilter} [filter] The filter applied to this collector * @property {number} [time] How long to run the collector for in milliseconds * @property {number} [idle] How long to stop the collector after inactivity in milliseconds @@ -25,6 +27,7 @@ const { flatten } = require('../../util/Util.js'); /** * Abstract class for defining a new Collector. + * * @extends {AsyncEventEmitter} * @abstract */ @@ -34,6 +37,7 @@ class Collector extends AsyncEventEmitter { /** * The client that instantiated this Collector + * * @name Collector#client * @type {Client} * @readonly @@ -42,6 +46,7 @@ class Collector extends AsyncEventEmitter { /** * The filter applied to this collector + * * @type {CollectorFilter} * @returns {boolean|Promise} */ @@ -49,24 +54,28 @@ class Collector extends AsyncEventEmitter { /** * The options of this collector + * * @type {CollectorOptions} */ this.options = options; /** * The items collected by this collector + * * @type {Collection} */ this.collected = new Collection(); /** * Whether this collector has finished collecting + * * @type {boolean} */ this.ended = false; /** * Timeout for cleanup + * * @type {?Timeout} * @private */ @@ -74,6 +83,7 @@ class Collector extends AsyncEventEmitter { /** * Timeout for cleanup due to inactivity + * * @type {?Timeout} * @private */ @@ -81,6 +91,7 @@ class Collector extends AsyncEventEmitter { /** * The reason the collector ended + * * @type {?string} * @private */ @@ -98,6 +109,7 @@ class Collector extends AsyncEventEmitter { /** * The timestamp at which this collector last collected an item + * * @type {?number} */ this.lastCollectedTimestamp = null; @@ -105,6 +117,7 @@ class Collector extends AsyncEventEmitter { /** * The Date at which this collector last collected an item + * * @type {?Date} */ get lastCollectedAt() { @@ -113,6 +126,7 @@ class Collector extends AsyncEventEmitter { /** * Call this to handle an event as a collectable element. Accepts any event data as parameters. + * * @param {...*} args The arguments emitted by the listener * @returns {Promise} * @emits Collector#collect @@ -127,6 +141,7 @@ class Collector extends AsyncEventEmitter { /** * Emitted whenever an element is collected. + * * @event Collector#collect * @param {...*} args The arguments emitted by the listener */ @@ -140,17 +155,20 @@ class Collector extends AsyncEventEmitter { } else { /** * Emitted whenever an element is not collected by the collector. + * * @event Collector#ignore * @param {...*} args The arguments emitted by the listener */ this.emit('ignore', ...args); } } + this.checkEnd(); } /** * Call this to remove an element from the collection. Accepts any event data as parameters. + * * @param {...*} args The arguments emitted by the listener * @returns {Promise} * @emits Collector#dispose @@ -164,6 +182,7 @@ class Collector extends AsyncEventEmitter { /** * Emitted whenever an element is disposed of. + * * @event Collector#dispose * @param {...*} args The arguments emitted by the listener */ @@ -174,6 +193,7 @@ class Collector extends AsyncEventEmitter { /** * Returns a promise that resolves with the next collected element; * rejects with collected elements if the collector finishes without receiving a next element + * * @type {Promise} * @readonly */ @@ -185,7 +205,9 @@ class Collector extends AsyncEventEmitter { } const cleanup = () => { + // eslint-disable-next-line @typescript-eslint/no-use-before-define this.removeListener('collect', onCollect); + // eslint-disable-next-line @typescript-eslint/no-use-before-define this.removeListener('end', onEnd); }; @@ -206,7 +228,8 @@ class Collector extends AsyncEventEmitter { /** * Stops this collector and emits the `end` event. - * @param {string} [reason='user'] The reason this collector is ending + * + * @param {string} [reason] The reason this collector is ending * @emits Collector#end */ stop(reason = 'user') { @@ -216,6 +239,7 @@ class Collector extends AsyncEventEmitter { clearTimeout(this._timeout); this._timeout = null; } + if (this._idletimeout) { clearTimeout(this._idletimeout); this._idletimeout = null; @@ -226,6 +250,7 @@ class Collector extends AsyncEventEmitter { /** * Emitted when the collector is finished collecting. + * * @event Collector#end * @param {Collection} collected The elements collected by the collector * @param {string} reason The reason the collector ended @@ -235,13 +260,15 @@ class Collector extends AsyncEventEmitter { /** * Options used to reset the timeout and idle timer of a {@link Collector}. - * @typedef {Object} CollectorResetTimerOptions + * + * @typedef {object} CollectorResetTimerOptions * @property {number} [time] How long to run the collector for (in milliseconds) * @property {number} [idle] How long to wait to stop the collector after inactivity (in milliseconds) */ /** * Resets the collector's timeout and idle timer. + * * @param {CollectorResetTimerOptions} [options] Options for resetting */ resetTimer({ time, idle } = {}) { @@ -249,6 +276,7 @@ class Collector extends AsyncEventEmitter { clearTimeout(this._timeout); this._timeout = setTimeout(() => this.stop('time'), time ?? this.options.time).unref(); } + if (this._idletimeout) { clearTimeout(this._idletimeout); this._idletimeout = setTimeout(() => this.stop('idle'), idle ?? this.options.idle).unref(); @@ -257,6 +285,7 @@ class Collector extends AsyncEventEmitter { /** * Checks whether the collector should end, and if so, ends it. + * * @returns {boolean} Whether the collector ended or not */ checkEnd() { @@ -267,6 +296,7 @@ class Collector extends AsyncEventEmitter { /** * Allows collectors to be consumed with for-await-of loops + * * @see {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for-await...of} */ async *[Symbol.asyncIterator]() { @@ -279,13 +309,13 @@ class Collector extends AsyncEventEmitter { if (queue.length) { yield queue.shift(); } else { - // eslint-disable-next-line no-await-in-loop await new Promise(resolve => { const tick = () => { this.removeListener('collect', tick); this.removeListener('end', tick); - return resolve(); + resolve(); }; + this.on('collect', tick); this.on('end', tick); }); @@ -300,9 +330,9 @@ class Collector extends AsyncEventEmitter { return flatten(this); } - /* eslint-disable no-empty-function */ /** * The reason this collector has ended with, or null if it hasn't ended yet + * * @type {?string} * @readonly */ @@ -313,23 +343,24 @@ class Collector extends AsyncEventEmitter { /** * Handles incoming events from the `handleCollect` function. Returns null if the event should not * be collected, or returns an object describing the data that should be stored. + * * @see Collector#handleCollect * @param {...*} args Any args the event listener emits * @returns {?(*|Promise)} Data to insert into collection, if any * @abstract */ - collect() {} + collect(...args) {} /** * Handles incoming events from the `handleDispose`. Returns null if the event should not * be disposed, or returns the key that should be removed. + * * @see Collector#handleDispose * @param {...*} args Any args the event listener emits * @returns {?*} Key to remove from the collection, if any * @abstract */ - dispose() {} - /* eslint-enable no-empty-function */ + dispose(...args) {} } exports.Collector = Collector; diff --git a/packages/discord.js/src/structures/interfaces/InteractionResponses.js b/packages/discord.js/src/structures/interfaces/InteractionResponses.js index c32b82bf0180..8a79a3b2c688 100644 --- a/packages/discord.js/src/structures/interfaces/InteractionResponses.js +++ b/packages/discord.js/src/structures/interfaces/InteractionResponses.js @@ -10,7 +10,7 @@ const { InteractionCollector } = require('../InteractionCollector.js'); const { MessagePayload } = require('../MessagePayload.js'); /** - * @typedef {Object} ModalComponentData + * @typedef {object} ModalComponentData * @property {string} title The title of the modal * @property {string} customId The custom id of the modal * @property {ActionRow[]} components The components within this modal @@ -18,12 +18,14 @@ const { MessagePayload } = require('../MessagePayload.js'); /** * Interface for classes that support shared interaction response types. + * * @interface */ class InteractionResponses { /** * Options for deferring the reply to an {@link BaseInteraction}. - * @typedef {Object} InteractionDeferReplyOptions + * + * @typedef {object} InteractionDeferReplyOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response * @property {MessageFlagsResolvable} [flags] Flags for the reply. * Only `MessageFlags.Ephemeral` can be set. @@ -31,12 +33,14 @@ class InteractionResponses { /** * Options for deferring and updating the reply to a {@link MessageComponentInteraction}. - * @typedef {Object} InteractionDeferUpdateOptions + * + * @typedef {object} InteractionDeferUpdateOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response */ /** * Options for a reply to a {@link BaseInteraction}. + * * @typedef {BaseMessageOptionsWithPoll} InteractionReplyOptions * @property {boolean} [tts=false] Whether the message should be spoken aloud * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response @@ -47,24 +51,28 @@ class InteractionResponses { /** * Options for updating the message received from a {@link MessageComponentInteraction}. + * * @typedef {MessageEditOptions} InteractionUpdateOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response */ /** * Options for launching activity in response to a {@link BaseInteraction} - * @typedef {Object} LaunchActivityOptions + * + * @typedef {object} LaunchActivityOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response */ /** * Options for showing a modal in response to a {@link BaseInteraction} - * @typedef {Object} ShowModalOptions + * + * @typedef {object} ShowModalOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response */ /** * Defers the reply to this interaction. + * * @param {InteractionDeferReplyOptions} [options] Options for deferring the reply to this interaction * @returns {Promise} * @example @@ -103,6 +111,7 @@ class InteractionResponses { /** * Creates a reply to this interaction. * Use the `withResponse` option to get the interaction callback response. + * * @param {string|MessagePayload|InteractionReplyOptions} options The options for the reply * @returns {Promise} * @example @@ -145,8 +154,9 @@ class InteractionResponses { /** * Fetches a reply to this interaction. + * * @see Webhook#fetchMessage - * @param {Snowflake|'@original'} [message='@original'] The response to fetch + * @param {Snowflake|'@original'} [message] The response to fetch * @returns {Promise} * @example * // Fetch the initial reply to this interaction @@ -154,18 +164,20 @@ class InteractionResponses { * .then(reply => console.log(`Replied with ${reply.content}`)) * .catch(console.error); */ - fetchReply(message = '@original') { + async fetchReply(message = '@original') { return this.webhook.fetchMessage(message); } /** * Options that can be passed into {@link InteractionResponses#editReply}. + * * @typedef {WebhookMessageEditOptions} InteractionEditReplyOptions * @property {MessageResolvable|'@original'} [message='@original'] The response to edit */ /** * Edits a reply to this interaction. + * * @see Webhook#editMessage * @param {string|MessagePayload|InteractionEditReplyOptions} options The new options for the message * @returns {Promise} @@ -184,8 +196,9 @@ class InteractionResponses { /** * Deletes a reply to this interaction. + * * @see Webhook#deleteMessage - * @param {MessageResolvable|'@original'} [message='@original'] The response to delete + * @param {MessageResolvable|'@original'} [message] The response to delete * @returns {Promise} * @example * // Delete the initial reply to this interaction @@ -201,6 +214,7 @@ class InteractionResponses { /** * Send a follow-up message to this interaction. + * * @param {string|MessagePayload|InteractionReplyOptions} options The options for the reply * @returns {Promise} */ @@ -213,6 +227,7 @@ class InteractionResponses { /** * Defers an update to the message to which the component was attached. + * * @param {InteractionDeferUpdateOptions} [options] Options for deferring the update to this interaction * @returns {Promise} * @example @@ -237,6 +252,7 @@ class InteractionResponses { /** * Updates the original message of the component on which the interaction was received on. + * * @param {string|MessagePayload|InteractionUpdateOptions} options The options for the updated message * @returns {Promise} * @example @@ -273,7 +289,8 @@ class InteractionResponses { /** * Launches this application's activity, if enabled - * @param {LaunchActivityOptions} [options={}] Options for launching the activity + * + * @param {LaunchActivityOptions} [options] Options for launching the activity * @returns {Promise} */ async launchActivity({ withResponse } = {}) { @@ -292,8 +309,9 @@ class InteractionResponses { /** * Shows a modal component + * * @param {ModalBuilder|ModalComponentData|APIModalInteractionResponseCallbackData} modal The modal to show - * @param {ShowModalOptions} [options={}] The options for sending this interaction response + * @param {ShowModalOptions} [options] The options for sending this interaction response * @returns {Promise} */ async showModal(modal, options = {}) { @@ -313,7 +331,8 @@ class InteractionResponses { /** * An object containing the same properties as {@link CollectorOptions}, but a few less: - * @typedef {Object} AwaitModalSubmitOptions + * + * @typedef {object} AwaitModalSubmitOptions * @property {CollectorFilter} [filter] The filter applied to this collector * @property {number} time Time in milliseconds to wait for an interaction before rejecting */ @@ -321,6 +340,7 @@ class InteractionResponses { /** * Collects a single modal submit interaction that passes the filter. * The Promise will reject if the time expires. + * * @param {AwaitModalSubmitOptions} options Options to pass to the internal collector * @returns {Promise} * @example diff --git a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js index d7ab76b6e6d5..a7564130d722 100644 --- a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js +++ b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js @@ -6,28 +6,34 @@ const { InteractionType, Routes } = require('discord-api-types/v10'); const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../../errors/index.js'); const { MaxBulkDeletableMessageAge } = require('../../util/Constants.js'); const { InteractionCollector } = require('../InteractionCollector.js'); +// eslint-disable-next-line import-x/order const { MessageCollector } = require('../MessageCollector.js'); /** * Interface for classes that have text-channel-like features. + * * @interface */ class TextBasedChannel { constructor() { /** * A manager of the messages sent to this channel + * * @type {GuildMessageManager} */ + // eslint-disable-next-line @typescript-eslint/no-use-before-define this.messages = new GuildMessageManager(this); /** * The channel's last message id, if one was sent + * * @type {?Snowflake} */ this.lastMessageId = null; /** * The timestamp when the last pinned message was pinned, if there was one + * * @type {?number} */ this.lastPinTimestamp = null; @@ -35,6 +41,7 @@ class TextBasedChannel { /** * The Message object of the last message in the channel, if one was sent + * * @type {?Message} * @readonly */ @@ -44,6 +51,7 @@ class TextBasedChannel { /** * The date when the last pinned message was pinned, if there was one + * * @type {?Date} * @readonly */ @@ -53,14 +61,16 @@ class TextBasedChannel { /** * Represents the data for a poll answer. - * @typedef {Object} PollAnswerData + * + * @typedef {object} PollAnswerData * @property {string} text The text for the poll answer * @property {EmojiIdentifierResolvable} [emoji] The emoji for the poll answer */ /** * Represents the data for a poll. - * @typedef {Object} PollData + * + * @typedef {object} PollData * @property {PollQuestionMedia} question The question for the poll * @property {PollAnswerData[]} answers The answers for the poll * @property {number} duration The duration in hours for the poll @@ -70,7 +80,8 @@ class TextBasedChannel { /** * The base message options for messages. - * @typedef {Object} BaseMessageOptions + * + * @typedef {object} BaseMessageOptions * @property {?string} [content=''] The content for the message. This can only be `null` when editing a message. * @property {Array<(EmbedBuilder|Embed|APIEmbed)>} [embeds] The embeds for the message * @property {MessageMentionOptions} [allowedMentions] Which mentions should be parsed from the message content @@ -83,12 +94,14 @@ class TextBasedChannel { /** * The base message options for messages including a poll. + * * @typedef {BaseMessageOptions} BaseMessageOptionsWithPoll * @property {PollData} [poll] The poll to send with the message */ /** * The options for sending a message. + * * @typedef {BaseMessageOptionsWithPoll} BaseMessageCreateOptions * @property {boolean} [tts=false] Whether the message should be spoken aloud * @property {string} [nonce] The nonce for the message @@ -109,13 +122,15 @@ class TextBasedChannel { /** * The options for sending a message. + * * @typedef {BaseMessageCreateOptions} MessageCreateOptions * @property {MessageReferenceOptions} [messageReference] The options for a reference to a message */ /** * Options provided to control parsing of mentions by Discord - * @typedef {Object} MessageMentionOptions + * + * @typedef {object} MessageMentionOptions * @property {MessageMentionTypes[]} [parse] Types of mentions to be parsed * @property {Snowflake[]} [users] Snowflakes of Users to be parsed as mentions * @property {Snowflake[]} [roles] Snowflakes of Roles to be parsed as mentions @@ -127,11 +142,13 @@ class TextBasedChannel { * - `roles` * - `users` * - `everyone` + * * @typedef {string} MessageMentionTypes */ /** * Sends a message to this channel. + * * @param {string|MessagePayload|MessageCreateOptions} options The options to provide * @returns {Promise} * @example @@ -158,12 +175,13 @@ class TextBasedChannel { * .then(console.log) * .catch(console.error); */ - send(options) { + async send(options) { return this.client.channels.createMessage(this, options); } /** * Sends a typing indicator in the channel. + * * @returns {Promise} Resolves upon the typing status being sent * @example * // Start typing in a channel @@ -175,7 +193,8 @@ class TextBasedChannel { /** * Creates a Message Collector. - * @param {MessageCollectorOptions} [options={}] The options to pass to the collector + * + * @param {MessageCollectorOptions} [options] The options to pass to the collector * @returns {MessageCollector} * @example * // Create a message collector @@ -190,6 +209,7 @@ class TextBasedChannel { /** * An object containing the same properties as CollectorOptions, but a few more: + * * @typedef {MessageCollectorOptions} AwaitMessagesOptions * @property {string[]} [errors] Stop/end reasons that cause the promise to reject */ @@ -197,7 +217,8 @@ class TextBasedChannel { /** * Similar to createMessageCollector but in promise form. * Resolves with a collection of messages that pass the specified filter. - * @param {AwaitMessagesOptions} [options={}] Optional options to pass to the internal collector + * + * @param {AwaitMessagesOptions} [options] Optional options to pass to the internal collector * @returns {Promise>} * @example * // Await !vote messages @@ -207,7 +228,7 @@ class TextBasedChannel { * .then(collected => console.log(collected.size)) * .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`)); */ - awaitMessages(options = {}) { + async awaitMessages(options = {}) { return new Promise((resolve, reject) => { const collector = this.createMessageCollector(options); collector.once('end', (collection, reason) => { @@ -222,7 +243,8 @@ class TextBasedChannel { /** * Creates a component interaction collector. - * @param {MessageComponentCollectorOptions} [options={}] Options to send to the collector + * + * @param {MessageComponentCollectorOptions} [options] Options to send to the collector * @returns {InteractionCollector} * @example * // Create a button interaction collector @@ -242,7 +264,8 @@ class TextBasedChannel { /** * Collects a single component interaction that passes the filter. * The Promise will reject if the time expires. - * @param {AwaitMessageComponentOptions} [options={}] Options to pass to the internal collector + * + * @param {AwaitMessageComponentOptions} [options] Options to pass to the internal collector * @returns {Promise} * @example * // Collect a message component interaction @@ -251,7 +274,7 @@ class TextBasedChannel { * .then(interaction => console.log(`${interaction.customId} was clicked!`)) * .catch(console.error); */ - awaitMessageComponent(options = {}) { + async awaitMessageComponent(options = {}) { const _options = { ...options, max: 1 }; return new Promise((resolve, reject) => { const collector = this.createMessageComponentCollector(_options); @@ -265,9 +288,10 @@ class TextBasedChannel { /** * Bulk deletes given messages up to 2 weeks old. + * * @param {Collection|MessageResolvable[]|number} messages * Messages or number of messages to delete - * @param {boolean} [filterOld=false] Filter messages to remove those which are older than two weeks automatically + * @param {boolean} [filterOld] Filter messages to remove those which are older than two weeks automatically * @returns {Promise} Returns the deleted messages ids * @example * // Bulk delete messages @@ -307,6 +331,7 @@ class TextBasedChannel { /** * Fetches all webhooks for the channel. + * * @returns {Promise>} * @example * // Fetch webhooks @@ -314,13 +339,14 @@ class TextBasedChannel { * .then(hooks => console.log(`This channel has ${hooks.size} hooks`)) * .catch(console.error); */ - fetchWebhooks() { + async fetchWebhooks() { return this.guild.channels.fetchWebhooks(this.id); } /** * Options used to create a {@link Webhook}. - * @typedef {Object} ChannelWebhookCreateOptions + * + * @typedef {object} ChannelWebhookCreateOptions * @property {string} name The name of the webhook * @property {?(BufferResolvable|Base64Resolvable)} [avatar] Avatar for the webhook * @property {string} [reason] Reason for creating the webhook @@ -328,6 +354,7 @@ class TextBasedChannel { /** * Creates a webhook for the channel. + * * @param {ChannelWebhookCreateOptions} [options] Options for creating the webhook * @returns {Promise} Returns the created Webhook * @example @@ -340,27 +367,29 @@ class TextBasedChannel { * .then(console.log) * .catch(console.error) */ - createWebhook(options) { + async createWebhook(options) { return this.guild.channels.createWebhook({ channel: this.id, ...options }); } /** * Sets the rate limit per user (slowmode) for this channel. + * * @param {number} rateLimitPerUser The new rate limit in seconds * @param {string} [reason] Reason for changing the channel's rate limit * @returns {Promise} */ - setRateLimitPerUser(rateLimitPerUser, reason) { + async setRateLimitPerUser(rateLimitPerUser, reason) { return this.edit({ rateLimitPerUser, reason }); } /** * Sets whether this channel is flagged as NSFW. - * @param {boolean} [nsfw=true] Whether the channel should be considered NSFW + * + * @param {boolean} [nsfw] Whether the channel should be considered NSFW * @param {string} [reason] Reason for changing the channel's NSFW flag * @returns {Promise} */ - setNSFW(nsfw = true, reason) { + async setNSFW(nsfw = true, reason = undefined) { return this.edit({ nsfw, reason }); } @@ -395,5 +424,5 @@ class TextBasedChannel { exports.TextBasedChannel = TextBasedChannel; // Fixes Circular -// eslint-disable-next-line import/order +// eslint-disable-next-line import-x/order const { GuildMessageManager } = require('../../managers/GuildMessageManager.js'); diff --git a/packages/discord.js/src/util/APITypes.js b/packages/discord.js/src/util/APITypes.js index c40af6c289cc..6425565e2fe6 100644 --- a/packages/discord.js/src/util/APITypes.js +++ b/packages/discord.js/src/util/APITypes.js @@ -1,4 +1,4 @@ -/* eslint-disable max-len */ +/* eslint-disable unicorn/no-empty-file */ /** * @external ActivityFlags diff --git a/packages/discord.js/src/util/ActivityFlagsBitField.js b/packages/discord.js/src/util/ActivityFlagsBitField.js index 4734992f1b25..8e886a47fac4 100644 --- a/packages/discord.js/src/util/ActivityFlagsBitField.js +++ b/packages/discord.js/src/util/ActivityFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with an {@link Activity#flags} bitfield. + * * @extends {BitField} */ class ActivityFlagsBitField extends BitField { /** * Numeric activity flags. + * * @type {ActivityFlags} * @memberof ActivityFlagsBitField */ @@ -18,7 +20,7 @@ class ActivityFlagsBitField extends BitField { /** * @name ActivityFlagsBitField - * @kind constructor + * @constructor * @memberof ActivityFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/ApplicationFlagsBitField.js b/packages/discord.js/src/util/ApplicationFlagsBitField.js index 8e78c7156e2a..2df418b4ec7f 100644 --- a/packages/discord.js/src/util/ApplicationFlagsBitField.js +++ b/packages/discord.js/src/util/ApplicationFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with a {@link ClientApplication#flags} bitfield. + * * @extends {BitField} */ class ApplicationFlagsBitField extends BitField { /** * Numeric application flags. All available properties: + * * @type {ApplicationFlags} * @memberof ApplicationFlagsBitField */ @@ -18,23 +20,25 @@ class ApplicationFlagsBitField extends BitField { /** * @name ApplicationFlagsBitField - * @kind constructor + * @constructor * @memberof ApplicationFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ /** * Bitfield of the packed bits + * * @type {number} * @name ApplicationFlagsBitField#bitfield */ /** * Data that can be resolved to give an application flag bit field. This can be: - * * A string (see {@link ApplicationFlagsBitField.Flags}) - * * An application flag - * * An instance of ApplicationFlagsBitField - * * An Array of ApplicationFlagsResolvable + * A string (see {@link ApplicationFlagsBitField.Flags}) + * An application flag + * An instance of ApplicationFlagsBitField + * An Array of ApplicationFlagsResolvable + * * @typedef {string|number|ApplicationFlagsBitField|ApplicationFlagsResolvable[]} ApplicationFlagsResolvable */ diff --git a/packages/discord.js/src/util/AttachmentFlagsBitField.js b/packages/discord.js/src/util/AttachmentFlagsBitField.js index 82dff9bb7de4..8afcefaebbbf 100644 --- a/packages/discord.js/src/util/AttachmentFlagsBitField.js +++ b/packages/discord.js/src/util/AttachmentFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with an {@link Attachment#flags} bitfield. + * * @extends {BitField} */ class AttachmentFlagsBitField extends BitField { /** * Numeric attachment flags. + * * @type {AttachmentFlags} * @memberof AttachmentFlagsBitField */ @@ -18,7 +20,7 @@ class AttachmentFlagsBitField extends BitField { /** * @name AttachmentFlagsBitField - * @kind constructor + * @constructor * @memberof AttachmentFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/BitField.js b/packages/discord.js/src/util/BitField.js index 8766a8c5d416..ca9379e6d8fa 100644 --- a/packages/discord.js/src/util/BitField.js +++ b/packages/discord.js/src/util/BitField.js @@ -9,7 +9,8 @@ class BitField { /** * Numeric bitfield flags. * Defined in extension classes - * @type {Object} + * + * @type {object} * @memberof BitField * @abstract */ @@ -23,11 +24,12 @@ class BitField { static DefaultBit = 0; /** - * @param {BitFieldResolvable} [bits=this.constructor.DefaultBit] Bit(s) to read from + * @param {BitFieldResolvable} [bits] Bit(s) to read from */ constructor(bits = this.constructor.DefaultBit) { /** * Bitfield of the packed bits + * * @type {number|bigint} */ this.bitfield = this.constructor.resolve(bits); @@ -35,6 +37,7 @@ class BitField { /** * Checks whether the bitfield has a bit, or any of multiple bits. + * * @param {BitFieldResolvable} bit Bit(s) to check for * @returns {boolean} */ @@ -44,6 +47,7 @@ class BitField { /** * Checks if this bitfield equals another + * * @param {BitFieldResolvable} bit Bit(s) to check for * @returns {boolean} */ @@ -53,6 +57,7 @@ class BitField { /** * Checks whether the bitfield has a bit, or multiple bits. + * * @param {BitFieldResolvable} bit Bit(s) to check for * @returns {boolean} */ @@ -63,6 +68,7 @@ class BitField { /** * Gets all given bits that are missing from the bitfield. + * * @param {BitFieldResolvable} bits Bit(s) to check for * @param {...*} hasParams Additional parameters for the has method, if any * @returns {string[]} @@ -73,6 +79,7 @@ class BitField { /** * Freezes these bits, making them immutable. + * * @returns {Readonly} */ freeze() { @@ -81,6 +88,7 @@ class BitField { /** * Adds bits to these ones. + * * @param {...BitFieldResolvable} [bits] Bits to add * @returns {BitField} These bits or new BitField if the instance is frozen. */ @@ -89,6 +97,7 @@ class BitField { for (const bit of bits) { total |= this.constructor.resolve(bit); } + if (Object.isFrozen(this)) return new this.constructor(this.bitfield | total); this.bitfield |= total; return this; @@ -96,6 +105,7 @@ class BitField { /** * Removes bits from these. + * * @param {...BitFieldResolvable} [bits] Bits to remove * @returns {BitField} These bits or new BitField if the instance is frozen. */ @@ -104,6 +114,7 @@ class BitField { for (const bit of bits) { total |= this.constructor.resolve(bit); } + if (Object.isFrozen(this)) return new this.constructor(this.bitfield & ~total); this.bitfield &= ~total; return this; @@ -112,19 +123,22 @@ class BitField { /** * Gets an object mapping field names to a {@link boolean} indicating whether the * bit is available. + * * @param {...*} hasParams Additional parameters for the has method, if any - * @returns {Object} + * @returns {object} */ serialize(...hasParams) { const serialized = {}; for (const [flag, bit] of Object.entries(this.constructor.Flags)) { - if (isNaN(flag)) serialized[flag] = this.has(bit, ...hasParams); + if (Number.isNaN(flag)) serialized[flag] = this.has(bit, ...hasParams); } + return serialized; } /** * Gets an {@link Array} of bitfield names based on the bits available. + * * @param {...*} hasParams Additional parameters for the has method, if any * @returns {string[]} */ @@ -142,21 +156,23 @@ class BitField { *[Symbol.iterator](...hasParams) { for (const bitName of Object.keys(this.constructor.Flags)) { - if (isNaN(bitName) && this.has(bitName, ...hasParams)) yield bitName; + if (Number.isNaN(bitName) && this.has(bitName, ...hasParams)) yield bitName; } } /** * Data that can be resolved to give a bitfield. This can be: - * * A bit number (this can be a number literal or a value taken from {@link BitField.Flags}) - * * A string bit number - * * An instance of BitField - * * An Array of BitFieldResolvable + * A bit number (this can be a number literal or a value taken from {@link BitField.Flags}) + * A string bit number + * An instance of BitField + * An Array of BitFieldResolvable + * * @typedef {number|string|bigint|BitField|BitFieldResolvable[]} BitFieldResolvable */ /** * Resolves bitfields to their numeric form. + * * @param {BitFieldResolvable} [bit] bit(s) to resolve * @returns {number|bigint} */ @@ -167,10 +183,12 @@ class BitField { if (Array.isArray(bit)) { return bit.map(bit_ => this.resolve(bit_)).reduce((prev, bit_) => prev | bit_, DefaultBit); } + if (typeof bit === 'string') { - if (!isNaN(bit)) return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(bit); + if (!Number.isNaN(bit)) return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(bit); if (this.Flags[bit] !== undefined) return this.Flags[bit]; } + throw new DiscordjsRangeError(ErrorCodes.BitFieldInvalid, bit); } } diff --git a/packages/discord.js/src/util/ChannelFlagsBitField.js b/packages/discord.js/src/util/ChannelFlagsBitField.js index 4e1032029f06..407abc7a1abf 100644 --- a/packages/discord.js/src/util/ChannelFlagsBitField.js +++ b/packages/discord.js/src/util/ChannelFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with a {@link BaseChannel#flags} bitfield. + * * @extends {BitField} */ class ChannelFlagsBitField extends BitField { /** * Numeric guild channel flags. + * * @type {ChannelFlags} * @memberof ChannelFlagsBitField */ @@ -18,23 +20,25 @@ class ChannelFlagsBitField extends BitField { /** * @name ChannelFlagsBitField - * @kind constructor + * @constructor * @memberof ChannelFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ /** * Bitfield of the packed bits + * * @type {number} * @name ChannelFlagsBitField#bitfield */ /** * Data that can be resolved to give a channel flag bitfield. This can be: - * * A string (see {@link ChannelFlagsBitField.Flags}) - * * A channel flag - * * An instance of ChannelFlagsBitField - * * An Array of ChannelFlagsResolvable + * A string (see {@link ChannelFlagsBitField.Flags}) + * A channel flag + * An instance of ChannelFlagsBitField + * An Array of ChannelFlagsResolvable + * * @typedef {string|number|ChannelFlagsBitField|ChannelFlagsResolvable[]} ChannelFlagsResolvable */ diff --git a/packages/discord.js/src/util/Channels.js b/packages/discord.js/src/util/Channels.js index a84fdacef59e..2a05235b0ae8 100644 --- a/packages/discord.js/src/util/Channels.js +++ b/packages/discord.js/src/util/Channels.js @@ -17,13 +17,15 @@ const getMediaChannel = lazy(() => require('../structures/MediaChannel.js').Medi /** * Extra options for creating a channel. - * @typedef {Object} CreateChannelOptions + * + * @typedef {object} CreateChannelOptions * @property {boolean} [allowFromUnknownGuild] Whether to allow creating a channel from an unknown guild * @private */ /** * Creates a discord.js channel from data received from the API. + * * @param {Client} client The client * @param {APIChannel} data The data of the channel to create * @param {Guild} [guild] The guild where this channel belongs @@ -33,7 +35,7 @@ const getMediaChannel = lazy(() => require('../structures/MediaChannel.js').Medi */ function createChannel(client, data, guild, { allowUnknownGuild } = {}) { let channel; - let resolvedGuild = guild || client.guilds.cache.get(data.guild_id); + const resolvedGuild = guild ?? client.guilds.cache.get(data.guild_id); if (!data.guild_id && !resolvedGuild) { if ((data.recipients && data.type !== ChannelType.GroupDM) || data.type === ChannelType.DM) { @@ -47,22 +49,27 @@ function createChannel(client, data, guild, { allowUnknownGuild } = {}) { channel = new (getTextChannel())(resolvedGuild, data, client); break; } + case ChannelType.GuildVoice: { channel = new (getVoiceChannel())(resolvedGuild, data, client); break; } + case ChannelType.GuildCategory: { channel = new (getCategoryChannel())(resolvedGuild, data, client); break; } + case ChannelType.GuildAnnouncement: { channel = new (getAnnouncementChannel())(resolvedGuild, data, client); break; } + case ChannelType.GuildStageVoice: { channel = new (getStageChannel())(resolvedGuild, data, client); break; } + case ChannelType.AnnouncementThread: case ChannelType.PublicThread: case ChannelType.PrivateThread: { @@ -70,6 +77,7 @@ function createChannel(client, data, guild, { allowUnknownGuild } = {}) { if (!allowUnknownGuild) channel.parent?.threads.cache.set(channel.id, channel); break; } + case ChannelType.GuildDirectory: channel = new (getDirectoryChannel())(resolvedGuild, data, client); break; @@ -80,13 +88,16 @@ function createChannel(client, data, guild, { allowUnknownGuild } = {}) { channel = new (getMediaChannel())(resolvedGuild, data, client); break; } + if (channel && !allowUnknownGuild) resolvedGuild.channels?.cache.set(channel.id, channel); } + return channel; } /** * Transforms an API guild forum tag to camel-cased guild forum tag. + * * @param {APIGuildForumTag} tag The tag to transform * @returns {GuildForumTag} * @ignore @@ -108,6 +119,7 @@ function transformAPIGuildForumTag(tag) { /** * Transforms a camel-cased guild forum tag to an API guild forum tag. + * * @param {GuildForumTag} tag The tag to transform * @returns {APIGuildForumTag} * @ignore @@ -125,6 +137,7 @@ function transformGuildForumTag(tag) { /** * Transforms an API guild forum default reaction object to a * camel-cased guild forum default reaction object. + * * @param {APIGuildForumDefaultReactionEmoji} defaultReaction The default reaction to transform * @returns {DefaultReactionEmoji} * @ignore @@ -139,6 +152,7 @@ function transformAPIGuildDefaultReaction(defaultReaction) { /** * Transforms a camel-cased guild forum default reaction object to an * API guild forum default reaction object. + * * @param {DefaultReactionEmoji} defaultReaction The default reaction to transform * @returns {APIGuildForumDefaultReactionEmoji} * @ignore diff --git a/packages/discord.js/src/util/Colors.js b/packages/discord.js/src/util/Colors.js index eecda00ea15d..4f5bb1cec92f 100644 --- a/packages/discord.js/src/util/Colors.js +++ b/packages/discord.js/src/util/Colors.js @@ -1,7 +1,7 @@ 'use strict'; /** - * @typedef {Object} Colors + * @typedef {object} Colors * @property {number} Aqua 0x1ABC9C | rgb(26,188,156) * @property {number} Blue 0x3498DB | rgb(52,152,219) * @property {number} Blurple 0x5865F2 | rgb(88,101,242) diff --git a/packages/discord.js/src/util/Components.js b/packages/discord.js/src/util/Components.js index 1d74aa72b1ca..1c66ef21dce5 100644 --- a/packages/discord.js/src/util/Components.js +++ b/packages/discord.js/src/util/Components.js @@ -1,9 +1,11 @@ +/* eslint-disable @typescript-eslint/no-use-before-define */ +/* eslint-disable import-x/order */ 'use strict'; const { ComponentType } = require('discord-api-types/v10'); /** - * @typedef {Object} BaseComponentData + * @typedef {object} BaseComponentData * @property {ComponentType} type The type of component */ @@ -23,7 +25,7 @@ const { ComponentType } = require('discord-api-types/v10'); */ /** - * @typedef {Object} SelectMenuComponentOptionData + * @typedef {object} SelectMenuComponentOptionData * @property {string} label The label of the option * @property {string} value The value of the option * @property {?string} description The description of the option @@ -63,6 +65,7 @@ const { ComponentType } = require('discord-api-types/v10'); /** * Transforms API data into a component + * * @param {APIMessageComponent|Component} data The data to create the component from * @returns {Component} * @ignore diff --git a/packages/discord.js/src/util/Constants.js b/packages/discord.js/src/util/Constants.js index c4209cb3c4bc..b6413285672b 100644 --- a/packages/discord.js/src/util/Constants.js +++ b/packages/discord.js/src/util/Constants.js @@ -4,28 +4,30 @@ const { ChannelType, MessageType, ComponentType, ImageFormat, StickerFormatType /** * Max bulk deletable message age + * * @typedef {number} MaxBulkDeletableMessageAge */ exports.MaxBulkDeletableMessageAge = 1_209_600_000; /** * The name of an item to be swept in Sweepers - * * `autoModerationRules` - * * `applicationCommands` - both global and guild commands - * * `bans` - * * `emojis` - * * `entitlements` - * * `invites` - accepts the `lifetime` property, using it will sweep based on expires timestamp - * * `guildMembers` - * * `messages` - accepts the `lifetime` property, using it will sweep based on edited or created timestamp - * * `presences` - * * `reactions` - * * `stageInstances` - * * `stickers` - * * `threadMembers` - * * `threads` - accepts the `lifetime` property, using it will sweep archived threads based on archived timestamp - * * `users` - * * `voiceStates` + * `autoModerationRules` + * `applicationCommands` - both global and guild commands + * `bans` + * `emojis` + * `entitlements` + * `invites` - accepts the `lifetime` property, using it will sweep based on expires timestamp + * `guildMembers` + * `messages` - accepts the `lifetime` property, using it will sweep based on edited or created timestamp + * `presences` + * `reactions` + * `stageInstances` + * `stickers` + * `threadMembers` + * `threads` - accepts the `lifetime` property, using it will sweep archived threads based on archived timestamp + * `users` + * `voiceStates` + * * @typedef {string} SweeperKey */ exports.SweeperKeys = [ @@ -49,10 +51,11 @@ exports.SweeperKeys = [ /** * The types of messages that are not `System`. The available types are: - * * {@link MessageType.Default} - * * {@link MessageType.Reply} - * * {@link MessageType.ChatInputCommand} - * * {@link MessageType.ContextMenuCommand} + * {@link MessageType.Default} + * {@link MessageType.Reply} + * {@link MessageType.ChatInputCommand} + * {@link MessageType.ContextMenuCommand} + * * @typedef {MessageType[]} NonSystemMessageTypes */ exports.NonSystemMessageTypes = [ @@ -64,23 +67,25 @@ exports.NonSystemMessageTypes = [ /** * The guild channels that are text-based. - * * TextChannel - * * AnnouncementChannel - * * ThreadChannel - * * VoiceChannel - * * StageChannel + * TextChannel + * AnnouncementChannel + * ThreadChannel + * VoiceChannel + * StageChannel + * * @typedef {TextChannel|AnnouncementChannel|ThreadChannel|VoiceChannel|StageChannel} GuildTextBasedChannel */ /** * The types of guild channels that are text-based. The available types are: - * * {@link ChannelType.GuildText} - * * {@link ChannelType.GuildAnnouncement} - * * {@link ChannelType.AnnouncementThread} - * * {@link ChannelType.PublicThread} - * * {@link ChannelType.PrivateThread} - * * {@link ChannelType.GuildVoice} - * * {@link ChannelType.GuildStageVoice} + * {@link ChannelType.GuildText} + * {@link ChannelType.GuildAnnouncement} + * {@link ChannelType.AnnouncementThread} + * {@link ChannelType.PublicThread} + * {@link ChannelType.PrivateThread} + * {@link ChannelType.GuildVoice} + * {@link ChannelType.GuildStageVoice} + * * @typedef {ChannelType[]} GuildTextBasedChannelTypes */ exports.GuildTextBasedChannelTypes = [ @@ -95,71 +100,78 @@ exports.GuildTextBasedChannelTypes = [ /** * The channels that are text-based. - * * {@link DMChannel} - * * {@link GuildTextBasedChannel} + * {@link DMChannel} + * {@link GuildTextBasedChannel} + * * @typedef {DMChannel|GuildTextBasedChannel} TextBasedChannels */ /** * Data that resolves to give a text-based channel. This can be: - * * A {@link TextBasedChannel} - * * A {@link Snowflake} + * A {@link TextBasedChannel} + * A {@link Snowflake} + * * @typedef {TextBasedChannels|Snowflake} TextBasedChannelsResolvable */ /** * The types of channels that are text-based. The available types are: - * * {@link ChannelType.DM} - * * {@link ChannelType.GuildText} - * * {@link ChannelType.GuildAnnouncement} - * * {@link ChannelType.AnnouncementThread} - * * {@link ChannelType.PublicThread} - * * {@link ChannelType.PrivateThread} - * * {@link ChannelType.GuildVoice} - * * {@link ChannelType.GuildStageVoice} - * * {@link ChannelType.GroupDM} + * {@link ChannelType.DM} + * {@link ChannelType.GuildText} + * {@link ChannelType.GuildAnnouncement} + * {@link ChannelType.AnnouncementThread} + * {@link ChannelType.PublicThread} + * {@link ChannelType.PrivateThread} + * {@link ChannelType.GuildVoice} + * {@link ChannelType.GuildStageVoice} + * {@link ChannelType.GroupDM} + * * @typedef {ChannelType[]} TextBasedChannelTypes */ exports.TextBasedChannelTypes = [...exports.GuildTextBasedChannelTypes, ChannelType.DM, ChannelType.GroupDM]; /** * The types of channels that are text-based and can have messages sent into. The available types are: - * * {@link ChannelType.DM} - * * {@link ChannelType.GuildText} - * * {@link ChannelType.GuildAnnouncement} - * * {@link ChannelType.AnnouncementThread} - * * {@link ChannelType.PublicThread} - * * {@link ChannelType.PrivateThread} - * * {@link ChannelType.GuildVoice} - * * {@link ChannelType.GuildStageVoice} + * {@link ChannelType.DM} + * {@link ChannelType.GuildText} + * {@link ChannelType.GuildAnnouncement} + * {@link ChannelType.AnnouncementThread} + * {@link ChannelType.PublicThread} + * {@link ChannelType.PrivateThread} + * {@link ChannelType.GuildVoice} + * {@link ChannelType.GuildStageVoice} + * * @typedef {ChannelType[]} SendableChannels */ exports.SendableChannels = [...exports.GuildTextBasedChannelTypes, ChannelType.DM]; /** * The types of channels that are threads. The available types are: - * * {@link ChannelType.AnnouncementThread} - * * {@link ChannelType.PublicThread} - * * {@link ChannelType.PrivateThread} + * {@link ChannelType.AnnouncementThread} + * {@link ChannelType.PublicThread} + * {@link ChannelType.PrivateThread} + * * @typedef {ChannelType[]} ThreadChannelTypes */ exports.ThreadChannelTypes = [ChannelType.AnnouncementThread, ChannelType.PublicThread, ChannelType.PrivateThread]; /** * The types of channels that are voice-based. The available types are: - * * {@link ChannelType.GuildVoice} - * * {@link ChannelType.GuildStageVoice} + * {@link ChannelType.GuildVoice} + * {@link ChannelType.GuildStageVoice} + * * @typedef {ChannelType[]} VoiceBasedChannelTypes */ exports.VoiceBasedChannelTypes = [ChannelType.GuildVoice, ChannelType.GuildStageVoice]; /** * The types of select menus. The available types are: - * * {@link ComponentType.StringSelect} - * * {@link ComponentType.UserSelect} - * * {@link ComponentType.RoleSelect} - * * {@link ComponentType.MentionableSelect} - * * {@link ComponentType.ChannelSelect} + * {@link ComponentType.StringSelect} + * {@link ComponentType.UserSelect} + * {@link ComponentType.RoleSelect} + * {@link ComponentType.MentionableSelect} + * {@link ComponentType.ChannelSelect} + * * @typedef {ComponentType[]} SelectMenuTypes */ exports.SelectMenuTypes = [ @@ -172,12 +184,13 @@ exports.SelectMenuTypes = [ /** * The types of messages that cannot be deleted. The available types are: - * * {@link MessageType.RecipientAdd} - * * {@link MessageType.RecipientRemove} - * * {@link MessageType.Call} - * * {@link MessageType.ChannelNameChange} - * * {@link MessageType.ChannelIconChange} - * * {@link MessageType.ThreadStarterMessage} + * {@link MessageType.RecipientAdd} + * {@link MessageType.RecipientRemove} + * {@link MessageType.Call} + * {@link MessageType.ChannelNameChange} + * {@link MessageType.ChannelIconChange} + * {@link MessageType.ThreadStarterMessage} + * * @typedef {MessageType[]} UndeletableMessageTypes */ exports.UndeletableMessageTypes = [ @@ -191,11 +204,16 @@ exports.UndeletableMessageTypes = [ /** * A mapping between sticker formats and their respective image formats. - * * {@link StickerFormatType.PNG} -> {@link ImageFormat.PNG} - * * {@link StickerFormatType.APNG} -> {@link ImageFormat.PNG} - * * {@link StickerFormatType.Lottie} -> {@link ImageFormat.Lottie} - * * {@link StickerFormatType.GIF} -> {@link ImageFormat.GIF} - * @typedef {Object} StickerFormatExtensionMap + * {@link StickerFormatType.PNG} -> {@link ImageFormat.PNG} + * {@link StickerFormatType.APNG} -> {@link ImageFormat.PNG} + * {@link StickerFormatType.Lottie} -> {@link ImageFormat.Lottie} + * {@link StickerFormatType.GIF} -> {@link ImageFormat.GIF} + * + * @typedef {object} StickerFormatExtensionMap + * @property {"png"} 1 PNG + * @property {"png"} 2 APNG + * @property {"json"} 3 Lottie + * @property {"gif"} 4 GIF */ exports.StickerFormatExtensionMap = { [StickerFormatType.PNG]: ImageFormat.PNG, @@ -205,7 +223,7 @@ exports.StickerFormatExtensionMap = { }; /** - * @typedef {Object} Constants Constants that can be used in an enum or object-like way. + * @typedef {object} Constants Constants that can be used in an enum or object-like way. * @property {number} MaxBulkDeletableMessageAge Max bulk deletable message age * @property {SweeperKey[]} SweeperKeys The possible names of items that can be swept in sweepers * @property {NonSystemMessageTypes} NonSystemMessageTypes The types of messages that are not deemed a system type @@ -213,5 +231,5 @@ exports.StickerFormatExtensionMap = { * @property {ThreadChannelTypes} ThreadChannelTypes The types of channels that are threads * @property {VoiceBasedChannelTypes} VoiceBasedChannelTypes The types of channels that are voice-based * @property {SelectMenuTypes} SelectMenuTypes The types of components that are select menus. - * @property {Object} StickerFormatExtensionMap A mapping between sticker formats and their respective image formats. + * @property {object} StickerFormatExtensionMap A mapping between sticker formats and their respective image formats. */ diff --git a/packages/discord.js/src/util/DataResolver.js b/packages/discord.js/src/util/DataResolver.js index 6f1351591290..0df2886177f1 100644 --- a/packages/discord.js/src/util/DataResolver.js +++ b/packages/discord.js/src/util/DataResolver.js @@ -9,20 +9,23 @@ const { Invite } = require('../structures/Invite.js'); /** * Data that can be resolved to give an invite code. This can be: - * * An invite code - * * An invite URL + * An invite code + * An invite URL + * * @typedef {string} InviteResolvable */ /** * Data that can be resolved to give a template code. This can be: - * * A template code - * * A template URL + * A template code + * A template URL + * * @typedef {string} GuildTemplateResolvable */ /** * Resolves the string to a code based on the passed regex. + * * @param {string} data The string to resolve * @param {RegExp} regex The RegExp used to extract the code * @returns {string} @@ -34,6 +37,7 @@ function resolveCode(data, regex) { /** * Resolves InviteResolvable to an invite code. + * * @param {InviteResolvable} data The invite resolvable to resolve * @returns {string} * @private @@ -44,6 +48,7 @@ function resolveInviteCode(data) { /** * Resolves GuildTemplateResolvable to a template code. + * * @param {GuildTemplateResolvable} data The template resolvable to resolve * @returns {string} * @private @@ -55,10 +60,11 @@ function resolveGuildTemplateCode(data) { /** * Data that can be resolved to give a Buffer. This can be: - * * A Buffer - * * The path to a local file - * * A URL When provided a URL, discord.js will fetch the URL internally in order to create a Buffer. + * A Buffer + * The path to a local file + * A URL When provided a URL, discord.js will fetch the URL internally in order to create a Buffer. * This can pose a security risk when the URL has not been sanitized + * * @typedef {string|Buffer} BufferResolvable */ @@ -68,7 +74,7 @@ function resolveGuildTemplateCode(data) { */ /** - * @typedef {Object} ResolvedFile + * @typedef {object} ResolvedFile * @property {Buffer} data Buffer containing the file data * @property {string} [contentType] Content-Type of the file * @private @@ -76,6 +82,7 @@ function resolveGuildTemplateCode(data) { /** * Resolves a BufferResolvable to a Buffer. + * * @param {BufferResolvable|Stream} resource The buffer or stream resolvable to resolve * @returns {Promise} * @private @@ -107,15 +114,17 @@ async function resolveFile(resource) { /** * Data that resolves to give a Base64 string, typically for image uploading. This can be: - * * A Buffer - * * A base64 string + * A Buffer + * A base64 string + * * @typedef {Buffer|string} Base64Resolvable */ /** * Resolves a Base64Resolvable to a Base 64 string. + * * @param {Base64Resolvable} data The base 64 resolvable you want to resolve - * @param {string} [contentType='image/jpg'] The content type of the data + * @param {string} [contentType] The content type of the data * @returns {string} * @private */ @@ -126,6 +135,7 @@ function resolveBase64(data, contentType = 'image/jpg') { /** * Resolves a Base64Resolvable, a string, or a BufferResolvable to a Base 64 image. + * * @param {BufferResolvable|Base64Resolvable} image The image to be resolved * @returns {Promise} * @private @@ -135,6 +145,7 @@ async function resolveImage(image) { if (typeof image === 'string' && image.startsWith('data:')) { return image; } + const file = await resolveFile(image); return resolveBase64(file.data); } diff --git a/packages/discord.js/src/util/Enums.js b/packages/discord.js/src/util/Enums.js index aafb646c09fb..1536c7e18c4b 100644 --- a/packages/discord.js/src/util/Enums.js +++ b/packages/discord.js/src/util/Enums.js @@ -7,6 +7,7 @@ function createEnum(keys) { obj[key] = index; obj[index] = key; } + return obj; } diff --git a/packages/discord.js/src/util/Events.js b/packages/discord.js/src/util/Events.js index c546055e755b..92ab18111e78 100644 --- a/packages/discord.js/src/util/Events.js +++ b/packages/discord.js/src/util/Events.js @@ -1,7 +1,7 @@ 'use strict'; /** - * @typedef {Object} Events + * @typedef {object} Events * @property {string} ApplicationCommandPermissionsUpdate applicationCommandPermissionsUpdate * @property {string} AutoModerationActionExecution autoModerationActionExecution * @property {string} AutoModerationRuleCreate autoModerationRuleCreate diff --git a/packages/discord.js/src/util/GuildMemberFlagsBitField.js b/packages/discord.js/src/util/GuildMemberFlagsBitField.js index 775f2adeac04..f0182d7c795c 100644 --- a/packages/discord.js/src/util/GuildMemberFlagsBitField.js +++ b/packages/discord.js/src/util/GuildMemberFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with a {@link GuildMember#flags} bitfield. + * * @extends {BitField} */ class GuildMemberFlagsBitField extends BitField { /** * Numeric guild guild member flags. + * * @type {GuildMemberFlags} * @memberof GuildMemberFlagsBitField */ @@ -18,23 +20,25 @@ class GuildMemberFlagsBitField extends BitField { /** * @name GuildMemberFlagsBitField - * @kind constructor + * @constructor * @memberof GuildMemberFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ /** * Bitfield of the packed bits + * * @type {number} * @name GuildMemberFlagsBitField#bitfield */ /** * Data that can be resolved to give a guild member flag bitfield. This can be: - * * A string (see {@link GuildMemberFlagsBitField.Flags}) - * * A guild member flag - * * An instance of GuildMemberFlagsBitField - * * An Array of GuildMemberFlagsResolvable + * A string (see {@link GuildMemberFlagsBitField.Flags}) + * A guild member flag + * An instance of GuildMemberFlagsBitField + * An Array of GuildMemberFlagsResolvable + * * @typedef {string|number|GuildMemberFlagsBitField|GuildMemberFlagsResolvable[]} GuildMemberFlagsResolvable */ diff --git a/packages/discord.js/src/util/IntentsBitField.js b/packages/discord.js/src/util/IntentsBitField.js index e6db0ec080f5..ac6f904b0da9 100644 --- a/packages/discord.js/src/util/IntentsBitField.js +++ b/packages/discord.js/src/util/IntentsBitField.js @@ -4,11 +4,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to calculate intents. + * * @extends {BitField} */ class IntentsBitField extends BitField { /** * Numeric WebSocket intents + * * @type {GatewayIntentBits} * @memberof IntentsBitField */ @@ -17,17 +19,18 @@ class IntentsBitField extends BitField { /** * @name IntentsBitField - * @kind constructor + * @constructor * @memberof IntentsBitField * @param {IntentsResolvable} [bits=0] Bit(s) to read from */ /** * Data that can be resolved to give a permission number. This can be: - * * A string (see {@link IntentsBitField.Flags}) - * * An intents flag - * * An instance of {@link IntentsBitField} - * * An array of IntentsResolvable + * A string (see {@link IntentsBitField.Flags}) + * An intents flag + * An instance of {@link IntentsBitField} + * An array of IntentsResolvable + * * @typedef {string|number|IntentsBitField|IntentsResolvable[]} IntentsResolvable */ diff --git a/packages/discord.js/src/util/LimitedCollection.js b/packages/discord.js/src/util/LimitedCollection.js index 37b349766fb6..2272a8f9d566 100644 --- a/packages/discord.js/src/util/LimitedCollection.js +++ b/packages/discord.js/src/util/LimitedCollection.js @@ -5,7 +5,8 @@ const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); /** * Options for defining the behavior of a LimitedCollection - * @typedef {Object} LimitedCollectionOptions + * + * @typedef {object} LimitedCollectionOptions * @property {?number} [maxSize=Infinity] The maximum size of the Collection * @property {?Function} [keepOverLimit=null] A function, which is passed the value and key of an entry, ran to decide * to keep an entry past the maximum size @@ -13,20 +14,23 @@ const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); /** * A Collection which holds a max amount of entries. + * * @extends {Collection} * @param {LimitedCollectionOptions} [options={}] Options for constructing the Collection. - * @param {Iterable} [iterable=null] Optional entries passed to the Map constructor. + * @param {Iterable} [iterable] Optional entries passed to the Map constructor. */ class LimitedCollection extends Collection { - constructor(options = {}, iterable) { + constructor(options = {}, iterable = undefined) { if (typeof options !== 'object' || options === null) { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); } + const { maxSize = Infinity, keepOverLimit = null } = options; if (typeof maxSize !== 'number') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'maxSize', 'number'); } + if (keepOverLimit !== null && typeof keepOverLimit !== 'function') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'keepOverLimit', 'function'); } @@ -35,12 +39,14 @@ class LimitedCollection extends Collection { /** * The max size of the Collection. + * * @type {number} */ this.maxSize = maxSize; /** * A function called to check if an entry should be kept when the Collection is at max size. + * * @type {?Function} */ this.keepOverLimit = keepOverLimit; @@ -49,14 +55,15 @@ class LimitedCollection extends Collection { set(key, value) { if (this.maxSize === 0 && !this.keepOverLimit?.(value, key, this)) return this; if (this.size >= this.maxSize && !this.has(key)) { - for (const [k, v] of this.entries()) { - const keep = this.keepOverLimit?.(v, k, this) ?? false; + for (const [iteratedKey, iteratedValue] of this.entries()) { + const keep = this.keepOverLimit?.(iteratedValue, iteratedKey, this) ?? false; if (!keep) { - this.delete(k); + this.delete(iteratedKey); break; } } } + return super.set(key, value); } diff --git a/packages/discord.js/src/util/MessageFlagsBitField.js b/packages/discord.js/src/util/MessageFlagsBitField.js index a2b04c968c71..b9a7a4e15127 100644 --- a/packages/discord.js/src/util/MessageFlagsBitField.js +++ b/packages/discord.js/src/util/MessageFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with a {@link Message#flags} bitfield. + * * @extends {BitField} */ class MessageFlagsBitField extends BitField { /** * Numeric message flags. + * * @type {MessageFlags} * @memberof MessageFlagsBitField */ @@ -18,22 +20,24 @@ class MessageFlagsBitField extends BitField { /** * @name MessageFlagsBitField - * @kind constructor + * @constructor * @memberof MessageFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ /** * Data that can be resolved to give a message flags bit field. This can be: - * * A string (see {@link MessageFlagsBitField.Flags}) - * * A message flag - * * An instance of {@link MessageFlagsBitField} - * * An array of `MessageFlagsResolvable` + * A string (see {@link MessageFlagsBitField.Flags}) + * A message flag + * An instance of {@link MessageFlagsBitField} + * An array of `MessageFlagsResolvable` + * * @typedef {string|number|MessageFlagsBitField|MessageFlagsResolvable[]} MessageFlagsResolvable */ /** * Bitfield of the packed bits + * * @type {number} * @name MessageFlagsBitField#bitfield */ diff --git a/packages/discord.js/src/util/Options.js b/packages/discord.js/src/util/Options.js index 7f7a83623692..58728ab9d300 100644 --- a/packages/discord.js/src/util/Options.js +++ b/packages/discord.js/src/util/Options.js @@ -2,8 +2,8 @@ const { DefaultRestOptions, DefaultUserAgentAppendix } = require('@discordjs/rest'); const { DefaultWebSocketManagerOptions } = require('@discordjs/ws'); -const { toSnakeCase } = require('./Transformers.js'); const { version } = require('../../package.json'); +const { toSnakeCase } = require('./Transformers.js'); // TODO(ckohen): switch order of params so full manager is first and "type" is optional /** @@ -16,7 +16,8 @@ const { version } = require('../../package.json'); /** * Options for a client. - * @typedef {Object} ClientOptions + * + * @typedef {object} ClientOptions * @property {number} [closeTimeout=5_000] The amount of time in milliseconds to wait for the close frame to be received * from the WebSocket. Don't have this too high/low. It's best to have it between 2_000-6_000 ms. * @property {CacheFactory} [makeCache] Function to create a cache. @@ -42,12 +43,14 @@ const { version } = require('../../package.json'); /** * Options for {@link Sweepers} defining the behavior of cache sweeping - * @typedef {Object} SweeperOptions + * + * @typedef {Record} SweeperOptions */ /** * Options for sweeping a single type of item from cache - * @typedef {Object} SweepOptions + * + * @typedef {object} SweepOptions * @property {number} interval The interval (in seconds) at which to perform sweeping of the item * @property {number} [lifetime] How long an item should stay in cache until it is considered sweepable. * This property is only valid for the `invites`, `messages`, and `threads` keys. The `filter` property @@ -62,6 +65,7 @@ const { version } = require('../../package.json'); class Options extends null { /** * The default user agent appendix. + * * @type {string} * @memberof Options * @private @@ -70,6 +74,7 @@ class Options extends null { /** * The default client options. + * * @returns {ClientOptions} */ static createDefault() { @@ -96,7 +101,8 @@ class Options extends null { /** * Create a cache factory using predefined settings to sweep or limit. - * @param {Object} [settings={}] Settings passed to the relevant constructor. + * + * @param {Record} [settings] Settings passed to the relevant constructor. * If no setting is provided for a manager, it uses Collection. * If a number is provided for a manager, it uses that number as the max size for a LimitedCollection. * If LimitedCollectionOptions are provided for a manager, it uses those settings to form a LimitedCollection. @@ -117,27 +123,32 @@ class Options extends null { return (managerType, _, manager) => { const setting = settings[manager.name] ?? settings[managerType.name]; - /* eslint-disable-next-line eqeqeq */ + /* eslint-disable-next-line eqeqeq, no-eq-null */ if (setting == null) { return new Collection(); } + if (typeof setting === 'number') { if (setting === Infinity) { return new Collection(); } + return new LimitedCollection({ maxSize: setting }); } - /* eslint-disable-next-line eqeqeq */ + + /* eslint-disable-next-line eqeqeq, no-eq-null */ const noLimit = setting.maxSize == null || setting.maxSize === Infinity; if (noLimit) { return new Collection(); } + return new LimitedCollection(setting); }; } /** * Create a cache factory that always caches everything. + * * @returns {CacheFactory} */ static cacheEverything() { @@ -148,10 +159,11 @@ class Options extends null { /** * The default settings passed to {@link ClientOptions.makeCache}. * The caches that this changes are: - * * `MessageManager` - Limit to 200 messages + * `MessageManager` - Limit to 200 messages * If you want to keep default behavior and add on top of it you can use this object and add on to it, e.g. * `makeCache: Options.cacheWithLimits({ ...Options.DefaultMakeCacheSettings, ReactionManager: 0 })` - * @type {Object} + * + * @type {Record} */ static get DefaultMakeCacheSettings() { return { @@ -162,16 +174,17 @@ class Options extends null { /** * The default settings passed to {@link ClientOptions.sweepers}. * The sweepers that this changes are: - * * `threads` - Sweep archived threads every hour, removing those archived more than 4 hours ago + * `threads` - Sweep archived threads every hour, removing those archived more than 4 hours ago * If you want to keep default behavior and add on top of it you can use this object and add on to it, e.g. * `sweepers: { ...Options.DefaultSweeperSettings, messages: { interval: 300, lifetime: 600 } }` + * * @type {SweeperOptions} */ static get DefaultSweeperSettings() { return { threads: { - interval: 3600, - lifetime: 14400, + interval: 3_600, + lifetime: 14_400, }, }; } diff --git a/packages/discord.js/src/util/Partials.js b/packages/discord.js/src/util/Partials.js index 5dbddbefa618..e671adcb9a8f 100644 --- a/packages/discord.js/src/util/Partials.js +++ b/packages/discord.js/src/util/Partials.js @@ -8,16 +8,17 @@ const { createEnum } = require('./Enums.js'); * import { Client, Partials } from 'discord.js'; * * const client = new Client({ - * intents: [ - * // Intents... - * ], - * partials: [ - * Partials.User, // We want to receive uncached users! - * Partials.Message // We want to receive uncached messages! - * ] + * intents: [ + * // Intents... + * ], + * partials: [ + * Partials.User, // We want to receive uncached users! + * Partials.Message // We want to receive uncached messages! + * ] * }); * ``` - * @typedef {Object} Partials + * + * @typedef {object} Partials * @property {number} User The partial to receive uncached users. * @property {number} Channel The partial to receive uncached channels. * This is required to receive direct messages! diff --git a/packages/discord.js/src/util/PermissionsBitField.js b/packages/discord.js/src/util/PermissionsBitField.js index 19488190a953..77c711feaf21 100644 --- a/packages/discord.js/src/util/PermissionsBitField.js +++ b/packages/discord.js/src/util/PermissionsBitField.js @@ -7,11 +7,13 @@ const { BitField } = require('./BitField.js'); * Data structure that makes it easy to interact with a permission bitfield. All {@link GuildMember}s have a set of * permissions in their guild, and each channel in the guild may also have {@link PermissionOverwrites} for the member * that override their default permissions. + * * @extends {BitField} */ class PermissionsBitField extends BitField { /** * Numeric permission flags. + * * @type {PermissionFlagsBits} * @memberof PermissionsBitField * @see {@link https://discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags} @@ -20,20 +22,24 @@ class PermissionsBitField extends BitField { /** * Bitfield representing every permission combined + * * @type {bigint} * @memberof PermissionsBitField */ - static All = Object.values(PermissionFlagsBits).reduce((all, p) => all | p, 0n); + + static All = Object.values(PermissionFlagsBits).reduce((all, perm) => all | perm, 0n); /** * Bitfield representing the default permissions for users + * * @type {bigint} * @memberof PermissionsBitField */ - static Default = BigInt(104324673); + static Default = BigInt(104_324_673); /** * Bitfield representing the permissions required for moderators of stage channels + * * @type {bigint} * @memberof PermissionsBitField */ @@ -49,23 +55,26 @@ class PermissionsBitField extends BitField { /** * Bitfield of the packed bits + * * @type {bigint} * @name PermissionsBitField#bitfield */ /** * Data that can be resolved to give a permission number. This can be: - * * A string (see {@link PermissionsBitField.Flags}) - * * A permission number - * * An instance of {@link PermissionsBitField} - * * An Array of PermissionResolvable + * A string (see {@link PermissionsBitField.Flags}) + * A permission number + * An instance of {@link PermissionsBitField} + * An Array of PermissionResolvable + * * @typedef {string|bigint|PermissionsBitField|PermissionResolvable[]} PermissionResolvable */ /** * Gets all given bits that are missing from the bitfield. + * * @param {BitFieldResolvable} bits Bit(s) to check for - * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override + * @param {boolean} [checkAdmin] Whether to allow the administrator permission to override * @returns {string[]} */ missing(bits, checkAdmin = true) { @@ -74,8 +83,9 @@ class PermissionsBitField extends BitField { /** * Checks whether the bitfield has a permission, or any of multiple permissions. + * * @param {PermissionResolvable} permission Permission(s) to check for - * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override + * @param {boolean} [checkAdmin] Whether to allow the administrator permission to override * @returns {boolean} */ any(permission, checkAdmin = true) { @@ -84,8 +94,9 @@ class PermissionsBitField extends BitField { /** * Checks whether the bitfield has a permission, or multiple permissions. + * * @param {PermissionResolvable} permission Permission(s) to check for - * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override + * @param {boolean} [checkAdmin] Whether to allow the administrator permission to override * @returns {boolean} */ has(permission, checkAdmin = true) { @@ -94,6 +105,7 @@ class PermissionsBitField extends BitField { /** * Gets an {@link Array} of bitfield names based on the permissions available. + * * @returns {string[]} */ toArray() { diff --git a/packages/discord.js/src/util/RoleFlagsBitField.js b/packages/discord.js/src/util/RoleFlagsBitField.js index e6625749ad87..e0d4c117c482 100644 --- a/packages/discord.js/src/util/RoleFlagsBitField.js +++ b/packages/discord.js/src/util/RoleFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with a {@link Role#flags} bitfield. + * * @extends {BitField} */ class RoleFlagsBitField extends BitField { /** * Numeric role flags. + * * @type {RoleFlags} * @memberof RoleFlagsBitField */ @@ -18,7 +20,7 @@ class RoleFlagsBitField extends BitField { /** * @name RoleFlagsBitField - * @kind constructor + * @constructor * @memberof RoleFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/SKUFlagsBitField.js b/packages/discord.js/src/util/SKUFlagsBitField.js index ec11f66411de..fa46485f4cac 100644 --- a/packages/discord.js/src/util/SKUFlagsBitField.js +++ b/packages/discord.js/src/util/SKUFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with an {@link SKU#flags} bitfield. + * * @extends {BitField} */ class SKUFlagsBitField extends BitField { /** * Numeric SKU flags. + * * @type {SKUFlags} * @memberof SKUFlagsBitField */ @@ -18,7 +20,7 @@ class SKUFlagsBitField extends BitField { /** * @name SKUFlagsBitField - * @kind constructor + * @constructor * @memberof SKUFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/ShardEvents.js b/packages/discord.js/src/util/ShardEvents.js index 831e44913df9..4b079db90527 100644 --- a/packages/discord.js/src/util/ShardEvents.js +++ b/packages/discord.js/src/util/ShardEvents.js @@ -1,7 +1,7 @@ 'use strict'; /** - * @typedef {Object} ShardEvents + * @typedef {object} ShardEvents * @property {string} Death death * @property {string} Disconnect disconnect * @property {string} Error error diff --git a/packages/discord.js/src/util/Status.js b/packages/discord.js/src/util/Status.js index 8a3ab137bdaa..d603751ddd55 100644 --- a/packages/discord.js/src/util/Status.js +++ b/packages/discord.js/src/util/Status.js @@ -3,10 +3,10 @@ const { createEnum } = require('./Enums.js'); /** - * @typedef {Object} Status - * @property {number} Ready - * @property {number} Idle - * @property {number} WaitingForGuilds + * @typedef {object} Status + * @property {number} Ready ready + * @property {number} Idle idle + * @property {number} WaitingForGuilds waiting for guilds */ // JSDoc for IntelliSense purposes diff --git a/packages/discord.js/src/util/Sweepers.js b/packages/discord.js/src/util/Sweepers.js index c03475697a75..a256bd7b21ed 100644 --- a/packages/discord.js/src/util/Sweepers.js +++ b/packages/discord.js/src/util/Sweepers.js @@ -1,9 +1,9 @@ 'use strict'; const { setInterval, clearInterval } = require('node:timers'); +const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const { ThreadChannelTypes, SweeperKeys } = require('./Constants.js'); const { Events } = require('./Events.js'); -const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); /** * @typedef {Function} GlobalSweepFilter @@ -19,6 +19,7 @@ class Sweepers { constructor(client, options) { /** * The client that instantiated this + * * @type {Client} * @readonly */ @@ -26,13 +27,15 @@ class Sweepers { /** * The options the sweepers were instantiated with + * * @type {SweeperOptions} */ this.options = options; /** * A record of interval timeout that is used to sweep the indicated items, or null if not being swept - * @type {Object} + * + * @type {Record} */ this.intervals = Object.fromEntries(SweeperKeys.map(key => [key, null])); @@ -63,6 +66,7 @@ class Sweepers { /** * Sweeps all guild and global application commands and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which commands will be removed from the caches. * @returns {number} Amount of commands that were removed from the caches */ @@ -80,6 +84,7 @@ class Sweepers { /** * Sweeps all auto moderation rules and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine * which auto moderation rules will be removed from the caches * @returns {number} Amount of auto moderation rules that were removed from the caches @@ -90,6 +95,7 @@ class Sweepers { /** * Sweeps all guild bans and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which bans will be removed from the caches. * @returns {number} Amount of bans that were removed from the caches */ @@ -99,6 +105,7 @@ class Sweepers { /** * Sweeps all guild emojis and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which emojis will be removed from the caches. * @returns {number} Amount of emojis that were removed from the caches */ @@ -108,6 +115,7 @@ class Sweepers { /** * Sweeps all client application entitlements and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which entitlements will be removed from the caches. * @returns {number} Amount of entitlements that were removed from the caches */ @@ -125,6 +133,7 @@ class Sweepers { /** * Sweeps all guild invites and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which invites will be removed from the caches. * @returns {number} Amount of invites that were removed from the caches */ @@ -135,6 +144,7 @@ class Sweepers { /** * Sweeps all guild members and removes the ones which are indicated by the filter. * It is highly recommended to keep the client guild member cached + * * @param {Function} filter The function used to determine which guild members will be removed from the caches. * @returns {number} Amount of guild members that were removed from the caches */ @@ -144,6 +154,7 @@ class Sweepers { /** * Sweeps all text-based channels' messages and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which messages will be removed from the caches. * @returns {number} Amount of messages that were removed from the caches * @example @@ -160,6 +171,7 @@ class Sweepers { if (typeof filter !== 'function') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function'); } + let channels = 0; let messages = 0; @@ -169,12 +181,14 @@ class Sweepers { channels++; messages += channel.messages.cache.sweep(filter); } + this.client.emit(Events.CacheSweep, `Swept ${messages} messages in ${channels} text-based channels.`); return messages; } /** * Sweeps all presences and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which presences will be removed from the caches. * @returns {number} Amount of presences that were removed from the caches */ @@ -184,6 +198,7 @@ class Sweepers { /** * Sweeps all message reactions and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which reactions will be removed from the caches. * @returns {number} Amount of reactions that were removed from the caches */ @@ -191,6 +206,7 @@ class Sweepers { if (typeof filter !== 'function') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function'); } + let channels = 0; let messages = 0; let reactions = 0; @@ -204,6 +220,7 @@ class Sweepers { reactions += message.reactions.cache.sweep(filter); } } + this.client.emit( Events.CacheSweep, `Swept ${reactions} reactions on ${messages} messages in ${channels} text-based channels.`, @@ -213,6 +230,7 @@ class Sweepers { /** * Sweeps all guild stage instances and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which stage instances will be removed from the caches. * @returns {number} Amount of stage instances that were removed from the caches */ @@ -222,6 +240,7 @@ class Sweepers { /** * Sweeps all guild stickers and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which stickers will be removed from the caches. * @returns {number} Amount of stickers that were removed from the caches */ @@ -232,6 +251,7 @@ class Sweepers { /** * Sweeps all thread members and removes the ones which are indicated by the filter. * It is highly recommended to keep the client thread member cached + * * @param {Function} filter The function used to determine which thread members will be removed from the caches. * @returns {number} Amount of thread members that were removed from the caches */ @@ -247,12 +267,14 @@ class Sweepers { threads++; members += channel.members.cache.sweep(filter); } + this.client.emit(Events.CacheSweep, `Swept ${members} thread members in ${threads} threads.`); return members; } /** * Sweeps all threads and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which threads will be removed from the caches. * @returns {number} filter Amount of threads that were removed from the caches * @example @@ -278,12 +300,14 @@ class Sweepers { this.client.channels._remove(key); } } + this.client.emit(Events.CacheSweep, `Swept ${threads} threads.`); return threads; } /** * Sweeps all users and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which users will be removed from the caches. * @returns {number} Amount of users that were removed from the caches */ @@ -301,6 +325,7 @@ class Sweepers { /** * Sweeps all guild voice states and removes the ones which are indicated by the filter. + * * @param {Function} filter The function used to determine which voice states will be removed from the caches. * @returns {number} Amount of voice states that were removed from the caches */ @@ -310,6 +335,7 @@ class Sweepers { /** * Cancels all sweeping intervals + * * @returns {void} */ destroy() { @@ -320,7 +346,8 @@ class Sweepers { /** * Options for generating a filter function based on lifetime - * @typedef {Object} LifetimeFilterOptions + * + * @typedef {object} LifetimeFilterOptions * @property {number} [lifetime=14400] How long, in seconds, an entry should stay in the collection * before it is considered sweepable. * @property {Function} [getComparisonTimestamp=e => e?.createdTimestamp] A function that takes an entry, key, @@ -331,23 +358,27 @@ class Sweepers { /** * Create a sweepFilter function that uses a lifetime to determine sweepability. - * @param {LifetimeFilterOptions} [options={}] The options used to generate the filter function + * + * @param {LifetimeFilterOptions} [options] The options used to generate the filter function * @returns {GlobalSweepFilter} */ static filterByLifetime({ - lifetime = 14400, - getComparisonTimestamp = e => e?.createdTimestamp, + lifetime = 14_400, + getComparisonTimestamp = item => item?.createdTimestamp, excludeFromSweep = () => false, } = {}) { if (typeof lifetime !== 'number') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'lifetime', 'number'); } + if (typeof getComparisonTimestamp !== 'function') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'getComparisonTimestamp', 'function'); } + if (typeof excludeFromSweep !== 'function') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'excludeFromSweep', 'function'); } + return () => { if (lifetime <= 0) return null; const lifetimeMs = lifetime * 1_000; @@ -356,6 +387,7 @@ class Sweepers { if (excludeFromSweep(entry, key, coll)) { return false; } + const comparisonTimestamp = getComparisonTimestamp(entry, key, coll); if (!comparisonTimestamp || typeof comparisonTimestamp !== 'number') return false; return now - comparisonTimestamp > lifetimeMs; @@ -365,44 +397,48 @@ class Sweepers { /** * Creates a sweep filter that sweeps archived threads - * @param {number} [lifetime=14400] How long a thread has to be archived to be valid for sweeping + * + * @param {number} [lifetime] How long a thread has to be archived to be valid for sweeping * @returns {GlobalSweepFilter} */ - static archivedThreadSweepFilter(lifetime = 14400) { + static archivedThreadSweepFilter(lifetime = 14_400) { return this.filterByLifetime({ lifetime, - getComparisonTimestamp: e => e.archiveTimestamp, - excludeFromSweep: e => !e.archived, + getComparisonTimestamp: thread => thread.archiveTimestamp, + excludeFromSweep: thread => !thread.archived, }); } /** * Creates a sweep filter that sweeps expired invites - * @param {number} [lifetime=14400] How long ago an invite has to have expired to be valid for sweeping + * + * @param {number} [lifetime] How long ago an invite has to have expired to be valid for sweeping * @returns {GlobalSweepFilter} */ - static expiredInviteSweepFilter(lifetime = 14400) { + static expiredInviteSweepFilter(lifetime = 14_400) { return this.filterByLifetime({ lifetime, - getComparisonTimestamp: i => i.expiresTimestamp, + getComparisonTimestamp: invite => invite.expiresTimestamp, }); } /** * Creates a sweep filter that sweeps outdated messages (edits taken into account) - * @param {number} [lifetime=3600] How long ago a message has to have been sent or edited to be valid for sweeping + * + * @param {number} [lifetime] How long ago a message has to have been sent or edited to be valid for sweeping * @returns {GlobalSweepFilter} */ - static outdatedMessageSweepFilter(lifetime = 3600) { + static outdatedMessageSweepFilter(lifetime = 3_600) { return this.filterByLifetime({ lifetime, - getComparisonTimestamp: m => m.editedTimestamp ?? m.createdTimestamp, + getComparisonTimestamp: message => message.editedTimestamp ?? mesage.createdTimestamp, }); } /** * Configuration options for emitting the cache sweep client event - * @typedef {Object} SweepEventOptions + * + * @typedef {object} SweepEventOptions * @property {boolean} [emit=true] Whether to emit the client event in this method * @property {string} [outputName] A name to output in the client event if it should differ from the key * @private @@ -410,10 +446,11 @@ class Sweepers { /** * Sweep a direct sub property of all guilds + * * @param {string} key The name of the property * @param {Function} filter Filter function passed to sweep - * @param {SweepEventOptions} [eventOptions={}] Options for the Client event emitted here - * @returns {Object} Object containing the number of guilds swept and the number of items swept + * @param {SweepEventOptions} [eventOptions] Options for the Client event emitted here + * @returns {object} Object containing the number of guilds swept and the number of items swept * @private */ _sweepGuildDirectProp(key, filter, { emit = true, outputName } = {}) { @@ -443,6 +480,7 @@ class Sweepers { /** * Validates a set of properties + * * @param {string} key Key of the options object to check * @private */ @@ -451,16 +489,20 @@ class Sweepers { if (typeof props !== 'object') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}`, 'object', true); } + if (typeof props.interval !== 'number') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.interval`, 'number'); } + // Invites, Messages, and Threads can be provided a lifetime parameter, which we use to generate the filter if (['invites', 'messages', 'threads'].includes(key) && !('filter' in props)) { if (typeof props.lifetime !== 'number') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.lifetime`, 'number'); } + return; } + if (typeof props.filter !== 'function') { throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.filter`, 'function'); } @@ -468,9 +510,10 @@ class Sweepers { /** * Initialize an interval for sweeping + * * @param {string} intervalKey The name of the property that stores the interval for this sweeper * @param {string} sweepKey The name of the function that sweeps the desired caches - * @param {Object} opts Validated options for a sweep + * @param {object} opts Validated options for a sweep * @private */ _initInterval(intervalKey, sweepKey, opts) { diff --git a/packages/discord.js/src/util/SystemChannelFlagsBitField.js b/packages/discord.js/src/util/SystemChannelFlagsBitField.js index 9570a54c1ff2..b855800af538 100644 --- a/packages/discord.js/src/util/SystemChannelFlagsBitField.js +++ b/packages/discord.js/src/util/SystemChannelFlagsBitField.js @@ -7,11 +7,13 @@ const { BitField } = require('./BitField.js'); * Data structure that makes it easy to interact with a {@link Guild#systemChannelFlags} bitfield. * Note that all event message types are enabled by default, * and by setting their corresponding flags you are disabling them + * * @extends {BitField} */ class SystemChannelFlagsBitField extends BitField { /** * Numeric system channel flags. + * * @type {GuildSystemChannelFlags} * @memberof SystemChannelFlagsBitField */ @@ -20,23 +22,25 @@ class SystemChannelFlagsBitField extends BitField { /** * @name SystemChannelFlagsBitField - * @kind constructor + * @constructor * @memberof SystemChannelFlagsBitField * @param {SystemChannelFlagsResolvable} [bits=0] Bit(s) to read from */ /** * Bitfield of the packed bits + * * @type {number} * @name SystemChannelFlagsBitField#bitfield */ /** * Data that can be resolved to give a system channel flag bitfield. This can be: - * * A string (see {@link SystemChannelFlagsBitField.Flags}) - * * A system channel flag - * * An instance of SystemChannelFlagsBitField - * * An Array of SystemChannelFlagsResolvable + * A string (see {@link SystemChannelFlagsBitField.Flags}) + * A system channel flag + * An instance of SystemChannelFlagsBitField + * An Array of SystemChannelFlagsResolvable + * * @typedef {string|number|SystemChannelFlagsBitField|SystemChannelFlagsResolvable[]} SystemChannelFlagsResolvable */ diff --git a/packages/discord.js/src/util/ThreadMemberFlagsBitField.js b/packages/discord.js/src/util/ThreadMemberFlagsBitField.js index 561fc51d4845..1aec66e402a0 100644 --- a/packages/discord.js/src/util/ThreadMemberFlagsBitField.js +++ b/packages/discord.js/src/util/ThreadMemberFlagsBitField.js @@ -4,12 +4,14 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with a {@link ThreadMember#flags} bitfield. + * * @extends {BitField} */ class ThreadMemberFlagsBitField extends BitField { /** * Numeric thread member flags. There are currently no bitflags relevant to bots for this. - * @type {Object} + * + * @type {Record} * @memberof ThreadMemberFlagsBitField */ static Flags = {}; @@ -17,13 +19,14 @@ class ThreadMemberFlagsBitField extends BitField { /** * @name ThreadMemberFlagsBitField - * @kind constructor + * @constructor * @memberof ThreadMemberFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ /** * Bitfield of the packed bits + * * @type {number} * @name ThreadMemberFlagsBitField#bitfield */ diff --git a/packages/discord.js/src/util/Transformers.js b/packages/discord.js/src/util/Transformers.js index 13182e38f6cb..5609d03b0a09 100644 --- a/packages/discord.js/src/util/Transformers.js +++ b/packages/discord.js/src/util/Transformers.js @@ -5,6 +5,7 @@ const snakeCase = require('lodash.snakecase'); /** * Transforms camel-cased keys into snake cased keys + * * @param {*} obj The object to transform * @returns {*} */ @@ -18,6 +19,7 @@ function toSnakeCase(obj) { /** * Transforms an API auto moderation action object to a camel-cased variant. + * * @param {APIAutoModerationAction} autoModerationAction The action to transform * @returns {AutoModerationAction} * @ignore @@ -35,6 +37,7 @@ function _transformAPIAutoModerationAction(autoModerationAction) { /** * Transforms an API message interaction metadata object to a camel-cased variant. + * * @param {Client} client The client * @param {APIMessageInteractionMetadata} messageInteractionMetadata The metadata to transform * @returns {MessageInteractionMetadata} @@ -56,6 +59,7 @@ function _transformAPIMessageInteractionMetadata(client, messageInteractionMetad /** * Transforms a guild scheduled event recurrence rule object to a snake-cased variant. + * * @param {GuildScheduledEventRecurrenceRuleOptions} recurrenceRule The recurrence rule to transform * @returns {APIGuildScheduledEventRecurrenceRule} * @ignore @@ -74,6 +78,7 @@ function _transformGuildScheduledEventRecurrenceRule(recurrenceRule) { /** * Transforms API incidents data to a camel-cased variant. + * * @param {APIIncidentsData} data The incidents data to transform * @returns {IncidentActions} * @ignore diff --git a/packages/discord.js/src/util/UserFlagsBitField.js b/packages/discord.js/src/util/UserFlagsBitField.js index 160bfcb23f3e..ce6c61d3f483 100644 --- a/packages/discord.js/src/util/UserFlagsBitField.js +++ b/packages/discord.js/src/util/UserFlagsBitField.js @@ -5,11 +5,13 @@ const { BitField } = require('./BitField.js'); /** * Data structure that makes it easy to interact with a {@link User#flags} bitfield. + * * @extends {BitField} */ class UserFlagsBitField extends BitField { /** * Numeric user flags. + * * @type {UserFlags} * @memberof UserFlagsBitField */ @@ -18,13 +20,14 @@ class UserFlagsBitField extends BitField { /** * @name UserFlagsBitField - * @kind constructor + * @constructor * @memberof UserFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ /** * Bitfield of the packed bits + * * @type {number} * @name UserFlagsBitField#bitfield */ diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index d51553e8f163..15578e0766f5 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -1,18 +1,22 @@ +/* eslint-disable import-x/order */ 'use strict'; +// eslint-disable-next-line @typescript-eslint/unbound-method const { parse } = require('node:path'); const { Collection } = require('@discordjs/collection'); const { ChannelType, RouteBases, Routes } = require('discord-api-types/v10'); const { fetch } = require('undici'); const { Colors } = require('./Colors.js'); const { DiscordjsError, DiscordjsRangeError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); -const isObject = d => typeof d === 'object' && d !== null; + +const isObject = data => typeof data === 'object' && data !== null; /** * Flatten an object. Any properties that are collections will get converted to an array of keys. - * @param {Object} obj The object to flatten. - * @param {...Object} [props] Specific properties to include/exclude. - * @returns {Object} + * + * @param {object} obj The object to flatten. + * @param {...Record} [props] Specific properties to include/exclude. + * @returns {object} */ function flatten(obj, ...props) { if (!isObject(obj)) return obj; @@ -25,6 +29,7 @@ function flatten(obj, ...props) { const out = {}; + // eslint-disable-next-line prefer-const for (let [prop, newProp] of Object.entries(mergedProps)) { if (!newProp) continue; newProp = newProp === true ? prop : newProp; @@ -54,13 +59,14 @@ function flatten(obj, ...props) { } /** - * @typedef {Object} FetchRecommendedShardCountOptions + * @typedef {object} FetchRecommendedShardCountOptions * @property {number} [guildsPerShard=1000] Number of guilds assigned per shard * @property {number} [multipleOf=1] The multiple the shard count should round up to. (16 for large bot sharding) */ /** * Gets the recommended shard count from Discord. + * * @param {string} token Discord auth token * @param {FetchRecommendedShardCountOptions} [options] Options for fetching the recommended shard count * @returns {Promise} The recommended number of shards @@ -69,19 +75,22 @@ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multi if (!token) throw new DiscordjsError(ErrorCodes.TokenMissing); const response = await fetch(RouteBases.api + Routes.gatewayBot(), { method: 'GET', - headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` }, + headers: { Authorization: `Bot ${token.replace(/^bot\s*/i, '')}` }, }); if (!response.ok) { if (response.status === 401) throw new DiscordjsError(ErrorCodes.TokenInvalid); + // eslint-disable-next-line @typescript-eslint/only-throw-error throw response; } + const { shards } = await response.json(); return Math.ceil((shards * (1_000 / guildsPerShard)) / multipleOf) * multipleOf; } /** * A partial emoji object. - * @typedef {Object} PartialEmoji + * + * @typedef {object} PartialEmoji * @property {boolean} animated Whether the emoji is animated * @property {Snowflake|undefined} id The id of the emoji * @property {string} name The name of the emoji @@ -89,27 +98,30 @@ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multi /** * Parses emoji info out of a string. The string must be one of: - * * A UTF-8 emoji (no id) - * * A URL-encoded UTF-8 emoji (no id) - * * A Discord custom emoji (`<:name:id>` or ``) + * A UTF-8 emoji (no id) + * A URL-encoded UTF-8 emoji (no id) + * A Discord custom emoji (`<:name:id>` or ``) + * * @param {string} text Emoji string to parse * @returns {?PartialEmoji} */ function parseEmoji(text) { const decodedText = text.includes('%') ? decodeURIComponent(text) : text; if (!decodedText.includes(':')) return { animated: false, name: decodedText, id: undefined }; - const match = decodedText.match(/?/); + const match = /?/.exec(decodedText); return match && { animated: Boolean(match[1]), name: match[2], id: match[3] }; } /** * A partial emoji object with only an id. - * @typedef {Object} PartialEmojiOnlyId + * + * @typedef {object} PartialEmojiOnlyId * @property {Snowflake} id The id of the emoji */ /** * Resolves a partial emoji object from an {@link EmojiIdentifierResolvable}, without checking a Client. + * * @param {Emoji|EmojiIdentifierResolvable} emoji Emoji identifier to resolve * @returns {?(PartialEmoji|PartialEmojiOnlyId)} Supplying a snowflake yields `PartialEmojiOnlyId`. */ @@ -123,6 +135,7 @@ function resolvePartialEmoji(emoji) { /** * Resolves a {@link GuildEmoji} from an emoji id. + * * @param {Client} client The client to use to resolve the emoji * @param {Snowflake} emojiId The emoji id to resolve * @returns {?GuildEmoji} @@ -146,7 +159,8 @@ function resolveGuildEmoji(client, emojiId) { /** * Options used to make an error object. - * @typedef {Object} MakeErrorOptions + * + * @typedef {object} MakeErrorOptions * @property {string} name Error type * @property {string} message Message for the error * @property {string} stack Stack for the error @@ -155,6 +169,7 @@ function resolveGuildEmoji(client, emojiId) { /** * Makes an Error from a plain info object. + * * @param {MakeErrorOptions} obj Error info * @returns {Error} * @private @@ -168,6 +183,7 @@ function makeError(obj) { /** * Makes a plain error info object from an Error. + * * @param {Error} err Error to get info from * @returns {MakeErrorOptions} * @private @@ -195,11 +211,13 @@ const CategorySortableGroupTypes = [ChannelType.GuildCategory]; * return an array containing the types that can be ordered within the text channels (always at the top), and a voice * channel would return an array containing the types that can be ordered within the voice channels (always at the * bottom). + * * @param {ChannelType} type The type of the channel * @returns {ChannelType[]} * @private */ function getSortableGroupTypes(type) { + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check switch (type) { case ChannelType.GuildText: case ChannelType.GuildAnnouncement: @@ -218,10 +236,11 @@ function getSortableGroupTypes(type) { /** * Moves an element in an array *in place*. + * * @param {Array<*>} array Array to modify * @param {*} element Element to move * @param {number} newIndex Index or offset to move the element to - * @param {boolean} [offset=false] Move the element by an offset amount rather than to a set index + * @param {boolean} [offset] Move the element by an offset amount rather than to a set index * @returns {number} * @private */ @@ -232,15 +251,17 @@ function moveElementInArray(array, element, newIndex, offset = false) { const removedElement = array.splice(index, 1)[0]; array.splice(targetIndex, 0, removedElement); } + return array.indexOf(element); } /** * Verifies the provided data is a string, otherwise throws provided error. + * * @param {string} data The string resolvable to resolve * @param {Function} [error] The Error constructor to instantiate. Defaults to Error * @param {string} [errorMessage] The error message to throw with. Defaults to "Expected string, got instead." - * @param {boolean} [allowEmpty=true] Whether an empty string should be allowed + * @param {boolean} [allowEmpty] Whether an empty string should be allowed * @returns {string} */ function verifyString( @@ -291,11 +312,13 @@ function verifyString( * - `DarkButNotBlack` * - `NotQuiteBlack` * - `Random` + * * @typedef {string|number|number[]} ColorResolvable */ /** * Resolves a ColorResolvable into a color number. + * * @param {ColorResolvable} color Color to resolve * @returns {number} A color */ @@ -305,7 +328,7 @@ function resolveColor(color) { if (typeof color === 'string') { if (color === 'Random') return Math.floor(Math.random() * (0xffffff + 1)); if (color === 'Default') return 0; - if (/^#?[\da-f]{6}$/i.test(color)) return parseInt(color.replace('#', ''), 16); + if (/^#?[\da-f]{6}$/i.test(color)) return Number.parseInt(color.replace('#', ''), 16); resolvedColor = Colors[color]; } else if (Array.isArray(color)) { resolvedColor = (color[0] << 16) + (color[1] << 8) + color[2]; @@ -326,10 +349,12 @@ function resolveColor(color) { /** * Sorts by Discord's position and id. + * * @param {Collection} collection Collection of objects to sort * @returns {Collection} */ function discordSort(collection) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define const isGuildChannel = collection.first() instanceof GuildChannel; return collection.toSorted( isGuildChannel @@ -340,6 +365,7 @@ function discordSort(collection) { /** * Sets the position of a Channel or Role. + * * @param {BaseChannel|Role} item Object to set the position of * @param {number} position New position for the object * @param {boolean} relative Whether `position` is relative to its current position @@ -353,13 +379,14 @@ function discordSort(collection) { async function setPosition(item, position, relative, sorted, client, route, reason) { let updatedItems = [...sorted.values()]; moveElementInArray(updatedItems, item, position, relative); - updatedItems = updatedItems.map((r, i) => ({ id: r.id, position: i })); + updatedItems = updatedItems.map((item, index) => ({ id: item.id, position: index })); await client.rest.patch(route, { body: updatedItems, reason }); return updatedItems; } /** * Alternative to Node's `path.basename`, removing query string after the extension if it exists. + * * @param {string} path Path to get the basename of * @param {string} [ext] File extension to remove * @returns {string} Basename of the path @@ -372,13 +399,13 @@ function basename(path, ext) { /** * The content to have all mentions replaced by the equivalent text. + * * @param {string} str The string to be converted * @param {TextBasedChannels} channel The channel the string was sent in * @returns {string} */ function cleanContent(str, channel) { return str.replaceAll( - /* eslint-disable max-len */ /<(?:(?@[!&]?|#)|(?:\/(?[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai} ]+):)|(?:a?:(?[\w]+):))(?\d{17,19})>/gu, (match, type, commandName, emojiName, id) => { if (commandName) return `/${commandName}`; @@ -396,15 +423,18 @@ function cleanContent(str, channel) { const user = channel.client.users.cache.get(id); return user ? `@${user.displayName}` : match; } + case '@&': { if (channel.type === ChannelType.DM) return match; const role = channel.guild.roles.cache.get(id); return role ? `@${role.name}` : match; } + case '#': { const mentionedChannel = channel.client.channels.cache.get(id); return mentionedChannel ? `#${mentionedChannel.name}` : match; } + default: { return match; } @@ -415,22 +445,23 @@ function cleanContent(str, channel) { /** * The content to put in a code block with all code block fences replaced by the equivalent backticks. + * * @param {string} text The string to be converted * @returns {string} */ function cleanCodeBlockContent(text) { - return text.replaceAll('```', '`\u200b``'); + return text.replaceAll('```', '`\u200B``'); } /** * Parses a webhook URL for the id and token. + * * @param {string} url The URL to parse * @returns {?WebhookClientDataIdWithToken} `null` if the URL is invalid, otherwise the id and the token */ function parseWebhookURL(url) { - const matches = url.match( - /https?:\/\/(?:ptb\.|canary\.)?discord\.com\/api(?:\/v\d{1,2})?\/webhooks\/(\d{17,19})\/([\w-]{68})/i, - ); + const matches = + /https?:\/\/(?:ptb\.|canary\.)?discord\.com\/api(?:\/v\d{1,2})?\/webhooks\/(\d{17,19})\/([\w-]{68})/i.exec(url); if (!matches || matches.length <= 2) return null; @@ -443,7 +474,8 @@ function parseWebhookURL(url) { /** * Supportive data for interaction resolved data. - * @typedef {Object} SupportingInteractionResolvedData + * + * @typedef {object} SupportingInteractionResolvedData * @property {Client} client The client * @property {Guild} [guild] A guild * @property {GuildTextBasedChannel} [channel] A channel @@ -452,6 +484,7 @@ function parseWebhookURL(url) { /** * Transforms the resolved data received from the API. + * * @param {SupportingInteractionResolvedData} supportingData Data to support the transformation * @param {APIInteractionDataResolved} [data] The received resolved objects * @returns {CommandInteractionResolvedData} @@ -502,6 +535,7 @@ function transformResolved( if (attachments) { result.attachments = new Collection(); for (const attachment of Object.values(attachments)) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define const patched = new Attachment(attachment); result.attachments.set(attachment.id, patched); } @@ -512,11 +546,13 @@ function transformResolved( /** * Resolves a SKU id from a SKU resolvable. + * * @param {SKUResolvable} resolvable The SKU resolvable to resolve * @returns {?Snowflake} The resolved SKU id, or `null` if the resolvable was invalid */ function resolveSKUId(resolvable) { if (typeof resolvable === 'string') return resolvable; + // eslint-disable-next-line @typescript-eslint/no-use-before-define if (resolvable instanceof SKU) return resolvable.id; return null; } diff --git a/packages/discord.js/tsconfig.eslint.json b/packages/discord.js/tsconfig.eslint.json new file mode 100644 index 000000000000..b0baf69334d6 --- /dev/null +++ b/packages/discord.js/tsconfig.eslint.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig.json", + "extends": "./tsconfig.json", + "compilerOptions": { + "allowJs": true + }, + "include": [ + "*.ts", + "*.js", + "*.cjs", + "*.mjs", + "src/**/*.ts", + "src/**/*.js", + "src/**/*.cjs", + "src/**/*.mjs", + "typings/*.d.ts", + "typings/*.d.mts", + "typings/*.test-d.ts", + "bin", + "scripts", + "__tests__", + "__mocks__" + ], + "exclude": ["node_modules"] +} From 1fcd05806d4b2985b0b442762c5376c90971fc3e Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 01:24:54 +0200 Subject: [PATCH 02/38] fix: lint --- eslint.config.js | 3 +- packages/discord.js/.eslintrc.json.bak | 283 -- packages/discord.js/src/errors/ErrorCodes.js | 36 - .../ApplicationCommandPermissionsManager.js | 22 +- packages/discord.js/src/util/Util.js | 12 +- packages/discord.js/typings/index.d.ts | 2896 +++++++++++------ 6 files changed, 1837 insertions(+), 1415 deletions(-) delete mode 100644 packages/discord.js/.eslintrc.json.bak diff --git a/eslint.config.js b/eslint.config.js index 4894a87bc700..f2c04c14ba92 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -88,7 +88,6 @@ export default tseslint.config( '**/storybook-static/', '**/.next/', '**/shiki.bundle.ts', - // 'packages/discord.js/', ], }, commonRuleset, @@ -138,7 +137,7 @@ export default tseslint.config( }, }, { - files: [`packages/discord.js/**/*${commonFiles}`], + files: [`packages/discord.js/**/*{js,mjs,cjs}`], languageOptions: { sourceType: 'commonjs', parserOptions: { diff --git a/packages/discord.js/.eslintrc.json.bak b/packages/discord.js/.eslintrc.json.bak deleted file mode 100644 index b30599c63c19..000000000000 --- a/packages/discord.js/.eslintrc.json.bak +++ /dev/null @@ -1,283 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/eslintrc.json", - "root": true, - "overrides": [ - { - "files": ["src/**/*.js", "test/**/*.js"], - "extends": ["eslint:recommended"], - "plugins": ["import", "jsdoc"], - "parserOptions": { - "ecmaVersion": 2022 - }, - "env": { - "es2022": true, - "node": true - }, - "settings": { - "jsdoc": { - "tagNamePreference": { - "augments": "extends", - "return": "returns", - "arg": "param", - "fires": "emits", - "function": "method" - }, - "preferredTypes": { - "String": "string", - "Number": "number", - "Boolean": "boolean", - "Symbol": "symbol", - "object": "Object", - "function": "Function", - "array": "Array", - "date": "Date", - "error": "Error", - "null": "void" - } - } - }, - "rules": { - "import/order": [ - "error", - { - "groups": ["builtin", "external", "internal", "index", "sibling", "parent"], - "alphabetize": { - "order": "asc" - } - } - ], - "import/extensions": ["error", "ignorePackages"], - "strict": ["error", "global"], - "no-await-in-loop": "warn", - "no-compare-neg-zero": "error", - "no-template-curly-in-string": "error", - "no-unsafe-negation": "error", - "jsdoc/require-returns": "off", - "jsdoc/require-returns-description": "off", - "jsdoc/check-tag-names": "error", - "jsdoc/check-types": "error", - - "accessor-pairs": "warn", - "array-callback-return": "error", - "consistent-return": "error", - "curly": ["error", "multi-line", "consistent"], - "dot-location": ["error", "property"], - "dot-notation": "error", - "eqeqeq": "error", - "no-empty-function": "error", - "no-floating-decimal": "error", - "no-implied-eval": "error", - "no-invalid-this": "error", - "no-lone-blocks": "error", - "no-multi-spaces": "error", - "no-new-func": "error", - "no-new-wrappers": "error", - "no-new": "error", - "no-octal-escape": "error", - "no-return-assign": "error", - "no-return-await": "error", - "no-self-compare": "error", - "no-sequences": "error", - "no-throw-literal": "error", - "no-unmodified-loop-condition": "error", - "no-unused-expressions": "error", - "no-useless-call": "error", - "no-useless-concat": "error", - "no-useless-escape": "error", - "no-useless-return": "error", - "no-void": "error", - "no-warning-comments": "warn", - "prefer-promise-reject-errors": "error", - "require-await": "off", - "wrap-iife": "error", - "yoda": "error", - - "no-label-var": "error", - "no-shadow": "error", - "no-undef-init": "error", - - "callback-return": "error", - "getter-return": "off", - "handle-callback-err": "error", - "no-mixed-requires": "error", - "no-new-require": "error", - "no-path-concat": "error", - - "array-bracket-spacing": "error", - "block-spacing": "error", - "brace-style": ["error", "1tbs", { "allowSingleLine": true }], - "capitalized-comments": ["error", "always", { "ignoreConsecutiveComments": true }], - "comma-dangle": ["error", "always-multiline"], - "comma-spacing": "error", - "comma-style": "error", - "computed-property-spacing": "error", - "consistent-this": ["error", "$this"], - "eol-last": "error", - "func-names": "error", - "func-name-matching": "error", - "func-style": ["error", "declaration", { "allowArrowFunctions": true }], - "key-spacing": "error", - "keyword-spacing": "error", - "max-depth": "error", - "max-len": ["error", 120, 2], - "max-nested-callbacks": ["error", { "max": 4 }], - "max-statements-per-line": ["error", { "max": 2 }], - "new-cap": "off", - "newline-per-chained-call": ["error", { "ignoreChainWithDepth": 3 }], - "no-array-constructor": "error", - "no-inline-comments": "error", - "no-lonely-if": "error", - "no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }], - "no-new-object": "error", - "no-spaced-func": "error", - "no-trailing-spaces": "error", - "no-unneeded-ternary": "error", - "no-whitespace-before-property": "error", - "nonblock-statement-body-position": "error", - "object-curly-spacing": ["error", "always"], - "operator-assignment": "error", - "padded-blocks": ["error", "never"], - "quote-props": ["error", "as-needed"], - "quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }], - "semi-spacing": "error", - "semi": "error", - "space-before-blocks": "error", - "space-before-function-paren": [ - "error", - { - "anonymous": "never", - "named": "never", - "asyncArrow": "always" - } - ], - "space-in-parens": "error", - "space-infix-ops": "error", - "space-unary-ops": "error", - "spaced-comment": "error", - "template-tag-spacing": "error", - "unicode-bom": "error", - - "arrow-body-style": "error", - "arrow-parens": ["error", "as-needed"], - "arrow-spacing": "error", - "no-duplicate-imports": "error", - "no-useless-computed-key": "error", - "no-useless-constructor": "error", - "prefer-arrow-callback": "error", - "prefer-numeric-literals": "error", - "prefer-rest-params": "error", - "prefer-spread": "error", - "prefer-template": "error", - "prefer-object-has-own": "error", - "rest-spread-spacing": "error", - "template-curly-spacing": "error", - "yield-star-spacing": "error", - "no-param-reassign": "error", - - "no-restricted-globals": [ - "error", - { - "name": "Buffer", - "message": "Import Buffer from `node:buffer` instead" - }, - { - "name": "process", - "message": "Import process from `node:process` instead" - }, - { - "name": "setTimeout", - "message": "Import setTimeout from `node:timers` instead" - }, - { - "name": "setInterval", - "message": "Import setInterval from `node:timers` instead" - }, - { - "name": "setImmediate", - "message": "Import setImmediate from `node:timers` instead" - }, - { - "name": "clearTimeout", - "message": "Import clearTimeout from `node:timers` instead" - }, - { - "name": "clearInterval", - "message": "Import clearInterval from `node:timers` instead" - } - ], - - "no-restricted-syntax": [ - "error", - { - "selector": "AssignmentExpression[left.object.name='module'][left.property.name='exports']", - "message": "Use named exports instead of module.exports" - }, - { - "selector": "VariableDeclarator[init.callee.name='require'][init.arguments.0.value=/^\\./]:not([id.type='ObjectPattern'])", - "message": "Use object destructuring when requiring local modules" - } - ] - } - }, - { - "files": ["src/client/websocket/handlers/*.js"], - "rules": { - "no-restricted-syntax": [ - "error", - { - "selector": "VariableDeclarator[init.callee.name='require'][init.arguments.0.value=/^\\./]:not([id.type='ObjectPattern'])", - "message": "Use object destructuring when requiring local modules" - } - ] - } - }, - { - "files": ["typings/*.ts", "scripts/*.mjs"], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "project": "./tsconfig.json" - }, - "plugins": ["@typescript-eslint"], - "rules": { - "@typescript-eslint/naming-convention": [ - 2, - { - "selector": "typeParameter", - "format": ["PascalCase"], - "custom": { - "regex": "^\\w{3,}", - "match": true - } - } - ], - "no-restricted-syntax": [ - 2, - { - "selector": "MethodDefinition[key.name!=on][key.name!=once][key.name!=off] > TSEmptyBodyFunctionExpression > Identifier :not(TSTypeOperator[operator=readonly]) > TSArrayType", - "message": "Array parameters on methods must be readonly" - }, - { - "selector": "MethodDefinition > TSEmptyBodyFunctionExpression > Identifier TSTypeReference > Identifier[name=Collection]", - "message": "Parameters of type Collection on methods must use ReadonlyCollection" - }, - { - "selector": "TSDeclareFunction > Identifier :not(TSTypeOperator[operator=readonly]) > TSArrayType", - "message": "Array parameters on functions must be readonly" - }, - { - "selector": "TSDeclareFunction Identifier TSTypeReference > Identifier[name=Collection]", - "message": "Parameters of type Collection on functions must use ReadonlyCollection" - }, - { - "selector": "TSInterfaceDeclaration TSPropertySignature :not(TSTypeOperator[operator=readonly]) > TSArrayType", - "message": "Array properties on interfaces must be readonly" - }, - { - "selector": "TSInterfaceDeclaration TSPropertySignature TSTypeReference > Identifier[name=Collection]", - "message": "Interface properties of type Collection must use ReadonlyCollection" - } - ] - } - } - ] -} diff --git a/packages/discord.js/src/errors/ErrorCodes.js b/packages/discord.js/src/errors/ErrorCodes.js index 9a2820a2ce0e..74fbcaaa9a7a 100644 --- a/packages/discord.js/src/errors/ErrorCodes.js +++ b/packages/discord.js/src/errors/ErrorCodes.js @@ -1,4 +1,3 @@ -/* eslint-disable jsdoc/tag-lines */ /* eslint-disable jsdoc/require-property-description */ 'use strict'; @@ -24,35 +23,23 @@ * @property {'ShardingReadyDied'} ShardingReadyDied * @property {'ShardingNoChildExists'} ShardingNoChildExists * @property {'ShardingShardMiscalculation'} ShardingShardMiscalculation - * * @property {'ColorRange'} ColorRange * @property {'ColorConvert'} ColorConvert - * * @property {'InviteOptionsMissingChannel'} InviteOptionsMissingChannel - * * @property {'InteractionCollectorError'} InteractionCollectorError - * * @property {'FileNotFound'} FileNotFound - * * @property {'UserNoDMChannel'} UserNoDMChannel - * * @property {'VoiceNotStageChannel'} VoiceNotStageChannel - * * @property {'VoiceStateNotOwn'} VoiceStateNotOwn * @property {'VoiceStateInvalidType'} VoiceStateInvalidType - * * @property {'ReqResourceType'} ReqResourceType - * * @property {'MessageBulkDeleteType'} MessageBulkDeleteType * @property {'MessageContentType'} MessageContentType * @property {'MessageNonceRequired'} MessageNonceRequired * @property {'MessageNonceType'} MessageNonceType - * * @property {'BanResolveId'} BanResolveId * @property {'FetchBanResolveId'} FetchBanResolveId - * * @property {'PruneDaysType'} PruneDaysType - * * @property {'GuildChannelResolve'} GuildChannelResolve * @property {'GuildVoiceChannelResolve'} GuildVoiceChannelResolve * @property {'GuildChannelOrphan'} GuildChannelOrphan @@ -65,46 +52,32 @@ * @property {'StageChannelResolve'} StageChannelResolve * @property {'GuildScheduledEventResolve'} GuildScheduledEventResolve * @property {'FetchOwnerId'} FetchOwnerId - * * @property {'InvalidType'} InvalidType * @property {'InvalidElement'} InvalidElement - * * @property {'MessageThreadParent'} MessageThreadParent * @property {'MessageExistingThread'} MessageExistingThread * @property {'ThreadInvitableType'} ThreadInvitableType * @property {'NotAThreadOfParent'} NotAThreadOfParent - * * @property {'WebhookMessage'} WebhookMessage * @property {'WebhookTokenUnavailable'} WebhookTokenUnavailable * @property {'WebhookURLInvalid'} WebhookURLInvalid * @property {'WebhookApplication'} WebhookApplication * @property {'MessageReferenceMissing'} MessageReferenceMissing - * * @property {'EmojiType'} EmojiType * @property {'EmojiManaged'} EmojiManaged * @property {'MissingManageGuildExpressionsPermission'} MissingManageGuildExpressionsPermission - * - * * @property {'NotGuildSoundboardSound'} NotGuildSoundboardSound * @property {'NotGuildSticker'} NotGuildSticker - * * @property {'ReactionResolveUser'} ReactionResolveUser - * * @property {'InviteResolveCode'} InviteResolveCode - * * @property {'InviteNotFound'} InviteNotFound - * * @property {'DeleteGroupDMChannel'} DeleteGroupDMChannel * @property {'FetchGroupDMChannel'} FetchGroupDMChannel - * * @property {'MemberFetchNonceLength'} MemberFetchNonceLength - * * @property {'GlobalCommandPermissions'} GlobalCommandPermissions * @property {'GuildUncachedEntityResolve'} GuildUncachedEntityResolve - * * @property {'InteractionAlreadyReplied'} InteractionAlreadyReplied * @property {'InteractionNotReplied'} InteractionNotReplied - * * @property {'CommandInteractionOptionNotFound'} CommandInteractionOptionNotFound * @property {'CommandInteractionOptionType'} CommandInteractionOptionType * @property {'CommandInteractionOptionEmpty'} CommandInteractionOptionEmpty @@ -112,25 +85,16 @@ * @property {'CommandInteractionOptionNoSubcommandGroup'} CommandInteractionOptionNoSubcommandGroup * @property {'CommandInteractionOptionInvalidChannelType'} CommandInteractionOptionInvalidChannelType * @property {'AutocompleteInteractionOptionNoFocusedOption'} AutocompleteInteractionOptionNoFocusedOption - * * @property {'ModalSubmitInteractionFieldNotFound'} ModalSubmitInteractionFieldNotFound * @property {'ModalSubmitInteractionFieldType'} ModalSubmitInteractionFieldType - * * @property {'InvalidMissingScopes'} InvalidMissingScopes * @property {'InvalidScopesWithPermissions'} InvalidScopesWithPermissions - * * @property {'NotImplemented'} NotImplemented - * * @property {'GuildForumMessageRequired'} GuildForumMessageRequired - * * @property {'SweepFilterReturn'} SweepFilterReturn - * * @property {'EntitlementCreateInvalidOwner'} EntitlementCreateInvalidOwner - * * @property {'BulkBanUsersOptionEmpty'} BulkBanUsersOptionEmpty - * * @property {'PollAlreadyExpired'} PollAlreadyExpired - * * @property {'PermissionOverwritesTypeMandatory'} PermissionOverwritesTypeMandatory * @property {'PermissionOverwritesTypeMismatch'} PermissionOverwritesTypeMismatch */ diff --git a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js index 0a7fbcb0d10c..b68019fc73a9 100644 --- a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js @@ -165,8 +165,8 @@ class ApplicationCommandPermissionsManager extends BaseManager { throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing); } - // eslint-disable-next-line prefer-const - let { guildId, commandId } = this._validateOptions(guild, command); + const options = this._validateOptions(guild, command); + let { commandId } = options; if (!Array.isArray(permissions)) { throw new DiscordjsTypeError( @@ -179,7 +179,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { commandId ??= this.client.user.id; - const data = await this.client.rest.put(this.permissionsPath(guildId, commandId), { + const data = await this.client.rest.put(this.permissionsPath(options.guildId, commandId), { body: { permissions }, auth: false, headers: { Authorization: `Bearer ${token}` }, @@ -209,8 +209,8 @@ class ApplicationCommandPermissionsManager extends BaseManager { throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing); } - // eslint-disable-next-line prefer-const - let { guildId, commandId } = this._validateOptions(guild, command); + const options = this._validateOptions(guild, command); + let { commandId } = options; commandId ??= this.client.user.id; if (!Array.isArray(permissions)) { @@ -224,7 +224,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { let existingPermissions = []; try { - existingPermissions = await this.fetch({ guild: guildId, command: commandId }); + existingPermissions = await this.fetch({ guild: options.guildId, command: commandId }); } catch (error) { if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) throw error; } @@ -236,7 +236,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { } } - return this.set({ guild: guildId, command: commandId, permissions: newPermissions, token }); + return this.set({ guild: options.guildId, command: commandId, permissions: newPermissions, token }); } /** @@ -291,8 +291,8 @@ class ApplicationCommandPermissionsManager extends BaseManager { throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing); } - // eslint-disable-next-line prefer-const - let { guildId, commandId } = this._validateOptions(guild, command); + const options = this._validateOptions(guild, command); + let { commandId } = options; commandId ??= this.client.user.id; if (!users && !roles && !channels) { @@ -340,7 +340,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { let existing = []; try { - existing = await this.fetch({ guild: guildId, command: commandId }); + existing = await this.fetch({ guild: options.guildId, command: commandId }); } catch (error) { if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) throw error; } @@ -358,7 +358,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { return true; }); - return this.set({ guild: guildId, command: commandId, permissions, token }); + return this.set({ guild: options.guildId, command: commandId, permissions, token }); } /** diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index 15578e0766f5..a8a76a580016 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -108,8 +108,8 @@ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multi function parseEmoji(text) { const decodedText = text.includes('%') ? decodeURIComponent(text) : text; if (!decodedText.includes(':')) return { animated: false, name: decodedText, id: undefined }; - const match = /?/.exec(decodedText); - return match && { animated: Boolean(match[1]), name: match[2], id: match[3] }; + const match = /a):)?(?\w{2,32}):(?\d{17,19})?>?/.exec(decodedText); + return match && { animated: Boolean(match.groups.animated), name: match.groups.name, id: match.groups.id }; } /** @@ -461,11 +461,13 @@ function cleanCodeBlockContent(text) { */ function parseWebhookURL(url) { const matches = - /https?:\/\/(?:ptb\.|canary\.)?discord\.com\/api(?:\/v\d{1,2})?\/webhooks\/(\d{17,19})\/([\w-]{68})/i.exec(url); + /https?:\/\/(?:ptb\.|canary\.)?discord\.com\/api(?:\/v\d{1,2})?\/webhooks\/(?\d{17,19})\/(?[\w-]{68})/i.exec( + url, + ); - if (!matches || matches.length <= 2) return null; + if (!matches?.groups) return null; - const [, id, token] = matches; + const { id, token } = matches.groups; return { id, token, diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index b8520649fac1..28608b926595 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -1,9 +1,21 @@ -import { Awaitable, JSONEncodable } from '@discordjs/util'; -import { Collection, ReadonlyCollection } from '@discordjs/collection'; -import { BaseImageURLOptions, ImageURLOptions, RawFile, REST, RESTOptions } from '@discordjs/rest'; -import { WebSocketManager, WebSocketManagerOptions } from '@discordjs/ws'; +/* eslint-disable n/prefer-global/buffer */ +/* eslint-disable no-restricted-globals */ +/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ +/* eslint-disable @typescript-eslint/no-empty-object-type */ +/* eslint-disable @typescript-eslint/no-use-before-define */ +import type { ChildProcess } from 'node:child_process'; +import type { Stream } from 'node:stream'; +import type { MessagePort, Worker } from 'node:worker_threads'; +import type { + ApplicationCommandOptionAllowedChannelTypes, + MessageActionRowComponentBuilder, +} from '@discordjs/builders'; +import type { Collection, ReadonlyCollection } from '@discordjs/collection'; +import type { BaseImageURLOptions, ImageURLOptions, RawFile, REST, RESTOptions } from '@discordjs/rest'; +import type { Awaitable, JSONEncodable } from '@discordjs/util'; +import type { WebSocketManager, WebSocketManagerOptions } from '@discordjs/ws'; import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter'; -import { +import type { APIActionRowComponent, APIApplicationCommandInteractionData, APIApplicationCommandOption, @@ -40,7 +52,6 @@ import { MessageType, OAuth2Scopes, RESTPostAPIApplicationCommandsJSONBody, - Snowflake, StageInstancePrivacyLevel, StickerFormatType, StickerType, @@ -161,11 +172,9 @@ import { RESTAPIPoll, EntryPointCommandHandlerType, APISoundboardSound, + Snowflake, } from 'discord-api-types/v10'; -import { ChildProcess } from 'node:child_process'; -import { Stream } from 'node:stream'; -import { MessagePort, Worker } from 'node:worker_threads'; -import { +import type { RawActivityData, RawAnonymousGuildData, RawApplicationCommandData, @@ -221,33 +230,46 @@ import { RawWidgetData, RawWidgetMemberData, } from './rawDataTypes.js'; -import { ApplicationCommandOptionAllowedChannelTypes, MessageActionRowComponentBuilder } from '@discordjs/builders'; -//#region Classes +// #region Classes export class Activity { private constructor(presence: Presence, data?: RawActivityData); public readonly presence: Presence; + public applicationId: Snowflake | null; + public assets: RichPresenceAssets | null; + public buttons: string[]; + public get createdAt(): Date; public createdTimestamp: number; + public details: string | null; + public emoji: Emoji | null; + public flags: Readonly; + public name: string; + public party: { id: string | null; size: [number, number]; } | null; + public state: string | null; + public syncId: string | null; + public timestamps: { - start: Date | null; end: Date | null; + start: Date | null; } | null; + public type: ActivityType; + public url: string | null; public equals(activity: Activity): boolean; public toString(): string; @@ -260,13 +282,13 @@ export interface BaseComponentData { } export type MessageActionRowComponentData = - | JSONEncodable | ButtonComponentData - | StringSelectMenuComponentData - | UserSelectMenuComponentData - | RoleSelectMenuComponentData + | ChannelSelectMenuComponentData + | JSONEncodable | MentionableSelectMenuComponentData - | ChannelSelectMenuComponentData; + | RoleSelectMenuComponentData + | StringSelectMenuComponentData + | UserSelectMenuComponentData; export type ModalActionRowComponentData = JSONEncodable | TextInputComponentData; @@ -274,18 +296,18 @@ export type ActionRowComponentData = MessageActionRowComponentData | ModalAction export type ActionRowComponent = MessageActionRowComponent | ModalActionRowComponent; -export interface ActionRowData | ActionRowComponentData> +export interface ActionRowData> extends BaseComponentData { components: readonly ComponentType[]; } export type MessageActionRowComponent = | ButtonComponent - | StringSelectMenuComponent - | UserSelectMenuComponent - | RoleSelectMenuComponent + | ChannelSelectMenuComponent | MentionableSelectMenuComponent - | ChannelSelectMenuComponent; + | RoleSelectMenuComponent + | StringSelectMenuComponent + | UserSelectMenuComponent; export type ModalActionRowComponent = TextInputComponent; export class ActionRow extends Component< @@ -304,11 +326,17 @@ export class ActivityFlagsBitField extends BitField { export abstract class AnonymousGuild extends BaseGuild { protected constructor(client: Client, data: RawAnonymousGuildData, immediatePatch?: boolean); public banner: string | null; + public description: string | null; + public nsfwLevel: GuildNSFWLevel; + public premiumSubscriptionCount: number | null; + public splash: string | null; + public vanityURLCode: string | null; + public verificationLevel: GuildVerificationLevel; public bannerURL(options?: ImageURLOptions): string | null; public splashURL(options?: ImageURLOptions): string | null; @@ -317,18 +345,28 @@ export abstract class AnonymousGuild extends BaseGuild { export class AutoModerationActionExecution { private constructor(data: GatewayAutoModerationActionExecutionDispatchData, guild: Guild); public guild: Guild; + public action: AutoModerationAction; + public ruleId: Snowflake; + public ruleTriggerType: AutoModerationRuleTriggerType; + public get user(): User | null; public userId: Snowflake; - public get channel(): GuildTextBasedChannel | ForumChannel | MediaChannel | null; + + public get channel(): ForumChannel | GuildTextBasedChannel | MediaChannel | null; public channelId: Snowflake | null; + public get member(): GuildMember | null; public messageId: Snowflake | null; + public alertSystemMessageId: Snowflake | null; + public content: string; + public matchedKeyword: string | null; + public matchedContent: string | null; public get autoModerationRule(): AutoModerationRule | null; } @@ -336,15 +374,25 @@ export class AutoModerationActionExecution { export class AutoModerationRule extends Base { private constructor(client: Client, data: APIAutoModerationRule, guild: Guild); public id: Snowflake; + public guild: Guild; + public name: string; + public creatorId: Snowflake; + public eventType: AutoModerationRuleEventType; + public triggerType: AutoModerationRuleTriggerType; + public triggerMetadata: AutoModerationTriggerMetadata; + public actions: AutoModerationAction[]; + public enabled: boolean; + public exemptRoles: Collection; + public exemptChannels: Collection; public edit(options: AutoModerationRuleEditOptions): Promise; public delete(reason?: string): Promise; @@ -379,13 +427,21 @@ export abstract class Application extends Base { public get createdAt(): Date; public get createdTimestamp(): number; public description: string | null; + public icon: string | null; + public id: Snowflake; + public name: string | null; + public termsOfServiceURL: string | null; + public privacyPolicyURL: string | null; + public rpcOrigins: string[]; + public cover: string | null; + public verifyKey: string | null; public coverURL(options?: ImageURLOptions): string | null; public iconURL(options?: ImageURLOptions): string | null; @@ -396,31 +452,49 @@ export abstract class Application extends Base { export class ApplicationCommand extends Base { private constructor(client: Client, data: RawApplicationCommandData, guild?: Guild, guildId?: Snowflake); public applicationId: Snowflake; + public contexts: InteractionContextType[] | null; + public get createdAt(): Date; public get createdTimestamp(): number; public defaultMemberPermissions: Readonly | null; + public description: string; + public descriptionLocalizations: LocalizationMap | null; + public descriptionLocalized: string | null; + public guild: Guild | null; + public guildId: Snowflake | null; + public get manager(): ApplicationCommandManager; public id: Snowflake; + public integrationTypes: ApplicationIntegrationType[] | null; + public handler: EntryPointCommandHandlerType | null; + public name: string; + public nameLocalizations: LocalizationMap | null; + public nameLocalized: string | null; - public options: (ApplicationCommandOption & { nameLocalized?: string; descriptionLocalized?: string })[]; + + public options: (ApplicationCommandOption & { descriptionLocalized?: string; nameLocalized?: string })[]; + public permissions: ApplicationCommandPermissionsManager< PermissionsFetchType, PermissionsFetchType, Guild | null, Snowflake >; + public type: ApplicationCommandType; + public version: Snowflake; + public nsfw: boolean; public delete(): Promise>; public edit(data: Partial): Promise>; @@ -443,14 +517,14 @@ export class ApplicationCommand extends Base { public static optionsEqual( existing: readonly ApplicationCommandOption[], options: + | readonly APIApplicationCommandOption[] | readonly ApplicationCommandOption[] - | readonly ApplicationCommandOptionData[] - | readonly APIApplicationCommandOption[], + | readonly ApplicationCommandOptionData[], enforceOptionOrder?: boolean, ): boolean; private static _optionEquals( existing: ApplicationCommandOption, - options: ApplicationCommandOption | ApplicationCommandOptionData | APIApplicationCommandOption, + options: APIApplicationCommandOption | ApplicationCommandOption | ApplicationCommandOptionData, enforceOptionOrder?: boolean, ): boolean; private static transformOption(option: ApplicationCommandOptionData, received?: boolean): unknown; @@ -461,14 +535,19 @@ export class ApplicationCommand extends Base { export class ApplicationRoleConnectionMetadata { private constructor(data: APIApplicationRoleConnectionMetadata); public name: string; + public nameLocalizations: LocalizationMap | null; + public description: string; + public descriptionLocalizations: LocalizationMap | null; + public key: string; + public type: ApplicationRoleConnectionMetadataType; } -export type ApplicationResolvable = Application | Activity | Snowflake; +export type ApplicationResolvable = Activity | Application | Snowflake; export class ApplicationFlagsBitField extends BitField { public static Flags: typeof ApplicationFlags; @@ -492,6 +571,7 @@ export class BaseClient extends AsyncEventEmitter imp private incrementMaxListeners(): void; public options: ClientOptions | WebhookClientOptions; + public rest: REST; public destroy(): void; public toJSON(...props: Record[]): unknown; @@ -502,25 +582,34 @@ export type GuildCacheMessage = CacheTypeReducer< Cached, Message, APIMessage, - Message | APIMessage, - Message | APIMessage + APIMessage | Message, + APIMessage | Message >; export type BooleanCache = Cached extends 'cached' ? true : false; export abstract class CommandInteraction extends BaseInteraction { public type: InteractionType.ApplicationCommand; + public get command(): ApplicationCommand | ApplicationCommand<{ guild: GuildResolvable }> | null; public channelId: Snowflake; + public commandId: Snowflake; + public commandName: string; + public commandType: ApplicationCommandType; + public commandGuildId: Snowflake | null; + public deferred: boolean; + public ephemeral: boolean | null; + public replied: boolean; + public webhook: InteractionWebhook; - public inGuild(): this is CommandInteraction<'raw' | 'cached'>; + public inGuild(): this is CommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is CommandInteraction<'cached'>; public inRawGuild(): this is CommandInteraction<'raw'>; public deferReply( @@ -532,16 +621,16 @@ export abstract class CommandInteraction e ): Promise> | undefined>; public deleteReply(message?: MessageResolvable | '@original'): Promise; public editReply( - options: string | MessagePayload | InteractionEditReplyOptions, + options: InteractionEditReplyOptions | MessagePayload | string, ): Promise>>; public fetchReply(message?: Snowflake | '@original'): Promise>>; - public followUp(options: string | MessagePayload | InteractionReplyOptions): Promise>>; + public followUp(options: InteractionReplyOptions | MessagePayload | string): Promise>>; public reply( options: InteractionReplyOptions & { withResponse: true }, ): Promise>>; public reply(options: InteractionReplyOptions & { withResponse: false }): Promise; public reply( - options: string | MessagePayload | InteractionReplyOptions, + options: InteractionReplyOptions | MessagePayload | string, ): Promise> | undefined>; public launchActivity( options: LaunchActivityOptions & { withResponse: true }, @@ -552,23 +641,23 @@ export abstract class CommandInteraction e ): Promise> | undefined>; public showModal( modal: + | APIModalInteractionResponseCallbackData | JSONEncodable - | ModalComponentData - | APIModalInteractionResponseCallbackData, + | ModalComponentData, options: ShowModalOptions & { withResponse: true }, ): Promise>>; public showModal( modal: + | APIModalInteractionResponseCallbackData | JSONEncodable - | ModalComponentData - | APIModalInteractionResponseCallbackData, + | ModalComponentData, options?: ShowModalOptions & { withResponse: false }, ): Promise; public showModal( modal: + | APIModalInteractionResponseCallbackData | JSONEncodable - | ModalComponentData - | APIModalInteractionResponseCallbackData, + | ModalComponentData, options?: ShowModalOptions, ): Promise> | undefined>; public awaitModalSubmit( @@ -585,8 +674,11 @@ export abstract class BaseGuild extends Base { public get createdAt(): Date; public get createdTimestamp(): number; public features: `${GuildFeature}`[]; + public icon: string | null; + public id: Snowflake; + public name: string; public get nameAcronym(): string; public get partnered(): boolean; @@ -601,23 +693,31 @@ export class BaseGuildEmoji extends Emoji { public imageURL(options?: ImageURLOptions): string; public get url(): string; public available: boolean | null; + public get createdAt(): Date; public get createdTimestamp(): number; public guild: Guild | GuildPreview; + public id: Snowflake; + public managed: boolean | null; + public requiresColons: boolean | null; } -// tslint:disable-next-line no-empty-interface export interface BaseGuildTextChannel extends TextBasedChannelFields {} export class BaseGuildTextChannel extends GuildChannel { protected constructor(guild: Guild, data?: RawGuildChannelData, client?: Client, immediatePatch?: boolean); public defaultAutoArchiveDuration?: ThreadAutoArchiveDuration; + public defaultThreadRateLimitPerUser: number | null; + public rateLimitPerUser: number | null; + public nsfw: boolean; - public threads: GuildTextThreadManager; + + public threads: GuildTextThreadManager; + public topic: string | null; public createInvite(options?: InviteCreateOptions): Promise; public fetchInvites(cache?: boolean): Promise>; @@ -630,18 +730,22 @@ export class BaseGuildTextChannel extends GuildChannel { public setType(type: ChannelType.GuildAnnouncement, reason?: string): Promise; } -// tslint:disable-next-line no-empty-interface -export interface BaseGuildVoiceChannel extends Omit, 'lastPinTimestamp' | 'lastPinAt'> {} +export interface BaseGuildVoiceChannel extends Omit, 'lastPinAt' | 'lastPinTimestamp'> {} export class BaseGuildVoiceChannel extends GuildChannel { public constructor(guild: Guild, data?: RawGuildChannelData); public bitrate: number; + public get full(): boolean; public get joinable(): boolean; public get members(): Collection; public nsfw: boolean; + public rateLimitPerUser: number | null; + public rtcRegion: string | null; + public userLimit: number; + public videoQualityMode: VideoQualityMode | null; public createInvite(options?: InviteCreateOptions): Promise; public fetchInvites(cache?: boolean): Promise>; @@ -653,9 +757,10 @@ export class BaseGuildVoiceChannel extends GuildChannel { export type EnumLike = Record; -export class BitField { +export class BitField { public constructor(bits?: BitFieldResolvable); public bitfield: Type; + public add(...bits: BitFieldResolvable[]): BitField; public any(bit: BitFieldResolvable): boolean; public equals(bit: BitFieldResolvable): boolean; @@ -668,8 +773,8 @@ export class BitField; - public static Flags: EnumLike; - public static resolve(bit?: BitFieldResolvable): number | bigint; + public static Flags: EnumLike; + public static resolve(bit?: BitFieldResolvable): bigint | number; } export class ButtonInteraction extends MessageComponentInteraction { @@ -679,24 +784,24 @@ export class ButtonInteraction extends Mes Cached, ButtonComponent, APIButtonComponent, - ButtonComponent | APIButtonComponent, - ButtonComponent | APIButtonComponent + APIButtonComponent | ButtonComponent, + APIButtonComponent | ButtonComponent >; - public inGuild(): this is ButtonInteraction<'raw' | 'cached'>; + public inGuild(): this is ButtonInteraction<'cached' | 'raw'>; public inCachedGuild(): this is ButtonInteraction<'cached'>; public inRawGuild(): this is ButtonInteraction<'raw'>; } export type AnyComponent = + | APIActionRowComponent | APIMessageComponent - | APIModalComponent - | APIActionRowComponent; + | APIModalComponent; export class Component { public readonly data: Readonly; public get type(): RawComponentData['type']; public toJSON(): RawComponentData; - public equals(other: this | RawComponentData): boolean; + public equals(other: RawComponentData | this): boolean; } export class ButtonComponent extends Component { @@ -740,18 +845,18 @@ export class ChannelSelectMenuComponent extends BaseSelectMenuComponent | null; + public get partial(): false; public type: ChannelType; public get url(): string; @@ -837,7 +945,7 @@ export abstract class BaseChannel extends Base { public fetch(force?: boolean): Promise; public isThread(): this is AnyThreadChannel; public isTextBased(): this is TextBasedChannel; - public isDMBased(): this is PartialGroupDMChannel | DMChannel | PartialDMChannel; + public isDMBased(): this is DMChannel | PartialDMChannel | PartialGroupDMChannel; public isVoiceBased(): this is VoiceBasedChannel; public isThreadOnly(): this is ThreadOnlyChannel; public isSendable(): this is SendableChannels; @@ -848,16 +956,22 @@ export type If = Value ex ? TrueResult : Value extends false ? FalseResult - : TrueResult | FalseResult; + : FalseResult | TrueResult; export class Client extends BaseClient { public constructor(options: ClientOptions); - private actions: unknown; - private expectedGuilds: Set; + private readonly actions: unknown; + + private readonly expectedGuilds: Set; + private readonly packetQueue: unknown[]; - private presence: ClientPresence; - private pings: Collection; - private readyTimeout: NodeJS.Timeout | null; + + private readonly presence: ClientPresence; + + private readonly pings: Collection; + + private readonly readyTimeout: NodeJS.Timeout | null; + private _broadcast(packet: GatewaySendPayload): void; private _eval(script: string): unknown; private _handlePacket(packet?: GatewayDispatchPayload, shardId?: number): boolean; @@ -869,21 +983,34 @@ export class Client extends BaseClient; + public channels: ChannelManager; + public guilds: GuildManager; + public lastPingTimestamps: ReadonlyCollection; + public options: Omit & { intents: IntentsBitField }; + public get ping(): number | null; public get readyAt(): If; public readyTimestamp: If; + public sweepers: Sweepers; + public shard: ShardClientUtil | null; + public status: Status; + public token: If; + public get uptime(): If; public user: If; + public users: UserManager; + public voice: ClientVoiceManager; + public ws: WebSocketManager; public destroy(): Promise; @@ -911,27 +1038,47 @@ export interface StickerPackFetchOptions { export class ClientApplication extends Application { private constructor(client: Client, data: RawClientApplicationData); public botPublic: boolean | null; + public botRequireCodeGrant: boolean | null; + public bot: User | null; + public commands: ApplicationCommandManager; + public emojis: ApplicationEmojiManager; + public entitlements: EntitlementManager; + public subscriptions: SubscriptionManager; + public guildId: Snowflake | null; + public get guild(): Guild | null; public flags: Readonly; + public approximateGuildCount: number | null; + public approximateUserInstallCount: number | null; + public tags: string[]; + public installParams: ClientApplicationInstallParams | null; + public integrationTypesConfig: IntegrationTypesConfiguration | null; + public customInstallURL: string | null; - public owner: User | Team | null; + + public owner: Team | User | null; + public get partial(): boolean; public interactionsEndpointURL: string | null; + public eventWebhooksURL: string | null; + public eventWebhooksStatus: ApplicationWebhookEventStatus | null; + public eventWebhooksTypes: ApplicationWebhookEventType[] | null; + public roleConnectionsVerificationURL: string | null; public edit(options: ClientApplicationEditOptions): Promise; public fetch(): Promise; @@ -951,14 +1098,15 @@ export class ClientPresence extends Presence { export class ClientUser extends User { public mfaEnabled: boolean; + public get presence(): ClientPresence; public verified: boolean; public edit(options: ClientUserEditOptions): Promise; public setActivity(options?: ActivityOptions): ClientPresence; public setActivity(name: string, options?: Omit): ClientPresence; public setAFK(afk?: boolean, shardId?: number | readonly number[]): ClientPresence; - public setAvatar(avatar: BufferResolvable | Base64Resolvable | null): Promise; - public setBanner(banner: BufferResolvable | Base64Resolvable | null): Promise; + public setAvatar(avatar: Base64Resolvable | BufferResolvable | null): Promise; + public setBanner(banner: Base64Resolvable | BufferResolvable | null): Promise; public setPresence(data: PresenceData): ClientPresence; public setStatus(status: PresenceStatusData, shardId?: number | readonly number[]): ClientPresence; public setUsername(username: string): Promise; @@ -966,7 +1114,7 @@ export class ClientUser extends User { export class Options extends null { private constructor(); - private static userAgentAppendix: string; + private static readonly userAgentAppendix: string; public static get DefaultMakeCacheSettings(): CacheWithLimitsOptions; public static get DefaultSweeperSettings(): SweeperOptions; public static createDefault(): ClientOptions; @@ -977,16 +1125,17 @@ export class Options extends null { export class ClientVoiceManager { private constructor(client: Client); public readonly client: Client; + public adapters: Map; } -export { Collection, ReadonlyCollection } from '@discordjs/collection'; +export { Collection, type ReadonlyCollection } from '@discordjs/collection'; export interface CollectorEventTypes { collect: [Value, ...Extras]; - ignore: [Value, ...Extras]; dispose: [Value, ...Extras]; end: [collected: ReadonlyCollection, reason: string]; + ignore: [Value, ...Extras]; } export abstract class Collector< @@ -996,17 +1145,24 @@ export abstract class Collector< EventTypes extends {} = CollectorEventTypes, > extends AsyncEventEmitter { protected constructor(client: Client, options?: CollectorOptions<[Value, ...Extras]>); - private _timeout: NodeJS.Timeout | null; - private _idletimeout: NodeJS.Timeout | null; - private _endReason: string | null; + private readonly _timeout: NodeJS.Timeout | null; + + private readonly _idletimeout: NodeJS.Timeout | null; + + private readonly _endReason: string | null; public readonly client: Client; + public collected: Collection; + public lastCollectedTimestamp: number | null; + public get lastCollectedAt(): Date | null; public ended: boolean; + public get endReason(): string | null; public filter: CollectorFilter<[Value, ...Extras]>; + public get next(): Promise; public options: CollectorOptions<[Value, ...Extras]>; public checkEnd(): boolean; @@ -1024,8 +1180,9 @@ export abstract class Collector< export class ChatInputCommandInteraction extends CommandInteraction { public commandType: ApplicationCommandType.ChatInput; - public options: Omit, 'getMessage' | 'getFocused'>; - public inGuild(): this is ChatInputCommandInteraction<'raw' | 'cached'>; + + public options: Omit, 'getFocused' | 'getMessage'>; + public inGuild(): this is ChatInputCommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is ChatInputCommandInteraction<'cached'>; public inRawGuild(): this is ChatInputCommandInteraction<'raw'>; public toString(): string; @@ -1033,18 +1190,25 @@ export class ChatInputCommandInteraction e export class AutocompleteInteraction extends BaseInteraction { public type: InteractionType.ApplicationCommandAutocomplete; + public get command(): ApplicationCommand | ApplicationCommand<{ guild: GuildResolvable }> | null; public channelId: Snowflake; + public commandId: Snowflake; + public commandName: string; + public commandType: ApplicationCommandType.ChatInput; + public commandGuildId: Snowflake | null; + public responded: boolean; + public options: Omit< CommandInteractionOptionResolver, - 'getMessage' | 'getUser' | 'getAttachment' | 'getChannel' | 'getMember' | 'getMentionable' | 'getRole' + 'getAttachment' | 'getChannel' | 'getMember' | 'getMentionable' | 'getMessage' | 'getRole' | 'getUser' >; - public inGuild(): this is AutocompleteInteraction<'raw' | 'cached'>; + public inGuild(): this is AutocompleteInteraction<'cached' | 'raw'>; public inCachedGuild(): this is AutocompleteInteraction<'cached'>; public inRawGuild(): this is AutocompleteInteraction<'raw'>; public respond(options: readonly ApplicationCommandOptionChoiceData[]): Promise; @@ -1057,11 +1221,16 @@ export class CommandInteractionOptionResolver[]; + public readonly resolved: Readonly> | null; - private _group: string | null; - private _hoistedOptions: CommandInteractionOption[]; - private _subcommand: string | null; + + private readonly _group: string | null; + + private readonly _hoistedOptions: CommandInteractionOption[]; + + private readonly _subcommand: string | null; private _getTypedOption( name: string, allowedTypes: readonly ApplicationCommandOptionType[], @@ -1097,8 +1266,8 @@ export class CommandInteractionOptionResolver['channel']>, { - type: Type extends ChannelType.PublicThread | ChannelType.AnnouncementThread - ? ChannelType.PublicThread | ChannelType.AnnouncementThread + type: Type extends ChannelType.AnnouncementThread | ChannelType.PublicThread + ? ChannelType.AnnouncementThread | ChannelType.PublicThread : Type; } >; @@ -1115,8 +1284,8 @@ export class CommandInteractionOptionResolver['channel']>, { - type: Type extends ChannelType.PublicThread | ChannelType.AnnouncementThread - ? ChannelType.PublicThread | ChannelType.AnnouncementThread + type: Type extends ChannelType.AnnouncementThread | ChannelType.PublicThread + ? ChannelType.AnnouncementThread | ChannelType.PublicThread : Type; } > | null; @@ -1152,24 +1321,26 @@ export class CommandInteractionOptionResolver extends CommandInteraction { public options: Omit< CommandInteractionOptionResolver, - | 'getMessage' + | 'getAttachment' + | 'getBoolean' + | 'getChannel' | 'getFocused' - | 'getMentionable' - | 'getRole' - | 'getUser' + | 'getInteger' | 'getMember' - | 'getAttachment' + | 'getMentionable' + | 'getMessage' | 'getNumber' - | 'getInteger' + | 'getRole' | 'getString' - | 'getChannel' - | 'getBoolean' - | 'getSubcommandGroup' | 'getSubcommand' + | 'getSubcommandGroup' + | 'getUser' >; + public commandType: ApplicationCommandType.Message | ApplicationCommandType.User; + public targetId: Snowflake; - public inGuild(): this is ContextMenuCommandInteraction<'raw' | 'cached'>; + public inGuild(): this is ContextMenuCommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is ContextMenuCommandInteraction<'cached'>; public inRawGuild(): this is ContextMenuCommandInteraction<'raw'>; private resolveContextMenuOptions(data: APIApplicationCommandInteractionData): CommandInteractionOption[]; @@ -1179,21 +1350,22 @@ export class PrimaryEntryPointCommandInteraction< Cached extends CacheType = CacheType, > extends CommandInteraction { public commandType: ApplicationCommandType.PrimaryEntryPoint; - public inGuild(): this is PrimaryEntryPointCommandInteraction<'raw' | 'cached'>; + public inGuild(): this is PrimaryEntryPointCommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is PrimaryEntryPointCommandInteraction<'cached'>; public inRawGuild(): this is PrimaryEntryPointCommandInteraction<'raw'>; } -// tslint:disable-next-line no-empty-interface export interface DMChannel extends Omit< TextBasedChannelFields, - 'bulkDelete' | 'fetchWebhooks' | 'createWebhook' | 'setRateLimitPerUser' | 'setNSFW' + 'bulkDelete' | 'createWebhook' | 'fetchWebhooks' | 'setNSFW' | 'setRateLimitPerUser' > {} export class DMChannel extends BaseChannel { private constructor(client: Client, data?: RawDMChannelData); public flags: Readonly; + public recipientId: Snowflake; + public get recipient(): User | null; public type: ChannelType.DM; public fetch(force?: boolean): Promise; @@ -1203,9 +1375,11 @@ export class DMChannel extends BaseChannel { export class Emoji extends Base { protected constructor(client: Client, emoji: RawEmojiData); public animated: boolean | null; + public get createdAt(): Date | null; public get createdTimestamp(): number | null; public id: Snowflake | null; + public name: string | null; public get identifier(): string; public imageURL(options?: ImageURLOptions): string | null; @@ -1215,7 +1389,7 @@ export class Emoji extends Base { } export interface ApplicationEmojiCreateOptions { - attachment: BufferResolvable | Base64Resolvable; + attachment: Base64Resolvable | BufferResolvable; name: string; } @@ -1227,9 +1401,13 @@ export class ApplicationEmoji extends Emoji { private constructor(client: Client, data: RawApplicationEmojiData, application: ClientApplication); public application: ClientApplication; + public author: User | null; + public id: Snowflake; + public managed: boolean | null; + public requiresColons: boolean | null; public delete(): Promise; public edit(options: ApplicationEmojiEditOptions): Promise; @@ -1252,14 +1430,23 @@ export class ApplicationEmojiManager extends CachedManager, data: APIEntitlement); public id: Snowflake; + public skuId: Snowflake; + public userId: Snowflake; + public guildId: Snowflake | null; + public applicationId: Snowflake; + public type: EntitlementType; + public consumed: boolean; + public deleted: boolean; + public startsTimestamp: number | null; + public endsTimestamp: number | null; public get guild(): Guild | null; public get startsAt(): Date | null; @@ -1268,13 +1455,13 @@ export class Entitlement extends Base { public fetchUser(): Promise; public isActive(): boolean; public isTest(): this is this & { - startsTimestamp: null; + get endsAt(): null; endsTimestamp: null; get startsAt(): null; - get endsAt(): null; + startsTimestamp: null; }; - public isUserSubscription(): this is this & { guildId: null; get guild(): null }; - public isGuildSubscription(): this is this & { guildId: Snowflake; guild: Guild }; + public isUserSubscription(): this is this & { get guild(): null; guildId: null }; + public isGuildSubscription(): this is this & { guild: Guild; guildId: Snowflake }; } export class Guild extends AnonymousGuild { @@ -1284,62 +1471,106 @@ export class Guild extends AnonymousGuild { public get afkChannel(): VoiceChannel | null; public afkChannelId: Snowflake | null; + public afkTimeout: number; + public applicationId: Snowflake | null; + public maxVideoChannelUsers: number | null; + public approximateMemberCount: number | null; + public approximatePresenceCount: number | null; + public autoModerationRules: AutoModerationRuleManager; + public available: boolean; + public bans: GuildBanManager; + public channels: GuildChannelManager; + public commands: GuildApplicationCommandManager; + public defaultMessageNotifications: GuildDefaultMessageNotifications; + public discoverySplash: string | null; + public emojis: GuildEmojiManager; + public explicitContentFilter: GuildExplicitContentFilter; + public invites: GuildInviteManager; + public get joinedAt(): Date; public joinedTimestamp: number; + public large: boolean; + public maximumMembers: number | null; + public maximumPresences: number | null; + public maxStageVideoChannelUsers: number | null; + public memberCount: number; + public members: GuildMemberManager; + public mfaLevel: GuildMFALevel; + public ownerId: Snowflake; + public preferredLocale: Locale; + public premiumProgressBarEnabled: boolean; + public premiumTier: GuildPremiumTier; + public presences: PresenceManager; + public get publicUpdatesChannel(): TextChannel | null; public publicUpdatesChannelId: Snowflake | null; + public roles: RoleManager; + public get rulesChannel(): TextChannel | null; public rulesChannelId: Snowflake | null; + public get safetyAlertsChannel(): TextChannel | null; public safetyAlertsChannelId: Snowflake | null; + public scheduledEvents: GuildScheduledEventManager; + public shardId: number; + public soundboardSounds: GuildSoundboardSoundManager; + public stageInstances: StageInstanceManager; + public stickers: GuildStickerManager; + public incidentsData: IncidentActions | null; + public get systemChannel(): TextChannel | null; public systemChannelFlags: Readonly; + public systemChannelId: Snowflake | null; + public vanityURLUses: number | null; + public get voiceAdapterCreator(): InternalDiscordGatewayAdapterCreator; public voiceStates: VoiceStateManager; + public get widgetChannel(): - | TextChannel | AnnouncementChannel - | VoiceBasedChannel | ForumChannel | MediaChannel + | TextChannel + | VoiceBasedChannel | null; public widgetChannelId: Snowflake | null; + public widgetEnabled: boolean | null; public get maximumBitrate(): number; public createTemplate(name: string, description?: string): Promise; @@ -1368,27 +1599,27 @@ export class Guild extends AnonymousGuild { public setIncidentActions(incidentActions: IncidentActionsEditOptions): Promise; public setAFKChannel(afkChannel: VoiceChannelResolvable | null, reason?: string): Promise; public setAFKTimeout(afkTimeout: number, reason?: string): Promise; - public setBanner(banner: BufferResolvable | Base64Resolvable | null, reason?: string): Promise; + public setBanner(banner: Base64Resolvable | BufferResolvable | null, reason?: string): Promise; public setDefaultMessageNotifications( defaultMessageNotifications: GuildDefaultMessageNotifications | null, reason?: string, ): Promise; public setDiscoverySplash( - discoverySplash: BufferResolvable | Base64Resolvable | null, + discoverySplash: Base64Resolvable | BufferResolvable | null, reason?: string, ): Promise; public setExplicitContentFilter( explicitContentFilter: GuildExplicitContentFilter | null, reason?: string, ): Promise; - public setIcon(icon: BufferResolvable | Base64Resolvable | null, reason?: string): Promise; + public setIcon(icon: Base64Resolvable | BufferResolvable | null, reason?: string): Promise; public setName(name: string, reason?: string): Promise; public setOwner(owner: UserResolvable, reason?: string): Promise; public setPreferredLocale(preferredLocale: Locale | null, reason?: string): Promise; public setPublicUpdatesChannel(publicUpdatesChannel: TextChannelResolvable | null, reason?: string): Promise; public setRulesChannel(rulesChannel: TextChannelResolvable | null, reason?: string): Promise; public setSafetyAlertsChannel(safetyAlertsChannel: TextChannelResolvable | null, reason?: string): Promise; - public setSplash(splash: BufferResolvable | Base64Resolvable | null, reason?: string): Promise; + public setSplash(splash: Base64Resolvable | BufferResolvable | null, reason?: string): Promise; public setSystemChannel(systemChannel: TextChannelResolvable | null, reason?: string): Promise; public setSystemChannelFlags(systemChannelFlags: SystemChannelFlagsResolvable, reason?: string): Promise; public setVerificationLevel(verificationLevel: GuildVerificationLevel | null, reason?: string): Promise; @@ -1400,11 +1631,16 @@ export class Guild extends AnonymousGuild { export class GuildAuditLogs { private constructor(guild: Guild, data: RawGuildAuditLogData); - private applicationCommands: Collection; - private webhooks: Collection>; - private integrations: Collection; - private guildScheduledEvents: Collection; - private autoModerationRules: Collection; + private readonly applicationCommands: Collection; + + private readonly webhooks: Collection>; + + private readonly integrations: Collection; + + private readonly guildScheduledEvents: Collection; + + private readonly autoModerationRules: Collection; + public entries: Collection>; public toJSON(): unknown; } @@ -1420,20 +1656,31 @@ export class GuildAuditLogsEntry< > { private constructor(guild: Guild, data: RawGuildAuditLogEntryData, logs?: GuildAuditLogs); public static Targets: GuildAuditLogsTargets; + public action: TAction; + public actionType: TActionType; + public changes: AuditLogChange[]; + public get createdAt(): Date; public get createdTimestamp(): number; public executorId: Snowflake | null; - public executor: User | PartialUser | null; + + public executor: PartialUser | User | null; + public extra: TAction extends keyof GuildAuditLogsEntryExtraField ? GuildAuditLogsEntryExtraField[TAction] : null; + public id: Snowflake; + public reason: string | null; + public targetId: Snowflake | null; + public target: TTargetType extends keyof GuildAuditLogsEntryTargetField ? GuildAuditLogsEntryTargetField[TTargetType] - : { id: Snowflake | undefined; [x: string]: unknown } | null; + : { [x: string]: unknown; id: Snowflake | undefined } | null; + public targetType: TTargetType; public static actionType(action: AuditLogEvent): GuildAuditLogsActionType; public static targetType(target: AuditLogEvent): GuildAuditLogsTargetType; @@ -1450,7 +1697,9 @@ export class GuildAuditLogsEntry< export class GuildBan extends Base { private constructor(client: Client, data: RawGuildBanData, guild: Guild); public guild: Guild; + public user: User; + public get partial(): boolean; public reason?: string | null; public fetch(force?: boolean): Promise; @@ -1464,17 +1713,24 @@ export abstract class GuildChannel extends BaseChannel { public get createdTimestamp(): number; public get deletable(): boolean; public flags: Readonly; + public guild: Guild; + public guildId: Snowflake; + public get manageable(): boolean; public get members(): Collection; public name: string; + public get parent(): CategoryChannel | null; public parentId: Snowflake | null; + public permissionOverwrites: PermissionOverwriteManager; + public get permissionsLocked(): boolean | null; public get position(): number; public rawPosition: number; + public type: GuildChannelTypes; public get viewable(): boolean; public clone(options?: GuildChannelCloneOptions): Promise; @@ -1484,7 +1740,7 @@ export abstract class GuildChannel extends BaseChannel { public lockPermissions(): Promise; public permissionsFor(memberOrRole: GuildMember | Role, checkAdmin?: boolean): Readonly; public permissionsFor( - memberOrRole: UserResolvable | RoleResolvable, + memberOrRole: RoleResolvable | UserResolvable, checkAdmin?: boolean, ): Readonly | null; public setName(name: string, reason?: string): Promise; @@ -1496,10 +1752,11 @@ export abstract class GuildChannel extends BaseChannel { export class GuildEmoji extends BaseGuildEmoji { private constructor(client: Client, data: RawGuildEmojiData, guild: Guild); - private _roles: Snowflake[]; + private readonly _roles: Snowflake[]; public get deletable(): boolean; public guild: Guild; + public author: User | null; public get roles(): GuildEmojiRoleManager; public delete(reason?: string): Promise; @@ -1521,30 +1778,40 @@ export class GuildMemberFlagsBitField extends BitField { export interface GuildMember extends PartialTextBasedChannelFields {} export class GuildMember extends Base { private constructor(client: Client, data: RawGuildMemberData, guild: Guild); - private _roles: Snowflake[]; + private readonly _roles: Snowflake[]; + public avatar: string | null; + public banner: string | null; + public get bannable(): boolean; public get dmChannel(): DMChannel | null; public get displayColor(): number; public get displayHexColor(): HexColorString; public get displayName(): string; public guild: Guild; + public get id(): Snowflake; public pending: boolean; + public get communicationDisabledUntil(): Date | null; public communicationDisabledUntilTimestamp: number | null; + public flags: Readonly; + public get joinedAt(): Date | null; public joinedTimestamp: number | null; + public get kickable(): boolean; public get manageable(): boolean; public get moderatable(): boolean; public nickname: string | null; + public get partial(): false; public get permissions(): Readonly; public get premiumSince(): Date | null; public premiumSinceTimestamp: number | null; + public get presence(): Presence | null; public get roles(): GuildMemberRoleManager; public user: User; @@ -1561,8 +1828,8 @@ export class GuildMember extends Base { public displayBannerURL(options?: ImageURLOptions): string | null; public edit(options: GuildMemberEditOptions): Promise; public isCommunicationDisabled(): this is GuildMember & { - communicationDisabledUntilTimestamp: number; readonly communicationDisabledUntil: Date; + communicationDisabledUntilTimestamp: number; }; public kick(reason?: string): Promise; public permissionsIn(channel: GuildChannelResolvable): Readonly; @@ -1577,53 +1844,79 @@ export class GuildOnboarding extends Base { private constructor(client: Client, data: RESTGetAPIGuildOnboardingResult); public get guild(): Guild; public guildId: Snowflake; + public prompts: Collection; + public defaultChannels: Collection; + public enabled: boolean; + public mode: GuildOnboardingMode; } export class GuildOnboardingPrompt extends Base { private constructor(client: Client, data: APIGuildOnboardingPrompt, guildId: Snowflake); public id: Snowflake; + public get guild(): Guild; public guildId: Snowflake; + public options: Collection; + public title: string; + public singleSelect: boolean; + public required: boolean; + public inOnboarding: boolean; + public type: GuildOnboardingPromptType; } export class GuildOnboardingPromptOption extends Base { private constructor(client: Client, data: APIGuildOnboardingPromptOption, guildId: Snowflake); - private _emoji: APIPartialEmoji; + private readonly _emoji: APIPartialEmoji; public id: Snowflake; + public get emoji(): Emoji | GuildEmoji | null; public get guild(): Guild; public guildId: Snowflake; + public channels: Collection; + public roles: Collection; + public title: string; + public description: string | null; } export class GuildPreview extends Base { private constructor(client: Client, data: RawGuildPreviewData); public approximateMemberCount: number; + public approximatePresenceCount: number; + public get createdAt(): Date; public get createdTimestamp(): number; public description: string | null; + public discoverySplash: string | null; + public emojis: Collection; + public stickers: Collection; + public features: `${GuildFeature}`[]; + public icon: string | null; + public id: Snowflake; + public name: string; + public splash: string | null; public discoverySplashURL(options?: ImageURLOptions): string | null; public iconURL(options?: ImageURLOptions): string | null; @@ -1636,26 +1929,42 @@ export class GuildPreview extends Base { export class GuildScheduledEvent extends Base { private constructor(client: Client, data: RawGuildScheduledEventData); public id: Snowflake; + public guildId: Snowflake; + public channelId: Snowflake | null; + public creatorId: Snowflake | null; + public name: string; + public description: string | null; + public scheduledStartTimestamp: number | null; + public scheduledEndTimestamp: number | null; + public privacyLevel: GuildScheduledEventPrivacyLevel; + public status: Status; + public entityType: GuildScheduledEventEntityType; + public entityId: Snowflake | null; + public entityMetadata: GuildScheduledEventEntityMetadata | null; + public userCount: number | null; + public creator: User | null; + public recurrenceRule: GuildScheduledEventRecurrenceRule | null; + public get createdTimestamp(): number; public get createdAt(): Date; public get scheduledStartAt(): Date | null; public get scheduledEndAt(): Date | null; - public get channel(): VoiceChannel | StageChannel | null; + public get channel(): StageChannel | VoiceChannel | null; public get guild(): Guild | null; public get url(): string; public image: string | null; @@ -1690,43 +1999,54 @@ export class GuildScheduledEvent, data: RawGuildTemplateData); public createdTimestamp: number; + public updatedTimestamp: number; + public get url(): string; public code: string; + public name: string; + public description: string | null; + public usageCount: number; + public creator: User; + public creatorId: Snowflake; + public get createdAt(): Date; public get updatedAt(): Date; public get guild(): Guild | null; public guildId: Snowflake; + public serializedGuild: APITemplateSerializedSourceGuild; + public unSynced: boolean | null; - public createGuild(name: string, icon?: BufferResolvable | Base64Resolvable): Promise; + + public createGuild(name: string, icon?: Base64Resolvable | BufferResolvable): Promise; public delete(): Promise; public edit(options?: GuildTemplateEditOptions): Promise; public sync(): Promise; @@ -1736,29 +2056,46 @@ export class GuildTemplate extends Base { export class GuildPreviewEmoji extends BaseGuildEmoji { private constructor(client: Client, data: RawGuildEmojiData, guild: GuildPreview); public guild: GuildPreview; + public roles: Snowflake[]; } export class Integration extends Base { private constructor(client: Client, data: RawIntegrationData, guild: Guild); public account: IntegrationAccount; + public application: IntegrationApplication | null; + public enabled: boolean | null; + public expireBehavior: IntegrationExpireBehavior | null; + public expireGracePeriod: number | null; + public guild: Guild; + public id: Snowflake | string; + public name: string; + public role: Role | null; + public enableEmoticons: boolean | null; + public get roles(): Collection; public scopes: OAuth2Scopes[]; + public get syncedAt(): Date | null; public syncedTimestamp: number | null; + public syncing: boolean | null; + public type: IntegrationType; + public user: User | null; + public subscriberCount: number | null; + public revoked: boolean | null; public delete(reason?: string): Promise; } @@ -1766,10 +2103,15 @@ export class Integration extends Base { export class IntegrationApplication extends Application { private constructor(client: Client, data: RawIntegrationApplicationData); public bot: User | null; + public termsOfServiceURL: string | null; + public privacyPolicyURL: string | null; + public rpcOrigins: string[]; + public cover: string | null; + public verifyKey: string | null; } @@ -1792,19 +2134,19 @@ export type CacheTypeReducer< ? CachedType : [State] extends ['raw'] ? RawType - : [State] extends ['raw' | 'cached'] + : [State] extends ['cached' | 'raw'] ? PresentType : Fallback; export type Interaction = + | AutocompleteInteraction + | ButtonInteraction | ChatInputCommandInteraction | MessageContextMenuCommandInteraction - | UserContextMenuCommandInteraction + | ModalSubmitInteraction | PrimaryEntryPointCommandInteraction | SelectMenuInteraction - | ButtonInteraction - | AutocompleteInteraction - | ModalSubmitInteraction; + | UserContextMenuCommandInteraction; export type RepliableInteraction = Exclude< Interaction, @@ -1814,9 +2156,12 @@ export type RepliableInteraction = Exclude export class BaseInteraction extends Base { // This a technique used to brand different cached types. Or else we'll get `never` errors on typeguard checks. private readonly _cacheType: Cached; + protected constructor(client: Client, data: RawInteractionData); public applicationId: Snowflake; + public authorizingIntegrationOwners: APIAuthorizingIntegrationOwnersMap; + public get channel(): CacheTypeReducer< Cached, GuildTextBasedChannel | null, @@ -1825,24 +2170,38 @@ export class BaseInteraction extends Base TextBasedChannel | null >; public channelId: Snowflake | null; + public context: InteractionContextType | null; + public get createdAt(): Date; public get createdTimestamp(): number; public get guild(): CacheTypeReducer; public guildId: CacheTypeReducer; + public id: Snowflake; + public member: CacheTypeReducer; + public readonly token: string; + public type: InteractionType; + public user: User; + public version: number; + public appPermissions: Readonly; + public memberPermissions: CacheTypeReducer>; + public locale: Locale; + public guildLocale: CacheTypeReducer; + public entitlements: Collection; + public attachmentSizeLimit: number; - public inGuild(): this is BaseInteraction<'raw' | 'cached'>; + public inGuild(): this is BaseInteraction<'cached' | 'raw'>; public inCachedGuild(): this is BaseInteraction<'cached'>; public inRawGuild(): this is BaseInteraction<'raw'>; public isButton(): this is ButtonInteraction; @@ -1867,27 +2226,37 @@ export class BaseInteraction extends Base export class InteractionCallback { private constructor(client: Client, data: RESTAPIInteractionCallbackObject); public activityInstanceId: string | null; + public readonly client: Client; + public get createdAt(): Date; public get createdTimestamp(): number; public id: Snowflake; + public responseMessageEphemeral: boolean | null; + public responseMessageId: Snowflake | null; + public responseMessageLoading: boolean | null; + public type: InteractionType; } export class InteractionCallbackResponse { private constructor(client: Client, data: RESTPostAPIInteractionCallbackWithResponseResult); public readonly client: Client; + public interaction: InteractionCallback; + public resource: InteractionCallbackResource | null; } export class InteractionCallbackResource { private constructor(client: Client, data: RESTAPIInteractionCallbackResourceObject); public activityInstance: RESTAPIInteractionCallbackActivityInstanceResource | null; + public message: Message | null; + public type: InteractionResponseType; } @@ -1898,12 +2267,19 @@ export class InteractionCollector exte private _handleGuildDeletion(guild: Guild): void; public channelId: Snowflake | null; + public componentType: ComponentType | null; + public guildId: Snowflake | null; + public interactionType: InteractionType | null; + public messageId: Snowflake | null; + public options: InteractionCollectorOptions; + public total: number; + public users: Collection; public collect(interaction: Interaction): Snowflake; @@ -1911,16 +2287,16 @@ export class InteractionCollector exte public dispose(interaction: Interaction): Snowflake; } -// tslint:disable-next-line no-empty-interface export interface InteractionWebhook extends PartialWebhookFields {} export class InteractionWebhook { public constructor(client: Client, id: Snowflake, token: string); public readonly client: Client; + public token: string; - public send(options: string | MessagePayload | InteractionReplyOptions): Promise; + public send(options: InteractionReplyOptions | MessagePayload | string): Promise; public editMessage( message: MessageResolvable | '@original', - options: string | MessagePayload | WebhookMessageEditOptions, + options: MessagePayload | WebhookMessageEditOptions | string, ): Promise; public fetchMessage(message: Snowflake | '@original'): Promise; } @@ -1928,31 +2304,48 @@ export class InteractionWebhook { export class Invite extends Base { private constructor(client: Client, data: RawInviteData); public channel: NonThreadGuildBasedChannel | PartialGroupDMChannel | null; + public channelId: Snowflake | null; + public code: string; + public get deletable(): boolean; public get createdAt(): Date | null; public createdTimestamp: number | null; + public get expiresAt(): Date | null; public get expiresTimestamp(): number | null; - public guild: InviteGuild | Guild | null; + public guild: Guild | InviteGuild | null; + public get inviter(): User | null; public inviterId: Snowflake | null; + public maxAge: number | null; + public maxUses: number | null; + public memberCount: number; + public presenceCount: number; + public targetApplication: IntegrationApplication | null; + public targetUser: User | null; + public targetType: InviteTargetType | null; + public temporary: boolean | null; + public type: InviteType; + public get url(): string; public uses: number | null; + public delete(reason?: string): Promise; public toJSON(): unknown; public toString(): string; public static InvitesPattern: RegExp; + public guildScheduledEvent: GuildScheduledEvent | null; } @@ -1964,6 +2357,7 @@ export class InviteGuild extends AnonymousGuild { export class LimitedCollection extends Collection { public constructor(options?: LimitedCollectionOptions, iterable?: Iterable); public maxSize: number; + public keepOverLimit: ((value: Value, key: Key, collection: this) => boolean) | null; } @@ -2006,13 +2400,13 @@ export interface AwaitMessageCollectorOptionsParams< } export interface StringMappedInteractionTypes { + ActionRow: MessageComponentInteraction; Button: ButtonInteraction; + ChannelSelectMenu: ChannelSelectMenuInteraction; + MentionableSelectMenu: MentionableSelectMenuInteraction; + RoleSelectMenu: RoleSelectMenuInteraction; StringSelectMenu: StringSelectMenuInteraction; UserSelectMenu: UserSelectMenuInteraction; - RoleSelectMenu: RoleSelectMenuInteraction; - MentionableSelectMenu: MentionableSelectMenuInteraction; - ChannelSelectMenu: ChannelSelectMenuInteraction; - ActionRow: MessageComponentInteraction; } export type WrapBooleanCache = If; @@ -2029,53 +2423,83 @@ export interface MappedInteractionTypes { export class Message extends Base { private readonly _cacheType: InGuild; private constructor(client: Client, data: RawMessageData); - private _patch(data: RawPartialMessageData | RawMessageData): void; + private _patch(data: RawMessageData | RawPartialMessageData): void; public activity: MessageActivity | null; + public applicationId: Snowflake | null; + public attachments: Collection; + public author: User; + public get bulkDeletable(): boolean; public get channel(): If; public channelId: Snowflake; + public get cleanContent(): string; public components: ActionRow[]; + public content: string; + public get createdAt(): Date; public createdTimestamp: number; + public get crosspostable(): boolean; public get deletable(): boolean; public get editable(): boolean; public get editedAt(): Date | null; public editedTimestamp: number | null; + public embeds: Embed[]; + public groupActivityApplication: ClientApplication | null; + public guildId: If; + public get guild(): If; public get hasThread(): boolean; public id: Snowflake; + public interactionMetadata: MessageInteractionMetadata | null; + public get member(): GuildMember | null; public mentions: MessageMentions; - public nonce: string | number | null; + + public nonce: number | string | null; + public get partial(): false; public get pinnable(): boolean; public pinned: boolean; + public reactions: ReactionManager; + public stickers: Collection; + public position: number | null; + public roleSubscriptionData: RoleSubscriptionData | null; + public resolved: CommandInteractionResolvedData | null; + public system: boolean; + public get thread(): AnyThreadChannel | null; public tts: boolean; + public poll: Poll | null; + public call: MessageCall | null; + public type: MessageType; + public get url(): string; public webhookId: Snowflake | null; + public flags: Readonly; + public reference: MessageReference | null; + public messageSnapshots: Collection; public awaitMessageComponent( options?: AwaitMessageCollectorOptionsParams, @@ -2087,7 +2511,7 @@ export class Message extends Base { ): InteractionCollector[ComponentType]>; public delete(): Promise>>; public edit( - content: string | MessageEditOptions | MessagePayload, + content: MessageEditOptions | MessagePayload | string, ): Promise>>; public equals(message: Message, rawData: unknown): boolean; public fetchReference(): Promise>>; @@ -2098,7 +2522,7 @@ export class Message extends Base { public react(emoji: EmojiIdentifierResolvable): Promise; public removeAttachments(): Promise>>; public reply( - options: string | MessagePayload | MessageReplyOptions, + options: MessagePayload | MessageReplyOptions | string, ): Promise>>; public forward( channel: Exclude, @@ -2115,7 +2539,9 @@ export class Message extends Base { export class AttachmentBuilder { public constructor(attachment: BufferResolvable | Stream, data?: AttachmentData); public attachment: BufferResolvable | Stream; + public description: string | null; + public name: string | null; public get spoiler(): boolean; public setDescription(description: string): this; @@ -2128,21 +2554,35 @@ export class AttachmentBuilder { export class Attachment { private constructor(data: APIAttachment); - private attachment: BufferResolvable | Stream; + private readonly attachment: BufferResolvable | Stream; + public contentType: string | null; + public description: string | null; + public duration: number | null; + public ephemeral: boolean; + public flags: AttachmentFlagsBitField; + public height: number | null; + public id: Snowflake; + public name: string; + public proxyURL: string; + public size: number; + public get spoiler(): boolean; public title: string | null; + public url: string; + public waveform: string | null; + public width: number | null; public toJSON(): unknown; } @@ -2160,7 +2600,9 @@ export class MessageCollector extends Collector extends BaseInteraction { protected constructor(client: Client, data: RawMessageComponentInteractionData); public type: InteractionType.MessageComponent; + public get component(): CacheTypeReducer< Cached, MessageActionRowComponent, APIComponentInMessageActionRow, - MessageActionRowComponent | APIComponentInMessageActionRow, - MessageActionRowComponent | APIComponentInMessageActionRow + APIComponentInMessageActionRow | MessageActionRowComponent, + APIComponentInMessageActionRow | MessageActionRowComponent >; public componentType: MessageComponentType; + public customId: string; + public channelId: Snowflake; + public deferred: boolean; + public ephemeral: boolean | null; + public message: Message>; + public replied: boolean; + public webhook: InteractionWebhook; - public inGuild(): this is MessageComponentInteraction<'raw' | 'cached'>; + public inGuild(): this is MessageComponentInteraction<'cached' | 'raw'>; public inCachedGuild(): this is MessageComponentInteraction<'cached'>; public inRawGuild(): this is MessageComponentInteraction<'raw'>; public deferReply( @@ -2204,23 +2654,23 @@ export class MessageComponentInteraction e ): Promise> | undefined>; public deleteReply(message?: MessageResolvable | '@original'): Promise; public editReply( - options: string | MessagePayload | InteractionEditReplyOptions, + options: InteractionEditReplyOptions | MessagePayload | string, ): Promise>>; public fetchReply(message?: Snowflake | '@original'): Promise>>; - public followUp(options: string | MessagePayload | InteractionReplyOptions): Promise>>; + public followUp(options: InteractionReplyOptions | MessagePayload | string): Promise>>; public reply( options: InteractionReplyOptions & { withResponse: true }, ): Promise>>; public reply(options: InteractionReplyOptions & { withResponse: false }): Promise; public reply( - options: string | MessagePayload | InteractionReplyOptions, + options: InteractionReplyOptions | MessagePayload | string, ): Promise> | undefined>; public update( options: InteractionUpdateOptions & { withResponse: true }, ): Promise>>; public update(options: InteractionUpdateOptions & { withResponse: false }): Promise; public update( - options: string | MessagePayload | InteractionUpdateOptions, + options: InteractionUpdateOptions | MessagePayload | string, ): Promise> | undefined>; public launchActivity( options: LaunchActivityOptions & { withResponse: true }, @@ -2231,23 +2681,23 @@ export class MessageComponentInteraction e ): Promise> | undefined>; public showModal( modal: + | APIModalInteractionResponseCallbackData | JSONEncodable - | ModalComponentData - | APIModalInteractionResponseCallbackData, + | ModalComponentData, options: ShowModalOptions & { withResponse: true }, ): Promise>>; public showModal( modal: + | APIModalInteractionResponseCallbackData | JSONEncodable - | ModalComponentData - | APIModalInteractionResponseCallbackData, + | ModalComponentData, options?: ShowModalOptions & { withResponse: false }, ): Promise; public showModal( modal: + | APIModalInteractionResponseCallbackData | JSONEncodable - | ModalComponentData - | APIModalInteractionResponseCallbackData, + | ModalComponentData, options?: ShowModalOptions, ): Promise> | undefined>; public awaitModalSubmit( @@ -2259,23 +2709,24 @@ export class MessageContextMenuCommandInteraction< Cached extends CacheType = CacheType, > extends ContextMenuCommandInteraction { public commandType: ApplicationCommandType.Message; + public options: Omit< CommandInteractionOptionResolver, + | 'getAttachment' + | 'getBoolean' + | 'getChannel' | 'getFocused' + | 'getInteger' | 'getMentionable' - | 'getRole' - | 'getUser' | 'getNumber' - | 'getAttachment' - | 'getInteger' + | 'getRole' | 'getString' - | 'getChannel' - | 'getBoolean' - | 'getSubcommandGroup' | 'getSubcommand' + | 'getSubcommandGroup' + | 'getUser' >; public get targetMessage(): NonNullable['message']>; - public inGuild(): this is MessageContextMenuCommandInteraction<'raw' | 'cached'>; + public inGuild(): this is MessageContextMenuCommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is MessageContextMenuCommandInteraction<'cached'>; public inRawGuild(): this is MessageContextMenuCommandInteraction<'raw'>; } @@ -2290,63 +2741,80 @@ export class MessageFlagsBitField extends BitField { export class MessageMentions { private constructor( message: Message, - users: readonly APIUser[] | ReadonlyCollection, - roles: readonly Snowflake[] | ReadonlyCollection, + users: ReadonlyCollection | readonly APIUser[], + roles: ReadonlyCollection | readonly Snowflake[], everyone: boolean, repliedUser?: APIUser | User, ); - private _channels: Collection | null; + private readonly _channels: Collection | null; + private readonly _content: string; - private _members: Collection | null; - private _parsedUsers: Collection | null; + + private readonly _members: Collection | null; + + private readonly _parsedUsers: Collection | null; public get channels(): Collection; public readonly client: Client; + public everyone: boolean; + public readonly guild: If; - public has(data: UserResolvable | RoleResolvable | ChannelResolvable, options?: MessageMentionsHasOptions): boolean; + + public has(data: ChannelResolvable | RoleResolvable | UserResolvable, options?: MessageMentionsHasOptions): boolean; public get members(): If>; public get parsedUsers(): Collection; public repliedUser: User | null; + public roles: Collection; + public users: Collection; + public crosspostedChannels: Collection; public toJSON(): unknown; - private static GlobalChannelsPattern: RegExp; - private static GlobalUsersPattern: RegExp; + private static readonly GlobalChannelsPattern: RegExp; + + private static readonly GlobalUsersPattern: RegExp; + public static ChannelsPattern: typeof FormattingPatterns.Channel; + public static EveryonePattern: RegExp; + public static RolesPattern: typeof FormattingPatterns.Role; + public static UsersPattern: typeof FormattingPatterns.User; } export type MessagePayloadOption = + | InteractionReplyOptions + | InteractionUpdateOptions | MessageCreateOptions | MessageEditOptions | WebhookMessageCreateOptions - | WebhookMessageEditOptions - | InteractionReplyOptions - | InteractionUpdateOptions; + | WebhookMessageEditOptions; export class MessagePayload { public constructor(target: MessageTarget, options: MessagePayloadOption); public body: RawMessagePayloadData | null; + public get isUser(): boolean; public get isWebhook(): boolean; public get isMessage(): boolean; public get isMessageManager(): boolean; public files: RawFile[] | null; + public options: MessagePayloadOption; + public target: MessageTarget; public static create( target: MessageTarget, - options: string | MessagePayloadOption, + options: MessagePayloadOption | string, extra?: MessagePayloadOption, ): MessagePayload; public static resolveFile( - fileLike: BufferResolvable | Stream | AttachmentPayload | JSONEncodable, + fileLike: AttachmentPayload | BufferResolvable | JSONEncodable | Stream, ): Promise; public makeContent(): string | undefined; @@ -2356,16 +2824,23 @@ export class MessagePayload { export class MessageReaction { private constructor(client: Client, data: RawMessageReactionData, message: Message); - private _emoji: GuildEmoji | ReactionEmoji | ApplicationEmoji; + private readonly _emoji: ApplicationEmoji | GuildEmoji | ReactionEmoji; public burstColors: string[] | null; + public readonly client: Client; + public count: number; + public countDetails: ReactionCountDetailsData; - public get emoji(): GuildEmoji | ReactionEmoji | ApplicationEmoji; + + public get emoji(): ApplicationEmoji | GuildEmoji | ReactionEmoji; public me: boolean; + public meBurst: boolean; + public message: Message | PartialMessage; + public get partial(): false; public users: ReactionUserManager; public react(): Promise; @@ -2376,17 +2851,17 @@ export class MessageReaction { } export interface MessageReactionEventDetails { - type: ReactionType; burst: boolean; + type: ReactionType; } export interface ModalComponentData { - customId: string; - title: string; components: readonly ( - | JSONEncodable> | ActionRowData + | JSONEncodable> )[]; + customId: string; + title: string; } export interface BaseModalData { @@ -2400,56 +2875,65 @@ export interface TextInputModalData extends BaseModalData { } export interface ActionRowModalData { - type: ComponentType.ActionRow; components: readonly TextInputModalData[]; + type: ComponentType.ActionRow; } export class ModalSubmitFields { private constructor(components: readonly (readonly ModalActionRowComponent[])[]); public components: ActionRowModalData[]; + public fields: Collection; - public getField(customId: string, type: Type): { type: Type } & TextInputModalData; + public getField(customId: string, type: Type): TextInputModalData & { type: Type }; public getField(customId: string, type?: ComponentType): TextInputModalData; public getTextInputValue(customId: string): string; } export interface ModalMessageModalSubmitInteraction extends ModalSubmitInteraction { - message: Message>; channelId: Snowflake; + inCachedGuild(): this is ModalMessageModalSubmitInteraction<'cached'>; + inGuild(): this is ModalMessageModalSubmitInteraction<'cached' | 'raw'>; + inRawGuild(): this is ModalMessageModalSubmitInteraction<'raw'>; + message: Message>; update( options: InteractionUpdateOptions & { withResponse: true }, ): Promise>>; - update(options: InteractionUpdateOptions & { withResponse: false }): Promise; update( - options: string | MessagePayload | InteractionUpdateOptions, + options: InteractionUpdateOptions | MessagePayload | string, ): Promise> | undefined>; - inGuild(): this is ModalMessageModalSubmitInteraction<'raw' | 'cached'>; - inCachedGuild(): this is ModalMessageModalSubmitInteraction<'cached'>; - inRawGuild(): this is ModalMessageModalSubmitInteraction<'raw'>; + update(options: InteractionUpdateOptions & { withResponse: false }): Promise; } export class ModalSubmitInteraction extends BaseInteraction { private constructor(client: Client, data: APIModalSubmitInteraction); public type: InteractionType.ModalSubmit; + public readonly customId: string; + public readonly components: ActionRowModalData[]; + public readonly fields: ModalSubmitFields; + public deferred: boolean; + public ephemeral: boolean | null; + public message: Message> | null; + public replied: boolean; + public readonly webhook: InteractionWebhook; public reply( options: InteractionReplyOptions & { withResponse: true }, ): Promise>>; public reply(options: InteractionReplyOptions & { withResponse: false }): Promise; public reply( - options: string | MessagePayload | InteractionReplyOptions, + options: InteractionReplyOptions | MessagePayload | string, ): Promise> | undefined>; public deleteReply(message?: MessageResolvable | '@original'): Promise; public editReply( - options: string | MessagePayload | InteractionEditReplyOptions, + options: InteractionEditReplyOptions | MessagePayload | string, ): Promise>>; public deferReply( options: InteractionDeferReplyOptions & { withResponse: true }, @@ -2459,7 +2943,7 @@ export class ModalSubmitInteraction extend options?: InteractionDeferReplyOptions, ): Promise> | undefined>; public fetchReply(message?: Snowflake | '@original'): Promise>>; - public followUp(options: string | MessagePayload | InteractionReplyOptions): Promise>>; + public followUp(options: InteractionReplyOptions | MessagePayload | string): Promise>>; public deferUpdate( options: InteractionDeferUpdateOptions & { withResponse: true }, ): Promise>>; @@ -2474,7 +2958,7 @@ export class ModalSubmitInteraction extend public launchActivity( options?: LaunchActivityOptions, ): Promise> | undefined>; - public inGuild(): this is ModalSubmitInteraction<'raw' | 'cached'>; + public inGuild(): this is ModalSubmitInteraction<'cached' | 'raw'>; public inCachedGuild(): this is ModalSubmitInteraction<'cached'>; public inRawGuild(): this is ModalSubmitInteraction<'raw'>; public isFromMessage(): this is ModalMessageModalSubmitInteraction; @@ -2482,6 +2966,7 @@ export class ModalSubmitInteraction extend export class AnnouncementChannel extends BaseGuildTextChannel { public threads: GuildTextThreadManager; + public type: ChannelType.GuildAnnouncement; public addFollower(channel: TextChannelResolvable, reason?: string): Promise; } @@ -2491,29 +2976,35 @@ export type AnnouncementChannelResolvable = AnnouncementChannel | Snowflake; export class OAuth2Guild extends BaseGuild { private constructor(client: Client, data: RawOAuth2GuildData); public owner: boolean; + public permissions: Readonly; } export interface PartialGroupDMChannel extends Omit< TextBasedChannelFields, + | 'awaitMessages' | 'bulkDelete' - | 'send' - | 'sendTyping' | 'createMessageCollector' - | 'awaitMessages' - | 'fetchWebhooks' | 'createWebhook' - | 'setRateLimitPerUser' + | 'fetchWebhooks' + | 'send' + | 'sendTyping' | 'setNSFW' + | 'setRateLimitPerUser' > {} export class PartialGroupDMChannel extends BaseChannel { private constructor(client: Client, data: RawPartialGroupDMChannelData); public type: ChannelType.GroupDM; + public flags: null; + public name: string | null; + public icon: string | null; + public recipients: PartialRecipient[]; + public ownerId: Snowflake | null; public iconURL(options?: ImageURLOptions): string | null; public fetchOwner(options?: BaseFetchOptions): Promise; @@ -2526,10 +3017,10 @@ export interface GuildForumTagEmoji { } export interface GuildForumTag { + emoji: GuildForumTagEmoji | null; id: Snowflake; - name: string; moderated: boolean; - emoji: GuildForumTagEmoji | null; + name: string; } export interface GuildForumTagData extends Partial { @@ -2544,27 +3035,36 @@ export interface DefaultReactionEmoji { export interface ThreadOnlyChannel extends Omit< TextBasedChannelFields, - | 'send' - | 'lastMessage' - | 'lastPinAt' + | 'awaitMessageComponent' + | 'awaitMessages' | 'bulkDelete' - | 'sendTyping' | 'createMessageCollector' - | 'awaitMessages' | 'createMessageComponentCollector' - | 'awaitMessageComponent' + | 'lastMessage' + | 'lastPinAt' | 'messages' + | 'send' + | 'sendTyping' > {} export abstract class ThreadOnlyChannel extends GuildChannel { public type: ChannelType.GuildForum | ChannelType.GuildMedia; + public threads: GuildForumThreadManager; + public availableTags: GuildForumTag[]; + public defaultReactionEmoji: DefaultReactionEmoji | null; + public defaultThreadRateLimitPerUser: number | null; + public rateLimitPerUser: number | null; + public defaultAutoArchiveDuration: ThreadAutoArchiveDuration | null; + public nsfw: boolean; + public topic: string | null; + public defaultSortOrder: SortOrderType | null; public setAvailableTags(tags: readonly GuildForumTagData[], reason?: string): Promise; public setDefaultReactionEmoji(emojiId: DefaultReactionEmoji | null, reason?: string): Promise; @@ -2581,6 +3081,7 @@ export abstract class ThreadOnlyChannel extends GuildChannel { export class ForumChannel extends ThreadOnlyChannel { public type: ChannelType.GuildForum; + public defaultForumLayout: ForumLayoutType; public setDefaultForumLayout(defaultForumLayout: ForumLayoutType, reason?: string): Promise; } @@ -2592,9 +3093,13 @@ export class MediaChannel extends ThreadOnlyChannel { export class PermissionOverwrites extends Base { private constructor(client: Client, data: RawPermissionOverwriteData, channel: NonThreadGuildBasedChannel); public allow: Readonly; + public readonly channel: NonThreadGuildBasedChannel; + public deny: Readonly; + public id: Snowflake; + public type: OverwriteType; public edit(options: PermissionOverwriteOptions, reason?: string): Promise; public delete(reason?: string): Promise; @@ -2616,8 +3121,11 @@ export class PermissionsBitField extends BitField { public toArray(): PermissionsString[]; public static All: bigint; + public static Default: bigint; + public static StageModerator: bigint; + public static Flags: typeof PermissionFlagsBits; public static resolve(permission?: PermissionResolvable): bigint; } @@ -2625,10 +3133,14 @@ export class PermissionsBitField extends BitField { export class Presence extends Base { protected constructor(client: Client, data?: RawPresenceData); public activities: Activity[]; + public clientStatus: ClientPresenceStatusData | null; + public guild: Guild | null; + public get member(): GuildMember | null; public status: PresenceStatus; + public get user(): User | null; public userId: Snowflake; public equals(presence: Presence): boolean; @@ -2647,15 +3159,24 @@ export class PollAnswerVoterManager extends CachedManager, data: APIPoll, message: Message, channel: TextBasedChannel); public readonly channel: TextBasedChannel; + public channelId: Snowflake; + public readonly message: Message; + public messageId: Snowflake; + public question: PollQuestionMedia; - public answers: Collection; + + public answers: Collection; + public expiresTimestamp: number | null; + public get expiresAt(): Date | null; public allowMultiselect: boolean; + public layoutType: PollLayoutType; + public resultsFinalized: boolean; public get partial(): false; public fetch(): Promise; @@ -2669,15 +3190,22 @@ export interface BaseFetchPollAnswerVotersOptions { export class PollAnswer extends Base { private constructor(client: Client, data: APIPollAnswer & { count?: number }, poll: Poll); - private _emoji: APIPartialEmoji | null; - public readonly poll: Poll | PartialPoll; + private readonly _emoji: APIPartialEmoji | null; + + public readonly poll: PartialPoll | Poll; + public id: number; + public text: string | null; + public voteCount: number; + public voters: PollAnswerVoterManager; - public get emoji(): GuildEmoji | Emoji | null; + public get emoji(): Emoji | GuildEmoji | null; public get partial(): false; - /** @deprecated Use {@link PollAnswerVoterManager.fetch} instead */ + /** + * @deprecated Use {@link PollAnswerVoterManager.fetch} instead + */ public fetchVoters(options?: BaseFetchPollAnswerVotersOptions): Promise>; } @@ -2697,8 +3225,11 @@ export class ReactionCollector extends Collector< private _handleMessageDeletion(message: Message): void; public message: Message; + public options: ReactionCollectorOptions; + public total: number; + public users: Collection; public static key(reaction: MessageReaction): Snowflake | string; @@ -2717,9 +3248,13 @@ export class ReactionEmoji extends Emoji { export class RichPresenceAssets { private constructor(activity: Activity, assets: RawRichPresenceAssets); public readonly activity: Activity; + public largeImage: Snowflake | null; + public largeText: string | null; + public smallImage: Snowflake | null; + public smallText: string | null; public largeImageURL(options?: ImageURLOptions): string | null; public smallImageURL(options?: ImageURLOptions): string | null; @@ -2728,24 +3263,36 @@ export class RichPresenceAssets { export class Role extends Base { private constructor(client: Client, data: RawRoleData, guild: Guild); public color: number; + public get createdAt(): Date; public get createdTimestamp(): number; public get editable(): boolean; public flags: RoleFlagsBitField; + public guild: Guild; + public get hexColor(): HexColorString; public hoist: boolean; + public id: Snowflake; + public managed: boolean; + public get members(): Collection; public mentionable: boolean; + public name: string; + public permissions: Readonly; + public get position(): number; public rawPosition: number; + public tags: RoleTagData | null; + public comparePositionTo(role: RoleResolvable): number; public icon: string | null; + public unicodeEmoji: string | null; public delete(reason?: string): Promise; public edit(options: RoleEditOptions): Promise; @@ -2760,7 +3307,7 @@ export class Role extends Base { public setMentionable(mentionable?: boolean, reason?: string): Promise; public setName(name: string, reason?: string): Promise; public setPermissions(permissions: PermissionResolvable, reason?: string): Promise; - public setIcon(icon: BufferResolvable | Base64Resolvable | EmojiResolvable | null, reason?: string): Promise; + public setIcon(icon: Base64Resolvable | BufferResolvable | EmojiResolvable | null, reason?: string): Promise; public setPosition(position: number, options?: SetRolePositionOptions): Promise; public setUnicodeEmoji(unicodeEmoji: string | null, reason?: string): Promise; public toJSON(): unknown; @@ -2782,12 +3329,13 @@ export class StringSelectMenuInteraction< Cached, StringSelectMenuComponent, APIStringSelectComponent, - StringSelectMenuComponent | APIStringSelectComponent, - StringSelectMenuComponent | APIStringSelectComponent + APIStringSelectComponent | StringSelectMenuComponent, + APIStringSelectComponent | StringSelectMenuComponent >; public componentType: ComponentType.StringSelect; + public values: string[]; - public inGuild(): this is StringSelectMenuInteraction<'raw' | 'cached'>; + public inGuild(): this is StringSelectMenuInteraction<'cached' | 'raw'>; public inCachedGuild(): this is StringSelectMenuInteraction<'cached'>; public inRawGuild(): this is StringSelectMenuInteraction<'raw'>; } @@ -2800,17 +3348,20 @@ export class UserSelectMenuInteraction< Cached, UserSelectMenuComponent, APIUserSelectComponent, - UserSelectMenuComponent | APIUserSelectComponent, - UserSelectMenuComponent | APIUserSelectComponent + APIUserSelectComponent | UserSelectMenuComponent, + APIUserSelectComponent | UserSelectMenuComponent >; public componentType: ComponentType.UserSelect; + public values: Snowflake[]; + public users: Collection; + public members: Collection< Snowflake, - CacheTypeReducer + CacheTypeReducer >; - public inGuild(): this is UserSelectMenuInteraction<'raw' | 'cached'>; + public inGuild(): this is UserSelectMenuInteraction<'cached' | 'raw'>; public inCachedGuild(): this is UserSelectMenuInteraction<'cached'>; public inRawGuild(): this is UserSelectMenuInteraction<'raw'>; } @@ -2823,13 +3374,15 @@ export class RoleSelectMenuInteraction< Cached, RoleSelectMenuComponent, APIRoleSelectComponent, - RoleSelectMenuComponent | APIRoleSelectComponent, - RoleSelectMenuComponent | APIRoleSelectComponent + APIRoleSelectComponent | RoleSelectMenuComponent, + APIRoleSelectComponent | RoleSelectMenuComponent >; public componentType: ComponentType.RoleSelect; + public values: Snowflake[]; - public roles: Collection>; - public inGuild(): this is RoleSelectMenuInteraction<'raw' | 'cached'>; + + public roles: Collection>; + public inGuild(): this is RoleSelectMenuInteraction<'cached' | 'raw'>; public inCachedGuild(): this is RoleSelectMenuInteraction<'cached'>; public inRawGuild(): this is RoleSelectMenuInteraction<'raw'>; } @@ -2842,18 +3395,22 @@ export class MentionableSelectMenuInteraction< Cached, MentionableSelectMenuComponent, APIMentionableSelectComponent, - MentionableSelectMenuComponent | APIMentionableSelectComponent, - MentionableSelectMenuComponent | APIMentionableSelectComponent + APIMentionableSelectComponent | MentionableSelectMenuComponent, + APIMentionableSelectComponent | MentionableSelectMenuComponent >; public componentType: ComponentType.MentionableSelect; + public values: Snowflake[]; + public users: Collection; + public members: Collection< Snowflake, - CacheTypeReducer + CacheTypeReducer >; - public roles: Collection>; - public inGuild(): this is MentionableSelectMenuInteraction<'raw' | 'cached'>; + + public roles: Collection>; + public inGuild(): this is MentionableSelectMenuInteraction<'cached' | 'raw'>; public inCachedGuild(): this is MentionableSelectMenuInteraction<'cached'>; public inRawGuild(): this is MentionableSelectMenuInteraction<'raw'>; } @@ -2866,26 +3423,28 @@ export class ChannelSelectMenuInteraction< Cached, ChannelSelectMenuComponent, APIChannelSelectComponent, - ChannelSelectMenuComponent | APIChannelSelectComponent, - ChannelSelectMenuComponent | APIChannelSelectComponent + APIChannelSelectComponent | ChannelSelectMenuComponent, + APIChannelSelectComponent | ChannelSelectMenuComponent >; public componentType: ComponentType.ChannelSelect; + public values: Snowflake[]; + public channels: Collection< Snowflake, - CacheTypeReducer + CacheTypeReducer >; - public inGuild(): this is ChannelSelectMenuInteraction<'raw' | 'cached'>; + public inGuild(): this is ChannelSelectMenuInteraction<'cached' | 'raw'>; public inCachedGuild(): this is ChannelSelectMenuInteraction<'cached'>; public inRawGuild(): this is ChannelSelectMenuInteraction<'raw'>; } export type SelectMenuInteraction = - | StringSelectMenuInteraction - | UserSelectMenuInteraction - | RoleSelectMenuInteraction + | ChannelSelectMenuInteraction | MentionableSelectMenuInteraction - | ChannelSelectMenuInteraction; + | RoleSelectMenuInteraction + | StringSelectMenuInteraction + | UserSelectMenuInteraction; export type SelectMenuType = APISelectMenuComponent['type']; @@ -2902,22 +3461,32 @@ export interface ShardEventTypes { export class Shard extends AsyncEventEmitter { private constructor(manager: ShardingManager, id: number); - private _evals: Map>; - private _exitListener: (...args: any[]) => void; - private _fetches: Map>; + private readonly _evals: Map>; + + private readonly _exitListener: (...args: any[]) => void; + + private readonly _fetches: Map>; private _handleExit(respawn?: boolean, timeout?: number): void; private _handleMessage(message: unknown): void; - private incrementMaxListeners(emitter: Worker | ChildProcess): void; - private decrementMaxListeners(emitter: Worker | ChildProcess): void; + private incrementMaxListeners(emitter: ChildProcess | Worker): void; + private decrementMaxListeners(emitter: ChildProcess | Worker): void; public args: string[]; + public execArgv: string[]; + public env: unknown; + public id: number; + public manager: ShardingManager; + public process: ChildProcess | null; + public ready: boolean; + public silent: boolean; + public worker: Worker | null; public eval(script: string): Promise; public eval(fn: (client: Client) => Result): Promise; @@ -2936,11 +3505,13 @@ export class ShardClientUtil { private constructor(client: Client, mode: ShardingManagerMode); private _handleMessage(message: unknown): void; private _respond(type: string, message: unknown): void; - private incrementMaxListeners(emitter: Worker | ChildProcess): void; - private decrementMaxListeners(emitter: Worker | ChildProcess): void; + private incrementMaxListeners(emitter: ChildProcess | Worker): void; + private decrementMaxListeners(emitter: ChildProcess | Worker): void; public client: Client; + public mode: ShardingManagerMode; + public parentPort: MessagePort | null; public broadcastEval(fn: (client: Client) => Awaitable): Promise[]>; public broadcastEval( @@ -2974,12 +3545,19 @@ export class ShardingManager extends AsyncEventEmitter; public file: string; + public respawn: boolean; + public silent: boolean; + public shardArgs: string[]; + public shards: Collection; + public token: string | null; + public totalShards: number | 'auto'; + public shardList: number[] | 'auto'; public broadcast(message: unknown): Promise; public broadcastEval(fn: (client: Client) => Awaitable): Promise[]>; @@ -3009,17 +3587,22 @@ export interface FetchRecommendedShardCountOptions { export { DiscordSnowflake as SnowflakeUtil, - SnowflakeGenerateOptions, - DeconstructedSnowflake, + type SnowflakeGenerateOptions, + type DeconstructedSnowflake, } from '@sapphire/snowflake'; export class SKU extends Base { private constructor(client: Client, data: APISKU); public id: Snowflake; + public type: SKUType; + public applicationId: Snowflake; + public name: string; + public slug: string; + public flags: Readonly; } @@ -3033,14 +3616,23 @@ export class SKUFlagsBitField extends BitField { export class Subscription extends Base { private constructor(client: Client, data: APISubscription); public id: Snowflake; + public userId: Snowflake; + public skuIds: Snowflake[]; + public entitlementIds: Snowflake[]; + public renewalSkuIds: Snowflake[] | null; + public currentPeriodStartTimestamp: number; + public currentPeriodEndTimestamp: number; + public status: SubscriptionStatus; + public canceledTimestamp: number | null; + public country: string | null; public get canceledAt(): Date | null; public get currentPeriodStartAt(): Date; @@ -3050,6 +3642,7 @@ export class Subscription extends Base { export class StageChannel extends BaseGuildVoiceChannel { public get stageInstance(): StageInstance | null; public topic: string | null; + public type: ChannelType.GuildStageVoice; public createStageInstance(options: StageInstanceCreateOptions): Promise; public setTopic(topic: string): Promise; @@ -3057,8 +3650,11 @@ export class StageChannel extends BaseGuildVoiceChannel { export class DirectoryChannel extends BaseChannel { public flags: Readonly; + public guild: InviteGuild; + public guildId: Snowflake; + public name: string; public toString(): ChannelMention; } @@ -3066,10 +3662,15 @@ export class DirectoryChannel extends BaseChannel { export class StageInstance extends Base { private constructor(client: Client, data: RawStageInstanceData, channel: StageChannel); public id: Snowflake; + public guildId: Snowflake; + public channelId: Snowflake; + public topic: string; + public privacyLevel: StageInstancePrivacyLevel; + public guildScheduledEventId?: Snowflake; public get channel(): StageChannel | null; public get guild(): Guild | null; @@ -3086,17 +3687,27 @@ export class Sticker extends Base { public get createdTimestamp(): number; public get createdAt(): Date; public available: boolean | null; + public description: string | null; + public format: StickerFormatType; + public get guild(): Guild | null; public guildId: Snowflake | null; + public id: Snowflake; + public name: string; + public packId: Snowflake | null; + public get partial(): boolean; public sortValue: number | null; + public tags: string | null; + public type: StickerType | null; + public user: User | null; public get url(): string; public fetch(): Promise; @@ -3112,12 +3723,18 @@ export class StickerPack extends Base { public get createdTimestamp(): number; public get createdAt(): Date; public bannerId: Snowflake | null; + public get coverSticker(): Sticker | null; public coverStickerId: Snowflake | null; + public description: string; + public id: Snowflake; + public name: string; + public skuId: Snowflake; + public stickers: Collection; public bannerURL(options?: ImageURLOptions): string | null; } @@ -3125,7 +3742,9 @@ export class StickerPack extends Base { export class Sweepers { public constructor(client: Client, options: SweeperOptions); public readonly client: Client; + public intervals: Record; + public options: SweeperOptions; public sweepApplicationCommands( @@ -3205,9 +3824,13 @@ export class SystemChannelFlagsBitField extends BitField, data: RawTeamData); public id: Snowflake; + public name: string; + public icon: string | null; + public ownerId: Snowflake | null; + public members: Collection; public get owner(): TeamMember | null; public get createdAt(): Date; @@ -3221,9 +3844,12 @@ export class Team extends Base { export class TeamMember extends Base { private constructor(team: Team, data: RawTeamMemberData); public team: Team; + public get id(): Snowflake; public membershipState: TeamMemberMembershipState; + public user: User; + public role: TeamMemberRole; public toString(): UserMention; @@ -3231,58 +3857,77 @@ export class TeamMember extends Base { export class TextChannel extends BaseGuildTextChannel { public rateLimitPerUser: number; + public threads: GuildTextThreadManager; + public type: ChannelType.GuildText; } export type ForumThreadChannel = PublicThreadChannel; -export type TextThreadChannel = PublicThreadChannel | PrivateThreadChannel; -export type AnyThreadChannel = TextThreadChannel | ForumThreadChannel; +export type TextThreadChannel = PrivateThreadChannel | PublicThreadChannel; +export type AnyThreadChannel = ForumThreadChannel | TextThreadChannel; export interface PublicThreadChannel extends ThreadChannel { - type: ChannelType.PublicThread | ChannelType.AnnouncementThread; + type: ChannelType.AnnouncementThread | ChannelType.PublicThread; } export interface PrivateThreadChannel extends ThreadChannel { - get createdTimestamp(): number; get createdAt(): Date; + get createdTimestamp(): number; type: ChannelType.PrivateThread; } -// tslint:disable-next-line no-empty-interface export interface ThreadChannel - extends Omit, 'fetchWebhooks' | 'createWebhook' | 'setNSFW'> {} + extends Omit, 'createWebhook' | 'fetchWebhooks' | 'setNSFW'> {} export class ThreadChannel extends BaseChannel { private constructor(guild: Guild, data?: RawThreadChannelData, client?: Client); public archived: boolean | null; + public get archivedAt(): Date | null; public archiveTimestamp: number | null; + public get createdAt(): Date | null; - private _createdTimestamp: number | null; + private readonly _createdTimestamp: number | null; + public get createdTimestamp(): number | null; public autoArchiveDuration: ThreadAutoArchiveDuration | null; + public get editable(): boolean; public flags: Readonly; + public guild: Guild; + public guildId: Snowflake; + public get guildMembers(): Collection; public invitable: boolean | null; + public get joinable(): boolean; public get joined(): boolean; public locked: boolean | null; + public get manageable(): boolean; public get viewable(): boolean; public get sendable(): boolean; public memberCount: number | null; + public messageCount: number | null; + public appliedTags: Snowflake[]; + public totalMessageSent: number | null; + public members: ThreadMemberManager; + public name: string; + public ownerId: Snowflake; - public get parent(): If | null; + + public get parent(): If | null; public parentId: Snowflake | null; + public rateLimitPerUser: number | null; + public type: ThreadChannelType; public get unarchivable(): boolean; public delete(reason?: string): Promise; @@ -3291,7 +3936,7 @@ export class ThreadChannel extends BaseCha public leave(): Promise; public permissionsFor(memberOrRole: GuildMember | Role, checkAdmin?: boolean): Readonly; public permissionsFor( - memberOrRole: UserResolvable | RoleResolvable, + memberOrRole: RoleResolvable | UserResolvable, checkAdmin?: boolean, ): Readonly | null; public fetchOwner(options?: FetchThreadOwnerOptions): Promise; @@ -3311,11 +3956,15 @@ export class ThreadChannel extends BaseCha export class ThreadMember extends Base { private constructor(thread: ThreadChannel, data: RawThreadMemberData, extra?: unknown); public flags: ThreadMemberFlagsBitField; - private member: If; + + private readonly member: If; + public get guildMember(): HasMemberData extends true ? GuildMember : GuildMember | null; public id: Snowflake; + public get joinedAt(): Date | null; public joinedTimestamp: number | null; + public get manageable(): boolean; public thread: AnyThreadChannel; public get user(): User | null; @@ -3333,13 +3982,15 @@ export class ThreadMemberFlagsBitField extends BitField export class Typing extends Base { private constructor(channel: TextBasedChannel, user: PartialUser, data?: RawTypingData); public channel: TextBasedChannel; - public user: User | PartialUser; + + public user: PartialUser | User; + public startedTimestamp: number; public get startedAt(): Date; public get guild(): Guild | null; public get member(): GuildMember | null; public inGuild(): this is this & { - channel: TextChannel | AnnouncementChannel | ThreadChannel; + channel: AnnouncementChannel | TextChannel | ThreadChannel; get guild(): Guild; }; } @@ -3349,29 +4000,38 @@ export interface AvatarDecorationData { skuId: Snowflake; } -// tslint:disable-next-line no-empty-interface export interface User extends PartialTextBasedChannelFields {} export class User extends Base { protected constructor(client: Client, data: RawUserData); private _equals(user: APIUser): boolean; public accentColor: number | null | undefined; + public avatar: string | null; + public avatarDecorationData: AvatarDecorationData | null; + public banner: string | null | undefined; + public bot: boolean; + public get createdAt(): Date; public get createdTimestamp(): number; public discriminator: string; + public get displayName(): string; public get defaultAvatarURL(): string; public get dmChannel(): DMChannel | null; public flags: Readonly | null; + public globalName: string | null; + public get hexAccentColor(): HexColorString | null | undefined; public id: Snowflake; + public get partial(): false; public system: boolean; + public get tag(): string; public username: string; public avatarURL(options?: ImageURLOptions): string | null; @@ -3389,24 +4049,25 @@ export class UserContextMenuCommandInteraction< Cached extends CacheType = CacheType, > extends ContextMenuCommandInteraction { public commandType: ApplicationCommandType.User; + public options: Omit< CommandInteractionOptionResolver, - | 'getMessage' + | 'getAttachment' + | 'getBoolean' + | 'getChannel' | 'getFocused' + | 'getInteger' | 'getMentionable' - | 'getRole' + | 'getMessage' | 'getNumber' - | 'getAttachment' - | 'getInteger' + | 'getRole' | 'getString' - | 'getChannel' - | 'getBoolean' - | 'getSubcommandGroup' | 'getSubcommand' + | 'getSubcommandGroup' >; public get targetUser(): User; public get targetMember(): CacheTypeReducer | null; - public inGuild(): this is UserContextMenuCommandInteraction<'raw' | 'cached'>; + public inGuild(): this is UserContextMenuCommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is UserContextMenuCommandInteraction<'cached'>; public inRawGuild(): this is UserContextMenuCommandInteraction<'raw'>; } @@ -3418,36 +4079,42 @@ export class UserFlagsBitField extends BitField { public static resolve(bit?: BitFieldResolvable): number; } -/** @internal */ +/** + * @internal + */ export function basename(path: string, ext?: string): string; export function cleanContent(str: string, channel: TextBasedChannel): string; -export function discordSort( +export function discordSort( collection: ReadonlyCollection, ): Collection; export function cleanCodeBlockContent(text: string): string; export function fetchRecommendedShardCount(token: string, options?: FetchRecommendedShardCountOptions): Promise; export function flatten(obj: unknown, ...props: Record[]): unknown; -/** @internal */ +/** + * @internal + */ export function makeError(obj: MakeErrorOptions): Error; -/** @internal */ +/** + * @internal + */ export function makePlainError(err: Error): MakeErrorOptions; -/** @internal */ -export function moveElementInArray( - // eslint-disable-next-line no-restricted-syntax - array: unknown[], - element: unknown, - newIndex: number, - offset?: boolean, -): number; +/** + * @internal + */ +export function moveElementInArray(array: unknown[], element: unknown, newIndex: number, offset?: boolean): number; export function parseEmoji(text: string): PartialEmoji | null; export function resolveColor(color: ColorResolvable): number; export function resolvePartialEmoji(emoji: Snowflake): PartialEmojiOnlyId; export function resolvePartialEmoji(emoji: Emoji | EmojiIdentifierResolvable): PartialEmoji | null; -/** @internal */ +/** + * @internal + */ export function resolveGuildEmoji(client: Client, emojiId: Snowflake): GuildEmoji | null; export function verifyString(data: string, error?: typeof Error, errorMessage?: string, allowEmpty?: boolean): string; -/** @internal */ +/** + * @internal + */ export function setPosition( item: Item, position: number, @@ -3458,19 +4125,25 @@ export function setPosition( reason?: string, ): Promise<{ id: Snowflake; position: number }[]>; export function parseWebhookURL(url: string): WebhookClientDataIdWithToken | null; -/** @internal */ +/** + * @internal + */ export function transformResolved( supportingData: SupportingInteractionResolvedData, data?: Extract['resolved'], ): CommandInteractionResolvedData; export function resolveSKUId(resolvable: SKUResolvable): Snowflake | null; -/** @internal */ +/** + * @internal + */ export interface CreateChannelOptions { allowFromUnknownGuild?: boolean; } -/** @internal */ +/** + * @internal + */ export function createChannel( client: Client, data: APIChannel, @@ -3479,30 +4152,37 @@ export function createChannel( ): Channel; export type ComponentData = + | ActionRowData | MessageActionRowComponentData - | ModalActionRowComponentData - | ActionRowData; + | ModalActionRowComponentData; export interface SendSoundboardSoundOptions { - soundId: Snowflake; guildId?: Snowflake; + soundId: Snowflake; } export class VoiceChannel extends BaseGuildVoiceChannel { public get speakable(): boolean; public type: ChannelType.GuildVoice; - public sendSoundboardSound(sound: SoundboardSound | SendSoundboardSoundOptions): Promise; + public sendSoundboardSound(sound: SendSoundboardSoundOptions | SoundboardSound): Promise; } export class VoiceChannelEffect { private constructor(data: GatewayVoiceChannelEffectSendDispatchData, guild: Guild); public guild: Guild; + public channelId: Snowflake; + public userId: Snowflake; + public emoji: Emoji | null; + public animationType: VoiceChannelEffectSendAnimationType | null; + public animationId: number | null; + public soundId: Snowflake | number | null; + public soundVolume: number | null; public get channel(): VoiceChannel | null; public get soundboardSound(): GuildSoundboardSound | null; @@ -3511,9 +4191,13 @@ export class VoiceChannelEffect { export class VoiceRegion { private constructor(data: RawVoiceRegionData); public custom: boolean; + public deprecated: boolean; + public id: string; + public name: string; + public optimal: boolean; public toJSON(): unknown; } @@ -3522,19 +4206,30 @@ export class VoiceState extends Base { private constructor(guild: Guild, data: RawVoiceStateData); public get channel(): VoiceBasedChannel | null; public channelId: Snowflake | null; + public get deaf(): boolean | null; public guild: Guild; + public id: Snowflake; + public get member(): GuildMember | null; public get mute(): boolean | null; public selfDeaf: boolean | null; + public selfMute: boolean | null; + public serverDeaf: boolean | null; + public serverMute: boolean | null; + public sessionId: string | null; + public streaming: boolean | null; + public selfVideo: boolean | null; + public suppress: boolean | null; + public requestToSpeakTimestamp: number | null; public setDeaf(deaf?: boolean, reason?: string): Promise; @@ -3547,36 +4242,45 @@ export class VoiceState extends Base { public fetch(force?: boolean): Promise; } -// tslint:disable-next-line no-empty-interface export interface Webhook extends WebhookFields {} export class Webhook { private constructor(client: Client, data?: RawWebhookData); public avatar: string | null; + public avatarURL(options?: ImageURLOptions): string | null; public channelId: Snowflake; + public readonly client: Client; + public guildId: Snowflake; + public name: string; - public owner: Type extends WebhookType.Incoming ? User | APIUser | null : User | APIUser; - public sourceGuild: Type extends WebhookType.ChannelFollower ? Guild | APIPartialGuild : null; + + public owner: Type extends WebhookType.Incoming ? APIUser | User | null : APIUser | User; + + public sourceGuild: Type extends WebhookType.ChannelFollower ? APIPartialGuild | Guild : null; + public sourceChannel: Type extends WebhookType.ChannelFollower ? AnnouncementChannel | APIPartialChannel : null; + public token: Type extends WebhookType.Incoming ? string : Type extends WebhookType.ChannelFollower ? null : string | null; + public type: Type; + public applicationId: Type extends WebhookType.Application ? Snowflake : null; public get channel(): - | TextChannel - | VoiceChannel | AnnouncementChannel - | StageChannel | ForumChannel | MediaChannel + | StageChannel + | TextChannel + | VoiceChannel | null; public isUserCreated(): this is Webhook & { - owner: User | APIUser; + owner: APIUser | User; }; public isApplicationCreated(): this is Webhook; public isIncoming(): this is Webhook; @@ -3584,25 +4288,26 @@ export class Webhook { public editMessage( message: MessageResolvable, - options: string | MessagePayload | WebhookMessageEditOptions, + options: MessagePayload | WebhookMessageEditOptions | string, ): Promise; public fetchMessage(message: Snowflake, options?: WebhookFetchMessageOptions): Promise; - public send(options: string | MessagePayload | WebhookMessageCreateOptions): Promise; + public send(options: MessagePayload | WebhookMessageCreateOptions | string): Promise; } -// tslint:disable-next-line no-empty-interface export interface WebhookClient extends WebhookFields, BaseClient<{}> {} export class WebhookClient extends BaseClient<{}> { public constructor(data: WebhookClientData, options?: WebhookClientOptions); public readonly client: this; + public options: WebhookClientOptions; + public token: string; public editMessage( message: MessageResolvable, - options: string | MessagePayload | WebhookMessageEditOptions, + options: MessagePayload | WebhookMessageEditOptions | string, ): Promise; public fetchMessage(message: Snowflake, options?: WebhookFetchMessageOptions): Promise; - public send(options: string | MessagePayload | WebhookMessageCreateOptions): Promise; + public send(options: MessagePayload | WebhookMessageCreateOptions | string): Promise; } export class Widget extends Base { @@ -3611,40 +4316,63 @@ export class Widget extends Base { public fetch(): Promise; public imageURL(style?: GuildWidgetStyle): string; public id: Snowflake; + public name: string; + public instantInvite?: string; + public channels: Collection; + public members: Collection; + public presenceCount: number; } export class WidgetMember extends Base { private constructor(client: Client, data: RawWidgetMemberData); public id: string; + public username: string; + public discriminator: string; + public avatar: string | null; + public status: PresenceStatus; + public deaf: boolean | null; + public mute: boolean | null; + public selfDeaf: boolean | null; + public selfMute: boolean | null; + public suppress: boolean | null; + public channelId: Snowflake | null; + public avatarURL: string; + public activity: WidgetActivity | null; } -export type SoundboardSoundResolvable = SoundboardSound | Snowflake | string; +export type SoundboardSoundResolvable = Snowflake | SoundboardSound | string; export class SoundboardSound extends Base { private constructor(client: Client, data: APISoundboardSound); public name: string; + public soundId: Snowflake | string; + public volume: number; - private _emoji: Omit | null; + + private readonly _emoji: Omit | null; + public guildId: Snowflake | null; + public available: boolean; + public user: User | null; public get createdAt(): Date; public get createdTimestamp(): number; @@ -3653,7 +4381,7 @@ export class SoundboardSound extends Base { public get url(): string; public edit(options?: GuildSoundboardSoundEditOptions): Promise; public delete(reason?: string): Promise; - public equals(other: SoundboardSound | APISoundboardSound): boolean; + public equals(other: APISoundboardSound | SoundboardSound): boolean; } export type DefaultSoundboardSound = SoundboardSound & { get guild(): null; guildId: null; soundId: string }; @@ -3661,186 +4389,187 @@ export type GuildSoundboardSound = SoundboardSound & { get guild(): Guild; guild export class WelcomeChannel extends Base { private constructor(guild: Guild, data: RawWelcomeChannelData); - private _emoji: Omit; + private readonly _emoji: Omit; + public channelId: Snowflake; + public guild: Guild | InviteGuild; + public description: string; - public get channel(): TextChannel | AnnouncementChannel | ForumChannel | MediaChannel | null; - public get emoji(): GuildEmoji | Emoji; + public get channel(): AnnouncementChannel | ForumChannel | MediaChannel | TextChannel | null; + public get emoji(): Emoji | GuildEmoji; } export class WelcomeScreen extends Base { private constructor(guild: Guild, data: RawWelcomeScreenData); public get enabled(): boolean; public guild: Guild | InviteGuild; + public description: string | null; + public welcomeChannels: Collection; } -//#endregion +// #endregion -//#region Constants +// #region Constants export type NonSystemMessageType = - | MessageType.Default - | MessageType.Reply | MessageType.ChatInputCommand - | MessageType.ContextMenuCommand; + | MessageType.ContextMenuCommand + | MessageType.Default + | MessageType.Reply; export type UndeletableMessageType = - | MessageType.RecipientAdd - | MessageType.RecipientRemove | MessageType.Call - | MessageType.ChannelNameChange | MessageType.ChannelIconChange + | MessageType.ChannelNameChange + | MessageType.RecipientAdd + | MessageType.RecipientRemove | MessageType.ThreadStarterMessage; export const Constants: { + GuildTextBasedChannelTypes: GuildTextBasedChannelTypes[]; MaxBulkDeletableMessageAge: 1_209_600_000; - SweeperKeys: SweeperKey[]; NonSystemMessageTypes: NonSystemMessageType[]; - TextBasedChannelTypes: TextBasedChannelTypes[]; + SelectMenuTypes: SelectMenuType[]; SendableChannels: SendableChannelTypes[]; - GuildTextBasedChannelTypes: GuildTextBasedChannelTypes[]; + StickerFormatExtensionMap: Record; + SweeperKeys: SweeperKey[]; + TextBasedChannelTypes: TextBasedChannelTypes[]; ThreadChannelTypes: ThreadChannelType[]; - VoiceBasedChannelTypes: VoiceBasedChannelTypes[]; - SelectMenuTypes: SelectMenuType[]; UndeletableMessageTypes: UndeletableMessageType[]; - StickerFormatExtensionMap: Record; + VoiceBasedChannelTypes: VoiceBasedChannelTypes[]; }; export const version: string; -//#endregion +// #endregion -//#region Errors +// #region Errors export enum DiscordjsErrorCodes { + ApplicationCommandPermissionsTokenMissing = 'ApplicationCommandPermissionsTokenMissing', + AutocompleteInteractionOptionNoFocusedOption = 'AutocompleteInteractionOptionNoFocusedOption', + BanResolveId = 'BanResolveId', + BitFieldInvalid = 'BitFieldInvalid', + + BulkBanUsersOptionEmpty = 'BulkBanUsersOptionEmpty', + ChannelNotCached = 'ChannelNotCached', ClientInvalidOption = 'ClientInvalidOption', + ClientInvalidProvidedShards = 'ClientInvalidProvidedShards', + ClientMissingIntents = 'ClientMissingIntents', ClientNotReady = 'ClientNotReady', + ColorConvert = 'ColorConvert', + ColorRange = 'ColorRange', + CommandInteractionOptionEmpty = 'CommandInteractionOptionEmpty', + CommandInteractionOptionNoSubcommand = 'CommandInteractionOptionNoSubcommand', + CommandInteractionOptionNoSubcommandGroup = 'CommandInteractionOptionNoSubcommandGroup', + CommandInteractionOptionNotFound = 'CommandInteractionOptionNotFound', + CommandInteractionOptionType = 'CommandInteractionOptionType', + DeleteGroupDMChannel = 'DeleteGroupDMChannel', + EmojiManaged = 'EmojiManaged', + EmojiType = 'EmojiType', - TokenInvalid = 'TokenInvalid', - TokenMissing = 'TokenMissing', - ApplicationCommandPermissionsTokenMissing = 'ApplicationCommandPermissionsTokenMissing', - - BitFieldInvalid = 'BitFieldInvalid', + EntitlementCreateInvalidOwner = 'EntitlementCreateInvalidOwner', + FetchBanResolveId = 'FetchBanResolveId', - ShardingNoShards = 'ShardingNoShards', - ShardingInProcess = 'ShardingInProcess', - ShardingInvalidEvalBroadcast = 'ShardingInvalidEvalBroadcast', - ShardingShardNotFound = 'ShardingShardNotFound', - ShardingAlreadySpawned = 'ShardingAlreadySpawned', - ShardingProcessExists = 'ShardingProcessExists', - ShardingWorkerExists = 'ShardingWorkerExists', - ShardingReadyTimeout = 'ShardingReadyTimeout', - ShardingReadyDisconnected = 'ShardingReadyDisconnected', - ShardingReadyDied = 'ShardingReadyDied', - ShardingNoChildExists = 'ShardingNoChildExists', - ShardingShardMiscalculation = 'ShardingShardMiscalculation', + FetchGroupDMChannel = 'FetchGroupDMChannel', + FetchOwnerId = 'FetchOwnerId', - ColorRange = 'ColorRange', - ColorConvert = 'ColorConvert', + FileNotFound = 'FileNotFound', - InviteOptionsMissingChannel = 'InviteOptionsMissingChannel', + GlobalCommandPermissions = 'GlobalCommandPermissions', - InteractionCollectorError = 'InteractionCollectorError', + GuildChannelOrphan = 'GuildChannelOrphan', - FileNotFound = 'FileNotFound', + GuildChannelResolve = 'GuildChannelResolve', + GuildChannelUnowned = 'GuildChannelUnowned', - UserNoDMChannel = 'UserNoDMChannel', + GuildForumMessageRequired = 'GuildForumMessageRequired', - VoiceNotStageChannel = 'VoiceNotStageChannel', + GuildMembersTimeout = 'GuildMembersTimeout', + GuildOwned = 'GuildOwned', + GuildScheduledEventResolve = 'GuildScheduledEventResolve', + GuildSoundboardSoundsTimeout = 'GuildSoundboardSoundsTimeout', - VoiceStateNotOwn = 'VoiceStateNotOwn', - VoiceStateInvalidType = 'VoiceStateInvalidType', + GuildUncachedEntityResolve = 'GuildUncachedEntityResolve', + GuildUncachedMe = 'GuildUncachedMe', - ReqResourceType = 'ReqResourceType', + GuildVoiceChannelResolve = 'GuildVoiceChannelResolve', + InteractionAlreadyReplied = 'InteractionAlreadyReplied', + InteractionCollectorError = 'InteractionCollectorError', + InteractionNotReplied = 'InteractionNotReplied', + InvalidElement = 'InvalidElement', + InvalidMissingScopes = 'InvalidMissingScopes', + InvalidScopesWithPermissions = 'InvalidScopesWithPermissions', + InvalidType = 'InvalidType', + InviteNotFound = 'InviteNotFound', + InviteOptionsMissingChannel = 'InviteOptionsMissingChannel', + InviteResolveCode = 'InviteResolveCode', + MemberFetchNonceLength = 'MemberFetchNonceLength', MessageBulkDeleteType = 'MessageBulkDeleteType', + MessageContentType = 'MessageContentType', + MessageExistingThread = 'MessageExistingThread', + MessageNonceRequired = 'MessageNonceRequired', MessageNonceType = 'MessageNonceType', - - BanResolveId = 'BanResolveId', - FetchBanResolveId = 'FetchBanResolveId', - - PruneDaysType = 'PruneDaysType', - - GuildChannelResolve = 'GuildChannelResolve', - GuildVoiceChannelResolve = 'GuildVoiceChannelResolve', - GuildChannelOrphan = 'GuildChannelOrphan', - GuildChannelUnowned = 'GuildChannelUnowned', - GuildOwned = 'GuildOwned', - GuildMembersTimeout = 'GuildMembersTimeout', - GuildSoundboardSoundsTimeout = 'GuildSoundboardSoundsTimeout', - GuildUncachedMe = 'GuildUncachedMe', - ChannelNotCached = 'ChannelNotCached', - StageChannelResolve = 'StageChannelResolve', - GuildScheduledEventResolve = 'GuildScheduledEventResolve', - FetchOwnerId = 'FetchOwnerId', - - InvalidType = 'InvalidType', - InvalidElement = 'InvalidElement', + MessageReferenceMissing = 'MessageReferenceMissing', MessageThreadParent = 'MessageThreadParent', - MessageExistingThread = 'MessageExistingThread', - ThreadInvitableType = 'ThreadInvitableType', - - WebhookMessage = 'WebhookMessage', - WebhookTokenUnavailable = 'WebhookTokenUnavailable', - WebhookURLInvalid = 'WebhookURLInvalid', - WebhookApplication = 'WebhookApplication', - MessageReferenceMissing = 'MessageReferenceMissing', - - EmojiType = 'EmojiType', - EmojiManaged = 'EmojiManaged', MissingManageGuildExpressionsPermission = 'MissingManageGuildExpressionsPermission', - + ModalSubmitInteractionFieldNotFound = 'ModalSubmitInteractionFieldNotFound', + ModalSubmitInteractionFieldType = 'ModalSubmitInteractionFieldType', NotGuildSoundboardSound = 'NotGuildSoundboardSound', + NotGuildSticker = 'NotGuildSticker', + NotImplemented = 'NotImplemented', + PollAlreadyExpired = 'PollAlreadyExpired', + PruneDaysType = 'PruneDaysType', ReactionResolveUser = 'ReactionResolveUser', - InviteResolveCode = 'InviteResolveCode', - - InviteNotFound = 'InviteNotFound', - - DeleteGroupDMChannel = 'DeleteGroupDMChannel', - FetchGroupDMChannel = 'FetchGroupDMChannel', - - MemberFetchNonceLength = 'MemberFetchNonceLength', + ReqResourceType = 'ReqResourceType', - GlobalCommandPermissions = 'GlobalCommandPermissions', - GuildUncachedEntityResolve = 'GuildUncachedEntityResolve', + ShardingAlreadySpawned = 'ShardingAlreadySpawned', - InteractionAlreadyReplied = 'InteractionAlreadyReplied', - InteractionNotReplied = 'InteractionNotReplied', + ShardingInProcess = 'ShardingInProcess', - CommandInteractionOptionNotFound = 'CommandInteractionOptionNotFound', - CommandInteractionOptionType = 'CommandInteractionOptionType', - CommandInteractionOptionEmpty = 'CommandInteractionOptionEmpty', - CommandInteractionOptionNoSubcommand = 'CommandInteractionOptionNoSubcommand', - CommandInteractionOptionNoSubcommandGroup = 'CommandInteractionOptionNoSubcommandGroup', - AutocompleteInteractionOptionNoFocusedOption = 'AutocompleteInteractionOptionNoFocusedOption', + ShardingInvalidEvalBroadcast = 'ShardingInvalidEvalBroadcast', + ShardingNoChildExists = 'ShardingNoChildExists', - ModalSubmitInteractionFieldNotFound = 'ModalSubmitInteractionFieldNotFound', - ModalSubmitInteractionFieldType = 'ModalSubmitInteractionFieldType', + ShardingNoShards = 'ShardingNoShards', - InvalidMissingScopes = 'InvalidMissingScopes', - InvalidScopesWithPermissions = 'InvalidScopesWithPermissions', + ShardingProcessExists = 'ShardingProcessExists', + ShardingReadyDied = 'ShardingReadyDied', - NotImplemented = 'NotImplemented', + ShardingReadyDisconnected = 'ShardingReadyDisconnected', + ShardingReadyTimeout = 'ShardingReadyTimeout', + ShardingShardMiscalculation = 'ShardingShardMiscalculation', + ShardingShardNotFound = 'ShardingShardNotFound', + ShardingWorkerExists = 'ShardingWorkerExists', + StageChannelResolve = 'StageChannelResolve', SweepFilterReturn = 'SweepFilterReturn', + ThreadInvitableType = 'ThreadInvitableType', - GuildForumMessageRequired = 'GuildForumMessageRequired', + TokenInvalid = 'TokenInvalid', + TokenMissing = 'TokenMissing', + UserNoDMChannel = 'UserNoDMChannel', + VoiceNotStageChannel = 'VoiceNotStageChannel', - EntitlementCreateInvalidOwner = 'EntitlementCreateInvalidOwner', + VoiceStateInvalidType = 'VoiceStateInvalidType', - BulkBanUsersOptionEmpty = 'BulkBanUsersOptionEmpty', + VoiceStateNotOwn = 'VoiceStateNotOwn', + WebhookApplication = 'WebhookApplication', + WebhookMessage = 'WebhookMessage', - PollAlreadyExpired = 'PollAlreadyExpired', + WebhookTokenUnavailable = 'WebhookTokenUnavailable', + + WebhookURLInvalid = 'WebhookURLInvalid', } export class DiscordjsError extends Error { @@ -3861,9 +4590,9 @@ export class DiscordjsRangeError extends RangeError { public get name(): `RangeError [${DiscordjsErrorCodes}]`; } -//#endregion +// #endregion -//#region Managers +// #region Managers export abstract class BaseManager { protected constructor(client: Client); @@ -3876,7 +4605,7 @@ export abstract class DataManager extends BaseManager { public get cache(): Collection; public resolve(resolvable: Holds): Holds; public resolve(resolvable: Resolvable): Holds | null; - public resolveId(resolvable: Key | Holds): Key; + public resolveId(resolvable: Holds | Key): Key; public resolveId(resolvable: Resolvable): Key | null; public valueOf(): Collection; } @@ -3884,13 +4613,13 @@ export abstract class DataManager extends BaseManager { export abstract class CachedManager extends DataManager { protected constructor(client: Client, holds: Constructable, iterable?: Iterable); private readonly _cache: Collection; - private _add(data: unknown, cache?: boolean, { id, extras }?: { id: Key; extras: unknown[] }): Holds; + private _add(data: unknown, cache?: boolean, { id, extras }?: { extras: unknown[]; id: Key }): Holds; } export type ApplicationCommandDataResolvable = | ApplicationCommandData - | RESTPostAPIApplicationCommandsJSONBody - | JSONEncodable; + | JSONEncodable + | RESTPostAPIApplicationCommandsJSONBody; export class ApplicationCommandManager< ApplicationCommandScope = ApplicationCommand<{ guild: GuildResolvable }>, @@ -3899,12 +4628,12 @@ export class ApplicationCommandManager< > extends CachedManager { protected constructor(client: Client, iterable?: Iterable); public permissions: ApplicationCommandPermissionsManager< - { command?: ApplicationCommandResolvable } & PermissionsOptionsExtras, - { command: ApplicationCommandResolvable } & PermissionsOptionsExtras, + PermissionsOptionsExtras & { command?: ApplicationCommandResolvable }, + PermissionsOptionsExtras & { command: ApplicationCommandResolvable }, PermissionsGuildType, null >; - private commandPath({ id, guildId }: { id?: Snowflake; guildId?: Snowflake }): string; + private commandPath({ id, guildId }: { guildId?: Snowflake; id?: Snowflake }): string; public create(command: ApplicationCommandDataResolvable, guildId?: Snowflake): Promise; public delete(command: ApplicationCommandResolvable, guildId?: Snowflake): Promise; public edit( @@ -3920,7 +4649,7 @@ export class ApplicationCommandManager< options: Snowflake | (Omit & { id: Snowflake }), ): Promise; public fetch( - options: FetchApplicationCommandOptions & { id: Snowflake; guildId: Snowflake }, + options: FetchApplicationCommandOptions & { guildId: Snowflake; id: Snowflake }, ): Promise; public fetch( options?: Omit, @@ -3941,14 +4670,16 @@ export class ApplicationCommandPermissionsManager< GuildType, CommandIdType, > extends BaseManager { - private constructor(manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand); - private manager: ApplicationCommandManager | GuildApplicationCommandManager | ApplicationCommand; + private constructor(manager: ApplicationCommand | ApplicationCommandManager | GuildApplicationCommandManager); + private readonly manager: ApplicationCommand | ApplicationCommandManager | GuildApplicationCommandManager; public commandId: CommandIdType; + public guild: GuildType; + public guildId: Snowflake | null; public add( - options: FetchSingleOptions & EditApplicationCommandPermissionsMixin, + options: EditApplicationCommandPermissionsMixin & FetchSingleOptions, ): Promise; public has( options: FetchSingleOptions & { @@ -3961,26 +4692,26 @@ export class ApplicationCommandPermissionsManager< public remove( options: | (FetchSingleOptions & { + channels: readonly (ChannelPermissionConstant | GuildChannelResolvable)[]; + roles?: readonly (RolePermissionConstant | RoleResolvable)[]; token: string; - channels?: readonly (GuildChannelResolvable | ChannelPermissionConstant)[]; - roles?: readonly (RoleResolvable | RolePermissionConstant)[]; - users: readonly UserResolvable[]; + users?: readonly UserResolvable[]; }) | (FetchSingleOptions & { + channels?: readonly (ChannelPermissionConstant | GuildChannelResolvable)[]; + roles: readonly (RolePermissionConstant | RoleResolvable)[]; token: string; - channels?: readonly (GuildChannelResolvable | ChannelPermissionConstant)[]; - roles: readonly (RoleResolvable | RolePermissionConstant)[]; users?: readonly UserResolvable[]; }) | (FetchSingleOptions & { + channels?: readonly (ChannelPermissionConstant | GuildChannelResolvable)[]; + roles?: readonly (RolePermissionConstant | RoleResolvable)[]; token: string; - channels: readonly (GuildChannelResolvable | ChannelPermissionConstant)[]; - roles?: readonly (RoleResolvable | RolePermissionConstant)[]; - users?: readonly UserResolvable[]; + users: readonly UserResolvable[]; }), ): Promise; public set( - options: FetchSingleOptions & EditApplicationCommandPermissionsMixin, + options: EditApplicationCommandPermissionsMixin & FetchSingleOptions, ): Promise; private permissionsPath(guildId: Snowflake, commandId?: Snowflake): string; } @@ -4017,18 +4748,18 @@ export class ChannelManager extends CachedManager, iterable: Iterable); public createMessage( channel: Exclude, - options: string | MessagePayload | MessageCreateOptions, + options: MessageCreateOptions | MessagePayload | string, ): Promise>; public fetch(id: Snowflake, options?: FetchChannelOptions): Promise; } -export type EntitlementResolvable = Snowflake | Entitlement; -export type SKUResolvable = Snowflake | SKU; +export type EntitlementResolvable = Entitlement | Snowflake; +export type SKUResolvable = SKU | Snowflake; export type SubscriptionResolvable = Snowflake | Subscription; export interface GuildEntitlementCreateOptions { - sku: SKUResolvable; guild: GuildResolvable; + sku: SKUResolvable; } export interface UserEntitlementCreateOptions { @@ -4041,15 +4772,15 @@ export interface FetchEntitlementOptions extends BaseFetchOptions { } export interface FetchEntitlementsOptions { - limit?: number; + after?: Snowflake; + before?: Snowflake; + cache?: boolean; + excludeDeleted?: boolean; + excludeEnded?: boolean; guild?: GuildResolvable; - user?: UserResolvable; + limit?: number; skus?: readonly SKUResolvable[]; - excludeEnded?: boolean; - excludeDeleted?: boolean; - cache?: boolean; - before?: Snowflake; - after?: Snowflake; + user?: UserResolvable; } export class EntitlementManager extends CachedManager { @@ -4105,9 +4836,9 @@ export interface FollowedChannelData { webhookId: Snowflake; } -export type MappedGuildChannelTypes = { +export type MappedGuildChannelTypes = MappedChannelCategoryTypes & { [ChannelType.GuildCategory]: CategoryChannel; -} & MappedChannelCategoryTypes; +}; export type GuildChannelTypes = CategoryChannelChildTypes | ChannelType.GuildCategory; @@ -4161,13 +4892,14 @@ export class GuildEmojiManager extends CachedManager { private constructor(emoji: GuildEmoji); public emoji: GuildEmoji; + public guild: Guild; public add( - roleOrRoles: RoleResolvable | readonly RoleResolvable[] | ReadonlyCollection, + roleOrRoles: ReadonlyCollection | RoleResolvable | readonly RoleResolvable[], ): Promise; - public set(roles: readonly RoleResolvable[] | ReadonlyCollection): Promise; + public set(roles: ReadonlyCollection | readonly RoleResolvable[]): Promise; public remove( - roleOrRoles: RoleResolvable | readonly RoleResolvable[] | ReadonlyCollection, + roleOrRoles: ReadonlyCollection | RoleResolvable | readonly RoleResolvable[], ): Promise; } @@ -4179,7 +4911,7 @@ export interface FetchSoundboardSoundsOptions { export class GuildManager extends CachedManager { private constructor(client: Client, iterable?: Iterable); public create(options: GuildCreateOptions): Promise; - public fetch(options: Snowflake | FetchGuildOptions): Promise; + public fetch(options: FetchGuildOptions | Snowflake): Promise; public fetch(options?: FetchGuildsOptions): Promise>; public fetchSoundboardSounds( options: FetchSoundboardSoundsOptions, @@ -4192,9 +4924,9 @@ export class GuildManager extends CachedManager { @@ -4213,13 +4945,13 @@ export class GuildMemberManager extends CachedManager; public edit(user: UserResolvable, options: GuildMemberEditOptions): Promise; public fetch( - options: UserResolvable | FetchMemberOptions | (FetchMembersOptions & { user: UserResolvable }), + options: FetchMemberOptions | UserResolvable | (FetchMembersOptions & { user: UserResolvable }), ): Promise; public fetch(options?: FetchMembersOptions): Promise>; public fetchMe(options?: BaseFetchOptions): Promise; public kick(user: UserResolvable, reason?: string): Promise; public list(options?: GuildListMembersOptions): Promise>; - public prune(options: GuildPruneMembersOptions & { dry?: false; count: false }): Promise; + public prune(options: GuildPruneMembersOptions & { count: false; dry?: false }): Promise; public prune(options?: GuildPruneMembersOptions): Promise; public search(options: GuildSearchMembersOptions): Promise>; public unban(user: UserResolvable, reason?: string): Promise; @@ -4231,7 +4963,7 @@ export class GuildBanManager extends CachedManager); public guild: Guild; public create(user: UserResolvable, options?: BanOptions): Promise; - public fetch(options: UserResolvable | FetchBanOptions): Promise; + public fetch(options: FetchBanOptions | UserResolvable): Promise; public fetch(options?: FetchBansOptions): Promise>; public remove(user: UserResolvable, reason?: string): Promise; public bulkCreate( @@ -4244,7 +4976,7 @@ export class GuildInviteManager extends DataManager); public guild: Guild; public create(channel: GuildInvitableChannelResolvable, options?: InviteCreateOptions): Promise; - public fetch(options: InviteResolvable | FetchInviteOptions): Promise; + public fetch(options: FetchInviteOptions | InviteResolvable): Promise; public fetch(options?: FetchInvitesOptions): Promise>; public delete(invite: InviteResolvable, reason?: string): Promise; } @@ -4259,7 +4991,7 @@ export class GuildScheduledEventManager extends CachedManager< public create(options: GuildScheduledEventCreateOptions): Promise; public fetch(): Promise>; public fetch< - Options extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions | FetchGuildScheduledEventsOptions, + Options extends FetchGuildScheduledEventOptions | FetchGuildScheduledEventsOptions | GuildScheduledEventResolvable, >(options?: Options): Promise>; public edit< Status extends GuildScheduledEventStatus, @@ -4276,20 +5008,20 @@ export class GuildScheduledEventManager extends CachedManager< } export interface GuildSoundboardSoundCreateOptions { - file: BufferResolvable | Stream; - name: string; contentType?: string; - volume?: number; emojiId?: Snowflake; emojiName?: string; + file: BufferResolvable | Stream; + name: string; reason?: string; + volume?: number; } export interface GuildSoundboardSoundEditOptions { - name?: string; - volume?: number | null; emojiId?: Snowflake | null; emojiName?: string | null; + name?: string; + volume?: number | null; } export class GuildSoundboardSoundManager extends CachedManager { @@ -4325,25 +5057,26 @@ export class GuildMemberRoleManager extends DataManager, + roleOrRoles: ReadonlyCollection | RoleResolvable | readonly RoleResolvable[], reason?: string, ): Promise; public set( - roles: readonly RoleResolvable[] | ReadonlyCollection, + roles: ReadonlyCollection | readonly RoleResolvable[], reason?: string, ): Promise; public remove( - roleOrRoles: RoleResolvable | readonly RoleResolvable[] | ReadonlyCollection, + roleOrRoles: ReadonlyCollection | RoleResolvable | readonly RoleResolvable[], reason?: string, ): Promise; } export interface FetchPollAnswerVotersOptions extends BaseFetchPollAnswerVotersOptions { - messageId: Snowflake; answerId: number; + messageId: Snowflake; } export abstract class MessageManager extends CachedManager< @@ -4356,9 +5089,9 @@ export abstract class MessageManager extends public delete(message: MessageResolvable): Promise; public edit( message: MessageResolvable, - options: string | MessagePayload | MessageEditOptions, + options: MessageEditOptions | MessagePayload | string, ): Promise>; - public fetch(options: MessageResolvable | FetchMessageOptions): Promise>; + public fetch(options: FetchMessageOptions | MessageResolvable): Promise>; public fetch(options?: FetchMessagesOptions): Promise>>; public fetchPinned(cache?: boolean): Promise>>; public react(message: MessageResolvable, emoji: EmojiIdentifierResolvable): Promise; @@ -4388,7 +5121,7 @@ export class PermissionOverwriteManager extends CachedManager< > { private constructor(client: Client, iterable?: Iterable); public set( - overwrites: readonly OverwriteResolvable[] | ReadonlyCollection, + overwrites: ReadonlyCollection | readonly OverwriteResolvable[], reason?: string, ): Promise; private upsert( @@ -4459,10 +5192,10 @@ export class ThreadManager extends CachedM ThreadChannelResolvable > { protected constructor( - channel: TextChannel | AnnouncementChannel | ForumChannel | MediaChannel, + channel: AnnouncementChannel | ForumChannel | MediaChannel | TextChannel, iterable?: Iterable, ); - public channel: If; + public channel: If; public fetch( options: ThreadChannelResolvable, cacheOptions?: BaseFetchOptions, @@ -4493,10 +5226,10 @@ export class ThreadMemberManager extends CachedManager; public fetch( - options: ThreadMember | ((FetchThreadMemberOptions & { withMember: true }) | { member: ThreadMember }), + options: ThreadMember | ({ member: ThreadMember } | (FetchThreadMemberOptions & { withMember: true })), ): Promise>; - public fetch(options: ThreadMemberResolvable | FetchThreadMemberOptions): Promise; + public fetch(options: FetchThreadMemberOptions | ThreadMemberResolvable): Promise; public fetch( options: FetchThreadMembersWithGuildMemberDataOptions, @@ -4513,7 +5246,7 @@ export class UserManager extends CachedManager public createDM(user: UserResolvable, options?: BaseFetchOptions): Promise; public deleteDM(user: UserResolvable): Promise; public fetch(user: UserResolvable, options?: BaseFetchOptions): Promise; - public send(user: UserResolvable, options: string | MessagePayload | MessageCreateOptions): Promise; + public send(user: UserResolvable, options: MessageCreateOptions | MessagePayload | string): Promise; } export class VoiceStateManager extends CachedManager { @@ -4522,9 +5255,9 @@ export class VoiceStateManager extends CachedManager; } -//#endregion +// #endregion -//#region Mixins +// #region Mixins // Model the TextBasedChannel mixin system, allowing application of these fields // to the classes that use these methods without having to manually add them @@ -4533,51 +5266,55 @@ export class VoiceStateManager extends CachedManager = abstract new (...args: any[]) => Entity; export interface PartialTextBasedChannelFields { - send(options: string | MessagePayload | MessageCreateOptions): Promise>; + send(options: MessageCreateOptions | MessagePayload | string): Promise>; } export interface TextBasedChannelFields extends PartialTextBasedChannelFields { - lastMessageId: Snowflake | null; - get lastMessage(): Message | null; - lastPinTimestamp: number | null; - get lastPinAt(): Date | null; - messages: If>; awaitMessageComponent( options?: AwaitMessageCollectorOptionsParams, ): Promise; awaitMessages(options?: AwaitMessagesOptions): Promise>; bulkDelete( - messages: Collection | readonly MessageResolvable[] | number, + messages: Collection | number | readonly MessageResolvable[], filterOld?: boolean, ): Promise; + createMessageCollector(options?: MessageCollectorOptions): MessageCollector; createMessageComponentCollector( options?: MessageChannelCollectorOptionsParams, ): InteractionCollector; - createMessageCollector(options?: MessageCollectorOptions): MessageCollector; createWebhook(options: ChannelWebhookCreateOptions): Promise>; fetchWebhooks(): Promise>>; + get lastMessage(): Message | null; + lastMessageId: Snowflake | null; + get lastPinAt(): Date | null; + lastPinTimestamp: number | null; + messages: If>; sendTyping(): Promise; - setRateLimitPerUser(rateLimitPerUser: number, reason?: string): Promise; setNSFW(nsfw?: boolean, reason?: string): Promise; + setRateLimitPerUser(rateLimitPerUser: number, reason?: string): Promise; } -/** @internal */ +/** + * @internal + */ export interface PartialWebhookFields { - id: Snowflake; - get url(): string; - deleteMessage(message: MessageResolvable | APIMessage | '@original', threadId?: Snowflake): Promise; + deleteMessage(message: APIMessage | MessageResolvable | '@original', threadId?: Snowflake): Promise; editMessage( message: MessageResolvable | '@original', - options: string | MessagePayload | WebhookMessageEditOptions, + options: MessagePayload | WebhookMessageEditOptions | string, ): Promise; fetchMessage(message: Snowflake | '@original', options?: WebhookFetchMessageOptions): Promise; + id: Snowflake; send( - options: string | MessagePayload | InteractionReplyOptions | WebhookMessageCreateOptions, + options: InteractionReplyOptions | MessagePayload | WebhookMessageCreateOptions | string, ): Promise; + get url(): string; } -/** @internal */ +/** + * @internal + */ export interface WebhookFields extends PartialWebhookFields { get createdAt(): Date; get createdTimestamp(): number; @@ -4586,58 +5323,58 @@ export interface WebhookFields extends PartialWebhookFields { sendSlackMessage(body: unknown): Promise; } -//#endregion +// #endregion -//#region Typedefs +// #region Typedefs export interface ActivitiesOptions extends Omit {} export interface ActivityOptions { name: string; + shardId?: number | readonly number[]; state?: string; - url?: string; type?: ActivityType; - shardId?: number | readonly number[]; + url?: string; } export interface AddGuildMemberOptions { accessToken: string; - nick?: string; - roles?: ReadonlyCollection | readonly RoleResolvable[]; - mute?: boolean; deaf?: boolean; - force?: boolean; fetchWhenExisting?: boolean; + force?: boolean; + mute?: boolean; + nick?: string; + roles?: ReadonlyCollection | readonly RoleResolvable[]; } export type AllowedPartial = - | User | Channel | GuildMember + | GuildScheduledEvent | Message | MessageReaction - | GuildScheduledEvent - | ThreadMember | Poll | PollAnswer - | SoundboardSound; + | SoundboardSound + | ThreadMember + | User; export type AllowedThreadTypeForAnnouncementChannel = ChannelType.AnnouncementThread; -export type AllowedThreadTypeForTextChannel = ChannelType.PublicThread | ChannelType.PrivateThread; +export type AllowedThreadTypeForTextChannel = ChannelType.PrivateThread | ChannelType.PublicThread; export interface BaseApplicationCommandData { + contexts?: readonly InteractionContextType[]; + defaultMemberPermissions?: PermissionResolvable | null; + integrationTypes?: readonly ApplicationIntegrationType[]; name: string; nameLocalizations?: LocalizationMap; - defaultMemberPermissions?: PermissionResolvable | null; nsfw?: boolean; - contexts?: readonly InteractionContextType[]; - integrationTypes?: readonly ApplicationIntegrationType[]; } export interface AttachmentData { - name?: string; description?: string; + name?: string; } export type CommandOptionDataTypeResolvable = ApplicationCommandOptionType; @@ -4649,8 +5386,8 @@ export type CommandOptionChoiceResolvableType = | CommandOptionNumericResolvableType; export type CommandOptionNumericResolvableType = - | ApplicationCommandOptionType.Number - | ApplicationCommandOptionType.Integer; + | ApplicationCommandOptionType.Integer + | ApplicationCommandOptionType.Number; export type CommandOptionSubOptionResolvableType = | ApplicationCommandOptionType.Subcommand @@ -4658,16 +5395,16 @@ export type CommandOptionSubOptionResolvableType = export type CommandOptionNonChoiceResolvableType = Exclude< CommandOptionDataTypeResolvable, - CommandOptionChoiceResolvableType | CommandOptionSubOptionResolvableType | CommandOptionChannelResolvableType + CommandOptionChannelResolvableType | CommandOptionChoiceResolvableType | CommandOptionSubOptionResolvableType >; export interface BaseApplicationCommandOptionsData { - name: string; - nameLocalizations?: LocalizationMap; + autocomplete?: never; description: string; descriptionLocalizations?: LocalizationMap; + name: string; + nameLocalizations?: LocalizationMap; required?: boolean; - autocomplete?: never; } export interface UserApplicationCommandData extends BaseApplicationCommandData { @@ -4681,32 +5418,32 @@ export interface MessageApplicationCommandData extends BaseApplicationCommandDat export interface ChatInputApplicationCommandData extends BaseApplicationCommandData { description: string; descriptionLocalizations?: LocalizationMap; - type?: ApplicationCommandType.ChatInput; options?: readonly ApplicationCommandOptionData[]; + type?: ApplicationCommandType.ChatInput; } export interface PrimaryEntryPointCommandData extends BaseApplicationCommandData { description?: string; descriptionLocalizations?: LocalizationMap; - type: ApplicationCommandType.PrimaryEntryPoint; handler?: EntryPointCommandHandlerType; + type: ApplicationCommandType.PrimaryEntryPoint; } export type ApplicationCommandData = - | UserApplicationCommandData - | MessageApplicationCommandData | ChatInputApplicationCommandData - | PrimaryEntryPointCommandData; + | MessageApplicationCommandData + | PrimaryEntryPointCommandData + | UserApplicationCommandData; export interface ApplicationCommandChannelOptionData extends BaseApplicationCommandOptionsData { - type: CommandOptionChannelResolvableType; channelTypes?: readonly ApplicationCommandOptionAllowedChannelTypes[]; channel_types?: readonly ApplicationCommandOptionAllowedChannelTypes[]; + type: CommandOptionChannelResolvableType; } export interface ApplicationCommandChannelOption extends BaseApplicationCommandOptionsData { - type: ApplicationCommandOptionType.Channel; channelTypes?: readonly ApplicationCommandOptionAllowedChannelTypes[]; + type: ApplicationCommandOptionType.Channel; } export interface ApplicationCommandRoleOptionData extends BaseApplicationCommandOptionsData { @@ -4739,68 +5476,68 @@ export interface ApplicationCommandAttachmentOption extends BaseApplicationComma export interface ApplicationCommandAutocompleteNumericOption extends Omit { - type: CommandOptionNumericResolvableType; - minValue?: number; - maxValue?: number; autocomplete: true; + maxValue?: number; + minValue?: number; + type: CommandOptionNumericResolvableType; } export interface ApplicationCommandAutocompleteStringOption extends Omit { - type: ApplicationCommandOptionType.String; - minLength?: number; - maxLength?: number; autocomplete: true; + maxLength?: number; + minLength?: number; + type: ApplicationCommandOptionType.String; } export interface ApplicationCommandAutocompleteNumericOptionData extends Omit { - type: CommandOptionNumericResolvableType; - minValue?: number; - min_value?: number; + autocomplete: true; maxValue?: number; max_value?: number; - autocomplete: true; + minValue?: number; + min_value?: number; + type: CommandOptionNumericResolvableType; } export interface ApplicationCommandAutocompleteStringOptionData extends Omit { - type: ApplicationCommandOptionType.String; - minLength?: number; - min_length?: number; + autocomplete: true; maxLength?: number; max_length?: number; - autocomplete: true; + minLength?: number; + min_length?: number; + type: ApplicationCommandOptionType.String; } -export interface ApplicationCommandChoicesData +export interface ApplicationCommandChoicesData extends Omit { - type: CommandOptionChoiceResolvableType; - choices?: readonly ApplicationCommandOptionChoiceData[]; autocomplete?: false; + choices?: readonly ApplicationCommandOptionChoiceData[]; + type: CommandOptionChoiceResolvableType; } -export interface ApplicationCommandChoicesOption +export interface ApplicationCommandChoicesOption extends Omit { - type: CommandOptionChoiceResolvableType; - choices?: readonly ApplicationCommandOptionChoiceData[]; autocomplete?: false; + choices?: readonly ApplicationCommandOptionChoiceData[]; + type: CommandOptionChoiceResolvableType; } export interface ApplicationCommandNumericOptionData extends ApplicationCommandChoicesData { - type: CommandOptionNumericResolvableType; - minValue?: number; - min_value?: number; maxValue?: number; max_value?: number; + minValue?: number; + min_value?: number; + type: CommandOptionNumericResolvableType; } export interface ApplicationCommandStringOptionData extends ApplicationCommandChoicesData { - type: ApplicationCommandOptionType.String; - minLength?: number; - min_length?: number; maxLength?: number; max_length?: number; + minLength?: number; + min_length?: number; + type: ApplicationCommandOptionType.String; } export interface ApplicationCommandBooleanOptionData extends BaseApplicationCommandOptionsData { @@ -4808,15 +5545,15 @@ export interface ApplicationCommandBooleanOptionData extends BaseApplicationComm } export interface ApplicationCommandNumericOption extends ApplicationCommandChoicesOption { - type: CommandOptionNumericResolvableType; - minValue?: number; maxValue?: number; + minValue?: number; + type: CommandOptionNumericResolvableType; } export interface ApplicationCommandStringOption extends ApplicationCommandChoicesOption { - type: ApplicationCommandOptionType.String; - minLength?: number; maxLength?: number; + minLength?: number; + type: ApplicationCommandOptionType.String; } export interface ApplicationCommandBooleanOption extends BaseApplicationCommandOptionsData { @@ -4824,26 +5561,26 @@ export interface ApplicationCommandBooleanOption extends BaseApplicationCommandO } export interface ApplicationCommandSubGroupData extends Omit { - type: ApplicationCommandOptionType.SubcommandGroup; options: readonly ApplicationCommandSubCommandData[]; + type: ApplicationCommandOptionType.SubcommandGroup; } export interface ApplicationCommandSubGroup extends Omit { - type: ApplicationCommandOptionType.SubcommandGroup; options?: readonly ApplicationCommandSubCommand[]; + type: ApplicationCommandOptionType.SubcommandGroup; } export interface ApplicationCommandSubCommandData extends Omit { - type: ApplicationCommandOptionType.Subcommand; options?: readonly Exclude< ApplicationCommandOptionData, - ApplicationCommandSubGroupData | ApplicationCommandSubCommandData + ApplicationCommandSubCommandData | ApplicationCommandSubGroupData >[]; + type: ApplicationCommandOptionType.Subcommand; } export interface ApplicationCommandSubCommand extends Omit { + options?: readonly Exclude[]; type: ApplicationCommandOptionType.Subcommand; - options?: readonly Exclude[]; } export interface ApplicationCommandNonOptionsData extends BaseApplicationCommandOptionsData { @@ -4855,35 +5592,35 @@ export interface ApplicationCommandNonOptions extends BaseApplicationCommandOpti } export type ApplicationCommandOptionData = - | ApplicationCommandSubGroupData - | ApplicationCommandNonOptionsData - | ApplicationCommandChannelOptionData | ApplicationCommandAutocompleteNumericOptionData | ApplicationCommandAutocompleteStringOptionData + | ApplicationCommandBooleanOptionData + | ApplicationCommandChannelOptionData + | ApplicationCommandMentionableOptionData + | ApplicationCommandNonOptionsData | ApplicationCommandNumericOptionData - | ApplicationCommandStringOptionData | ApplicationCommandRoleOptionData - | ApplicationCommandUserOptionData - | ApplicationCommandMentionableOptionData - | ApplicationCommandBooleanOptionData - | ApplicationCommandSubCommandData; + | ApplicationCommandStringOptionData + | ApplicationCommandSubCommandData + | ApplicationCommandSubGroupData + | ApplicationCommandUserOptionData; export type ApplicationCommandOption = - | ApplicationCommandSubGroup + | ApplicationCommandAttachmentOption | ApplicationCommandAutocompleteNumericOption | ApplicationCommandAutocompleteStringOption - | ApplicationCommandNonOptions + | ApplicationCommandBooleanOption | ApplicationCommandChannelOption + | ApplicationCommandMentionableOption + | ApplicationCommandNonOptions | ApplicationCommandNumericOption - | ApplicationCommandStringOption | ApplicationCommandRoleOption - | ApplicationCommandUserOption - | ApplicationCommandMentionableOption - | ApplicationCommandBooleanOption - | ApplicationCommandAttachmentOption - | ApplicationCommandSubCommand; + | ApplicationCommandStringOption + | ApplicationCommandSubCommand + | ApplicationCommandSubGroup + | ApplicationCommandUserOption; -export interface ApplicationCommandOptionChoiceData { +export interface ApplicationCommandOptionChoiceData { name: string; nameLocalizations?: LocalizationMap; value: Value; @@ -4891,14 +5628,14 @@ export interface ApplicationCommandOptionChoiceData extends Omit, 'max' | 'maxComponents' | 'maxUsers'> {} export interface ModalSubmitInteractionCollectorOptions - extends Omit, 'channel' | 'message' | 'guild' | 'interactionType'> {} + extends Omit, 'channel' | 'guild' | 'interactionType' | 'message'> {} export interface AwaitModalSubmitOptions extends Omit, 'max' | 'maxComponents' | 'maxUsers'> { @@ -4989,19 +5726,19 @@ export interface BulkBanResult { } export interface PollData { - question: PollQuestionMedia; + allowMultiselect: boolean; answers: readonly PollAnswerData[]; duration: number; - allowMultiselect: boolean; layoutType?: PollLayoutType; + question: PollQuestionMedia; } export interface PollAnswerData { - text: string; emoji?: EmojiIdentifierResolvable; + text: string; } -export type Base64Resolvable = Buffer | Base64String; +export type Base64Resolvable = Base64String | Buffer; export type Base64String = string; @@ -5010,12 +5747,12 @@ export interface BaseFetchOptions { force?: boolean; } -export type BitFieldResolvable = - | RecursiveReadonlyArray>> +export type BitFieldResolvable = | Flags + | Readonly> + | RecursiveReadonlyArray> | Type | `${bigint}`> | Type - | `${bigint}` - | Readonly>; + | `${bigint}`; export type BufferResolvable = Buffer | string; @@ -5075,24 +5812,24 @@ export type CacheWithLimitsOptions = { }; export interface CategoryCreateChannelOptions { + availableTags?: readonly GuildForumTagData[]; + bitrate?: number; + defaultAutoArchiveDuration?: ThreadAutoArchiveDuration; + defaultForumLayout?: ForumLayoutType; + defaultReactionEmoji?: DefaultReactionEmoji; + defaultSortOrder?: SortOrderType; + defaultThreadRateLimitPerUser?: number; name: string; - permissionOverwrites?: readonly OverwriteResolvable[] | ReadonlyCollection; - topic?: string; - type?: CategoryChannelChildTypes; nsfw?: boolean; - bitrate?: number; - userLimit?: number; - rateLimitPerUser?: number; + permissionOverwrites?: ReadonlyCollection | readonly OverwriteResolvable[]; position?: number; + rateLimitPerUser?: number; + reason?: string; rtcRegion?: string; + topic?: string; + type?: CategoryChannelChildTypes; + userLimit?: number; videoQualityMode?: VideoQualityMode; - defaultThreadRateLimitPerUser?: number; - availableTags?: readonly GuildForumTagData[]; - defaultReactionEmoji?: DefaultReactionEmoji; - defaultAutoArchiveDuration?: ThreadAutoArchiveDuration; - defaultSortOrder?: SortOrderType; - defaultForumLayout?: ForumLayoutType; - reason?: string; } export interface ChannelCreationOverwrites { @@ -5110,24 +5847,24 @@ export interface ChannelPosition { position?: number; } -export type GuildTextChannelResolvable = TextChannel | AnnouncementChannel | Snowflake; +export type GuildTextChannelResolvable = AnnouncementChannel | Snowflake | TextChannel; export type ChannelResolvable = Channel | Snowflake; export interface ChannelWebhookCreateOptions { + avatar?: Base64Resolvable | BufferResolvable | null; name: string; - avatar?: BufferResolvable | Base64Resolvable | null; reason?: string; } export interface WebhookCreateOptions extends ChannelWebhookCreateOptions { - channel: TextChannel | AnnouncementChannel | VoiceChannel | StageChannel | ForumChannel | MediaChannel | Snowflake; + channel: AnnouncementChannel | ForumChannel | MediaChannel | Snowflake | StageChannel | TextChannel | VoiceChannel; } export interface GuildMembersChunk { - index: number; count: number; - notFound: readonly unknown[]; + index: number; nonce: string | undefined; + notFound: readonly unknown[]; } export type OmitPartialGroupDMChannel = Structure & { @@ -5153,7 +5890,6 @@ export interface ClientEventTypes { ]; clientReady: [client: Client]; debug: [message: string]; - warn: [message: string]; emojiCreate: [emoji: GuildEmoji]; emojiDelete: [emoji: GuildEmoji]; emojiUpdate: [oldEmoji: GuildEmoji, newEmoji: GuildEmoji]; @@ -5167,85 +5903,86 @@ export interface ClientEventTypes { guildBanRemove: [ban: GuildBan]; guildCreate: [guild: Guild]; guildDelete: [guild: Guild]; - guildUnavailable: [guild: Guild]; guildIntegrationsUpdate: [guild: Guild]; guildMemberAdd: [member: GuildMember]; guildMemberAvailable: [member: GuildMember | PartialGuildMember]; guildMemberRemove: [member: GuildMember | PartialGuildMember]; - guildMembersChunk: [members: ReadonlyCollection, guild: Guild, data: GuildMembersChunk]; guildMemberUpdate: [oldMember: GuildMember | PartialGuildMember, newMember: GuildMember]; - guildUpdate: [oldGuild: Guild, newGuild: Guild]; + guildMembersChunk: [members: ReadonlyCollection, guild: Guild, data: GuildMembersChunk]; + guildScheduledEventCreate: [guildScheduledEvent: GuildScheduledEvent]; + guildScheduledEventDelete: [guildScheduledEvent: GuildScheduledEvent | PartialGuildScheduledEvent]; + guildScheduledEventUpdate: [ + oldGuildScheduledEvent: GuildScheduledEvent | PartialGuildScheduledEvent | null, + newGuildScheduledEvent: GuildScheduledEvent, + ]; + guildScheduledEventUserAdd: [guildScheduledEvent: GuildScheduledEvent | PartialGuildScheduledEvent, user: User]; + guildScheduledEventUserRemove: [guildScheduledEvent: GuildScheduledEvent | PartialGuildScheduledEvent, user: User]; guildSoundboardSoundCreate: [soundboardSound: SoundboardSound]; - guildSoundboardSoundDelete: [soundboardSound: SoundboardSound | PartialSoundboardSound]; + guildSoundboardSoundDelete: [soundboardSound: PartialSoundboardSound | SoundboardSound]; guildSoundboardSoundUpdate: [oldSoundboardSound: SoundboardSound | null, newSoundboardSound: SoundboardSound]; + guildUnavailable: [guild: Guild]; + guildUpdate: [oldGuild: Guild, newGuild: Guild]; + interactionCreate: [interaction: Interaction]; + invalidated: []; inviteCreate: [invite: Invite]; inviteDelete: [invite: Invite]; messageCreate: [message: OmitPartialGroupDMChannel]; messageDelete: [message: OmitPartialGroupDMChannel]; - messagePollVoteAdd: [pollAnswer: PollAnswer | PartialPollAnswer, userId: Snowflake]; - messagePollVoteRemove: [pollAnswer: PollAnswer | PartialPollAnswer, userId: Snowflake]; - messageReactionRemoveAll: [ - message: OmitPartialGroupDMChannel, - reactions: ReadonlyCollection, - ]; - messageReactionRemoveEmoji: [reaction: MessageReaction | PartialMessageReaction]; messageDeleteBulk: [ messages: ReadonlyCollection>, channel: GuildTextBasedChannel, ]; + messagePollVoteAdd: [pollAnswer: PartialPollAnswer | PollAnswer, userId: Snowflake]; + messagePollVoteRemove: [pollAnswer: PartialPollAnswer | PollAnswer, userId: Snowflake]; messageReactionAdd: [ reaction: MessageReaction | PartialMessageReaction, - user: User | PartialUser, + user: PartialUser | User, details: MessageReactionEventDetails, ]; messageReactionRemove: [ reaction: MessageReaction | PartialMessageReaction, - user: User | PartialUser, + user: PartialUser | User, details: MessageReactionEventDetails, ]; + messageReactionRemoveAll: [ + message: OmitPartialGroupDMChannel, + reactions: ReadonlyCollection, + ]; + messageReactionRemoveEmoji: [reaction: MessageReaction | PartialMessageReaction]; messageUpdate: [ oldMessage: OmitPartialGroupDMChannel, newMessage: OmitPartialGroupDMChannel, ]; presenceUpdate: [oldPresence: Presence | null, newPresence: Presence]; - invalidated: []; roleCreate: [role: Role]; roleDelete: [role: Role]; roleUpdate: [oldRole: Role, newRole: Role]; + soundboardSounds: [soundboardSounds: ReadonlyCollection, guild: Guild]; + stageInstanceCreate: [stageInstance: StageInstance]; + stageInstanceDelete: [stageInstance: StageInstance]; + stageInstanceUpdate: [oldStageInstance: StageInstance | null, newStageInstance: StageInstance]; + stickerCreate: [sticker: Sticker]; + stickerDelete: [sticker: Sticker]; + stickerUpdate: [oldSticker: Sticker, newSticker: Sticker]; + subscriptionCreate: [subscription: Subscription]; + subscriptionDelete: [subscription: Subscription]; + subscriptionUpdate: [oldSubscription: Subscription | null, newSubscription: Subscription]; threadCreate: [thread: AnyThreadChannel, newlyCreated: boolean]; threadDelete: [thread: AnyThreadChannel]; threadListSync: [threads: ReadonlyCollection, guild: Guild]; threadMemberUpdate: [oldMember: ThreadMember, newMember: ThreadMember]; threadMembersUpdate: [ addedMembers: ReadonlyCollection, - removedMembers: ReadonlyCollection, + removedMembers: ReadonlyCollection, thread: AnyThreadChannel, ]; threadUpdate: [oldThread: AnyThreadChannel, newThread: AnyThreadChannel]; typingStart: [typing: Typing]; - userUpdate: [oldUser: User | PartialUser, newUser: User]; + userUpdate: [oldUser: PartialUser | User, newUser: User]; voiceChannelEffectSend: [voiceChannelEffect: VoiceChannelEffect]; voiceStateUpdate: [oldState: VoiceState, newState: VoiceState]; - webhooksUpdate: [channel: TextChannel | AnnouncementChannel | VoiceChannel | ForumChannel | MediaChannel]; - interactionCreate: [interaction: Interaction]; - stageInstanceCreate: [stageInstance: StageInstance]; - stageInstanceUpdate: [oldStageInstance: StageInstance | null, newStageInstance: StageInstance]; - stageInstanceDelete: [stageInstance: StageInstance]; - stickerCreate: [sticker: Sticker]; - stickerDelete: [sticker: Sticker]; - stickerUpdate: [oldSticker: Sticker, newSticker: Sticker]; - subscriptionCreate: [subscription: Subscription]; - subscriptionDelete: [subscription: Subscription]; - subscriptionUpdate: [oldSubscription: Subscription | null, newSubscription: Subscription]; - guildScheduledEventCreate: [guildScheduledEvent: GuildScheduledEvent]; - guildScheduledEventUpdate: [ - oldGuildScheduledEvent: GuildScheduledEvent | PartialGuildScheduledEvent | null, - newGuildScheduledEvent: GuildScheduledEvent, - ]; - guildScheduledEventDelete: [guildScheduledEvent: GuildScheduledEvent | PartialGuildScheduledEvent]; - guildScheduledEventUserAdd: [guildScheduledEvent: GuildScheduledEvent | PartialGuildScheduledEvent, user: User]; - guildScheduledEventUserRemove: [guildScheduledEvent: GuildScheduledEvent | PartialGuildScheduledEvent, user: User]; - soundboardSounds: [soundboardSounds: ReadonlyCollection, guild: Guild]; + warn: [message: string]; + webhooksUpdate: [channel: AnnouncementChannel | ForumChannel | MediaChannel | TextChannel | VoiceChannel]; } export interface ClientFetchInviteOptions { @@ -5253,120 +5990,120 @@ export interface ClientFetchInviteOptions { } export interface ClientOptions { + allowedMentions?: MessageMentionOptions; closeTimeout?: number; + enforceNonce?: boolean; + failIfNotExists?: boolean; + intents: BitFieldResolvable; + jsonTransformer?(obj: unknown): unknown; makeCache?: CacheFactory; - allowedMentions?: MessageMentionOptions; partials?: readonly Partials[]; - failIfNotExists?: boolean; presence?: PresenceData; - intents: BitFieldResolvable; - waitGuildTimeout?: number; + rest?: Partial; sweepers?: SweeperOptions; + waitGuildTimeout?: number; ws?: Partial; - rest?: Partial; - jsonTransformer?: (obj: unknown) => unknown; - enforceNonce?: boolean; } -export type ClientPresenceStatus = 'online' | 'idle' | 'dnd'; +export type ClientPresenceStatus = 'dnd' | 'idle' | 'online'; export interface ClientPresenceStatusData { - web?: ClientPresenceStatus; - mobile?: ClientPresenceStatus; desktop?: ClientPresenceStatus; + mobile?: ClientPresenceStatus; + web?: ClientPresenceStatus; } export interface ClientUserEditOptions { + avatar?: Base64Resolvable | BufferResolvable | null; + banner?: Base64Resolvable | BufferResolvable | null; username?: string; - avatar?: BufferResolvable | Base64Resolvable | null; - banner?: BufferResolvable | Base64Resolvable | null; } export type CollectorFilter = (...args: Arguments) => Awaitable; export interface CollectorOptions { + dispose?: boolean; filter?: CollectorFilter; - time?: number; idle?: number; - dispose?: boolean; + time?: number; } export interface CollectorResetTimerOptions { - time?: number; idle?: number; + time?: number; } export type ColorResolvable = + | HexColorString + | number | keyof typeof Colors - | 'Random' | readonly [red: number, green: number, blue: number] - | number - | HexColorString; + | 'Random'; export interface CommandInteractionOption { - name: string; - type: ApplicationCommandOptionType; - value?: string | number | boolean; - focused?: boolean; + attachment?: Attachment; autocomplete?: boolean; - options?: readonly CommandInteractionOption[]; - user?: User; - member?: CacheTypeReducer; channel?: CacheTypeReducer; - role?: CacheTypeReducer; - attachment?: Attachment; + focused?: boolean; + member?: CacheTypeReducer; message?: Message>; + name: string; + options?: readonly CommandInteractionOption[]; + role?: CacheTypeReducer; + type: ApplicationCommandOptionType; + user?: User; + value?: boolean | number | string; } export interface CommandInteractionResolvedData { - users?: ReadonlyCollection; - members?: ReadonlyCollection>; - roles?: ReadonlyCollection>; + attachments?: ReadonlyCollection; channels?: ReadonlyCollection>; + members?: ReadonlyCollection>; messages?: ReadonlyCollection>; - attachments?: ReadonlyCollection; + roles?: ReadonlyCollection>; + users?: ReadonlyCollection; } export interface AutocompleteFocusedOption extends Pick { focused: true; type: - | ApplicationCommandOptionType.String | ApplicationCommandOptionType.Integer - | ApplicationCommandOptionType.Number; + | ApplicationCommandOptionType.Number + | ApplicationCommandOptionType.String; value: string; } export declare const Colors: { - Default: 0x000000; - White: 0xffffff; Aqua: 0x1abc9c; - Green: 0x57f287; Blue: 0x3498db; - Yellow: 0xfee75c; - Purple: 0x9b59b6; - LuminousVividPink: 0xe91e63; - Fuchsia: 0xeb459e; - Gold: 0xf1c40f; - Orange: 0xe67e22; - Red: 0xed4245; - Grey: 0x95a5a6; - Navy: 0x34495e; + Blurple: 0x5865f2; DarkAqua: 0x11806a; - DarkGreen: 0x1f8b4c; DarkBlue: 0x206694; - DarkPurple: 0x71368a; - DarkVividPink: 0xad1457; + DarkButNotBlack: 0x2c2f33; DarkGold: 0xc27c0e; + DarkGreen: 0x1f8b4c; + DarkGrey: 0x979c9f; + DarkNavy: 0x2c3e50; DarkOrange: 0xa84300; + DarkPurple: 0x71368a; DarkRed: 0x992d22; - DarkGrey: 0x979c9f; + DarkVividPink: 0xad1457; DarkerGrey: 0x7f8c8d; - LightGrey: 0xbcc0c0; - DarkNavy: 0x2c3e50; - Blurple: 0x5865f2; + Default: 0x000000; + Fuchsia: 0xeb459e; + Gold: 0xf1c40f; + Green: 0x57f287; + Grey: 0x95a5a6; Greyple: 0x99aab5; - DarkButNotBlack: 0x2c2f33; + LightGrey: 0xbcc0c0; + LuminousVividPink: 0xe91e63; + Navy: 0x34495e; NotQuiteBlack: 0x23272a; + Orange: 0xe67e22; + Purple: 0x9b59b6; + Red: 0xed4245; + White: 0xffffff; + Yellow: 0xfee75c; }; export enum Events { @@ -5375,84 +6112,84 @@ export enum Events { AutoModerationRuleCreate = 'autoModerationRuleCreate', AutoModerationRuleDelete = 'autoModerationRuleDelete', AutoModerationRuleUpdate = 'autoModerationRuleUpdate', + CacheSweep = 'cacheSweep', + ChannelCreate = 'channelCreate', + ChannelDelete = 'channelDelete', + ChannelPinsUpdate = 'channelPinsUpdate', + ChannelUpdate = 'channelUpdate', ClientReady = 'clientReady', + Debug = 'debug', EntitlementCreate = 'entitlementCreate', EntitlementDelete = 'entitlementDelete', EntitlementUpdate = 'entitlementUpdate', + Error = 'error', GuildAuditLogEntryCreate = 'guildAuditLogEntryCreate', GuildAvailable = 'guildAvailable', + GuildBanAdd = 'guildBanAdd', + GuildBanRemove = 'guildBanRemove', GuildCreate = 'guildCreate', GuildDelete = 'guildDelete', - GuildUpdate = 'guildUpdate', - GuildUnavailable = 'guildUnavailable', + GuildEmojiCreate = 'emojiCreate', + GuildEmojiDelete = 'emojiDelete', + GuildEmojiUpdate = 'emojiUpdate', + GuildIntegrationsUpdate = 'guildIntegrationsUpdate', GuildMemberAdd = 'guildMemberAdd', + GuildMemberAvailable = 'guildMemberAvailable', GuildMemberRemove = 'guildMemberRemove', GuildMemberUpdate = 'guildMemberUpdate', - GuildMemberAvailable = 'guildMemberAvailable', GuildMembersChunk = 'guildMembersChunk', - GuildIntegrationsUpdate = 'guildIntegrationsUpdate', GuildRoleCreate = 'roleCreate', GuildRoleDelete = 'roleDelete', + GuildRoleUpdate = 'roleUpdate', + GuildScheduledEventCreate = 'guildScheduledEventCreate', + GuildScheduledEventDelete = 'guildScheduledEventDelete', + GuildScheduledEventUpdate = 'guildScheduledEventUpdate', + GuildScheduledEventUserAdd = 'guildScheduledEventUserAdd', + GuildScheduledEventUserRemove = 'guildScheduledEventUserRemove', + GuildSoundboardSoundCreate = 'guildSoundboardSoundCreate', + GuildSoundboardSoundDelete = 'guildSoundboardSoundDelete', + GuildSoundboardSoundUpdate = 'guildSoundboardSoundUpdate', + GuildSoundboardSoundsUpdate = 'guildSoundboardSoundsUpdate', + GuildStickerCreate = 'stickerCreate', + GuildStickerDelete = 'stickerDelete', + GuildStickerUpdate = 'stickerUpdate', + GuildUnavailable = 'guildUnavailable', + GuildUpdate = 'guildUpdate', + InteractionCreate = 'interactionCreate', + Invalidated = 'invalidated', InviteCreate = 'inviteCreate', InviteDelete = 'inviteDelete', - GuildRoleUpdate = 'roleUpdate', - GuildEmojiCreate = 'emojiCreate', - GuildEmojiDelete = 'emojiDelete', - GuildEmojiUpdate = 'emojiUpdate', - GuildBanAdd = 'guildBanAdd', - GuildBanRemove = 'guildBanRemove', - ChannelCreate = 'channelCreate', - ChannelDelete = 'channelDelete', - ChannelUpdate = 'channelUpdate', - ChannelPinsUpdate = 'channelPinsUpdate', + MessageBulkDelete = 'messageDeleteBulk', MessageCreate = 'messageCreate', MessageDelete = 'messageDelete', - MessageUpdate = 'messageUpdate', - MessageBulkDelete = 'messageDeleteBulk', MessagePollVoteAdd = 'messagePollVoteAdd', MessagePollVoteRemove = 'messagePollVoteRemove', MessageReactionAdd = 'messageReactionAdd', MessageReactionRemove = 'messageReactionRemove', MessageReactionRemoveAll = 'messageReactionRemoveAll', MessageReactionRemoveEmoji = 'messageReactionRemoveEmoji', + MessageUpdate = 'messageUpdate', + PresenceUpdate = 'presenceUpdate', + SoundboardSounds = 'soundboardSounds', + StageInstanceCreate = 'stageInstanceCreate', + StageInstanceDelete = 'stageInstanceDelete', + StageInstanceUpdate = 'stageInstanceUpdate', + SubscriptionCreate = 'subscriptionCreate', + SubscriptionDelete = 'subscriptionDelete', + SubscriptionUpdate = 'subscriptionUpdate', ThreadCreate = 'threadCreate', ThreadDelete = 'threadDelete', - ThreadUpdate = 'threadUpdate', ThreadListSync = 'threadListSync', ThreadMemberUpdate = 'threadMemberUpdate', ThreadMembersUpdate = 'threadMembersUpdate', + ThreadUpdate = 'threadUpdate', + TypingStart = 'typingStart', UserUpdate = 'userUpdate', - PresenceUpdate = 'presenceUpdate', VoiceChannelEffectSend = 'voiceChannelEffectSend', VoiceServerUpdate = 'voiceServerUpdate', VoiceStateUpdate = 'voiceStateUpdate', - TypingStart = 'typingStart', - WebhooksUpdate = 'webhooksUpdate', - InteractionCreate = 'interactionCreate', - Error = 'error', Warn = 'warn', - Debug = 'debug', - CacheSweep = 'cacheSweep', - Invalidated = 'invalidated', - StageInstanceCreate = 'stageInstanceCreate', - StageInstanceUpdate = 'stageInstanceUpdate', - StageInstanceDelete = 'stageInstanceDelete', - SubscriptionCreate = 'subscriptionCreate', - SubscriptionUpdate = 'subscriptionUpdate', - SubscriptionDelete = 'subscriptionDelete', - GuildStickerCreate = 'stickerCreate', - GuildStickerDelete = 'stickerDelete', - GuildStickerUpdate = 'stickerUpdate', - GuildScheduledEventCreate = 'guildScheduledEventCreate', - GuildScheduledEventUpdate = 'guildScheduledEventUpdate', - GuildScheduledEventDelete = 'guildScheduledEventDelete', - GuildScheduledEventUserAdd = 'guildScheduledEventUserAdd', - GuildScheduledEventUserRemove = 'guildScheduledEventUserRemove', - GuildSoundboardSoundCreate = 'guildSoundboardSoundCreate', - GuildSoundboardSoundDelete = 'guildSoundboardSoundDelete', - GuildSoundboardSoundUpdate = 'guildSoundboardSoundUpdate', - GuildSoundboardSoundsUpdate = 'guildSoundboardSoundsUpdate', - SoundboardSounds = 'soundboardSounds', + WebhooksUpdate = 'webhooksUpdate', } export enum ShardEvents { @@ -5490,52 +6227,52 @@ export interface RoleEditOptions extends RoleData { } export interface StageInstanceCreateOptions { - topic: string; + guildScheduledEvent?: GuildScheduledEventResolvable; privacyLevel?: StageInstancePrivacyLevel; sendStartNotification?: boolean; - guildScheduledEvent?: GuildScheduledEventResolvable; + topic: string; } export interface CrosspostedChannel { channelId: Snowflake; guildId: Snowflake; - type: ChannelType; name: string; + type: ChannelType; } export type DateResolvable = Date | number | string; export interface GuildTemplateEditOptions { - name?: string; description?: string; + name?: string; } export interface EmbedField { + inline: boolean; name: string; value: string; - inline: boolean; } export type EmojiIdentifierResolvable = | EmojiResolvable - | `${'' | 'a:'}${string}:${Snowflake}` + | string | `<${'' | 'a'}:${string}:${Snowflake}>` - | string; + | `${'' | 'a:'}${string}:${Snowflake}`; -export type EmojiResolvable = Snowflake | GuildEmoji | ReactionEmoji | ApplicationEmoji; +export type EmojiResolvable = ApplicationEmoji | GuildEmoji | ReactionEmoji | Snowflake; export interface FetchApplicationCommandOptions extends BaseFetchOptions { - id?: Snowflake; guildId?: Snowflake; + id?: Snowflake; locale?: Locale; withLocalizations?: boolean; } export interface FetchArchivedThreadOptions { - type?: 'public' | 'private'; + before?: DateResolvable | ThreadChannelResolvable; fetchAll?: boolean; - before?: ThreadChannelResolvable | DateResolvable; limit?: number; + type?: 'private' | 'public'; } export interface FetchAutoModerationRuleOptions extends BaseFetchOptions { @@ -5551,10 +6288,10 @@ export interface FetchBanOptions extends BaseFetchOptions { } export interface FetchBansOptions { - limit?: number; - before?: Snowflake; after?: Snowflake; + before?: Snowflake; cache?: boolean; + limit?: number; } export interface FetchChannelOptions extends BaseFetchOptions { @@ -5562,8 +6299,8 @@ export interface FetchChannelOptions extends BaseFetchOptions { } export interface FetchedThreads { - threads: ReadonlyCollection; members: ReadonlyCollection; + threads: ReadonlyCollection; } export interface FetchedThreadsMore extends FetchedThreads { @@ -5576,8 +6313,8 @@ export interface FetchGuildOptions extends BaseFetchOptions { } export interface FetchGuildsOptions { - before?: Snowflake; after?: Snowflake; + before?: Snowflake; limit?: number; } @@ -5601,8 +6338,8 @@ export interface FetchInviteOptions extends BaseFetchOptions { } export interface FetchInvitesOptions { - channelId?: GuildInvitableChannelResolvable; cache?: boolean; + channelId?: GuildInvitableChannelResolvable; } export interface FetchMemberOptions extends BaseFetchOptions { @@ -5610,12 +6347,12 @@ export interface FetchMemberOptions extends BaseFetchOptions { } export interface FetchMembersOptions { - user?: UserResolvable | readonly UserResolvable[]; - query?: string; limit?: number; - withPresences?: boolean; - time?: number; nonce?: string; + query?: string; + time?: number; + user?: UserResolvable | readonly UserResolvable[]; + withPresences?: boolean; } export interface FetchMessageOptions extends BaseFetchOptions { @@ -5623,17 +6360,17 @@ export interface FetchMessageOptions extends BaseFetchOptions { } export interface FetchMessagesOptions { - limit?: number; - before?: Snowflake; after?: Snowflake; around?: Snowflake; + before?: Snowflake; cache?: boolean; + limit?: number; } export interface FetchReactionUsersOptions { - type?: ReactionType; - limit?: number; after?: Snowflake; + limit?: number; + type?: ReactionType; } export interface FetchThreadMemberOptions extends BaseFetchOptions { @@ -5646,15 +6383,15 @@ export interface FetchThreadOwnerOptions extends BaseFetchOptions { } export interface FetchThreadMembersWithGuildMemberDataOptions { - withMember: true; after?: Snowflake; - limit?: number; cache?: boolean; + limit?: number; + withMember: true; } export interface FetchThreadMembersWithoutGuildMemberDataOptions { - withMember?: false; cache?: boolean; + withMember?: false; } export type FetchThreadMembersOptions = @@ -5667,8 +6404,8 @@ export interface FetchThreadsOptions { export interface AttachmentPayload { attachment: BufferResolvable | Stream; - name?: string; description?: string; + name?: string; } export type GlobalSweepFilter = () => @@ -5744,7 +6481,7 @@ export type GuildAuditLogsActionType = GuildAuditLogsTypes[keyof GuildAuditLogsT export interface GuildAuditLogsEntryExtraField { [AuditLogEvent.MemberKick]: { integrationType: string } | null; [AuditLogEvent.MemberRoleUpdate]: { integrationType: string } | null; - [AuditLogEvent.MemberPrune]: { removed: number; days: number }; + [AuditLogEvent.MemberPrune]: { days: number; removed: number }; [AuditLogEvent.MemberMove]: { channel: VoiceBasedChannel | { id: Snowflake }; count: number }; [AuditLogEvent.MessageDelete]: { channel: GuildTextBasedChannel | { id: Snowflake }; count: number }; [AuditLogEvent.MessageBulkDelete]: { count: number }; @@ -5752,18 +6489,18 @@ export interface GuildAuditLogsEntryExtraField { [AuditLogEvent.MessageUnpin]: { channel: GuildTextBasedChannel | { id: Snowflake }; messageId: Snowflake }; [AuditLogEvent.MemberDisconnect]: { count: number }; [AuditLogEvent.ChannelOverwriteCreate]: - | Role | GuildMember + | Role | { id: Snowflake; name: string; type: AuditLogOptionsType.Role } | { id: Snowflake; type: AuditLogOptionsType.Member }; [AuditLogEvent.ChannelOverwriteUpdate]: - | Role | GuildMember + | Role | { id: Snowflake; name: string; type: AuditLogOptionsType.Role } | { id: Snowflake; type: AuditLogOptionsType.Member }; [AuditLogEvent.ChannelOverwriteDelete]: - | Role | GuildMember + | Role | { id: Snowflake; name: string; type: AuditLogOptionsType.Role } | { id: Snowflake; type: AuditLogOptionsType.Member }; [AuditLogEvent.StageInstanceCreate]: StageChannel | { id: Snowflake }; @@ -5788,32 +6525,32 @@ export interface GuildAuditLogsEntryExtraField { } export interface GuildAuditLogsEntryTargetField { - User: User | PartialUser | null; + ApplicationCommand: ApplicationCommand | { id: Snowflake }; + AutoModeration: AutoModerationRule; + Channel: NonThreadGuildBasedChannel | { [x: string]: unknown; id: Snowflake }; + Emoji: GuildEmoji | { id: Snowflake }; Guild: Guild; - Webhook: Webhook; + GuildOnboardingPrompt: GuildOnboardingPrompt | { [x: string]: unknown; id: Snowflake }; + GuildScheduledEvent: GuildScheduledEvent; + Integration: Integration; Invite: Invite; - Emoji: GuildEmoji | { id: Snowflake }; - Role: Role | { id: Snowflake }; Message: TAction extends AuditLogEvent.MessageBulkDelete ? GuildTextBasedChannel | { id: Snowflake } : User | null; - Integration: Integration; - Channel: NonThreadGuildBasedChannel | { id: Snowflake; [x: string]: unknown }; - Thread: AnyThreadChannel | { id: Snowflake; [x: string]: unknown }; - StageInstance: StageInstance; - Sticker: Sticker; - GuildScheduledEvent: GuildScheduledEvent; - ApplicationCommand: ApplicationCommand | { id: Snowflake }; - AutoModeration: AutoModerationRule; - GuildOnboardingPrompt: GuildOnboardingPrompt | { id: Snowflake; [x: string]: unknown }; + Role: Role | { id: Snowflake }; // TODO: Update when https://github.com/discordjs/discord.js/pull/10590 is merged SoundboardSound: { id: Snowflake }; + StageInstance: StageInstance; + Sticker: Sticker; + Thread: AnyThreadChannel | { [x: string]: unknown; id: Snowflake }; + User: PartialUser | User | null; + Webhook: Webhook; } export interface GuildAuditLogsFetchOptions { - before?: Snowflake | GuildAuditLogsEntry; - after?: Snowflake | GuildAuditLogsEntry; + after?: GuildAuditLogsEntry | Snowflake; + before?: GuildAuditLogsEntry | Snowflake; limit?: number; - user?: UserResolvable; type?: Event; + user?: UserResolvable; } export type GuildAuditLogsResolvable = AuditLogEvent | null; @@ -5826,18 +6563,18 @@ export type GuildAuditLogsTargets = { export type GuildBanResolvable = GuildBan | UserResolvable; -export type GuildChannelResolvable = Snowflake | GuildBasedChannel; +export type GuildChannelResolvable = GuildBasedChannel | Snowflake; export interface AutoModerationRuleCreateOptions { - name: string; - eventType: AutoModerationRuleEventType; - triggerType: AutoModerationRuleTriggerType; - triggerMetadata?: AutoModerationTriggerMetadataOptions; actions: readonly AutoModerationActionOptions[]; enabled?: boolean; - exemptRoles?: ReadonlyCollection | readonly RoleResolvable[]; + eventType: AutoModerationRuleEventType; exemptChannels?: ReadonlyCollection | readonly GuildChannelResolvable[]; + exemptRoles?: ReadonlyCollection | readonly RoleResolvable[]; + name: string; reason?: string; + triggerMetadata?: AutoModerationTriggerMetadataOptions; + triggerType: AutoModerationRuleTriggerType; } export interface AutoModerationRuleEditOptions extends Partial> {} @@ -5845,8 +6582,8 @@ export interface AutoModerationRuleEditOptions extends Partial {} export interface AutoModerationActionOptions { - type: AutoModerationActionType; metadata?: AutoModerationActionMetadataOptions; + type: AutoModerationActionType; } export interface AutoModerationActionMetadataOptions extends Partial> { @@ -5857,11 +6594,11 @@ export interface GuildChannelCreateOptions extends Omit; } @@ -5870,27 +6607,27 @@ export interface GuildChannelCloneOptions extends Omit; defaultAutoArchiveDuration?: ThreadAutoArchiveDuration; - rtcRegion?: string | null; - videoQualityMode?: VideoQualityMode | null; - availableTags?: readonly GuildForumTagData[]; + defaultForumLayout?: ForumLayoutType; defaultReactionEmoji?: DefaultReactionEmoji | null; + defaultSortOrder?: SortOrderType | null; defaultThreadRateLimitPerUser?: number; flags?: ChannelFlagsResolvable; - defaultSortOrder?: SortOrderType | null; - defaultForumLayout?: ForumLayoutType; + lockPermissions?: boolean; + name?: string; + nsfw?: boolean; + parent?: CategoryChannelResolvable | null; + permissionOverwrites?: ReadonlyCollection | readonly OverwriteResolvable[]; + position?: number; + rateLimitPerUser?: number; reason?: string; + rtcRegion?: string | null; + topic?: string | null; + type?: ChannelType.GuildAnnouncement | ChannelType.GuildText; + userLimit?: number; + videoQualityMode?: VideoQualityMode | null; } export interface GuildChannelOverwriteOptions { @@ -5899,88 +6636,88 @@ export interface GuildChannelOverwriteOptions { } export interface GuildCreateOptions { - name: string; - icon?: BufferResolvable | Base64Resolvable | null; - verificationLevel?: GuildVerificationLevel; + afkChannelId?: Snowflake | number; + afkTimeout?: number; + channels?: readonly PartialChannelData[]; defaultMessageNotifications?: GuildDefaultMessageNotifications; explicitContentFilter?: GuildExplicitContentFilter; + icon?: Base64Resolvable | BufferResolvable | null; + name: string; roles?: readonly PartialRoleData[]; - channels?: readonly PartialChannelData[]; - afkChannelId?: Snowflake | number; - afkTimeout?: number; - systemChannelId?: Snowflake | number; systemChannelFlags?: SystemChannelFlagsResolvable; + systemChannelId?: Snowflake | number; + verificationLevel?: GuildVerificationLevel; } export interface GuildWidgetSettings { + channel: AnnouncementChannel | ForumChannel | MediaChannel | TextChannel | VoiceBasedChannel | null; enabled: boolean; - channel: TextChannel | AnnouncementChannel | VoiceBasedChannel | ForumChannel | MediaChannel | null; } export interface GuildEditOptions { - name?: string; - verificationLevel?: GuildVerificationLevel | null; + afkChannel?: VoiceChannelResolvable | null; + afkTimeout?: number; + banner?: Base64Resolvable | BufferResolvable | null; defaultMessageNotifications?: GuildDefaultMessageNotifications | null; + description?: string | null; + discoverySplash?: Base64Resolvable | BufferResolvable | null; explicitContentFilter?: GuildExplicitContentFilter | null; - afkTimeout?: number; - afkChannel?: VoiceChannelResolvable | null; - icon?: BufferResolvable | Base64Resolvable | null; + features?: readonly `${GuildFeature}`[]; + icon?: Base64Resolvable | BufferResolvable | null; + name?: string; owner?: UserResolvable; - splash?: BufferResolvable | Base64Resolvable | null; - discoverySplash?: BufferResolvable | Base64Resolvable | null; - banner?: BufferResolvable | Base64Resolvable | null; - systemChannel?: TextChannelResolvable | null; - systemChannelFlags?: SystemChannelFlagsResolvable; - rulesChannel?: TextChannelResolvable | null; - publicUpdatesChannel?: TextChannelResolvable | null; - safetyAlertsChannel?: TextChannelResolvable | null; preferredLocale?: Locale | null; - features?: readonly `${GuildFeature}`[]; - description?: string | null; premiumProgressBarEnabled?: boolean; + publicUpdatesChannel?: TextChannelResolvable | null; reason?: string; + rulesChannel?: TextChannelResolvable | null; + safetyAlertsChannel?: TextChannelResolvable | null; + splash?: Base64Resolvable | BufferResolvable | null; + systemChannel?: TextChannelResolvable | null; + systemChannelFlags?: SystemChannelFlagsResolvable; + verificationLevel?: GuildVerificationLevel | null; } export interface GuildEmojiCreateOptions { - attachment: BufferResolvable | Base64Resolvable; + attachment: Base64Resolvable | BufferResolvable; name: string; - roles?: ReadonlyCollection | readonly RoleResolvable[]; reason?: string; + roles?: ReadonlyCollection | readonly RoleResolvable[]; } export interface GuildEmojiEditOptions { name?: string; - roles?: ReadonlyCollection | readonly RoleResolvable[]; reason?: string; + roles?: ReadonlyCollection | readonly RoleResolvable[]; } export interface GuildStickerCreateOptions { - file: BufferResolvable | Stream | AttachmentPayload | JSONEncodable; - name: string; - tags: string; description?: string | null; + file: AttachmentPayload | BufferResolvable | JSONEncodable | Stream; + name: string; reason?: string; + tags: string; } export interface GuildStickerEditOptions { - name?: string; description?: string | null; - tags?: string; + name?: string; reason?: string; + tags?: string; } export interface GuildMemberEditOptions { - nick?: string | null; - roles?: ReadonlyCollection | readonly RoleResolvable[]; - mute?: boolean; - deaf?: boolean; channel?: GuildVoiceChannelResolvable | null; communicationDisabledUntil?: DateResolvable | null; + deaf?: boolean; flags?: GuildMemberFlagsResolvable; + mute?: boolean; + nick?: string | null; reason?: string; + roles?: ReadonlyCollection | readonly RoleResolvable[]; } -export type GuildResolvable = Guild | NonThreadGuildBasedChannel | GuildMember | GuildEmoji | Invite | Role | Snowflake; +export type GuildResolvable = Guild | GuildEmoji | GuildMember | Invite | NonThreadGuildBasedChannel | Role | Snowflake; export interface GuildPruneMembersOptions { count?: boolean; @@ -5991,43 +6728,42 @@ export interface GuildPruneMembersOptions { } export interface GuildWidgetSettingsData { + channel: AnnouncementChannel | ForumChannel | MediaChannel | Snowflake | TextChannel | VoiceBasedChannel | null; enabled: boolean; - channel: TextChannel | AnnouncementChannel | VoiceBasedChannel | ForumChannel | MediaChannel | Snowflake | null; } export interface GuildSearchMembersOptions { - query: string; - limit?: number; cache?: boolean; + limit?: number; + query: string; } export interface GuildListMembersOptions { after?: Snowflake; - limit?: number; cache?: boolean; -} - -// TODO: use conditional types for better TS support -export interface GuildScheduledEventCreateOptions { - name: string; - scheduledStartTime: DateResolvable; - scheduledEndTime?: DateResolvable; - privacyLevel: GuildScheduledEventPrivacyLevel; - entityType: GuildScheduledEventEntityType; - description?: string; + limit?: number; +} + +// TODO: use conditional types for better TS support +export interface GuildScheduledEventCreateOptions { channel?: GuildVoiceChannelResolvable; + description?: string; entityMetadata?: GuildScheduledEventEntityMetadataOptions; - image?: BufferResolvable | Base64Resolvable | null; + entityType: GuildScheduledEventEntityType; + image?: Base64Resolvable | BufferResolvable | null; + name: string; + privacyLevel: GuildScheduledEventPrivacyLevel; reason?: string; recurrenceRule?: GuildScheduledEventRecurrenceRuleOptions; + scheduledEndTime?: DateResolvable; + scheduledStartTime: DateResolvable; } export type GuildScheduledEventRecurrenceRuleOptions = | BaseGuildScheduledEventRecurrenceRuleOptions< - GuildScheduledEventRecurrenceRuleFrequency.Yearly, + GuildScheduledEventRecurrenceRuleFrequency.Daily | GuildScheduledEventRecurrenceRuleFrequency.Weekly, { - byMonth: readonly GuildScheduledEventRecurrenceRuleMonth[]; - byMonthDay: readonly number[]; + byWeekday: readonly GuildScheduledEventRecurrenceRuleWeekday[]; } > | BaseGuildScheduledEventRecurrenceRuleOptions< @@ -6037,28 +6773,29 @@ export type GuildScheduledEventRecurrenceRuleOptions = } > | BaseGuildScheduledEventRecurrenceRuleOptions< - GuildScheduledEventRecurrenceRuleFrequency.Weekly | GuildScheduledEventRecurrenceRuleFrequency.Daily, + GuildScheduledEventRecurrenceRuleFrequency.Yearly, { - byWeekday: readonly GuildScheduledEventRecurrenceRuleWeekday[]; + byMonth: readonly GuildScheduledEventRecurrenceRuleMonth[]; + byMonthDay: readonly number[]; } >; type BaseGuildScheduledEventRecurrenceRuleOptions< Frequency extends GuildScheduledEventRecurrenceRuleFrequency, Extra extends {}, -> = { - startAt: DateResolvable; - interval: number; +> = Extra & { frequency: Frequency; -} & Extra; + interval: number; + startAt: DateResolvable; +}; export interface GuildScheduledEventEditOptions< Status extends GuildScheduledEventStatus, AcceptableStatus extends GuildScheduledEventSetStatusArg, > extends Omit, 'channel' | 'recurrenceRule'> { channel?: GuildVoiceChannelResolvable | null; - status?: AcceptableStatus; recurrenceRule?: GuildScheduledEventRecurrenceRuleOptions | null; + status?: AcceptableStatus; } export interface GuildScheduledEventEntityMetadata { @@ -6070,8 +6807,8 @@ export interface GuildScheduledEventEntityMetadataOptions { } export type GuildScheduledEventManagerFetchResult< - Options extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions | FetchGuildScheduledEventsOptions, -> = Options extends GuildScheduledEventResolvable | FetchGuildScheduledEventOptions + Options extends FetchGuildScheduledEventOptions | FetchGuildScheduledEventsOptions | GuildScheduledEventResolvable, +> = Options extends FetchGuildScheduledEventOptions | GuildScheduledEventResolvable ? GuildScheduledEvent : Collection; @@ -6081,7 +6818,7 @@ export type GuildScheduledEventManagerFetchSubscribersResult< ? Collection> : Collection>; -export type GuildScheduledEventResolvable = Snowflake | GuildScheduledEvent; +export type GuildScheduledEventResolvable = GuildScheduledEvent | Snowflake; export type GuildScheduledEventSetStatusArg = Status extends GuildScheduledEventStatus.Scheduled @@ -6092,61 +6829,61 @@ export type GuildScheduledEventSetStatusArg { guildScheduledEventId: Snowflake; - user: User; member: WithMember extends true ? GuildMember : null; + user: User; } export type GuildTemplateResolvable = string; -export type GuildVoiceChannelResolvable = VoiceBasedChannel | Snowflake; +export type GuildVoiceChannelResolvable = Snowflake | VoiceBasedChannel; export interface GuildOnboardingEditOptions { - prompts?: readonly GuildOnboardingPromptData[] | ReadonlyCollection; - defaultChannels?: readonly ChannelResolvable[] | ReadonlyCollection; + defaultChannels?: ReadonlyCollection | readonly ChannelResolvable[]; enabled?: boolean; mode?: GuildOnboardingMode; + prompts?: ReadonlyCollection | readonly GuildOnboardingPromptData[]; reason?: string; } export interface GuildOnboardingPromptData { id?: Snowflake; - title: string; - singleSelect?: boolean; - required?: boolean; inOnboarding?: boolean; + options: ReadonlyCollection | readonly GuildOnboardingPromptOptionData[]; + required?: boolean; + singleSelect?: boolean; + title: string; type?: GuildOnboardingPromptType; - options: readonly GuildOnboardingPromptOptionData[] | ReadonlyCollection; } export interface GuildOnboardingPromptOptionData { + channels?: ReadonlyCollection | readonly ChannelResolvable[]; + description?: string | null; + emoji?: Emoji | EmojiIdentifierResolvable | null; id?: Snowflake | null; - channels?: readonly ChannelResolvable[] | ReadonlyCollection; - roles?: readonly RoleResolvable[] | ReadonlyCollection; + roles?: ReadonlyCollection | readonly RoleResolvable[]; title: string; - description?: string | null; - emoji?: EmojiIdentifierResolvable | Emoji | null; } export type HexColorString = `#${string}`; export interface IncidentActions { - invitesDisabledUntil: Date | null; - dmsDisabledUntil: Date | null; dmSpamDetectedAt: Date | null; + dmsDisabledUntil: Date | null; + invitesDisabledUntil: Date | null; raidDetectedAt: Date | null; } export interface IncidentActionsEditOptions { - invitesDisabledUntil?: DateResolvable | null | undefined; dmsDisabledUntil?: DateResolvable | null | undefined; + invitesDisabledUntil?: DateResolvable | null | undefined; } export interface IntegrationAccount { - id: string | Snowflake; + id: Snowflake | string; name: string; } -export type IntegrationType = 'twitch' | 'youtube' | 'discord' | 'guild_subscription'; +export type IntegrationType = 'discord' | 'guild_subscription' | 'twitch' | 'youtube'; export type IntegrationTypesConfigurationParameters = ClientApplicationInstallParams; @@ -6159,13 +6896,13 @@ export type IntegrationTypesConfiguration = Partial< >; export type CollectedInteraction = - | StringSelectMenuInteraction - | UserSelectMenuInteraction - | RoleSelectMenuInteraction - | MentionableSelectMenuInteraction - | ChannelSelectMenuInteraction | ButtonInteraction - | ModalSubmitInteraction; + | ChannelSelectMenuInteraction + | MentionableSelectMenuInteraction + | ModalSubmitInteraction + | RoleSelectMenuInteraction + | StringSelectMenuInteraction + | UserSelectMenuInteraction; export interface InteractionCollectorOptions< Interaction extends CollectedInteraction, @@ -6191,14 +6928,14 @@ export interface InteractionDeferUpdateOptions { } export interface InteractionReplyOptions extends BaseMessageOptionsWithPoll { - tts?: boolean; - withResponse?: boolean; flags?: | BitFieldResolvable< Extract, MessageFlags.Ephemeral | MessageFlags.SuppressEmbeds | MessageFlags.SuppressNotifications > | undefined; + tts?: boolean; + withResponse?: boolean; } export interface InteractionUpdateOptions extends MessageEditOptions { @@ -6206,56 +6943,58 @@ export interface InteractionUpdateOptions extends MessageEditOptions { } export interface InviteGenerationOptions { - permissions?: PermissionResolvable; - guild?: GuildResolvable; disableGuildSelect?: boolean; + guild?: GuildResolvable; + permissions?: PermissionResolvable; scopes: readonly OAuth2Scopes[]; } export type GuildInvitableChannelResolvable = - | TextChannel - | VoiceChannel | AnnouncementChannel - | StageChannel | ForumChannel | MediaChannel - | Snowflake; + | Snowflake + | StageChannel + | TextChannel + | VoiceChannel; export interface InviteCreateOptions { - temporary?: boolean; maxAge?: number; maxUses?: number; - unique?: boolean; reason?: string; targetApplication?: ApplicationResolvable; - targetUser?: UserResolvable; targetType?: InviteTargetType; + targetUser?: UserResolvable; + temporary?: boolean; + unique?: boolean; } export type InviteResolvable = string; export interface LifetimeFilterOptions { - excludeFromSweep?: (value: Value, key: Key, collection: LimitedCollection) => boolean; - getComparisonTimestamp?: (value: Value, key: Key, collection: LimitedCollection) => number; + excludeFromSweep?(value: Value, key: Key, collection: LimitedCollection): boolean; + getComparisonTimestamp?(value: Value, key: Key, collection: LimitedCollection): number; lifetime?: number; } -/** @internal */ +/** + * @internal + */ export interface MakeErrorOptions { - name: string; message: string; + name: string; stack: string; } export type ActionRowComponentOptions = | ButtonComponentData - | StringSelectMenuComponentData - | UserSelectMenuComponentData - | RoleSelectMenuComponentData + | ChannelSelectMenuComponentData | MentionableSelectMenuComponentData - | ChannelSelectMenuComponentData; + | RoleSelectMenuComponentData + | StringSelectMenuComponentData + | UserSelectMenuComponentData; -export type MessageActionRowComponentResolvable = MessageActionRowComponent | ActionRowComponentOptions; +export type MessageActionRowComponentResolvable = ActionRowComponentOptions | MessageActionRowComponent; export interface MessageActivity { partyId?: string; @@ -6263,11 +7002,11 @@ export interface MessageActivity { } export interface BaseButtonComponentData extends BaseComponentData { - type: ComponentType.Button; - style: ButtonStyle; disabled?: boolean; emoji?: ComponentEmojiResolvable; label?: string; + style: ButtonStyle; + type: ComponentType.Button; } export interface LinkButtonComponentData extends BaseButtonComponentData { @@ -6276,8 +7015,8 @@ export interface LinkButtonComponentData extends BaseButtonComponentData { } export interface InteractionButtonComponentData extends BaseButtonComponentData { - style: Exclude; customId: string; + style: Exclude; } export type ButtonComponentData = InteractionButtonComponentData | LinkButtonComponentData; @@ -6293,36 +7032,36 @@ export type CollectedMessageInteraction = >; export interface MessageComponentCollectorOptions - extends Omit, 'channel' | 'message' | 'guild' | 'interactionType'> {} + extends Omit, 'channel' | 'guild' | 'interactionType' | 'message'> {} export interface MessageChannelComponentCollectorOptions extends Omit, 'channel' | 'guild' | 'interactionType'> {} export interface MessageInteractionMetadata { - id: Snowflake; - type: InteractionType; - user: User; authorizingIntegrationOwners: APIAuthorizingIntegrationOwnersMap; - originalResponseMessageId: Snowflake | null; + id: Snowflake; interactedMessageId: Snowflake | null; + originalResponseMessageId: Snowflake | null; triggeringInteractionMetadata: MessageInteractionMetadata | null; + type: InteractionType; + user: User; } export interface MessageMentionsHasOptions { ignoreDirect?: boolean; - ignoreRoles?: boolean; - ignoreRepliedUser?: boolean; ignoreEveryone?: boolean; + ignoreRepliedUser?: boolean; + ignoreRoles?: boolean; } export interface MessageMentionOptions { parse?: readonly MessageMentionTypes[]; + repliedUser?: boolean; roles?: readonly Snowflake[]; users?: readonly Snowflake[]; - repliedUser?: boolean; } -export type MessageMentionTypes = 'roles' | 'users' | 'everyone'; +export type MessageMentionTypes = 'everyone' | 'roles' | 'users'; export interface MessageSnapshot extends Partialize< @@ -6345,21 +7084,21 @@ export interface MessageSnapshot > {} export interface BaseMessageOptions { - content?: string; - embeds?: readonly (JSONEncodable | APIEmbed)[]; allowedMentions?: MessageMentionOptions; + components?: readonly ( + | ActionRowData + | APIActionRowComponent + | JSONEncodable> + )[]; + content?: string; + embeds?: readonly (APIEmbed | JSONEncodable)[]; files?: readonly ( - | BufferResolvable - | Stream - | JSONEncodable | Attachment | AttachmentBuilder | AttachmentPayload - )[]; - components?: readonly ( - | JSONEncodable> - | ActionRowData - | APIActionRowComponent + | BufferResolvable + | JSONEncodable + | Stream )[]; } @@ -6368,16 +7107,16 @@ export interface BaseMessageOptionsWithPoll extends BaseMessageOptions { } export interface BaseMessageCreateOptions extends BaseMessageOptionsWithPoll { - tts?: boolean; - nonce?: string | number; enforceNonce?: boolean; - stickers?: readonly StickerResolvable[]; flags?: | BitFieldResolvable< Extract, MessageFlags.SuppressEmbeds | MessageFlags.SuppressNotifications > | undefined; + nonce?: number | string; + stickers?: readonly StickerResolvable[]; + tts?: boolean; } export interface MessageCreateOptions extends BaseMessageCreateOptions { @@ -6393,8 +7132,8 @@ export interface MessageEditAttachmentData { } export interface MessageEditOptions extends Omit { - content?: string | null; attachments?: readonly (Attachment | MessageEditAttachmentData)[]; + content?: string | null; flags?: BitFieldResolvable, MessageFlags.SuppressEmbeds> | undefined; } @@ -6422,31 +7161,31 @@ export interface BaseSelectMenuComponentData extends BaseComponentData { } export interface StringSelectMenuComponentData extends BaseSelectMenuComponentData { - type: ComponentType.StringSelect; options: readonly SelectMenuComponentOptionData[]; + type: ComponentType.StringSelect; } export interface UserSelectMenuComponentData extends BaseSelectMenuComponentData { - type: ComponentType.UserSelect; defaultValues?: readonly APISelectMenuDefaultValue[]; + type: ComponentType.UserSelect; } export interface RoleSelectMenuComponentData extends BaseSelectMenuComponentData { - type: ComponentType.RoleSelect; defaultValues?: readonly APISelectMenuDefaultValue[]; + type: ComponentType.RoleSelect; } export interface MentionableSelectMenuComponentData extends BaseSelectMenuComponentData { - type: ComponentType.MentionableSelect; defaultValues?: readonly APISelectMenuDefaultValue< SelectMenuDefaultValueType.Role | SelectMenuDefaultValueType.User >[]; + type: ComponentType.MentionableSelect; } export interface ChannelSelectMenuComponentData extends BaseSelectMenuComponentData { - type: ComponentType.ChannelSelect; channelTypes?: readonly ChannelType[]; defaultValues?: readonly APISelectMenuDefaultValue[]; + type: ComponentType.ChannelSelect; } export interface MessageSelectOption { @@ -6471,15 +7210,15 @@ export interface SelectMenuComponentOptionData { } export interface TextInputComponentData extends BaseComponentData { - type: ComponentType.TextInput; customId: string; - style: TextInputStyle; label: string; - minLength?: number; maxLength?: number; + minLength?: number; + placeholder?: string; required?: boolean; + style: TextInputStyle; + type: ComponentType.TextInput; value?: string; - placeholder?: string; } export type MessageTarget = @@ -6493,8 +7232,8 @@ export type MessageTarget = | WebhookClient; export interface MultipleShardRespawnOptions { - shardDelay?: number; respawnDelay?: number; + shardDelay?: number; timeout?: number; } @@ -6507,7 +7246,7 @@ export interface MultipleShardSpawnOptions { export interface BaseOverwriteData { allow?: PermissionResolvable; deny?: PermissionResolvable; - id: UserResolvable | RoleResolvable; + id: RoleResolvable | UserResolvable; type?: OverwriteType; } @@ -6516,12 +7255,12 @@ export interface OverwriteDataWithMandatoryType extends BaseOverwriteData { } export interface OverwriteDataWithOptionalType extends BaseOverwriteData { - id: Exclude; + id: Exclude; } export type OverwriteData = OverwriteDataWithMandatoryType | OverwriteDataWithOptionalType; -export type OverwriteResolvable = PermissionOverwrites | OverwriteData; +export type OverwriteResolvable = OverwriteData | PermissionOverwrites; export type PermissionFlags = Record; @@ -6529,7 +7268,7 @@ export type PermissionOverwriteOptions = Partial; -export type PermissionOverwriteResolvable = UserResolvable | RoleResolvable | PermissionOverwrites; +export type PermissionOverwriteResolvable = PermissionOverwrites | RoleResolvable | UserResolvable; export interface RecursiveReadonlyArray extends ReadonlyArray> {} @@ -6538,27 +7277,27 @@ export interface PartialRecipient { } export interface PresenceData { - status?: PresenceStatusData; - afk?: boolean; activities?: readonly ActivitiesOptions[]; + afk?: boolean; shardId?: number | readonly number[]; + status?: PresenceStatusData; } -export type PresenceResolvable = Presence | UserResolvable | Snowflake; +export type PresenceResolvable = Presence | Snowflake | UserResolvable; export interface PartialChannelData { + bitrate?: number; id?: Snowflake | number; - parentId?: Snowflake | number; - type?: ChannelType.GuildText | ChannelType.GuildVoice | ChannelType.GuildCategory; name: string; - topic?: string | null; nsfw?: boolean; - bitrate?: number; - userLimit?: number; - rtcRegion?: string | null; - videoQualityMode?: VideoQualityMode; + parentId?: Snowflake | number; permissionOverwrites?: readonly PartialOverwriteData[]; rateLimitPerUser?: number; + rtcRegion?: string | null; + topic?: string | null; + type?: ChannelType.GuildCategory | ChannelType.GuildText | ChannelType.GuildVoice; + userLimit?: number; + videoQualityMode?: VideoQualityMode; } export interface PartialEmoji { @@ -6593,21 +7332,20 @@ export interface PartialDMChannel extends Partialize {} export interface PartialMessage - extends Partialize {} + extends Partialize {} export interface PartialMessageReaction extends Partialize {} export interface PartialPoll extends Partialize< Poll, - 'allowMultiselect' | 'layoutType' | 'expiresTimestamp', + 'allowMultiselect' | 'expiresTimestamp' | 'layoutType', null, - 'question' | 'message' | 'answers' + 'answers' | 'message' | 'question' > { - question: { text: null }; - message: PartialMessage; - // eslint-disable-next-line no-restricted-syntax answers: Collection; + message: PartialMessage; + question: { text: null }; } export interface PartialPollAnswer extends Partialize { @@ -6615,17 +7353,17 @@ export interface PartialPollAnswer extends Partialize {} + extends Partialize {} export interface PartialThreadMember extends Partialize {} export interface PartialSoundboardSound extends Partialize {} export interface PartialOverwriteData { - id: Snowflake | number; - type?: OverwriteType; allow?: PermissionResolvable; deny?: PermissionResolvable; + id: Snowflake | number; + type?: OverwriteType; } export interface PartialRoleData extends RoleData { @@ -6645,7 +7383,7 @@ export enum Partials { SoundboardSound, } -export interface PartialUser extends Partialize {} +export interface PartialUser extends Partialize {} export type PresenceStatusData = ClientPresenceStatus | 'invisible'; @@ -6667,44 +7405,44 @@ export interface ResolvedOverwriteOptions { } export interface RoleData { - name?: string; color?: ColorResolvable; hoist?: boolean; - position?: number; - permissions?: PermissionResolvable; + icon?: Base64Resolvable | BufferResolvable | EmojiResolvable | null; mentionable?: boolean; - icon?: BufferResolvable | Base64Resolvable | EmojiResolvable | null; + name?: string; + permissions?: PermissionResolvable; + position?: number; unicodeEmoji?: string | null; } export type RoleMention = '@everyone' | `<@&${Snowflake}>`; export interface RolePosition { - role: RoleResolvable; position: number; + role: RoleResolvable; } export type RoleResolvable = Role | Snowflake; export interface RoleSubscriptionData { + isRenewal: boolean; roleSubscriptionListingId: Snowflake; tierName: string; totalMonthsSubscribed: number; - isRenewal: boolean; } export interface RoleTagData { + availableForPurchase?: true; botId?: Snowflake; + guildConnections?: true; integrationId?: Snowflake; premiumSubscriberRole?: true; subscriptionListingId?: Snowflake; - availableForPurchase?: true; - guildConnections?: true; } export interface SetChannelPositionOptions { - relative?: boolean; reason?: string; + relative?: boolean; } export interface SetParentOptions { @@ -6713,21 +7451,21 @@ export interface SetParentOptions { } export interface SetRolePositionOptions { - relative?: boolean; reason?: string; + relative?: boolean; } export type ShardingManagerMode = 'process' | 'worker'; export interface ShardingManagerOptions { - totalShards?: number | 'auto'; - shardList?: readonly number[] | 'auto'; + execArgv?: readonly string[]; mode?: ShardingManagerMode; respawn?: boolean; - silent?: boolean; shardArgs?: readonly string[]; + shardList?: readonly number[] | 'auto'; + silent?: boolean; token?: string; - execArgv?: readonly string[]; + totalShards?: number | 'auto'; } export interface ShowModalOptions { @@ -6738,35 +7476,35 @@ export interface LaunchActivityOptions { withResponse?: boolean; } -export { Snowflake }; - -export type StageInstanceResolvable = StageInstance | Snowflake; +export type StageInstanceResolvable = Snowflake | StageInstance; export interface StartThreadOptions { - name: string; autoArchiveDuration?: ThreadAutoArchiveDuration; - reason?: string; + name: string; rateLimitPerUser?: number; + reason?: string; } export type ClientStatus = number; -export type StickerResolvable = Sticker | Snowflake; +export type StickerResolvable = Snowflake | Sticker; export type SystemChannelFlagsResolvable = BitFieldResolvable; -export type StageChannelResolvable = StageChannel | Snowflake; +export type StageChannelResolvable = Snowflake | StageChannel; export interface StageInstanceEditOptions { - topic?: string; privacyLevel?: StageInstancePrivacyLevel; + topic?: string; } -/** @internal */ +/** + * @internal + */ export interface SupportingInteractionResolvedData { + channel?: GuildTextBasedChannel; client: Client; guild?: Guild; - channel?: GuildTextBasedChannel; } export type SweeperKey = keyof SweeperDefinitions; @@ -6774,14 +7512,14 @@ export type SweeperKey = keyof SweeperDefinitions; export type CollectionSweepFilter = (value: Value, key: Key, collection: Collection) => boolean; export interface SweepOptions { - interval: number; filter: GlobalSweepFilter; + interval: number; } export interface LifetimeSweepOptions { + filter?: never; interval: number; lifetime: number; - filter?: never; } export interface SweeperDefinitions { @@ -6790,11 +7528,11 @@ export interface SweeperDefinitions { bans: [Snowflake, GuildBan]; emojis: [Snowflake, GuildEmoji]; entitlements: [Snowflake, Entitlement]; - invites: [string, Invite, true]; guildMembers: [Snowflake, GuildMember]; + invites: [string, Invite, true]; messages: [Snowflake, Message, true]; presences: [Snowflake, Presence]; - reactions: [string | Snowflake, MessageReaction]; + reactions: [Snowflake | string, MessageReaction]; stageInstances: [Snowflake, StageInstance]; stickers: [Snowflake, Sticker]; threadMembers: [Snowflake, ThreadMember]; @@ -6805,28 +7543,28 @@ export interface SweeperDefinitions { export type SweeperOptions = { [Key in keyof SweeperDefinitions]?: SweeperDefinitions[Key][2] extends true - ? SweepOptions | LifetimeSweepOptions + ? LifetimeSweepOptions | SweepOptions : SweepOptions; }; export interface LimitedCollectionOptions { + keepOverLimit?(value: Value, key: Key, collection: LimitedCollection): boolean; maxSize?: number; - keepOverLimit?: (value: Value, key: Key, collection: LimitedCollection) => boolean; } export type Channel = + | AnnouncementChannel | CategoryChannel | DMChannel + | ForumChannel + | MediaChannel | PartialDMChannel | PartialGroupDMChannel - | AnnouncementChannel + | PrivateThreadChannel + | PublicThreadChannel | StageChannel | TextChannel - | PublicThreadChannel - | PrivateThreadChannel - | VoiceChannel - | ForumChannel - | MediaChannel; + | VoiceChannel; export type TextBasedChannel = Exclude, ForumChannel | MediaChannel>; @@ -6840,7 +7578,7 @@ export type VoiceBasedChannel = Extract; export type GuildBasedChannel = Extract; -export type SendableChannels = Extract any }>; +export type SendableChannels = Extract; export type CategoryChildChannel = Exclude, CategoryChannel>; @@ -6856,28 +7594,28 @@ export type TextBasedChannelResolvable = Snowflake | TextBasedChannel; export type ThreadChannelResolvable = Snowflake | ThreadChannel; -export type ThreadChannelType = ChannelType.AnnouncementThread | ChannelType.PublicThread | ChannelType.PrivateThread; +export type ThreadChannelType = ChannelType.AnnouncementThread | ChannelType.PrivateThread | ChannelType.PublicThread; export interface GuildTextThreadCreateOptions extends StartThreadOptions { + invitable?: AllowedThreadType extends ChannelType.PrivateThread ? boolean : never; startMessage?: MessageResolvable; type?: AllowedThreadType; - invitable?: AllowedThreadType extends ChannelType.PrivateThread ? boolean : never; } export interface GuildForumThreadCreateOptions extends StartThreadOptions { - message: GuildForumThreadMessageCreateOptions | MessagePayload; appliedTags?: readonly Snowflake[]; + message: GuildForumThreadMessageCreateOptions | MessagePayload; } export interface ThreadEditOptions { - name?: string; + appliedTags?: readonly Snowflake[]; archived?: boolean; autoArchiveDuration?: ThreadAutoArchiveDuration; - rateLimitPerUser?: number; - locked?: boolean; - invitable?: boolean; - appliedTags?: readonly Snowflake[]; flags?: ChannelFlagsResolvable; + invitable?: boolean; + locked?: boolean; + name?: string; + rateLimitPerUser?: number; reason?: string; } @@ -6885,7 +7623,7 @@ export type ThreadMemberResolvable = ThreadMember | UserResolvable; export type UserMention = `<@${Snowflake}>`; -export type UserResolvable = User | Snowflake | Message | GuildMember | ThreadMember; +export type UserResolvable = GuildMember | Message | Snowflake | ThreadMember | User; export interface Vanity { code: string | null; @@ -6915,14 +7653,14 @@ export interface WebhookClientDataURL { export interface WebhookClientOptions extends Pick {} export interface WebhookDeleteOptions { - token?: string; reason?: string; + token?: string; } export interface WebhookEditOptions { - name?: string; avatar?: BufferResolvable | null; - channel?: GuildTextChannelResolvable | VoiceChannel | StageChannel | ForumChannel | MediaChannel; + channel?: ForumChannel | GuildTextChannelResolvable | MediaChannel | StageChannel | VoiceChannel; + name?: string; reason?: string; } @@ -6942,11 +7680,11 @@ export interface WebhookFetchMessageOptions { } export interface WebhookMessageCreateOptions extends Omit { - username?: string; + appliedTags?: readonly Snowflake[]; avatarURL?: string; threadId?: Snowflake; threadName?: string; - appliedTags?: readonly Snowflake[]; + username?: string; withComponents?: boolean; } @@ -6961,78 +7699,78 @@ export interface WidgetChannel { } export interface WelcomeChannelData { + channel: AnnouncementChannel | ForumChannel | MediaChannel | Snowflake | TextChannel; description: string; - channel: TextChannel | AnnouncementChannel | ForumChannel | MediaChannel | Snowflake; emoji?: EmojiIdentifierResolvable; } export interface WelcomeScreenEditOptions { - enabled?: boolean; description?: string; + enabled?: boolean; welcomeChannels?: readonly WelcomeChannelData[]; } export interface ClientApplicationEditOptions { + coverImage?: Base64Resolvable | BufferResolvable | null; customInstallURL?: string; description?: string; - roleConnectionsVerificationURL?: string; - installParams?: ClientApplicationInstallParams; + eventWebhooksStatus?: ApplicationWebhookEventStatus.Disabled | ApplicationWebhookEventStatus.Enabled; + eventWebhooksTypes?: readonly ApplicationWebhookEventType[]; + eventWebhooksURL?: string; flags?: ApplicationFlagsResolvable; - icon?: BufferResolvable | Base64Resolvable | null; - coverImage?: BufferResolvable | Base64Resolvable | null; + icon?: Base64Resolvable | BufferResolvable | null; + installParams?: ClientApplicationInstallParams; interactionsEndpointURL?: string; - eventWebhooksURL?: string; - eventWebhooksStatus?: ApplicationWebhookEventStatus.Enabled | ApplicationWebhookEventStatus.Disabled; - eventWebhooksTypes?: readonly ApplicationWebhookEventType[]; + roleConnectionsVerificationURL?: string; tags?: readonly string[]; } export interface ClientApplicationInstallParams { - scopes: readonly OAuth2Scopes[]; permissions: Readonly; + scopes: readonly OAuth2Scopes[]; } -export type Serialized = Value extends symbol | bigint | (() => any) +export type Serialized = Value extends bigint | symbol | (() => any) ? never - : Value extends number | string | boolean | undefined + : Value extends boolean | number | string | undefined ? Value : Value extends JSONEncodable ? JSONResult - : Value extends ReadonlyArray + : Value extends readonly (infer ItemType)[] ? Serialized[] : Value extends ReadonlyMap | ReadonlySet ? {} : { [K in keyof Value]: Serialized }; -//#endregion +// #endregion -//#region Voice +// #region Voice /** - * @internal Use `DiscordGatewayAdapterLibraryMethods` from `@discordjs/voice` instead. + * @internal */ export interface InternalDiscordGatewayAdapterLibraryMethods { + destroy(): void; onVoiceServerUpdate(data: GatewayVoiceServerUpdateDispatchData): void; onVoiceStateUpdate(data: GatewayVoiceStateUpdateDispatchData): void; - destroy(): void; } /** - * @internal Use `DiscordGatewayAdapterImplementerMethods` from `@discordjs/voice` instead. + * @internal */ export interface InternalDiscordGatewayAdapterImplementerMethods { - sendPayload(payload: unknown): boolean; destroy(): void; + sendPayload(payload: unknown): boolean; } /** - * @internal Use `DiscordGatewayAdapterCreator` from `@discordjs/voice` instead. + * @internal */ export type InternalDiscordGatewayAdapterCreator = ( methods: InternalDiscordGatewayAdapterLibraryMethods, ) => InternalDiscordGatewayAdapterImplementerMethods; -//#endregion +// #endregion // External export * from 'discord-api-types/v10'; @@ -7041,3 +7779,5 @@ export * from '@discordjs/formatters'; export * from '@discordjs/rest'; export * from '@discordjs/util'; export * from '@discordjs/ws'; + +export type { Snowflake } from 'discord-api-types/v10'; From 5b7485bb4208143f3ca06fe2cb3da93a21f8d8a5 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 02:22:14 +0200 Subject: [PATCH 03/38] fix: lint --- eslint.config.js | 10 + packages/discord.js/package.json | 2 +- packages/discord.js/tsconfig.eslint.json | 5 +- packages/discord.js/typings/index.d.ts | 5 - packages/discord.js/typings/index.test-d.ts | 950 +++++++++--------- packages/discord.js/typings/rawDataTypes.d.ts | 34 +- 6 files changed, 496 insertions(+), 510 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index f2c04c14ba92..3368f94d4414 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -157,6 +157,16 @@ export default tseslint.config( 'unicorn/consistent-function-scoping': 0, }, }, + { + files: [`packages/discord.js/**/*{ts,d.ts,mts,cts}`], + rules: { + 'n/prefer-global/buffer': 0, + 'no-restricted-globals': 0, + '@typescript-eslint/no-unsafe-declaration-merging': 0, + '@typescript-eslint/no-empty-object-type': 0, + '@typescript-eslint/no-use-before-define': 0, + }, + }, { files: [`packages/rest/**/*${commonFiles}`], rules: { diff --git a/packages/discord.js/package.json b/packages/discord.js/package.json index 4e83ed0728bb..e3fa50f7ee4f 100644 --- a/packages/discord.js/package.json +++ b/packages/discord.js/package.json @@ -7,7 +7,7 @@ "test": "pnpm run docs:test && pnpm run test:typescript", "test:typescript": "tsc --noEmit && tsd", "lint": "prettier --check . && tslint typings/index.d.ts && cross-env TIMING=1 eslint --format=pretty src typings", - "format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src", + "format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src typings", "fmt": "pnpm run format", "docs": "docgen -i \"./src/*.js\" \"./src/**/*.js\" -c ./docs/index.json -r ../../ -o ./docs/docs.json && pnpm run docs:new", "docs:test": "docgen -i \"./src/*.js\" \"./src/**/*.js\" -c ./docs/index.json -r ../../", diff --git a/packages/discord.js/tsconfig.eslint.json b/packages/discord.js/tsconfig.eslint.json index b0baf69334d6..71f4be685f0c 100644 --- a/packages/discord.js/tsconfig.eslint.json +++ b/packages/discord.js/tsconfig.eslint.json @@ -13,9 +13,8 @@ "src/**/*.js", "src/**/*.cjs", "src/**/*.mjs", - "typings/*.d.ts", - "typings/*.d.mts", - "typings/*.test-d.ts", + "typings/**/*.d.ts", + "typings/**/*.test-d.ts", "bin", "scripts", "__tests__", diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index 28608b926595..ea0c84468045 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -1,8 +1,3 @@ -/* eslint-disable n/prefer-global/buffer */ -/* eslint-disable no-restricted-globals */ -/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ -/* eslint-disable @typescript-eslint/no-empty-object-type */ -/* eslint-disable @typescript-eslint/no-use-before-define */ import type { ChildProcess } from 'node:child_process'; import type { Stream } from 'node:stream'; import type { MessagePort, Worker } from 'node:worker_threads'; diff --git a/packages/discord.js/typings/index.test-d.ts b/packages/discord.js/typings/index.test-d.ts index 4e41a80fd7ee..5b759ea25f3c 100644 --- a/packages/discord.js/typings/index.test-d.ts +++ b/packages/discord.js/typings/index.test-d.ts @@ -1,6 +1,12 @@ +/* eslint-disable @typescript-eslint/unbound-method */ +/* eslint-disable @typescript-eslint/ban-ts-comment */ +/* eslint-disable no-param-reassign */ +/* eslint-disable id-length */ import type { ChildProcess } from 'node:child_process'; import type { Worker } from 'node:worker_threads'; -import { +import type { ContextMenuCommandBuilder, ChatInputCommandBuilder } from '@discordjs/builders'; +import type { ReadonlyCollection } from '@discordjs/collection'; +import type { APIInteractionGuildMember, APIPartialChannel, APIPartialGuild, @@ -9,28 +15,31 @@ import { APIRole, APIButtonComponent, APISelectMenuComponent, + Locale, + APIEmbed, + APIMessage, + APIStringSelectComponent, + WebhookType, + APIButtonComponentWithCustomId, +} from 'discord-api-types/v10'; +import { ApplicationCommandOptionType, ComponentType, ApplicationCommandPermissionType, ChannelType, InteractionType, GatewayIntentBits, - Locale, PermissionFlagsBits, AuditLogEvent, ButtonStyle, TextInputStyle, - APIEmbed, ApplicationCommandType, - APIMessage, - APIStringSelectComponent, - WebhookType, GuildScheduledEventRecurrenceRuleFrequency, GuildScheduledEventRecurrenceRuleMonth, GuildScheduledEventRecurrenceRuleWeekday, - APIButtonComponentWithCustomId, } from 'discord-api-types/v10'; -import { +import { expectAssignable, expectNotAssignable, expectNotType, expectType } from 'tsd'; +import type { ApplicationCommand, ApplicationCommandData, ApplicationCommandManager, @@ -42,10 +51,8 @@ import { ButtonInteraction, CacheType, CategoryChannel, - Client, ClientApplication, ClientUser, - Collection, ChatInputCommandInteraction, CommandInteractionOption, CommandInteractionOptionResolver, @@ -59,20 +66,16 @@ import { GuildEmojiManager, GuildMember, GuildResolvable, - IntentsBitField, Interaction, InteractionCollector, Message, - AttachmentBuilder, MessageCollector, MessageComponentInteraction, MessageReaction, ModalBuilder, AnnouncementChannel, - Options, PartialTextBasedChannelFields, PartialUser, - PermissionsBitField, ReactionCollector, Role, RoleManager, @@ -82,12 +85,12 @@ import { Snowflake, StageChannel, TextBasedChannelFields, - type TextBasedChannel, - type TextBasedChannelTypes, - type VoiceBasedChannel, - type GuildBasedChannel, - type NonThreadGuildBasedChannel, - type GuildTextBasedChannel, + TextBasedChannel, + TextBasedChannelTypes, + VoiceBasedChannel, + GuildBasedChannel, + NonThreadGuildBasedChannel, + GuildTextBasedChannel, TextChannel, ThreadChannel, ThreadMember, @@ -98,25 +101,19 @@ import { Collector, GuildAuditLogsEntry, GuildAuditLogs, - type AuditLogChange, + AuditLogChange, StageInstance, - ActionRowBuilder, ButtonComponent, StringSelectMenuComponent, RepliableInteraction, ThreadChannelType, - Events, - Status, CategoryChannelChildManager, ActionRowData, MessageActionRowComponentData, PartialThreadMember, ThreadMemberFlagsBitField, ButtonBuilder, - EmbedBuilder, MessageActionRowComponent, - StringSelectMenuBuilder, - TextInputBuilder, TextInputComponent, Embed, GuildBanManager, @@ -131,7 +128,6 @@ import { AnyThreadChannel, ThreadMemberManager, CollectedMessageInteraction, - ShardEvents, Webhook, WebhookClient, InteractionWebhook, @@ -179,7 +175,6 @@ import { PartialGuildMember, PartialMessage, PartialMessageReaction, - resolvePartialEmoji, PartialEmojiOnlyId, Emoji, PartialEmoji, @@ -188,10 +183,6 @@ import { DirectoryChannel, Entitlement, SKU, - UserSelectMenuBuilder, - RoleSelectMenuBuilder, - ChannelSelectMenuBuilder, - MentionableSelectMenuBuilder, UserSelectMenuComponent, RoleSelectMenuComponent, ChannelSelectMenuComponent, @@ -211,26 +202,43 @@ import { PartialPollAnswer, PollAnswer, PollAnswerVoterManager, +} from './index.js'; +import { + Client, + Collection, + IntentsBitField, + AttachmentBuilder, + Options, + PermissionsBitField, + ActionRowBuilder, + Events, + Status, + EmbedBuilder, + StringSelectMenuBuilder, + TextInputBuilder, + ShardEvents, + resolvePartialEmoji, + UserSelectMenuBuilder, + RoleSelectMenuBuilder, + ChannelSelectMenuBuilder, + MentionableSelectMenuBuilder, PrimaryButtonBuilder, resolveColor, createComponentBuilder, } from './index.js'; -import { expectAssignable, expectNotAssignable, expectNotType, expectType } from 'tsd'; -import type { ContextMenuCommandBuilder, ChatInputCommandBuilder } from '@discordjs/builders'; -import { ReadonlyCollection } from '@discordjs/collection'; // Test type transformation: declare const serialize: (value: Value) => Serialized; declare const notPropertyOf: ( value: Value, - property: Property & Exclude, + property: Exclude & Property, ) => void; const client: Client = new Client({ intents: GatewayIntentBits.Guilds, makeCache: Options.cacheWithLimits({ MessageManager: 200, - // @ts-expect-error + // @ts-expect-error doesn't exist Message: 100, GuildMemberManager: { maxSize: 200, @@ -292,7 +300,11 @@ client.on('guildMemberAvailable', ({ client }) => expectType>(clien client.on('guildMemberRemove', member => { expectType>(member.client); - if (member.partial) return expectType(member.joinedAt); + if (member.partial) { + expectType(member.joinedAt); + return; + } + expectType(member.joinedAt); }); @@ -335,7 +347,7 @@ client.on('interactionCreate', async interaction => { expectType>(interaction.client); expectType(interaction.guildId); expectType(interaction.channelId); - expectType(interaction.member); + expectType(interaction.member); if (interaction.type === InteractionType.MessageComponent) { expectType(interaction.channelId); @@ -350,12 +362,12 @@ client.on('interactionCreate', async interaction => { await interaction.reply({ content: 'Hi!', components: [actionRow] }); - // @ts-expect-error - interaction.reply({ content: 'Hi!', components: [[button]] }); + // @ts-expect-error double nested components array + await interaction.reply({ content: 'Hi!', components: [[button]] }); void new ActionRowBuilder({}); - // @ts-expect-error + // @ts-expect-error button as top-level component await interaction.reply({ content: 'Hi!', components: [button] }); await interaction.reply({ @@ -387,7 +399,6 @@ client.on('interactionCreate', async interaction => { if (interaction.inCachedGuild()) { expectNotType(interaction); - return; } }); @@ -401,16 +412,14 @@ client.on('messageCreate', async message => { const { client, channel } = message; // https://github.com/discordjs/discord.js/issues/8545 - { - // These should not throw any errors when comparing messages from any source. - channel.messages.cache.filter(message => message); - (await channel.messages.fetch()).filter(({ author }) => author.id === message.author.id); + // These should not throw any errors when comparing messages from any source. + channel.messages.cache.filter(Boolean); + (await channel.messages.fetch()).filter(({ author }) => author.id === message.author.id); - if (channel.isDMBased()) { - expectType(channel.messages.channel.messages); - } else { - expectType(channel.messages.channel.messages); - } + if (channel.isDMBased()) { + expectType(channel.messages.channel.messages); + } else { + expectType(channel.messages.channel.messages); } if (!message.inGuild() && message.partial) { @@ -462,16 +471,16 @@ client.on('messageCreate', async message => { expectType>(message.channel); expectNotType(message.channel); - // @ts-expect-error - channel.send(); - // @ts-expect-error - client.channels.createMessage(); - // @ts-expect-error - channel.send({ another: 'property' }); - // @ts-expect-error - client.channels.createMessage({ another: 'property' }); - // @ts-expect-error - client.channels.createMessage('string'); + // @ts-expect-error empty message + await channel.send(); + // @ts-expect-error empty message + await client.channels.createMessage(); + // @ts-expect-error unknown property + await channel.send({ another: 'property' }); + // @ts-expect-error unknown property + await client.channels.createMessage({ another: 'property' }); + // @ts-expect-error plain string + await client.channels.createMessage('string'); // Check collector creations. // Verify that buttons interactions are inferred. @@ -508,21 +517,21 @@ client.on('messageCreate', async message => { expectAssignable>(channel.awaitMessageComponent()); expectAssignable>(defaultCollector); - defaultCollector.on('collect', (...args) => expectType<[SelectMenuInteraction | ButtonInteraction]>(args)); - defaultCollector.on('dispose', (...args) => expectType<[SelectMenuInteraction | ButtonInteraction]>(args)); + defaultCollector.on('collect', (...args) => expectType<[ButtonInteraction | SelectMenuInteraction]>(args)); + defaultCollector.on('dispose', (...args) => expectType<[ButtonInteraction | SelectMenuInteraction]>(args)); defaultCollector.on('end', (...args) => - expectType<[ReadonlyCollection, string]>(args), + expectType<[ReadonlyCollection, string]>(args), ); // Verify that additional options don't affect default collector types. - const semiDefaultCollector = message.createMessageComponentCollector({ time: 10000 }); + const semiDefaultCollector = message.createMessageComponentCollector({ time: 10_000 }); expectType>(semiDefaultCollector); - const semiDefaultCollectorChannel = message.createMessageComponentCollector({ time: 10000 }); + const semiDefaultCollectorChannel = message.createMessageComponentCollector({ time: 10_000 }); expectType>(semiDefaultCollectorChannel); // Verify that interaction collector options can't be used. message.createMessageComponentCollector({ - // @ts-expect-error + // @ts-expect-error not a component interactionType: InteractionType.ApplicationCommand, }); @@ -550,14 +559,14 @@ client.on('messageCreate', async message => { }, }); - message.awaitMessageComponent({ + await message.awaitMessageComponent({ filter: i => { expectType(i); return true; }, }); - message.awaitMessageComponent({ + await message.awaitMessageComponent({ componentType: ComponentType.Button, filter: i => { expectType(i); @@ -565,7 +574,7 @@ client.on('messageCreate', async message => { }, }); - message.awaitMessageComponent({ + await message.awaitMessageComponent({ componentType: ComponentType.StringSelect, filter: i => { expectType(i); @@ -576,7 +585,7 @@ client.on('messageCreate', async message => { const webhook = await message.fetchWebhook(); if (webhook.isChannelFollower()) { - expectAssignable(webhook.sourceGuild); + expectAssignable(webhook.sourceGuild); expectAssignable(webhook.sourceChannel); expectType>(webhook); } else if (webhook.isIncoming()) { @@ -584,18 +593,18 @@ client.on('messageCreate', async message => { expectType>(webhook); } - expectNotType(webhook.sourceGuild); + expectNotType(webhook.sourceGuild); expectNotType(webhook.sourceChannel); expectNotType(webhook.token); - channel.awaitMessageComponent({ + await channel.awaitMessageComponent({ filter: i => { expectType>(i); return true; }, }); - channel.awaitMessageComponent({ + await channel.awaitMessageComponent({ componentType: ComponentType.Button, filter: i => { expectType>(i); @@ -603,7 +612,7 @@ client.on('messageCreate', async message => { }, }); - channel.awaitMessageComponent({ + await channel.awaitMessageComponent({ componentType: ComponentType.StringSelect, filter: i => { expectType>(i); @@ -650,7 +659,7 @@ client.on('messageCreate', async message => { const embedData = { description: 'test', color: 0xff0000 }; - client.channels.createMessage(channel, { + await client.channels.createMessage(channel, { components: [row, rawButtonsRow, buttonsRow, rawStringSelectMenuRow, stringSelectRow], embeds: [embed, embedData], }); @@ -674,13 +683,13 @@ client.on('messagePollVoteAdd', async (answer, userId) => { expectNotType(answer.poll); await answer.poll.fetch(); - answer = answer.poll.answers?.get(answer.id) ?? answer; + const response = answer.poll.answers?.get(answer.id) ?? answer; - expectType(answer.voters.cache.get(userId)!); + expectType(response.voters.cache.get(userId)!); } expectType(answer.text); - expectType(answer.emoji); + expectType(answer.emoji); expectType(answer.id); expectType(answer.voteCount!); }); @@ -700,7 +709,7 @@ client.on('messagePollVoteRemove', async (answer, userId) => { } expectType(answer.text); - expectType(answer.emoji); + expectType(answer.emoji); expectType(answer.id); expectType(answer.voteCount!); }); @@ -715,7 +724,11 @@ client.on('messageReactionAdd', async (reaction, { client }) => { } expectType(reaction.count); - if (reaction.message.partial) return expectType(reaction.message.content); + if (reaction.message.partial) { + expectType(reaction.message.content); + return; + } + expectType(reaction.message.content); }); @@ -746,6 +759,7 @@ client.on('presenceUpdate', (oldPresence, { client }) => { declare const slashCommandBuilder: ChatInputCommandBuilder; declare const contextMenuCommandBuilder: ContextMenuCommandBuilder; +declare const guild: Guild; client.on('clientReady', async client => { expectType>(client); @@ -778,7 +792,7 @@ client.on('clientReady', async client => { await globalCommand?.edit({ defaultMemberPermissions: null }); await globalCommand?.setDefaultMemberPermissions(null); - // @ts-expect-error + // @ts-expect-error passing guildId on guild commands await client.guilds.cache.get(testGuildId)?.commands.fetch(guildCommandId, { guildId: testGuildId }); // Test command permissions @@ -828,43 +842,43 @@ client.on('clientReady', async client => { token: 'VeryRealToken', }); - // @ts-expect-error + // @ts-expect-error id on add await globalPermissionsManager?.add({ command: globalCommandId, permissions: [{ type: ApplicationCommandPermissionType.Role, id: testGuildId, permission: true }], token: 'VeryRealToken', }); - // @ts-expect-error + // @ts-expect-error guild permission on global manager await globalPermissionsManager?.has({ command: globalCommandId, permissionId: testGuildId }); - // @ts-expect-error + // @ts-expect-error fetch all from global await globalPermissionsManager?.fetch(); - // @ts-expect-error + // @ts-expect-error fetch global permissions await globalPermissionsManager?.fetch({ command: globalCommandId }); - // @ts-expect-error + // @ts-expect-error remove permission from global await globalPermissionsManager?.remove({ command: globalCommandId, roles: [testGuildId], token: 'VeryRealToken' }); - // @ts-expect-error + // @ts-expect-error remove permission from global await globalPermissionsManager?.remove({ command: globalCommandId, users: [testUserId], token: 'VeryRealToken' }); - // @ts-expect-error + // @ts-expect-error remove permission from global await globalPermissionsManager?.remove({ command: globalCommandId, roles: [testGuildId], users: [testUserId], token: 'VeryRealToken', }); - // @ts-expect-error + // @ts-expect-error set permission from global await globalPermissionsManager?.set({ command: globalCommandId, permissions: [{ type: ApplicationCommandPermissionType.Role, id: testGuildId, permission: true }], token: 'VeryRealToken', }); - // @ts-expect-error + // @ts-expect-error add permission from global await globalPermissionsManager?.add({ guild: testGuildId, permissions: [{ type: ApplicationCommandPermissionType.Role, id: testGuildId, permission: true }], token: 'VeryRealToken', }); - // @ts-expect-error + // @ts-expect-error check permissions from global await globalPermissionsManager?.has({ guild: testGuildId, permissionId: testGuildId }); // @ts-expect-error await globalPermissionsManager?.remove({ guild: testGuildId, roles: [testGuildId], token: 'VeryRealToken' }); @@ -1269,7 +1283,7 @@ client.on('threadMembersUpdate', (addedMembers, removedMembers, thread) => { expectType>(removedMembers.first()!.client); expectType>(thread.client); expectType>(addedMembers); - expectType>(removedMembers); + expectType>(removedMembers); expectType(thread); const left = removedMembers.first(); if (!left) return; @@ -1337,10 +1351,10 @@ client.on('guildCreate', async g => { ], }); - client.channels.createMessage(channel, { components: [row, row2] }); + await client.channels.createMessage(channel, { components: [row, row2] }); } - channel.setName('foo').then(updatedChannel => { + await channel.setName('foo').then(updatedChannel => { console.log(`New channel name: ${updatedChannel.name}`); }); @@ -1377,7 +1391,7 @@ client.on('guildCreate', async g => { expectType]>>(Client.once(client, 'clientReady')); expectAssignable]>>(Client.on(client, 'clientReady')); -client.login('absolutely-valid-token'); +await client.login('absolutely-valid-token'); declare const loggedInClient: Client; expectType(loggedInClient.application); @@ -1395,6 +1409,7 @@ expectType(loggedOutClient.token); expectType(loggedOutClient.uptime); expectType(loggedOutClient.user); +// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression expectType(serialize(undefined)); expectType(serialize(null)); expectType(serialize([1, 2, 3])); @@ -1437,14 +1452,13 @@ declare const threadChannelNotFromForum: ThreadChannel; declare const announcementChannel: AnnouncementChannel; declare const textChannel: TextChannel; declare const voiceChannel: VoiceChannel; -declare const guild: Guild; declare const user: User; declare const guildMember: GuildMember; // Test thread channels' parent inference -expectType(threadChannel.parent); +expectType(threadChannel.parent); expectType(threadChannelFromForum.parent); -expectType(threadChannelNotFromForum.parent); +expectType(threadChannelNotFromForum.parent); // Test whether the structures implement send expectType['send']>(dmChannel.send); @@ -1507,40 +1521,39 @@ declare const applicationCommandData: ApplicationCommandData; declare const applicationCommandOptionData: ApplicationCommandOptionData; declare const applicationCommandResolvable: ApplicationCommandResolvable; declare const applicationCommandManager: ApplicationCommandManager; -{ - type ApplicationCommandScope = ApplicationCommand<{ guild: GuildResolvable }>; - expectType>(applicationCommandManager.create(applicationCommandData)); - expectAssignable>(applicationCommandManager.create(applicationCommandData, '0')); - expectType>( - applicationCommandManager.edit(applicationCommandResolvable, applicationCommandData), - ); - expectType>( - applicationCommandManager.edit(applicationCommandResolvable, applicationCommandData, '0'), - ); - expectType>>( - applicationCommandManager.set([applicationCommandData]), - ); - expectType>>( - applicationCommandManager.set([applicationCommandData] as const, '0'), - ); +type ApplicationCommandScope = ApplicationCommand<{ guild: GuildResolvable }>; - // Test inference of choice values. - if ('choices' in applicationCommandOptionData) { - if (applicationCommandOptionData.type === ApplicationCommandOptionType.String) { - expectType(applicationCommandOptionData.choices[0]!.value); - expectNotType(applicationCommandOptionData.choices[0]!.value); - } +expectType>(applicationCommandManager.create(applicationCommandData)); +expectAssignable>(applicationCommandManager.create(applicationCommandData, '0')); +expectType>( + applicationCommandManager.edit(applicationCommandResolvable, applicationCommandData), +); +expectType>( + applicationCommandManager.edit(applicationCommandResolvable, applicationCommandData, '0'), +); +expectType>>( + applicationCommandManager.set([applicationCommandData]), +); +expectType>>( + applicationCommandManager.set([applicationCommandData] as const, '0'), +); - if (applicationCommandOptionData.type === ApplicationCommandOptionType.Integer) { - expectType(applicationCommandOptionData.choices[0]!.value); - expectNotType(applicationCommandOptionData.choices[0]!.value); - } +// Test inference of choice values. +if ('choices' in applicationCommandOptionData) { + if (applicationCommandOptionData.type === ApplicationCommandOptionType.String) { + expectType(applicationCommandOptionData.choices[0]!.value); + expectNotType(applicationCommandOptionData.choices[0]!.value); + } - if (applicationCommandOptionData.type === ApplicationCommandOptionType.Number) { - expectType(applicationCommandOptionData.choices[0]!.value); - expectNotType(applicationCommandOptionData.choices[0]!.value); - } + if (applicationCommandOptionData.type === ApplicationCommandOptionType.Integer) { + expectType(applicationCommandOptionData.choices[0]!.value); + expectNotType(applicationCommandOptionData.choices[0]!.value); + } + + if (applicationCommandOptionData.type === ApplicationCommandOptionType.Number) { + expectType(applicationCommandOptionData.choices[0]!.value); + expectNotType(applicationCommandOptionData.choices[0]!.value); } } @@ -1550,92 +1563,84 @@ declare const applicationCommandPermissionsManager: ApplicationCommandPermission Guild | null, Snowflake >; -{ - applicationCommandPermissionsManager.add({ permissions: [], token: '' }); - applicationCommandPermissionsManager.add({ permissions: [] as const, token: '' }); - applicationCommandPermissionsManager.set({ permissions: [], token: '' }); - applicationCommandPermissionsManager.set({ permissions: [] as const, token: '' }); - applicationCommandPermissionsManager.remove({ channels: [], roles: [], users: [], token: '' }); - - applicationCommandPermissionsManager.remove({ - channels: [] as const, - roles: [] as const, - users: [] as const, - token: '', - }); -} + +await applicationCommandPermissionsManager.add({ permissions: [], token: '' }); +await applicationCommandPermissionsManager.add({ permissions: [] as const, token: '' }); +await applicationCommandPermissionsManager.set({ permissions: [], token: '' }); +await applicationCommandPermissionsManager.set({ permissions: [] as const, token: '' }); +await applicationCommandPermissionsManager.remove({ channels: [], roles: [], users: [], token: '' }); + +await applicationCommandPermissionsManager.remove({ + channels: [] as const, + roles: [] as const, + users: [] as const, + token: '', +}); declare const chatInputApplicationCommandData: ChatInputApplicationCommandData; -{ - chatInputApplicationCommandData.options = []; - chatInputApplicationCommandData.options = [] as const; -} + +chatInputApplicationCommandData.options = []; +chatInputApplicationCommandData.options = [] as const; declare const applicationCommandChannelOptionData: ApplicationCommandChannelOptionData; declare const applicationCommandChannelOption: ApplicationCommandChannelOption; -{ - applicationCommandChannelOptionData.channelTypes = [] as const; - applicationCommandChannelOptionData.channel_types = [] as const; - applicationCommandChannelOption.channelTypes = [] as const; -} + +applicationCommandChannelOptionData.channelTypes = [] as const; +applicationCommandChannelOptionData.channel_types = [] as const; +applicationCommandChannelOption.channelTypes = [] as const; declare const applicationNonChoiceOptionData: ApplicationCommandOptionData & { type: CommandOptionNonChoiceResolvableType; }; -{ - // Options aren't allowed on this command type. - // @ts-expect-error - applicationNonChoiceOptionData.choices; -} +// Options aren't allowed on this command type. + +// @ts-expect-error +applicationNonChoiceOptionData.choices = []; declare const applicationCommandChoicesData: ApplicationCommandChoicesData; declare const applicationCommandChoicesOption: ApplicationCommandChoicesOption; -{ - applicationCommandChoicesData.choices = []; - applicationCommandChoicesData.choices = [] as const; - applicationCommandChoicesOption.choices = []; - applicationCommandChoicesOption.choices = [] as const; -} + +applicationCommandChoicesData.choices = []; +applicationCommandChoicesData.choices = [] as const; +applicationCommandChoicesOption.choices = []; +applicationCommandChoicesOption.choices = [] as const; declare const applicationCommandSubCommandData: ApplicationCommandSubCommandData; declare const applicationCommandSubCommand: ApplicationCommandSubCommand; -{ - applicationCommandSubCommandData.options = []; - applicationCommandSubCommandData.options = [] as const; - applicationCommandSubCommand.options = []; - applicationCommandSubCommand.options = [] as const; -} + +applicationCommandSubCommandData.options = []; +applicationCommandSubCommandData.options = [] as const; +applicationCommandSubCommand.options = []; +applicationCommandSubCommand.options = [] as const; declare const applicationSubGroupCommandData: ApplicationCommandSubGroupData; declare const applicationCommandSubGroup: ApplicationCommandSubGroup; -{ - expectType(applicationSubGroupCommandData.type); - applicationSubGroupCommandData.options = []; - applicationSubGroupCommandData.options = [] as const; - applicationCommandSubGroup.options = []; - applicationCommandSubGroup.options = [] as const; -} + +expectType(applicationSubGroupCommandData.type); +applicationSubGroupCommandData.options = []; +applicationSubGroupCommandData.options = [] as const; +applicationCommandSubGroup.options = []; +applicationCommandSubGroup.options = [] as const; declare const autoModerationRuleManager: AutoModerationRuleManager; -{ - expectType>(autoModerationRuleManager.fetch('1234567890')); - expectType>(autoModerationRuleManager.fetch({ autoModerationRule: '1234567890' })); - expectType>( - autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', cache: false }), - ); - expectType>( - autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', force: true }), - ); - expectType>( - autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', cache: false, force: true }), - ); - expectType>>(autoModerationRuleManager.fetch()); - expectType>>(autoModerationRuleManager.fetch({})); - expectType>>(autoModerationRuleManager.fetch({ cache: false })); - // @ts-expect-error The `force` option cannot be used alongside fetching all auto moderation rules. - autoModerationRuleManager.fetch({ force: false }); -} + +expectType>(autoModerationRuleManager.fetch('1234567890')); +expectType>(autoModerationRuleManager.fetch({ autoModerationRule: '1234567890' })); +expectType>( + autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', cache: false }), +); +expectType>( + autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', force: true }), +); +expectType>( + autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', cache: false, force: true }), +); +expectType>>(autoModerationRuleManager.fetch()); +expectType>>(autoModerationRuleManager.fetch({})); +expectType>>(autoModerationRuleManager.fetch({ cache: false })); +// @ts-expect-error The `force` option cannot be used alongside fetching all auto moderation rules. +await autoModerationRuleManager.fetch({ force: false }); declare const guildApplicationCommandManager: GuildApplicationCommandManager; expectType>(guildApplicationCommandManager.fetch('0')); @@ -1643,53 +1648,49 @@ expectType>(guildApplicationCommandManager.fetch({ i expectType>>(guildApplicationCommandManager.fetch()); declare const categoryChannelChildManager: CategoryChannelChildManager; -{ - expectType>(categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildVoice })); - expectType>(categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildText })); - expectType>( - categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildAnnouncement }), - ); - expectType>( - categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildStageVoice }), - ); - expectType>(categoryChannelChildManager.create({ name: 'name' })); - expectType>(categoryChannelChildManager.create({ name: 'name' })); -} + +expectType>(categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildVoice })); +expectType>(categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildText })); +expectType>( + categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildAnnouncement }), +); +expectType>( + categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildStageVoice }), +); +expectType>(categoryChannelChildManager.create({ name: 'name' })); +expectType>(categoryChannelChildManager.create({ name: 'name' })); declare const guildChannelManager: GuildChannelManager; -{ - expectType>(guildChannelManager.create({ name: 'name' })); - expectType>(guildChannelManager.create({ name: 'name' })); - expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildVoice })); - expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildCategory })); - expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildText })); - expectType>( - guildChannelManager.create({ name: 'name', type: ChannelType.GuildAnnouncement }), - ); - expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildStageVoice })); - expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildForum })); - expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildMedia })); - expectType>>(guildChannelManager.fetch()); - expectType>>( - guildChannelManager.fetch(undefined, {}), - ); - expectType>(guildChannelManager.fetch('0')); - - const channel = guildChannelManager.cache.first()!; - - if (channel.isTextBased()) { - const { messages } = channel; - const message = await messages.fetch('123'); - expectType(messages); - expectType>>(messages.crosspost('1234567890')); - expectType>>(messages.edit('1234567890', 'text')); - expectType>>(messages.fetch('1234567890')); - expectType>>>(messages.fetchPinned()); - expectType(message.guild); - expectType(message.guildId); - expectType(message.channel.messages.channel); - } +expectType>(guildChannelManager.create({ name: 'name' })); +expectType>(guildChannelManager.create({ name: 'name' })); +expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildVoice })); +expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildCategory })); +expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildText })); +expectType>( + guildChannelManager.create({ name: 'name', type: ChannelType.GuildAnnouncement }), +); +expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildStageVoice })); +expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildForum })); +expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildMedia })); + +expectType>>(guildChannelManager.fetch()); +expectType>>(guildChannelManager.fetch(undefined, {})); +expectType>(guildChannelManager.fetch('0')); + +const channel = guildChannelManager.cache.first()!; + +if (channel.isTextBased()) { + const { messages } = channel; + const message = await messages.fetch('123'); + expectType(messages); + expectType>>(messages.crosspost('1234567890')); + expectType>>(messages.edit('1234567890', 'text')); + expectType>>(messages.fetch('1234567890')); + expectType>>>(messages.fetchPinned()); + expectType(message.guild); + expectType(message.guildId); + expectType(message.channel.messages.channel); } { @@ -1701,7 +1702,7 @@ declare const guildChannelManager: GuildChannelManager; expectType>>(messages.fetchPinned()); expectType(message.guild); expectType(message.guildId); - expectType(message.channel.messages.channel); + expectType(message.channel.messages.channel); expectType(message.mentions); expectType(message.mentions.guild); expectType | null>(message.mentions.members); @@ -1716,68 +1717,64 @@ declare const guildChannelManager: GuildChannelManager; } declare const threadManager: ThreadManager; -{ - expectType>(threadManager.fetch('12345678901234567')); - expectType>(threadManager.fetch('12345678901234567', { cache: true, force: false })); - expectType>(threadManager.fetch()); - expectType>(threadManager.fetch({})); - expectType>(threadManager.fetch({ archived: { limit: 4 } })); - - // @ts-expect-error The force option has no effect here. - threadManager.fetch({ archived: {} }, { force: true }); -} + +expectType>(threadManager.fetch('12345678901234567')); +expectType>(threadManager.fetch('12345678901234567', { cache: true, force: false })); +expectType>(threadManager.fetch()); +expectType>(threadManager.fetch({})); +expectType>(threadManager.fetch({ archived: { limit: 4 } })); + +// @ts-expect-error The force option has no effect here. +await threadManager.fetch({ archived: {} }, { force: true }); declare const guildForumThreadManager: GuildForumThreadManager; expectType(guildForumThreadManager.channel); declare const guildTextThreadManager: GuildTextThreadManager< - ChannelType.PublicThread | ChannelType.PrivateThread | ChannelType.AnnouncementThread + ChannelType.AnnouncementThread | ChannelType.PrivateThread | ChannelType.PublicThread >; -expectType(guildTextThreadManager.channel); +expectType(guildTextThreadManager.channel); declare const guildMemberManager: GuildMemberManager; -{ - expectType>(guildMemberManager.fetch('12345678901234567')); - expectType>(guildMemberManager.fetch({ user: '12345678901234567' })); - expectType>(guildMemberManager.fetch({ user: '12345678901234567', cache: true, force: false })); - expectType>(guildMemberManager.fetch({ user: '12345678901234567', cache: true, force: false })); - expectType>>(guildMemberManager.fetch()); - expectType>>(guildMemberManager.fetch({})); - expectType>>(guildMemberManager.fetch({ user: ['12345678901234567'] })); - expectType>>(guildMemberManager.fetch({ withPresences: false })); - expectType>(guildMemberManager.fetch({ user: '12345678901234567', withPresences: true })); - - expectType>>( - guildMemberManager.fetch({ query: 'test', user: ['12345678901234567'], nonce: 'test' }), - ); - // @ts-expect-error The cache & force options have no effect here. - guildMemberManager.fetch({ cache: true, force: false }); - // @ts-expect-error The force option has no effect here. - guildMemberManager.fetch({ user: ['12345678901234567'], cache: true, force: false }); -} +expectType>(guildMemberManager.fetch('12345678901234567')); +expectType>(guildMemberManager.fetch({ user: '12345678901234567' })); +expectType>(guildMemberManager.fetch({ user: '12345678901234567', cache: true, force: false })); +expectType>(guildMemberManager.fetch({ user: '12345678901234567', cache: true, force: false })); +expectType>>(guildMemberManager.fetch()); +expectType>>(guildMemberManager.fetch({})); +expectType>>(guildMemberManager.fetch({ user: ['12345678901234567'] })); +expectType>>(guildMemberManager.fetch({ withPresences: false })); +expectType>(guildMemberManager.fetch({ user: '12345678901234567', withPresences: true })); + +expectType>>( + guildMemberManager.fetch({ query: 'test', user: ['12345678901234567'], nonce: 'test' }), +); + +// @ts-expect-error The cache & force options have no effect here. +await guildMemberManager.fetch({ cache: true, force: false }); +// @ts-expect-error The force option has no effect here. +await guildMemberManager.fetch({ user: ['12345678901234567'], cache: true, force: false }); declare const messageManager: MessageManager; -{ - expectType>(messageManager.fetch('1234567890')); - expectType>(messageManager.fetch({ message: '1234567890' })); - expectType>(messageManager.fetch({ message: '1234567890', cache: true, force: false })); - expectType>>(messageManager.fetch()); - expectType>>(messageManager.fetch({})); - expectType>>( - messageManager.fetch({ limit: 100, before: '1234567890', cache: false }), - ); - // @ts-expect-error - messageManager.fetch({ cache: true, force: false }); - // @ts-expect-error - messageManager.fetch({ message: '1234567890', after: '1234567890', cache: true, force: false }); -} + +expectType>(messageManager.fetch('1234567890')); +expectType>(messageManager.fetch({ message: '1234567890' })); +expectType>(messageManager.fetch({ message: '1234567890', cache: true, force: false })); +expectType>>(messageManager.fetch()); +expectType>>(messageManager.fetch({})); +expectType>>( + messageManager.fetch({ limit: 100, before: '1234567890', cache: false }), +); +// @ts-expect-error +await messageManager.fetch({ cache: true, force: false }); +// @ts-expect-error +await messageManager.fetch({ message: '1234567890', after: '1234567890', cache: true, force: false }); declare const pollAnswerVoterManager: PollAnswerVoterManager; -{ - expectType>>(pollAnswerVoterManager.fetch()); - expectType(pollAnswerVoterManager.answer); -} + +expectType>>(pollAnswerVoterManager.fetch()); +expectType(pollAnswerVoterManager.answer); declare const roleManager: RoleManager; expectType>>(roleManager.fetch()); @@ -1795,46 +1792,42 @@ expectType>>(applicationEmojiMan expectType>(applicationEmojiManager.fetch('0')); declare const guildBanManager: GuildBanManager; -{ - expectType>(guildBanManager.fetch('1234567890')); - expectType>(guildBanManager.fetch({ user: '1234567890' })); - expectType>(guildBanManager.fetch({ user: '1234567890', cache: true, force: false })); - expectType>>(guildBanManager.fetch()); - expectType>>(guildBanManager.fetch({})); - expectType>>(guildBanManager.fetch({ limit: 100, before: '1234567890' })); - // @ts-expect-error - guildBanManager.fetch({ cache: true, force: false }); - // @ts-expect-error - guildBanManager.fetch({ user: '1234567890', after: '1234567890', cache: true, force: false }); -} + +expectType>(guildBanManager.fetch('1234567890')); +expectType>(guildBanManager.fetch({ user: '1234567890' })); +expectType>(guildBanManager.fetch({ user: '1234567890', cache: true, force: false })); +expectType>>(guildBanManager.fetch()); +expectType>>(guildBanManager.fetch({})); +expectType>>(guildBanManager.fetch({ limit: 100, before: '1234567890' })); +// @ts-expect-error +await guildBanManager.fetch({ cache: true, force: false }); +// @ts-expect-error +await guildBanManager.fetch({ user: '1234567890', after: '1234567890', cache: true, force: false }); declare const threadMemberWithGuildMember: ThreadMember; declare const threadMemberManager: ThreadMemberManager; -{ - expectType>(threadMemberManager.fetch('12345678')); - expectType>(threadMemberManager.fetch({ member: '12345678', cache: false })); - expectType>(threadMemberManager.fetch({ member: '12345678', force: true })); - expectType>>(threadMemberManager.fetch({ member: threadMemberWithGuildMember })); - expectType>>(threadMemberManager.fetch({ member: '12345678901234567', withMember: true })); - expectType>>(threadMemberManager.fetch()); - expectType>>(threadMemberManager.fetch({})); - - expectType>>>( - threadMemberManager.fetch({ cache: true, limit: 50, withMember: true, after: '12345678901234567' }), - ); - expectType>>( - threadMemberManager.fetch({ cache: true, withMember: false }), - ); +expectType>(threadMemberManager.fetch('12345678')); +expectType>(threadMemberManager.fetch({ member: '12345678', cache: false })); +expectType>(threadMemberManager.fetch({ member: '12345678', force: true })); +expectType>>(threadMemberManager.fetch({ member: threadMemberWithGuildMember })); +expectType>>(threadMemberManager.fetch({ member: '12345678901234567', withMember: true })); +expectType>>(threadMemberManager.fetch()); +expectType>>(threadMemberManager.fetch({})); - // @ts-expect-error The `force` option cannot be used alongside fetching all thread members. - threadMemberManager.fetch({ cache: true, force: false }); - // @ts-expect-error `withMember` needs to be `true` to receive paginated results. - threadMemberManager.fetch({ withMember: false, limit: 5, after: '12345678901234567' }); -} +expectType>>>( + threadMemberManager.fetch({ cache: true, limit: 50, withMember: true, after: '12345678901234567' }), +); + +expectType>>(threadMemberManager.fetch({ cache: true, withMember: false })); + +// @ts-expect-error The `force` option cannot be used alongside fetching all thread members. +await threadMemberManager.fetch({ cache: true, force: false }); +// @ts-expect-error `withMember` needs to be `true` to receive paginated results. +await threadMemberManager.fetch({ withMember: false, limit: 5, after: '12345678901234567' }); declare const typing: Typing; -expectType(typing.user); +expectType(typing.user); if (typing.user.partial) expectType(typing.user.username); if (!typing.user.partial) expectType(typing.user.tag); @@ -1860,8 +1853,8 @@ if (interaction.inGuild()) { client.on('interactionCreate', async interaction => { if (interaction.type === InteractionType.MessageComponent) { - expectType(interaction); - expectType(interaction.component); + expectType(interaction); + expectType(interaction.component); expectType(interaction.message); if (interaction.inCachedGuild()) { expectAssignable(interaction); @@ -1923,7 +1916,7 @@ client.on('interactionCreate', async interaction => { ); } else if (interaction.inGuild()) { expectAssignable(interaction); - expectType(interaction.component); + expectType(interaction.component); expectType(interaction.message); expectType(interaction.guild); expectType>(interaction.reply({ content: 'a', withResponse: true })); @@ -2073,9 +2066,9 @@ client.on('interactionCreate', async interaction => { interaction.commandType === ApplicationCommandType.User ) { expectType(interaction.targetUser); - expectType(interaction.targetMember); + expectType(interaction.targetMember); expectType(interaction.options.getUser('user')); - expectType(interaction.options.getMember('user')); + expectType(interaction.options.getMember('user')); if (interaction.inCachedGuild()) { expectType(interaction.targetMember); expectType(interaction.options.getMember('user')); @@ -2083,14 +2076,14 @@ client.on('interactionCreate', async interaction => { expectType(interaction.targetMember); expectType(interaction.options.getMember('user')); } else if (interaction.inGuild()) { - expectType(interaction.targetMember); - expectType(interaction.options.getMember('user')); + expectType(interaction.targetMember); + expectType(interaction.options.getMember('user')); } } if (interaction.type === InteractionType.MessageComponent && interaction.componentType === ComponentType.Button) { expectType(interaction); - expectType(interaction.component); + expectType(interaction.component); expectType(interaction.message); if (interaction.inCachedGuild()) { expectAssignable(interaction); @@ -2106,7 +2099,7 @@ client.on('interactionCreate', async interaction => { expectType>>(interaction.reply({ withResponse: true })); } else if (interaction.inGuild()) { expectAssignable(interaction); - expectType(interaction.component); + expectType(interaction.component); expectType(interaction.message); expectAssignable(interaction.guild); expectType>(interaction.reply({ withResponse: true })); @@ -2118,7 +2111,7 @@ client.on('interactionCreate', async interaction => { interaction.componentType === ComponentType.StringSelect ) { expectType(interaction); - expectType(interaction.component); + expectType(interaction.component); expectType(interaction.message); if (interaction.inCachedGuild()) { expectAssignable(interaction); @@ -2134,7 +2127,7 @@ client.on('interactionCreate', async interaction => { expectType>>(interaction.reply({ withResponse: true })); } else if (interaction.inGuild()) { expectAssignable(interaction); - expectType(interaction.component); + expectType(interaction.component); expectType(interaction.message); expectType(interaction.guild); expectType>(interaction.reply({ withResponse: true })); @@ -2183,7 +2176,7 @@ client.on('interactionCreate', async interaction => { expectType>(interaction.reply({ withResponse: true })); expectType(interaction.options.getMember('test')); - expectType(interaction.options.getChannel('test', true)); + expectType(interaction.options.getChannel('test', true)); expectType(interaction.options.getRole('test', true)); } @@ -2222,7 +2215,7 @@ client.on('interactionCreate', async interaction => { expectType(interaction); // @ts-expect-error No options on primary entry point commands - interaction.options; + interaction.options = []; if (interaction.inCachedGuild()) { expectAssignable(interaction); expectAssignable(interaction.guild); @@ -2295,8 +2288,8 @@ client.on('interactionCreate', async interaction => { if (interaction.isRepliable()) { expectAssignable(interaction); - interaction.reply('test'); - interaction.reply({ withResponse: false }); + await interaction.reply('test'); + await interaction.reply({ withResponse: false }); } if ( @@ -2424,7 +2417,7 @@ expectType al.entries.first()?.extra), ); -expectType>( +expectType>( guild.fetchAuditLogs({ type: AuditLogEvent.MemberKick }).then(al => al.entries.first()?.target), ); expectType>( @@ -2456,18 +2449,18 @@ declare const GuildTextBasedChannel: GuildTextBasedChannel; expectType(TextBasedChannel); expectType< - | ChannelType.GuildText | ChannelType.DM | ChannelType.GroupDM | ChannelType.GuildAnnouncement - | ChannelType.GuildVoice | ChannelType.GuildStageVoice + | ChannelType.GuildText + | ChannelType.GuildVoice | ThreadChannelType >(TextBasedChannelTypes); expectType(VoiceBasedChannel); expectType(GuildBasedChannel); expectType< - CategoryChannel | AnnouncementChannel | StageChannel | TextChannel | VoiceChannel | ForumChannel | MediaChannel + AnnouncementChannel | CategoryChannel | ForumChannel | MediaChannel | StageChannel | TextChannel | VoiceChannel >(NonThreadGuildBasedChannel); expectType(GuildTextBasedChannel); @@ -2489,9 +2482,9 @@ expectType(chatInputInteraction.options.getAttachment('attach declare const modal: ModalBuilder; -chatInputInteraction.showModal(modal); +await chatInputInteraction.showModal(modal); -chatInputInteraction.showModal({ +await chatInputInteraction.showModal({ title: 'abc', custom_id: 'abc', components: [ @@ -2630,7 +2623,7 @@ client.on('guildAuditLogEntryCreate', (auditLogEntry, guild) => { expectType>(guildMember.flags); -declare const emojiResolvable: GuildEmoji | Emoji | string; +declare const emojiResolvable: Emoji | GuildEmoji | string; { const onboarding = await guild.fetchOnboarding(); @@ -2670,9 +2663,9 @@ expectType(partialMessage.type); expectType(partialMessage.system); expectType(partialMessage.pinned); expectType(partialMessage.tts); -expectAssignable(partialMessage.content); -expectAssignable(partialMessage.cleanContent); -expectAssignable(partialMessage.author); +expectAssignable(partialMessage.content); +expectAssignable(partialMessage.cleanContent); +expectAssignable(partialMessage.author); declare const partialMessageReaction: PartialMessageReaction; expectType(partialMessageReaction.partial); @@ -2691,61 +2684,59 @@ expectType(partialUser.tag); expectType(partialUser.discriminator); declare const emoji: Emoji; -{ - expectType(resolvePartialEmoji('12345678901234567')); - expectType(resolvePartialEmoji(emoji)); -} + +expectType(resolvePartialEmoji('12345678901234567')); +expectType(resolvePartialEmoji(emoji)); declare const application: ClientApplication; declare const entitlement: Entitlement; declare const sku: SKU; -{ - expectType>(await application.fetchSKUs()); - expectType>(await application.entitlements.fetch()); - await application.entitlements.fetch({ - guild, - skus: ['12345678901234567', sku], - user, - excludeEnded: true, - limit: 10, - }); +expectType>(await application.fetchSKUs()); +expectType>(await application.entitlements.fetch()); - await application.entitlements.createTest({ sku: '12345678901234567', user }); - await application.entitlements.createTest({ sku, guild }); +await application.entitlements.fetch({ + guild, + skus: ['12345678901234567', sku], + user, + excludeEnded: true, + limit: 10, +}); - await application.entitlements.deleteTest(entitlement); +await application.entitlements.createTest({ sku: '12345678901234567', user }); +await application.entitlements.createTest({ sku, guild }); - await application.entitlements.consume(snowflake); +await application.entitlements.deleteTest(entitlement); - expectType(entitlement.isActive()); +await application.entitlements.consume(snowflake); - if (entitlement.isUserSubscription()) { - expectType(entitlement.userId); - expectType(await entitlement.fetchUser()); - expectType(entitlement.guildId); - expectType(entitlement.guild); +expectType(entitlement.isActive()); - await application.entitlements.deleteTest(entitlement); - } else if (entitlement.isGuildSubscription()) { - expectType(entitlement.guildId); - expectType(entitlement.guild); +if (entitlement.isUserSubscription()) { + expectType(entitlement.userId); + expectType(await entitlement.fetchUser()); + expectType(entitlement.guildId); + expectType(entitlement.guild); - await application.entitlements.deleteTest(entitlement); - } + await application.entitlements.deleteTest(entitlement); +} else if (entitlement.isGuildSubscription()) { + expectType(entitlement.guildId); + expectType(entitlement.guild); - if (entitlement.isTest()) { - expectType(entitlement.startsTimestamp); - expectType(entitlement.endsTimestamp); - expectType(entitlement.startsAt); - expectType(entitlement.endsAt); - } + await application.entitlements.deleteTest(entitlement); +} - client.on(Events.InteractionCreate, async interaction => { - expectType>(interaction.entitlements); - }); +if (entitlement.isTest()) { + expectType(entitlement.startsTimestamp); + expectType(entitlement.endsTimestamp); + expectType(entitlement.startsAt); + expectType(entitlement.endsAt); } +client.on(Events.InteractionCreate, async interaction => { + expectType>(interaction.entitlements); +}); + await client.channels.createMessage('123', { poll: { question: { @@ -2758,25 +2749,24 @@ await client.channels.createMessage('123', { }); declare const partialPoll: PartialPoll; -{ - if (partialPoll.partial) { - expectType(partialPoll.question.text); - expectType(partialPoll.message); - expectType(partialPoll.allowMultiselect); - expectType(partialPoll.layoutType); - expectType(partialPoll.expiresTimestamp); - expectType>(partialPoll.answers); - } + +if (partialPoll.partial) { + expectType(partialPoll.question.text); + expectType(partialPoll.message); + expectType(partialPoll.allowMultiselect); + expectType(partialPoll.layoutType); + expectType(partialPoll.expiresTimestamp); + expectType>(partialPoll.answers); } declare const partialPollAnswer: PartialPollAnswer; -{ - if (partialPollAnswer.partial) { - expectType(partialPollAnswer.poll); - expectType(partialPollAnswer.emoji); - expectType(partialPollAnswer.text); - } + +if (partialPollAnswer.partial) { + expectType(partialPollAnswer.poll); + expectType(partialPollAnswer.emoji); + expectType(partialPollAnswer.text); } + declare const poll: Poll; declare const message: Message; declare const pollData: PollData; @@ -2812,7 +2802,7 @@ expectType>(await client.fetchStickerPacks()) expectType>(await client.fetchStickerPacks({})); expectType(await client.fetchStickerPacks({ packId: snowflake })); -client.on('interactionCreate', interaction => { +client.on('interactionCreate', async interaction => { if (!interaction.channel) { return; } @@ -2822,95 +2812,87 @@ client.on('interactionCreate', interaction => { if (interaction.channel.isSendable()) { expectType(interaction.channel); - interaction.channel.send({ embeds: [] }); + await interaction.channel.send({ embeds: [] }); } }); declare const guildScheduledEventManager: GuildScheduledEventManager; await guildScheduledEventManager.edit(snowflake, { recurrenceRule: null }); -{ - expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, - interval: 1, - byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], - byMonthDay: [4], - // Invalid property - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - }); - - expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, - interval: 1, - byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], - byMonthDay: [4], - // Invalid property - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], - }); - - expectAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, - interval: 1, - byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], - byMonthDay: [4], - }); -} +expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, + interval: 1, + byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], + byMonthDay: [4], + // Invalid property + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], +}); -{ - expectAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Monthly, - interval: 1, - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], - }); +expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, + interval: 1, + byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], + byMonthDay: [4], + // Invalid property + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], +}); - expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Monthly, - interval: 1, - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], - // Invalid property - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - }); -} +expectAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, + interval: 1, + byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], + byMonthDay: [4], +}); -{ - expectAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Weekly, - interval: 1, - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - }); +expectAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Monthly, + interval: 1, + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], +}); - expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Weekly, - interval: 1, - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - // Invalid property - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], - }); -} +expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Monthly, + interval: 1, + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], + // Invalid property + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], +}); -{ - expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Daily, - interval: 1, - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - // Invalid property - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], - }); - - expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Daily, - interval: 1, - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - // Invalid property - byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], - }); -} +expectAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Weekly, + interval: 1, + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], +}); + +expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Weekly, + interval: 1, + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + // Invalid property + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], +}); + +expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Daily, + interval: 1, + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + // Invalid property + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], +}); + +expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Daily, + interval: 1, + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + // Invalid property + byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], +}); diff --git a/packages/discord.js/typings/rawDataTypes.d.ts b/packages/discord.js/typings/rawDataTypes.d.ts index b6c29feb7992..23cf6b0f0dea 100644 --- a/packages/discord.js/typings/rawDataTypes.d.ts +++ b/packages/discord.js/typings/rawDataTypes.d.ts @@ -1,7 +1,7 @@ // These are aggregate types that are used in the typings file but do not exist as actual exported values. // To prevent them from showing up in an editor, they are imported from here instead of exporting them there directly. -import { +import type { APIApplication, APIApplicationCommand, APIApplicationCommandInteraction, @@ -76,31 +76,31 @@ import { Snowflake, APIGuildScheduledEvent, } from 'discord-api-types/v10'; -import { GuildChannel, Guild, PermissionOverwrites } from './index.js'; +import type { GuildChannel, Guild, PermissionOverwrites } from './index.js'; export type RawActivityData = GatewayActivity; export type RawApplicationData = RawClientApplicationData | RawIntegrationApplicationData; -export type RawClientApplicationData = GatewayReadyDispatchData['application'] | APIMessage['application']; +export type RawClientApplicationData = APIMessage['application'] | GatewayReadyDispatchData['application']; export type RawIntegrationApplicationData = APIGuildIntegrationApplication | Partial; export type RawApplicationCommandData = APIApplicationCommand; export type RawChannelData = - | RawGuildChannelData - | RawThreadChannelData | RawDMChannelData - | RawPartialGroupDMChannelData; + | RawGuildChannelData + | RawPartialGroupDMChannelData + | RawThreadChannelData; export type RawDMChannelData = APIChannel | APIInteractionDataResolvedChannel; export type RawGuildChannelData = APIChannel | APIInteractionDataResolvedChannel | Required; export type RawPartialGroupDMChannelData = APIChannel | Required; export type RawThreadChannelData = APIChannel | APIInteractionDataResolvedChannel; export type RawEmojiData = - | RawGuildEmojiData - | RawReactionEmojiData | GatewayActivityEmoji - | Omit, 'animated'>; + | Omit, 'animated'> + | RawGuildEmojiData + | RawReactionEmojiData; export type RawApplicationEmojiData = APIEmoji; export type RawGuildEmojiData = APIEmoji; export type RawReactionEmojiData = APIEmoji | APIPartialEmoji; @@ -109,7 +109,7 @@ export type RawGuildAuditLogData = APIAuditLog; export type RawGuildAuditLogEntryData = APIAuditLogEntry; -export type RawGuildBanData = GatewayGuildBanAddDispatchData | APIBan; +export type RawGuildBanData = APIBan | GatewayGuildBanAddDispatchData; export type RawGuildData = APIGuild | APIUnavailableGuild; export type RawAnonymousGuildData = RawGuildData | RawInviteGuildData; @@ -119,8 +119,8 @@ export type RawOAuth2GuildData = RESTAPIPartialCurrentUserGuild; export type RawGuildMemberData = | APIGuildMember - | APIInteractionGuildMember | APIInteractionDataResolvedGuildMember + | APIInteractionGuildMember | GatewayGuildMemberAddDispatchData | GatewayGuildMemberUpdateDispatchData | Required @@ -153,14 +153,14 @@ export type RawPartialMessageData = GatewayMessageUpdateDispatchData; export type RawAttachmentData = APIAttachment; export type RawMessagePayloadData = - | RESTPostAPIChannelMessageJSONBody | RESTPatchAPIChannelMessageJSONBody - | RESTPostAPIWebhookWithTokenJSONBody + | RESTPatchAPIInteractionFollowupJSONBody + | RESTPatchAPIInteractionOriginalResponseJSONBody | RESTPatchAPIWebhookWithTokenJSONBody + | RESTPostAPIChannelMessageJSONBody | RESTPostAPIInteractionCallbackFormDataBody - | RESTPatchAPIInteractionOriginalResponseJSONBody | RESTPostAPIInteractionFollowupJSONBody - | RESTPatchAPIInteractionFollowupJSONBody; + | RESTPostAPIWebhookWithTokenJSONBody; export type RawMessageReactionData = APIReaction | GatewayMessageReactionAddDispatchData; @@ -174,7 +174,7 @@ export type RawRichPresenceAssets = GatewayActivityAssets; export type RawStageInstanceData = | APIStageInstance - | (Partial & Pick); + | (Partial & Pick); export type RawStickerData = APISticker | APIStickerItem; @@ -197,7 +197,7 @@ export type RawVoiceStateData = APIVoiceState | Omit; export type RawWebhookData = | APIWebhook | RESTGetAPIWebhookWithTokenResult - | (Partial & Required>); + | (Partial & Required>); export type RawWelcomeChannelData = APIGuildWelcomeScreenChannel; From 835366498664b2642903c3c46a37365cb0ba44c0 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 02:34:47 +0200 Subject: [PATCH 04/38] fix: the way we lint --- packages/discord.js/package.json | 4 +- pnpm-lock.yaml | 1021 +++++++----------------------- 2 files changed, 237 insertions(+), 788 deletions(-) diff --git a/packages/discord.js/package.json b/packages/discord.js/package.json index e3fa50f7ee4f..f37156e7e8e6 100644 --- a/packages/discord.js/package.json +++ b/packages/discord.js/package.json @@ -6,7 +6,7 @@ "scripts": { "test": "pnpm run docs:test && pnpm run test:typescript", "test:typescript": "tsc --noEmit && tsd", - "lint": "prettier --check . && tslint typings/index.d.ts && cross-env TIMING=1 eslint --format=pretty src typings", + "lint": "prettier --check . && cross-env TIMING=1 eslint --format=pretty src typings", "format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src typings", "fmt": "pnpm run format", "docs": "docgen -i \"./src/*.js\" \"./src/**/*.js\" -c ./docs/index.json -r ../../ -o ./docs/docs.json && pnpm run docs:new", @@ -89,7 +89,6 @@ "@typescript-eslint/eslint-plugin": "^8.31.0", "@typescript-eslint/parser": "^8.29.0", "cross-env": "^7.0.3", - "dtslint": "4.2.1", "eslint": "^9.25.1", "eslint-formatter-compact": "^8.40.0", "eslint-formatter-pretty": "^5.0.0", @@ -98,7 +97,6 @@ "jest": "29.7.0", "prettier": "^3.5.3", "tsd": "^0.31.2", - "tslint": "6.1.3", "turbo": "^2.5.2", "typescript": "~5.8.3" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0c02207599ba..c422bc75ca06 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1067,19 +1067,16 @@ importers: version: 22.15.2 '@typescript-eslint/eslint-plugin': specifier: ^8.31.0 - version: 8.31.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3))(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3) + version: 8.31.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1)(typescript@5.8.3))(eslint@9.25.1)(typescript@5.8.3) '@typescript-eslint/parser': specifier: ^8.29.0 - version: 8.29.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3) + version: 8.29.0(eslint@9.25.1)(typescript@5.8.3) cross-env: specifier: ^7.0.3 version: 7.0.3 - dtslint: - specifier: 4.2.1 - version: 4.2.1(typescript@5.8.3) eslint: specifier: ^9.25.1 - version: 9.25.1(jiti@2.4.2) + version: 9.25.1 eslint-formatter-compact: specifier: ^8.40.0 version: 8.40.0 @@ -1088,22 +1085,19 @@ importers: version: 5.0.0 eslint-plugin-import: specifier: ^2.31.0 - version: 2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3))(eslint-import-resolver-typescript@4.3.4(eslint-plugin-import-x@4.10.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3))(eslint-plugin-import@2.31.0)(eslint@9.25.1(jiti@2.4.2)))(eslint@9.25.1(jiti@2.4.2)) + version: 2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1)(typescript@5.8.3))(eslint@9.25.1) eslint-plugin-jsdoc: specifier: ^50.6.11 - version: 50.6.11(eslint@9.25.1(jiti@2.4.2)) + version: 50.6.11(eslint@9.25.1) jest: specifier: 29.7.0 - version: 29.7.0(@types/node@22.15.2)(ts-node@10.9.2(@types/node@22.15.2)(typescript@5.8.3)) + version: 29.7.0(@types/node@22.15.2) prettier: specifier: ^3.5.3 version: 3.5.3 tsd: specifier: ^0.31.2 version: 0.31.2 - tslint: - specifier: 6.1.3 - version: 6.1.3(typescript@5.8.3) turbo: specifier: ^2.5.2 version: 2.5.2 @@ -2485,18 +2479,6 @@ packages: resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} - '@definitelytyped/header-parser@0.2.19': - resolution: {integrity: sha512-zu+RxQpUCgorYUQZoyyrRIn9CljL1CeM4qak3NDeMO1r7tjAkodfpAGnVzx/6JR2OUk0tAgwmZxNMSwd9LVgxw==} - engines: {node: '>=18.18.0'} - - '@definitelytyped/typescript-versions@0.1.8': - resolution: {integrity: sha512-iz6q9aTwWW7CzN2g8jFQfZ955D63LA+wdIAKz4+2pCc/7kokmEHie1/jVWSczqLFOlmH+69bWQxIurryBP/sig==} - engines: {node: '>=18.18.0'} - - '@definitelytyped/utils@0.1.8': - resolution: {integrity: sha512-4JINx4Rttha29f50PBsJo48xZXx/He5yaIWJRwVarhYAN947+S84YciHl+AIhQNRPAFkg8+5qFngEGtKxQDWXA==} - engines: {node: '>=18.18.0'} - '@discordjs/node-pre-gyp@0.4.5': resolution: {integrity: sha512-YJOVVZ545x24mHzANfYoy0BJX5PDyeZlpiJjDkUBM/V/Ao7TFX9lcUvCN4nr0tbr5ubeaXxtEBILUrHtTphVeQ==} hasBin: true @@ -3719,9 +3701,6 @@ packages: '@polka/url@1.0.0-next.28': resolution: {integrity: sha512-8LduaNlMZGwdZ6qWrKlfa+2M4gahzFkprZiAt2TF8uS0qQgBizKXpXURqvTJ4WtmupWxaLqjRb2UCTe72mu+Aw==} - '@qiwi/npm-registry-client@8.9.1': - resolution: {integrity: sha512-rZF+mG+NfijR0SHphhTLHRr4aM4gtfdwoAMY6we2VGQam8vkN1cxGG1Lg/Llrj8Dd0Mu6VjdFQRyMMRZxtZR2A==} - '@radix-ui/number@1.0.1': resolution: {integrity: sha512-T5gIdVO2mmPW3NNhjNgEP3cqMXjXL9UbO0BzWcXfvdBs+BohbQxvd/K5hSVKmn9/lbTdsQVKbUcP5WLCwvUbBg==} @@ -7102,10 +7081,6 @@ packages: resolution: {integrity: sha512-GdYO7a61mR0fOlAsvC9/rIHf7L96sBc6dEWzeOu+KAea5bZyQRPIpojrVoI4AXGJS/ycu/fBTdLrUkA4ODrvjw==} engines: {node: '>=18'} - ansi-regex@2.1.1: - resolution: {integrity: sha512-TIGnTpdo+E3+pCyAluZvtED5p5wCqLdezCyhPZzKPcxvFplEt4i+W7OONCKgeZFT3+y5NZZfOOS/Bdcanm1MYA==} - engines: {node: '>=0.10.0'} - ansi-regex@5.0.1: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} @@ -7117,10 +7092,6 @@ packages: ansi-sequence-parser@1.1.1: resolution: {integrity: sha512-vJXt3yiaUL4UU546s3rPXlsry/RnM730G1+HkpKE012AN0sx1eOrxSu95oKDIonskeLTijMgqWZ3uDEe3NFvyg==} - ansi-styles@2.2.1: - resolution: {integrity: sha512-kmCevFghRiWM7HB5zTPULl4r9bVFSWjz62MhqizDGUrq2NWuNMQyuv4tHHoKJHs69M/MF64lEcHdYIocrdWQYA==} - engines: {node: '>=0.10.0'} - ansi-styles@3.2.1: resolution: {integrity: sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==} engines: {node: '>=4'} @@ -7147,9 +7118,6 @@ packages: app-root-dir@1.0.2: resolution: {integrity: sha512-jlpIfsOoNoafl92Sz//64uQHGSyMrD2vYG5d8o2a4qGvyNCvXur7bzIsWtAC/6flI2RYAp3kv8rsfBtaLm7w0g==} - aproba@1.2.0: - resolution: {integrity: sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==} - aproba@2.0.0: resolution: {integrity: sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==} @@ -7157,10 +7125,6 @@ packages: resolution: {integrity: sha512-ixiS0nLNNG5jNQzgZJNoUpBKdo9yTYZMGJ+QgT2jmjR7G7+QHRCc4v6LQ3NgE7EBJq+o0ams3waJwkrlBom8Ig==} engines: {node: '>=14'} - are-we-there-yet@1.1.7: - resolution: {integrity: sha512-nxwy40TuMiUGqMyRHgCSWZ9FM4VAoRP4xUYSTv5ImRog+h9yISPbVH7H8fASCIzYn9wlEv4zvFL7uKDMCFQm3g==} - deprecated: This package is no longer supported. - are-we-there-yet@2.0.0: resolution: {integrity: sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==} engines: {node: '>=10'} @@ -7282,13 +7246,6 @@ packages: asap@2.0.6: resolution: {integrity: sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==} - asn1@0.2.6: - resolution: {integrity: sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==} - - assert-plus@1.0.0: - resolution: {integrity: sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==} - engines: {node: '>=0.8'} - assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} @@ -7349,12 +7306,6 @@ packages: resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} engines: {node: '>= 0.4'} - aws-sign2@0.7.0: - resolution: {integrity: sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==} - - aws4@1.13.2: - resolution: {integrity: sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==} - axe-core@4.10.2: resolution: {integrity: sha512-RE3mdQ7P3FRSe7eqCWoeQ/Z9QXrtniSjp1wUjt5nRC3WIpz5rSCve6o3fsZ2aCpJtrZjSZgjwXAoTO5k4tEI0w==} engines: {node: '>=4'} @@ -7363,12 +7314,6 @@ packages: resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} engines: {node: '>= 0.4'} - b4a@1.6.7: - resolution: {integrity: sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg==} - - babel-code-frame@6.26.0: - resolution: {integrity: sha512-XqYMR2dfdGMW+hd0IUZ2PwK+fGeFkOxZJ0wY+JaQAHzt1Zx8LcvpiZD2NiGkEG8qx0CfkAOr5xt76d1e8vG90g==} - babel-jest@29.7.0: resolution: {integrity: sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -7403,9 +7348,6 @@ packages: balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - bare-events@2.5.4: - resolution: {integrity: sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==} - base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} @@ -7413,9 +7355,6 @@ packages: resolution: {integrity: sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==} engines: {node: '>=10.0.0'} - bcrypt-pbkdf@1.0.2: - resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==} - before-after-hook@3.0.2: resolution: {integrity: sha512-Nik3Sc0ncrMK4UUdXQmAnRtzmNQTAAXmXIopizwZ1W1t8QmfJj+zL4OA2I7XPTPW5z5TDqv4hRo/JzouDJnX3A==} @@ -7490,10 +7429,6 @@ packages: resolution: {integrity: sha512-WDtdLmJvAuNNPzByAYpRo2rF1Mmradw6gvWsQKf63476DDXmomT9zUiGypLcG4ibIM67vhAj8jJRdbmEws2Aqw==} engines: {node: '>=6.14.2'} - builtin-modules@1.1.1: - resolution: {integrity: sha512-wxXCdllwGhI2kCC0MnvTGYTMvnVZTvqgypkiTI8Pa5tcz2i6VqsqwYGgqwXji+4RgCzms6EajE4IxiUH6HH8nQ==} - engines: {node: '>=0.10.0'} - builtin-modules@3.3.0: resolution: {integrity: sha512-zhaCDicdLuWN5UbN5IMnFqNMhNfo919sH85y2/ea+5Yg9TsTkeZxpL+JLbp6cgYFS4sRLp3YV4S6yDuqVWHYOw==} engines: {node: '>=6'} @@ -7502,9 +7437,6 @@ packages: resolution: {integrity: sha512-p1n8zyCkt1BVrKNFymOHjcDSAl7oq/gUvfgULv2EblgpPVQlQr9yHnWjg9IJ2MhfwPqiYqMMrr01OY7yQoK2yA==} engines: {node: '>=18.20'} - builtins@1.0.3: - resolution: {integrity: sha512-uYBjakWipfaO/bXI7E8rq6kpwHRZK5cNYrUv2OzZSI/FvmdMyXJ2tG9dKcjEC5YHmHpUAwsargWIZNWdxb/bnQ==} - bundle-require@5.1.0: resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -7538,10 +7470,6 @@ packages: resolution: {integrity: sha512-4gkeHlFpSKgm3vm2gJN5sPqfmijYRFYCQ6tv5cLw0xVmT6r1z1vd4FNnpuOREco3cBs1G709sZ72LdgddKvL5w==} engines: {node: '>=8'} - cachedir@2.4.0: - resolution: {integrity: sha512-9EtFOZR8g22CL7BWjJ9BUx1+A/djkofnyW3aOXZORNW2kxoUpx2h+uN2cOqwPmFhnpVmxg+KW2OjOSgChTEvsQ==} - engines: {node: '>=6'} - call-bind-apply-helpers@1.0.2: resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} engines: {node: '>= 0.4'} @@ -7590,10 +7518,6 @@ packages: resolution: {integrity: sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==} engines: {node: '>=12'} - chalk@1.1.3: - resolution: {integrity: sha512-U3lRVLMSlsCfjqYPbLyVv11M9CPW4I728d6TCKMAOJueEeB9/8o+eSsMnxPJD+Q+K909sdESg7C+tIkoH6on1A==} - engines: {node: '>=0.10.0'} - chalk@2.4.2: resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==} engines: {node: '>=4'} @@ -7632,9 +7556,6 @@ packages: chardet@0.7.0: resolution: {integrity: sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==} - charm@1.0.2: - resolution: {integrity: sha512-wqW3VdPnlSWT4eRiYX+hcs+C6ViBPUWk1qTCd+37qw9kEm/a5n2qcyQDMBWvSYKN/ctqZzeXNQaeBjOetJJUkw==} - check-error@2.1.1: resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==} engines: {node: '>= 16'} @@ -7723,9 +7644,6 @@ packages: client-only@0.0.1: resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} - cliui@6.0.0: - resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==} - cliui@8.0.1: resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} engines: {node: '>=12'} @@ -7758,10 +7676,6 @@ packages: code-block-writer@10.1.1: resolution: {integrity: sha512-67ueh2IRGst/51p0n6FvPrnRjAGHY5F8xdjkgrYE7DDzpJe6qA07RYQ9VcoUeo5ATOjSOiWpSL3SWBRRbempMw==} - code-point-at@1.1.0: - resolution: {integrity: sha512-RpAVKQA5T63xEj6/giIbUEtZwJ4UFIc3ZtvEkiaUERylqe8xb5IvqcgOurZLahv93CLKfxcw5YI+DZcUBRyLXA==} - engines: {node: '>=0.10.0'} - collapse-white-space@2.1.0: resolution: {integrity: sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==} @@ -7814,9 +7728,6 @@ packages: comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} - command-exists@1.2.9: - resolution: {integrity: sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w==} - command-line-args@5.2.1: resolution: {integrity: sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg==} engines: {node: '>=4.0.0'} @@ -8018,12 +7929,6 @@ packages: core-js-pure@3.41.0: resolution: {integrity: sha512-71Gzp96T9YPk63aUvE5Q5qP+DryB4ZloUZPSOebGM88VNw8VNfvdA7z6kGA8iGOTEzAomsRidp4jXSmUIJsL+Q==} - core-util-is@1.0.2: - resolution: {integrity: sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==} - - core-util-is@1.0.3: - resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==} - cosmiconfig-typescript-loader@6.1.0: resolution: {integrity: sha512-tJ1w35ZRUiM5FeTzT7DtYWAFFv37ZLqSRkGi2oeCK1gPhvaWjkAtfXvLmvE1pRfxxp9aQo6ba/Pvg1dKj05D4g==} engines: {node: '>=v18'} @@ -8129,10 +8034,6 @@ packages: resolution: {integrity: sha512-wAV9QHOsNbwnWdNW2FYvE1P56wtgSbM+3SZcdGiWQILwVjACCXDCI3Ai8QlCjMDB8YK5zySiXZYBiwGmNY3lnw==} engines: {node: '>=12'} - dashdash@1.14.1: - resolution: {integrity: sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==} - engines: {node: '>=0.10'} - data-uri-to-buffer@6.0.2: resolution: {integrity: sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==} engines: {node: '>= 14'} @@ -8296,10 +8197,6 @@ packages: resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} - diff@3.5.0: - resolution: {integrity: sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==} - engines: {node: '>=0.3.1'} - diff@4.0.2: resolution: {integrity: sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==} engines: {node: '>=0.3.1'} @@ -8348,20 +8245,6 @@ packages: resolution: {integrity: sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==} engines: {node: '>=12'} - dts-critic@3.3.11: - resolution: {integrity: sha512-HMO2f9AO7ge44YO8OK18f+cxm/IaE1CFuyNFbfJRCEbyazWj5X5wWDF6W4CGdo5Ax0ILYVfJ7L/rOwuUN1fzWw==} - engines: {node: '>=10.17.0'} - peerDependencies: - typescript: '*' - - dtslint@4.2.1: - resolution: {integrity: sha512-57mWY9osUEfS6k62ATS9RSgug1dZcuN4O31hO76u+iEexa6VUEbKoPGaA2mNtc0FQDcdTl0zEUtti79UQKSQyQ==} - engines: {node: '>=10.0.0'} - deprecated: See https://aka.ms/type-testing-tools - hasBin: true - peerDependencies: - typescript: '>= 3.0.0-dev || >= 3.1.0-dev || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.7.0-dev || >= 3.8.0-dev || >= 3.9.0-dev || >= 4.0.0-dev' - dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -8372,9 +8255,6 @@ packages: eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} - ecc-jsbn@0.1.2: - resolution: {integrity: sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==} - edge-runtime@2.5.9: resolution: {integrity: sha512-pk+k0oK0PVXdlT4oRp4lwh+unuKB7Ng4iZ2HB+EZ7QCEQizX360Rp/F4aRpgpRgdP2ufB35N+1KppHmYjqIGSg==} engines: {node: '>=16'} @@ -9052,19 +8932,12 @@ packages: resolution: {integrity: sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==} engines: {node: '>=4'} - extsprintf@1.3.0: - resolution: {integrity: sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==} - engines: {'0': node >=0.6.0} - fast-content-type-parse@2.0.0: resolution: {integrity: sha512-fCqg/6Sps8tqk8p+kqyKqYfOF0VjPNYrqpLiqNl0RBKmD80B080AJWVV6EkSkscjToNExcXg1+Mfzftrx6+iSA==} fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} - fast-fifo@1.3.2: - resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==} - fast-glob@3.3.1: resolution: {integrity: sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==} engines: {node: '>=8.6.0'} @@ -9196,16 +9069,9 @@ packages: resolution: {integrity: sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==} engines: {node: '>=14'} - forever-agent@0.6.1: - resolution: {integrity: sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==} - form-data-encoder@1.7.2: resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==} - form-data@2.3.3: - resolution: {integrity: sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==} - engines: {node: '>= 0.12'} - form-data@4.0.1: resolution: {integrity: sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==} engines: {node: '>= 6'} @@ -9254,9 +9120,6 @@ packages: resolution: {integrity: sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew==} engines: {node: '>=14.14'} - fs-extra@6.0.1: - resolution: {integrity: sha512-GnyIkKhhzXZUWFCaJzvyDLEEgDkPfb4/TPvJCJVuS8MWZgoSsErf++QpiAlDnKFcqhRlm+tIOcencCjyJE6ZCA==} - fs-extra@7.0.1: resolution: {integrity: sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==} engines: {node: '>=6 <7 || >=8'} @@ -9343,10 +9206,6 @@ packages: functions-have-names@1.2.3: resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} - gauge@2.7.4: - resolution: {integrity: sha512-14x4kjc6lkD3ltw589k0NrPD6cCNTD6CWoVUNpB85+DrtONoZn+Rug6xZU5RvSC4+TZPxA5AnBibQYAvZn41Hg==} - deprecated: This package is no longer supported. - gauge@3.0.2: resolution: {integrity: sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==} engines: {node: '>=10'} @@ -9412,9 +9271,6 @@ packages: resolution: {integrity: sha512-E1b1lFFLvLgak2whF2xDBcOy6NLVGZBqqjJjsIhvopKfWWEi64pLVTWWehV8KlLerZkfNTA95sTe2OdJKm1OzQ==} engines: {node: '>= 14'} - getpass@0.1.7: - resolution: {integrity: sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==} - git-cliff-darwin-arm64@2.7.0: resolution: {integrity: sha512-8D6Zxk9onts9r16yzuJEUq4ixGMJYvUI47GujUbs3ifsXB7x8SCOX7QCwmylRkZKnRC95fZ3jwi+gy95SwVaPQ==} cpu: [arm64] @@ -9555,23 +9411,10 @@ packages: engines: {node: '>=0.4.7'} hasBin: true - har-schema@2.0.0: - resolution: {integrity: sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==} - engines: {node: '>=4'} - - har-validator@5.1.5: - resolution: {integrity: sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==} - engines: {node: '>=6'} - deprecated: this library is no longer supported - hard-rejection@2.1.0: resolution: {integrity: sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA==} engines: {node: '>=6'} - has-ansi@2.0.0: - resolution: {integrity: sha512-C8vBJ8DwUCx19vhm7urhTuUsr4/IyP6l4VzNQDv+ryHQObW3TTTp9yB68WpYgRe2bbaGuZ/se74IqFeVnMnLZg==} - engines: {node: '>=0.10.0'} - has-bigints@1.1.0: resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} engines: {node: '>= 0.4'} @@ -9680,10 +9523,6 @@ packages: resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} engines: {node: '>= 14'} - http-signature@1.2.0: - resolution: {integrity: sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==} - engines: {node: '>=0.8', npm: '>=1.3.7'} - https-proxy-agent@5.0.1: resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} engines: {node: '>= 6'} @@ -9924,10 +9763,6 @@ packages: resolution: {integrity: sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==} engines: {node: '>= 0.4'} - is-fullwidth-code-point@1.0.0: - resolution: {integrity: sha512-1pqUqRjkhPJ9miNq9SwMfdvi6lBJcd6eFxvfaivQhaH3SgisfiuudvFntdKOmxuee/77l+FPjKrQjWvmPjWrRw==} - engines: {node: '>=0.10.0'} - is-fullwidth-code-point@3.0.0: resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} engines: {node: '>=8'} @@ -10041,9 +9876,6 @@ packages: resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} engines: {node: '>= 0.4'} - is-typedarray@1.0.0: - resolution: {integrity: sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==} - is-unicode-supported@0.1.0: resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} engines: {node: '>=10'} @@ -10078,9 +9910,6 @@ packages: isarray@0.0.1: resolution: {integrity: sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==} - isarray@1.0.0: - resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} - isarray@2.0.5: resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==} @@ -10095,9 +9924,6 @@ packages: resolution: {integrity: sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==} engines: {node: '>=16'} - isstream@0.1.2: - resolution: {integrity: sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==} - istanbul-lib-coverage@3.2.2: resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==} engines: {node: '>=8'} @@ -10298,9 +10124,6 @@ packages: resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} engines: {node: '>=10'} - js-tokens@3.0.2: - resolution: {integrity: sha512-RjTcuD4xjtthQkaWH7dFlH85L+QaVtSoOyGdZ3g6HFhS9dFNDfLyqgm2NFe2X6cQpeFmt0452FJjFG5UameExg==} - js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -10315,9 +10138,6 @@ packages: js2xmlparser@4.0.2: resolution: {integrity: sha512-6n4D8gLlLf1n5mNLQPRfViYzu9RATblzPEtm1SthMX1Pjao0r9YI9nw7ZIfRxQMERS87mcswrg+r/OYrPRX6jA==} - jsbn@0.1.1: - resolution: {integrity: sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==} - jsbn@1.1.0: resolution: {integrity: sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==} @@ -10378,13 +10198,6 @@ packages: json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} - json-stable-stringify@1.2.1: - resolution: {integrity: sha512-Lp6HbbBgosLmJbjx0pBLbgvx68FaFU1sdkmBuckmhhJ88kL13OA51CDtR2yJB50eCNMH9wRqtQNNiAqQH4YXnA==} - engines: {node: '>= 0.4'} - - json-stringify-safe@5.0.1: - resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==} - json5@1.0.2: resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==} hasBin: true @@ -10403,17 +10216,10 @@ packages: jsonfile@6.1.0: resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==} - jsonify@0.0.1: - resolution: {integrity: sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==} - jsonparse@1.3.1: resolution: {integrity: sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==} engines: {'0': node >= 0.2.0} - jsprim@1.4.2: - resolution: {integrity: sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==} - engines: {node: '>=0.6.0'} - jsx-ast-utils@3.3.5: resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==} engines: {node: '>=4.0'} @@ -11316,10 +11122,6 @@ packages: resolution: {integrity: sha512-aDxjFfPV3Liw0WOBWlyZLMBqtbgbg03rmGvHDJa2Ttv7tIz+1oB5qWec4psCDFZcZi9b5XdGkPdQiJxOPzvQRQ==} engines: {node: ^18.17.0 || >=20.5.0} - npm-package-arg@8.1.5: - resolution: {integrity: sha512-LhgZrg0n0VgvzVdSm1oiZworPbTxYHUJCgtsJW8mGvlDpxTM1vSJc3m5QZeUkhAHIzbz3VCHd/R4osi1L1Tg/Q==} - engines: {node: '>=10'} - npm-pick-manifest@9.1.0: resolution: {integrity: sha512-nkc+3pIIhqHVQr085X9d2JzPzLyjzQS96zbruppqC9aZRm/x8xx6xhI98gHtsfELP2bE+loHq8ZaHFHhe+NauA==} engines: {node: ^16.14.0 || >=18.0.0} @@ -11340,10 +11142,6 @@ packages: resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==} engines: {node: '>=18'} - npmlog@4.1.2: - resolution: {integrity: sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==} - deprecated: This package is no longer supported. - npmlog@5.0.1: resolution: {integrity: sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==} deprecated: This package is no longer supported. @@ -11351,10 +11149,6 @@ packages: nth-check@2.1.1: resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} - number-is-nan@1.0.1: - resolution: {integrity: sha512-4jbtZXNAsfZbAHiiqjLPBiCl16dES1zI4Hpzzxw61Tk+loF+sBDBKx1ICKKKwIqQ7M0mFn1TmkN7euSncWgHiQ==} - engines: {node: '>=0.10.0'} - nuqs@2.4.3: resolution: {integrity: sha512-BgtlYpvRwLYiJuWzxt34q2bXu/AIS66sLU1QePIMr2LWkb+XH0vKXdbLSgn9t6p7QKzwI7f38rX3Wl9llTXQ8Q==} peerDependencies: @@ -11373,9 +11167,6 @@ packages: react-router-dom: optional: true - oauth-sign@0.9.0: - resolution: {integrity: sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==} - object-assign@4.1.1: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} @@ -11676,9 +11467,6 @@ packages: perfect-debounce@1.0.0: resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==} - performance-now@2.1.0: - resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==} - pg-int8@1.0.1: resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} engines: {node: '>=4.0.0'} @@ -11962,9 +11750,6 @@ packages: resolution: {integrity: sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ==} engines: {node: ^18.17.0 || >=20.5.0} - process-nextick-args@2.0.1: - resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==} - process@0.11.10: resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==} engines: {node: '>= 0.6.0'} @@ -12004,9 +11789,6 @@ packages: proxy-from-env@1.1.0: resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} - psl@1.15.0: - resolution: {integrity: sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==} - punycode.js@2.3.1: resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} engines: {node: '>=6'} @@ -12026,10 +11808,6 @@ packages: resolution: {integrity: sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==} engines: {node: '>=0.6'} - qs@6.5.3: - resolution: {integrity: sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==} - engines: {node: '>=0.6'} - quansync@0.2.10: resolution: {integrity: sha512-t41VRkMYbkHyCYmOvx/6URnN80H7k4X0lLdBMGsz+maAwrJQYB1djpV6vHrQIBE0WBSGqhtEHrK9U3DWWH8v7A==} @@ -12170,9 +11948,6 @@ packages: resolution: {integrity: sha512-9viLL4/n1BJUCT1NXVTdS1jtm80yDEgR5T4yCelII49Mbj0v1rZdKqj7zCiYdbB0CuCgdrvHcNogAKTFPBocFA==} engines: {node: '>=18'} - readable-stream@2.3.8: - resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==} - readable-stream@3.6.2: resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} engines: {node: '>= 6'} @@ -12303,11 +12078,6 @@ packages: remark@15.0.1: resolution: {integrity: sha512-Eht5w30ruCXgFmxVUSlNWQ9iiimq07URKeFS3hNc8cUWy1llX4KDWfyEDZRycMc+znsN9Ux5/tJ/BFdgdOwA3A==} - request@2.88.2: - resolution: {integrity: sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==} - engines: {node: '>= 6'} - deprecated: request has been deprecated, see https://github.com/request/request/issues/3142 - require-directory@2.1.1: resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} engines: {node: '>=0.10.0'} @@ -12316,9 +12086,6 @@ packages: resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} engines: {node: '>=0.10.0'} - require-main-filename@2.0.0: - resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==} - requireindex@1.2.0: resolution: {integrity: sha512-L9jEkOi3ASd9PYit2cwRfyppc9NoABujTP8/5gFcbERmo5jUoAKovIC3fsF17pkTnGsrByysqX+Kxd2OTNI1ww==} engines: {node: '>=0.10.5'} @@ -12424,9 +12191,6 @@ packages: resolution: {integrity: sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==} engines: {node: '>=0.4'} - safe-buffer@5.1.2: - resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} - safe-buffer@5.2.1: resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} @@ -12608,9 +12372,6 @@ packages: resolution: {integrity: sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg==} engines: {node: '>=18'} - slide@1.1.6: - resolution: {integrity: sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==} - smart-buffer@4.2.0: resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==} engines: {node: '>= 6.0.0', npm: '>= 3.0.0'} @@ -12689,19 +12450,10 @@ packages: sprintf-js@1.1.3: resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==} - sshpk@1.18.0: - resolution: {integrity: sha512-2p2KJZTSqQ/I3+HX42EpYOa2l3f8Erv8MWKsy2I9uf4wA7yFIkXRffYdsx86y6z4vHtV8u7g+pPlr8/4ouAxsQ==} - engines: {node: '>=0.10.0'} - hasBin: true - ssri@12.0.0: resolution: {integrity: sha512-S7iGNosepx9RadX82oimUkvr0Ct7IjJbEbs4mJcTxst8um95J3sDYU1RBEOvdu6oL1Wek2ODI5i4MAw+dZ6cAQ==} engines: {node: ^18.17.0 || >=20.5.0} - ssri@8.0.1: - resolution: {integrity: sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==} - engines: {node: '>= 8'} - stable-hash@0.0.5: resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==} @@ -12760,9 +12512,6 @@ packages: resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==} engines: {node: '>=10.0.0'} - streamx@2.22.0: - resolution: {integrity: sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==} - string-argv@0.3.2: resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==} engines: {node: '>=0.6.19'} @@ -12771,10 +12520,6 @@ packages: resolution: {integrity: sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==} engines: {node: '>=10'} - string-width@1.0.2: - resolution: {integrity: sha512-0XsVpQLnVCXHJfyEs8tC0zpTVIr5PKKsQtkT29IwupnPTjtPmQ3xT/4yCREF9hYkV/3M3kzcUTSAZT6a6h81tw==} - engines: {node: '>=0.10.0'} - string-width@4.2.3: resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} engines: {node: '>=8'} @@ -12814,19 +12559,12 @@ packages: resolution: {integrity: sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==} engines: {node: '>= 0.4'} - string_decoder@1.1.1: - resolution: {integrity: sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==} - string_decoder@1.3.0: resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} stringify-entities@4.0.4: resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==} - strip-ansi@3.0.1: - resolution: {integrity: sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg==} - engines: {node: '>=0.10.0'} - strip-ansi@6.0.1: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} @@ -12919,10 +12657,6 @@ packages: resolution: {integrity: sha512-qlsr7fIC0lSddmA3tzojvzubYxvlGtzumcdHgPwbFWMISQwL22MhM2Y3LNt+6w9Yyx7559VW5ab70dgphm8qQA==} engines: {node: '>=14.18.0'} - supports-color@2.0.0: - resolution: {integrity: sha512-KKNVtd6pCYgPIKU4cp2733HWYCpplQhddZLBUryaAHou723x+FRzQ5Df824Fj+IyyuiQTRoub4SnIFfIcrp70g==} - engines: {node: '>=0.8.0'} - supports-color@5.5.0: resolution: {integrity: sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==} engines: {node: '>=4'} @@ -12987,9 +12721,6 @@ packages: resolution: {integrity: sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==} engines: {node: '>=6'} - tar-stream@3.1.7: - resolution: {integrity: sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==} - tar@6.2.1: resolution: {integrity: sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==} engines: {node: '>=10'} @@ -13033,9 +12764,6 @@ packages: resolution: {integrity: sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==} engines: {node: '>=4.0.0'} - text-decoder@1.2.3: - resolution: {integrity: sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==} - text-extensions@2.4.0: resolution: {integrity: sha512-te/NtwBwfiNRLf9Ijqx3T0nlqZiQ2XrrtBvu+cLL8ZRrGkO0NHTug8MYFKyoSrv/sHTaSKfilUkizV6XhxMJ3g==} engines: {node: '>=8'} @@ -13108,10 +12836,6 @@ packages: resolution: {integrity: sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==} engines: {node: '>=0.6.0'} - tmp@0.2.3: - resolution: {integrity: sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==} - engines: {node: '>=14.14'} - tmpl@1.0.5: resolution: {integrity: sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==} @@ -13127,10 +12851,6 @@ packages: resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==} engines: {node: '>=6'} - tough-cookie@2.5.0: - resolution: {integrity: sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==} - engines: {node: '>=0.8'} - tr46@0.0.3: resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} @@ -13225,21 +12945,6 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} - tslint@5.14.0: - resolution: {integrity: sha512-IUla/ieHVnB8Le7LdQFRGlVJid2T/gaJe5VkjzRVSRR6pA2ODYrnfR1hmxi+5+au9l50jBwpbBL34txgv4NnTQ==} - engines: {node: '>=4.8.0'} - hasBin: true - peerDependencies: - typescript: '>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >=3.0.0-dev || >= 3.1.0-dev || >= 3.2.0-dev' - - tslint@6.1.3: - resolution: {integrity: sha512-IbR4nkT96EQOvKE2PW/djGz8iGNeJ4rF2mBfiYaR/nvUWYKJhLwimoJKgjIFEIDibBtOevj7BqCRL4oHeWWUCg==} - engines: {node: '>=4.8.0'} - deprecated: TSLint has been deprecated in favor of ESLint. Please see https://github.com/palantir/tslint/issues/4534 for more information. - hasBin: true - peerDependencies: - typescript: '>=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >=3.0.0-dev || >= 3.1.0-dev || >= 3.2.0-dev || >= 4.0.0-dev' - tsup@8.4.0: resolution: {integrity: sha512-b+eZbPCjz10fRryaAA7C8xlIHnf8VnsaRqydheLIqwG/Mcpfk8Z5zp3HayX7GaTygkigHl5cBUs+IhcySiIexQ==} engines: {node: '>=18'} @@ -13266,11 +12971,6 @@ packages: tsutils: ^3.0.0 typescript: '>=4.0.0' - tsutils@2.29.0: - resolution: {integrity: sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==} - peerDependencies: - typescript: '>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev' - tsutils@3.21.0: resolution: {integrity: sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==} engines: {node: '>= 6'} @@ -13282,9 +12982,6 @@ packages: engines: {node: '>=18.0.0'} hasBin: true - tunnel-agent@0.6.0: - resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} - tunnel@0.0.6: resolution: {integrity: sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==} engines: {node: '>=0.6.11 <=0.7.0 || >=0.7.3'} @@ -13326,9 +13023,6 @@ packages: tw-animate-css@1.2.8: resolution: {integrity: sha512-AxSnYRvyFnAiZCUndS3zQZhNfV/B77ZhJ+O7d3K6wfg/jKJY+yv6ahuyXwnyaYA9UdLqnpCwhTRv9pPTBnPR2g==} - tweetnacl@0.14.5: - resolution: {integrity: sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==} - twoslash-protocol@0.3.1: resolution: {integrity: sha512-BMePTL9OkuNISSyyMclBBhV2s9++DiOCyhhCoV5Kaht6eaWLwVjCCUJHY33eZJPsyKeZYS8Wzz0h+XI01VohVw==} @@ -13658,11 +13352,6 @@ packages: deprecated: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. hasBin: true - uuid@3.4.0: - resolution: {integrity: sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==} - deprecated: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. - hasBin: true - uuid@9.0.1: resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==} hasBin: true @@ -13682,9 +13371,6 @@ packages: validate-npm-package-license@3.0.4: resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==} - validate-npm-package-name@3.0.0: - resolution: {integrity: sha512-M6w37eVCMMouJ9V/sdPGnC5H4uDr73/+xdq0FBLO3TFFX1+7wiUY6Es328NN+y43tmY+doUdN9g9J21vqB7iLw==} - validate-npm-package-name@5.0.1: resolution: {integrity: sha512-OljLrQ9SQdOUqTaQxqL5dEfZWrXExyyWsozYlAWFawPVNuD83igl7uJD2RTkNMbniIYgt8l81eCJGIdQF7avLQ==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} @@ -13702,10 +13388,6 @@ packages: engines: {node: '>= 18'} hasBin: true - verror@1.10.0: - resolution: {integrity: sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==} - engines: {'0': node >=0.6.0} - vfile-matter@5.0.0: resolution: {integrity: sha512-jhPSqlj8hTSkTXOqyxbUeZAFFVq/iwu/jukcApEqc/7DOidaAth6rDc0Zgg0vWpzUnWkwFP7aK28l6nBmxMqdQ==} @@ -13882,9 +13564,6 @@ packages: resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==} engines: {node: '>= 0.4'} - which-module@2.0.1: - resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==} - which-typed-array@1.1.19: resolution: {integrity: sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==} engines: {node: '>= 0.4'} @@ -13980,9 +13659,6 @@ packages: xmlcreate@2.0.4: resolution: {integrity: sha512-nquOebG4sngPmGPICTS5EnxqhKbCmz5Ox5hsszI2T6U5qdrJizBc+0ilYSEjTSzU0yZcmvppztXe/5Al5fUwdg==} - y18n@4.0.3: - resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==} - y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} @@ -14002,10 +13678,6 @@ packages: engines: {node: '>= 14'} hasBin: true - yargs-parser@18.1.3: - resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==} - engines: {node: '>=6'} - yargs-parser@20.2.9: resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} engines: {node: '>=10'} @@ -14014,10 +13686,6 @@ packages: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} - yargs@15.4.1: - resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==} - engines: {node: '>=8'} - yargs@17.7.2: resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} engines: {node: '>=12'} @@ -15174,25 +14842,6 @@ snapshots: dependencies: '@jridgewell/trace-mapping': 0.3.9 - '@definitelytyped/header-parser@0.2.19': - dependencies: - '@definitelytyped/typescript-versions': 0.1.8 - '@definitelytyped/utils': 0.1.8 - semver: 7.6.3 - - '@definitelytyped/typescript-versions@0.1.8': {} - - '@definitelytyped/utils@0.1.8': - dependencies: - '@qiwi/npm-registry-client': 8.9.1 - '@types/node': 18.19.87 - cachedir: 2.4.0 - charm: 1.0.2 - minimatch: 9.0.5 - tar: 6.2.1 - tar-stream: 3.1.7 - which: 4.0.0 - '@discordjs/node-pre-gyp@0.4.5(encoding@0.1.13)': dependencies: detect-libc: 2.0.3 @@ -15557,6 +15206,11 @@ snapshots: eslint: 9.25.1(jiti@2.4.2) eslint-visitor-keys: 3.4.3 + '@eslint-community/eslint-utils@4.6.1(eslint@9.25.1)': + dependencies: + eslint: 9.25.1 + eslint-visitor-keys: 3.4.3 + '@eslint-community/regexpp@4.12.1': {} '@eslint/compat@1.2.8(eslint@9.25.1(jiti@2.4.2))': @@ -15849,6 +15503,41 @@ snapshots: jest-util: 29.7.0 slash: 3.0.0 + '@jest/core@29.7.0': + dependencies: + '@jest/console': 29.7.0 + '@jest/reporters': 29.7.0 + '@jest/test-result': 29.7.0 + '@jest/transform': 29.7.0 + '@jest/types': 29.6.3 + '@types/node': 22.15.2 + ansi-escapes: 4.3.2 + chalk: 4.1.2 + ci-info: 3.9.0 + exit: 0.1.2 + graceful-fs: 4.2.11 + jest-changed-files: 29.7.0 + jest-config: 29.7.0(@types/node@22.15.2) + jest-haste-map: 29.7.0 + jest-message-util: 29.7.0 + jest-regex-util: 29.6.3 + jest-resolve: 29.7.0 + jest-resolve-dependencies: 29.7.0 + jest-runner: 29.7.0 + jest-runtime: 29.7.0 + jest-snapshot: 29.7.0 + jest-util: 29.7.0 + jest-validate: 29.7.0 + jest-watcher: 29.7.0 + micromatch: 4.0.8 + pretty-format: 29.7.0 + slash: 3.0.0 + strip-ansi: 6.0.1 + transitivePeerDependencies: + - babel-plugin-macros + - supports-color + - ts-node + '@jest/core@29.7.0(ts-node@10.9.2(@types/node@22.15.2)(typescript@5.5.4))': dependencies: '@jest/console': 29.7.0 @@ -16386,22 +16075,6 @@ snapshots: '@polka/url@1.0.0-next.28': {} - '@qiwi/npm-registry-client@8.9.1': - dependencies: - concat-stream: 2.0.0 - graceful-fs: 4.2.11 - normalize-package-data: 3.0.3 - npm-package-arg: 8.1.5 - once: 1.4.0 - request: 2.88.2 - retry: 0.12.0 - safe-buffer: 5.2.1 - semver: 7.6.3 - slide: 1.1.6 - ssri: 8.0.1 - optionalDependencies: - npmlog: 4.1.2 - '@radix-ui/number@1.0.1': dependencies: '@babel/runtime': 7.27.0 @@ -19884,15 +19557,15 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/eslint-plugin@8.31.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3))(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3)': + '@typescript-eslint/eslint-plugin@8.31.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1)(typescript@5.8.3))(eslint@9.25.1)(typescript@5.8.3)': dependencies: '@eslint-community/regexpp': 4.12.1 - '@typescript-eslint/parser': 8.29.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3) + '@typescript-eslint/parser': 8.29.0(eslint@9.25.1)(typescript@5.8.3) '@typescript-eslint/scope-manager': 8.31.0 - '@typescript-eslint/type-utils': 8.31.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3) - '@typescript-eslint/utils': 8.31.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3) + '@typescript-eslint/type-utils': 8.31.0(eslint@9.25.1)(typescript@5.8.3) + '@typescript-eslint/utils': 8.31.0(eslint@9.25.1)(typescript@5.8.3) '@typescript-eslint/visitor-keys': 8.31.0 - eslint: 9.25.1(jiti@2.4.2) + eslint: 9.25.1 graphemer: 1.4.0 ignore: 5.3.2 natural-compare: 1.4.0 @@ -19941,6 +19614,18 @@ snapshots: transitivePeerDependencies: - supports-color + '@typescript-eslint/parser@8.29.0(eslint@9.25.1)(typescript@5.8.3)': + dependencies: + '@typescript-eslint/scope-manager': 8.29.0 + '@typescript-eslint/types': 8.29.0 + '@typescript-eslint/typescript-estree': 8.29.0(typescript@5.8.3) + '@typescript-eslint/visitor-keys': 8.29.0 + debug: 4.4.0 + eslint: 9.25.1 + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + '@typescript-eslint/scope-manager@5.62.0': dependencies: '@typescript-eslint/types': 5.62.0 @@ -19988,12 +19673,12 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/type-utils@8.31.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3)': + '@typescript-eslint/type-utils@8.31.0(eslint@9.25.1)(typescript@5.8.3)': dependencies: '@typescript-eslint/typescript-estree': 8.31.0(typescript@5.8.3) - '@typescript-eslint/utils': 8.31.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3) + '@typescript-eslint/utils': 8.31.0(eslint@9.25.1)(typescript@5.8.3) debug: 4.4.0 - eslint: 9.25.1(jiti@2.4.2) + eslint: 9.25.1 ts-api-utils: 2.1.0(typescript@5.8.3) typescript: 5.8.3 transitivePeerDependencies: @@ -20218,6 +19903,17 @@ snapshots: transitivePeerDependencies: - supports-color + '@typescript-eslint/utils@8.31.0(eslint@9.25.1)(typescript@5.8.3)': + dependencies: + '@eslint-community/eslint-utils': 4.6.1(eslint@9.25.1) + '@typescript-eslint/scope-manager': 8.31.0 + '@typescript-eslint/types': 8.31.0 + '@typescript-eslint/typescript-estree': 8.31.0(typescript@5.8.3) + eslint: 9.25.1 + typescript: 5.8.3 + transitivePeerDependencies: + - supports-color + '@typescript-eslint/visitor-keys@5.62.0': dependencies: '@typescript-eslint/types': 5.62.0 @@ -21102,16 +20798,12 @@ snapshots: dependencies: environment: 1.1.0 - ansi-regex@2.1.1: {} - ansi-regex@5.0.1: {} ansi-regex@6.1.0: {} ansi-sequence-parser@1.1.1: {} - ansi-styles@2.2.1: {} - ansi-styles@3.2.1: dependencies: color-convert: 1.9.3 @@ -21133,19 +20825,10 @@ snapshots: app-root-dir@1.0.2: {} - aproba@1.2.0: - optional: true - aproba@2.0.0: {} are-docs-informative@0.0.2: {} - are-we-there-yet@1.1.7: - dependencies: - delegates: 1.0.0 - readable-stream: 2.3.8 - optional: true - are-we-there-yet@2.0.0: dependencies: delegates: 1.0.0 @@ -21284,12 +20967,6 @@ snapshots: asap@2.0.6: {} - asn1@0.2.6: - dependencies: - safer-buffer: 2.1.2 - - assert-plus@1.0.0: {} - assertion-error@2.0.1: {} ast-types-flow@0.0.8: {} @@ -21354,22 +21031,10 @@ snapshots: dependencies: possible-typed-array-names: 1.0.0 - aws-sign2@0.7.0: {} - - aws4@1.13.2: {} - axe-core@4.10.2: {} axobject-query@4.1.0: {} - b4a@1.6.7: {} - - babel-code-frame@6.26.0: - dependencies: - chalk: 1.1.3 - esutils: 2.0.3 - js-tokens: 3.0.2 - babel-jest@29.7.0(@babel/core@7.26.10): dependencies: '@babel/core': 7.26.10 @@ -21433,17 +21098,10 @@ snapshots: balanced-match@1.0.2: {} - bare-events@2.5.4: - optional: true - base64-js@1.5.1: {} basic-ftp@5.0.5: {} - bcrypt-pbkdf@1.0.2: - dependencies: - tweetnacl: 0.14.5 - before-after-hook@3.0.2: {} bent@7.3.12: @@ -21524,14 +21182,10 @@ snapshots: dependencies: node-gyp-build: 4.8.4 - builtin-modules@1.1.1: {} - builtin-modules@3.3.0: {} builtin-modules@4.0.0: {} - builtins@1.0.3: {} - bundle-require@5.1.0(esbuild@0.24.2): dependencies: esbuild: 0.24.2 @@ -21575,8 +21229,6 @@ snapshots: fs-then-native: 2.0.0 mkdirp2: 1.0.5 - cachedir@2.4.0: {} - call-bind-apply-helpers@1.0.2: dependencies: es-errors: 1.3.0 @@ -21629,14 +21281,6 @@ snapshots: loupe: 3.1.3 pathval: 2.0.0 - chalk@1.1.3: - dependencies: - ansi-styles: 2.2.1 - escape-string-regexp: 1.0.5 - has-ansi: 2.0.0 - strip-ansi: 3.0.1 - supports-color: 2.0.0 - chalk@2.4.2: dependencies: ansi-styles: 3.2.1 @@ -21688,10 +21332,6 @@ snapshots: chardet@0.7.0: {} - charm@1.0.2: - dependencies: - inherits: 2.0.4 - check-error@2.1.1: {} chokidar@3.6.0: @@ -21761,12 +21401,6 @@ snapshots: client-only@0.0.1: {} - cliui@6.0.0: - dependencies: - string-width: 4.2.3 - strip-ansi: 6.0.1 - wrap-ansi: 6.2.0 - cliui@8.0.1: dependencies: string-width: 4.2.3 @@ -21807,9 +21441,6 @@ snapshots: code-block-writer@10.1.1: {} - code-point-at@1.1.0: - optional: true - collapse-white-space@2.1.0: {} collect-all@1.0.4: @@ -21855,8 +21486,6 @@ snapshots: comma-separated-tokens@2.0.3: {} - command-exists@1.2.9: {} - command-line-args@5.2.1: dependencies: array-back: 3.1.0 @@ -22057,11 +21686,6 @@ snapshots: core-js-pure@3.41.0: {} - core-util-is@1.0.2: {} - - core-util-is@1.0.3: - optional: true - cosmiconfig-typescript-loader@6.1.0(@types/node@22.15.2)(cosmiconfig@9.0.0(typescript@5.8.3))(typescript@5.8.3): dependencies: '@types/node': 22.15.2 @@ -22109,6 +21733,21 @@ snapshots: p-filter: 3.0.0 p-map: 6.0.0 + create-jest@29.7.0(@types/node@22.15.2): + dependencies: + '@jest/types': 29.6.3 + chalk: 4.1.2 + exit: 0.1.2 + graceful-fs: 4.2.11 + jest-config: 29.7.0(@types/node@22.15.2) + jest-util: 29.7.0 + prompts: 2.4.2 + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node + create-jest@29.7.0(@types/node@22.15.2)(ts-node@10.9.2(@types/node@22.15.2)(typescript@5.5.4)): dependencies: '@jest/types': 29.6.3 @@ -22194,10 +21833,6 @@ snapshots: dargs@8.1.0: {} - dashdash@1.14.1: - dependencies: - assert-plus: 1.0.0 - data-uri-to-buffer@6.0.2: {} data-view-buffer@1.0.2: @@ -22346,8 +21981,6 @@ snapshots: diff-sequences@29.6.3: {} - diff@3.5.0: {} - diff@4.0.2: {} diff@5.2.0: {} @@ -22397,30 +22030,6 @@ snapshots: dotenv@16.4.7: {} - dts-critic@3.3.11(typescript@5.8.3): - dependencies: - '@definitelytyped/header-parser': 0.2.19 - command-exists: 1.2.9 - rimraf: 3.0.2 - semver: 6.3.1 - tmp: 0.2.3 - typescript: 5.8.3 - yargs: 15.4.1 - - dtslint@4.2.1(typescript@5.8.3): - dependencies: - '@definitelytyped/header-parser': 0.2.19 - '@definitelytyped/typescript-versions': 0.1.8 - '@definitelytyped/utils': 0.1.8 - dts-critic: 3.3.11(typescript@5.8.3) - fs-extra: 6.0.1 - json-stable-stringify: 1.2.1 - strip-json-comments: 2.0.1 - tslint: 5.14.0(typescript@5.8.3) - tsutils: 2.29.0(typescript@5.8.3) - typescript: 5.8.3 - yargs: 15.4.1 - dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -22431,11 +22040,6 @@ snapshots: eastasianwidth@0.2.0: {} - ecc-jsbn@0.1.2: - dependencies: - jsbn: 0.1.1 - safer-buffer: 2.1.2 - edge-runtime@2.5.9: dependencies: '@edge-runtime/format': 2.2.1 @@ -23142,6 +22746,17 @@ snapshots: eslint-import-resolver-typescript: 4.3.4(eslint-plugin-import-x@4.10.0(eslint@9.25.1(jiti@2.4.2))(typescript@5.8.3))(eslint-plugin-import@2.31.0)(eslint@9.25.1(jiti@2.4.2)) transitivePeerDependencies: - supports-color + optional: true + + eslint-module-utils@2.12.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1)(typescript@5.8.3))(eslint-import-resolver-node@0.3.9)(eslint@9.25.1): + dependencies: + debug: 3.2.7 + optionalDependencies: + '@typescript-eslint/parser': 8.29.0(eslint@9.25.1)(typescript@5.8.3) + eslint: 9.25.1 + eslint-import-resolver-node: 0.3.9 + transitivePeerDependencies: + - supports-color eslint-plugin-astro@1.3.1(eslint@9.25.1(jiti@2.4.2)): dependencies: @@ -23237,15 +22852,45 @@ snapshots: - eslint-import-resolver-typescript - eslint-import-resolver-webpack - supports-color + optional: true - eslint-plugin-jsdoc@50.6.11(eslint@9.25.1(jiti@2.4.2)): + eslint-plugin-import@2.31.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1)(typescript@5.8.3))(eslint@9.25.1): + dependencies: + '@rtsao/scc': 1.1.0 + array-includes: 3.1.8 + array.prototype.findlastindex: 1.2.6 + array.prototype.flat: 1.3.3 + array.prototype.flatmap: 1.3.3 + debug: 3.2.7 + doctrine: 2.1.0 + eslint: 9.25.1 + eslint-import-resolver-node: 0.3.9 + eslint-module-utils: 2.12.0(@typescript-eslint/parser@8.29.0(eslint@9.25.1)(typescript@5.8.3))(eslint-import-resolver-node@0.3.9)(eslint@9.25.1) + hasown: 2.0.2 + is-core-module: 2.16.1 + is-glob: 4.0.3 + minimatch: 3.1.2 + object.fromentries: 2.0.8 + object.groupby: 1.0.3 + object.values: 1.2.1 + semver: 6.3.1 + string.prototype.trimend: 1.0.9 + tsconfig-paths: 3.15.0 + optionalDependencies: + '@typescript-eslint/parser': 8.29.0(eslint@9.25.1)(typescript@5.8.3) + transitivePeerDependencies: + - eslint-import-resolver-typescript + - eslint-import-resolver-webpack + - supports-color + + eslint-plugin-jsdoc@50.6.11(eslint@9.25.1): dependencies: '@es-joy/jsdoccomment': 0.49.0 are-docs-informative: 0.0.2 comment-parser: 1.4.1 debug: 4.4.0 escape-string-regexp: 4.0.0 - eslint: 9.25.1(jiti@2.4.2) + eslint: 9.25.1 espree: 10.3.0 esquery: 1.6.0 parse-imports-exports: 0.2.4 @@ -23518,6 +23163,46 @@ snapshots: eslint-visitor-keys@4.2.0: {} + eslint@9.25.1: + dependencies: + '@eslint-community/eslint-utils': 4.6.1(eslint@9.25.1) + '@eslint-community/regexpp': 4.12.1 + '@eslint/config-array': 0.20.0 + '@eslint/config-helpers': 0.2.1 + '@eslint/core': 0.13.0 + '@eslint/eslintrc': 3.3.1 + '@eslint/js': 9.25.1 + '@eslint/plugin-kit': 0.2.8 + '@humanfs/node': 0.16.6 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.2 + '@types/estree': 1.0.7 + '@types/json-schema': 7.0.15 + ajv: 6.12.6 + chalk: 4.1.2 + cross-spawn: 7.0.6 + debug: 4.4.0 + escape-string-regexp: 4.0.0 + eslint-scope: 8.3.0 + eslint-visitor-keys: 4.2.0 + espree: 10.3.0 + esquery: 1.6.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 8.0.0 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + lodash.merge: 4.6.2 + minimatch: 3.1.2 + natural-compare: 1.4.0 + optionator: 0.9.4 + transitivePeerDependencies: + - supports-color + eslint@9.25.1(jiti@2.4.2): dependencies: '@eslint-community/eslint-utils': 4.6.1(eslint@9.25.1(jiti@2.4.2)) @@ -23694,14 +23379,10 @@ snapshots: iconv-lite: 0.4.24 tmp: 0.0.33 - extsprintf@1.3.0: {} - fast-content-type-parse@2.0.0: {} fast-deep-equal@3.1.3: {} - fast-fifo@1.3.2: {} - fast-glob@3.3.1: dependencies: '@nodelib/fs.stat': 2.0.5 @@ -23828,16 +23509,8 @@ snapshots: cross-spawn: 7.0.6 signal-exit: 4.1.0 - forever-agent@0.6.1: {} - form-data-encoder@1.7.2: {} - form-data@2.3.3: - dependencies: - asynckit: 0.4.0 - combined-stream: 1.0.8 - mime-types: 2.1.35 - form-data@4.0.1: dependencies: asynckit: 0.4.0 @@ -23897,12 +23570,6 @@ snapshots: jsonfile: 6.1.0 universalify: 2.0.1 - fs-extra@6.0.1: - dependencies: - graceful-fs: 4.2.11 - jsonfile: 4.0.0 - universalify: 0.1.2 - fs-extra@7.0.1: dependencies: graceful-fs: 4.2.11 @@ -24033,18 +23700,6 @@ snapshots: functions-have-names@1.2.3: {} - gauge@2.7.4: - dependencies: - aproba: 1.2.0 - console-control-strings: 1.1.0 - has-unicode: 2.0.1 - object-assign: 4.1.1 - signal-exit: 3.0.7 - string-width: 1.0.2 - strip-ansi: 3.0.1 - wide-align: 1.1.5 - optional: true - gauge@3.0.2: dependencies: aproba: 2.0.0 @@ -24118,10 +23773,6 @@ snapshots: transitivePeerDependencies: - supports-color - getpass@0.1.7: - dependencies: - assert-plus: 1.0.0 - git-cliff-darwin-arm64@2.7.0: optional: true @@ -24286,19 +23937,8 @@ snapshots: optionalDependencies: uglify-js: 3.19.3 - har-schema@2.0.0: {} - - har-validator@5.1.5: - dependencies: - ajv: 6.12.6 - har-schema: 2.0.0 - hard-rejection@2.1.0: {} - has-ansi@2.0.0: - dependencies: - ansi-regex: 2.1.1 - has-bigints@1.1.0: {} has-flag@3.0.0: {} @@ -24484,12 +24124,6 @@ snapshots: transitivePeerDependencies: - supports-color - http-signature@1.2.0: - dependencies: - assert-plus: 1.0.0 - jsprim: 1.4.2 - sshpk: 1.18.0 - https-proxy-agent@5.0.1: dependencies: agent-base: 6.0.2 @@ -24743,11 +24377,6 @@ snapshots: dependencies: call-bound: 1.0.4 - is-fullwidth-code-point@1.0.0: - dependencies: - number-is-nan: 1.0.1 - optional: true - is-fullwidth-code-point@3.0.0: {} is-fullwidth-code-point@4.0.0: {} @@ -24840,8 +24469,6 @@ snapshots: dependencies: which-typed-array: 1.1.19 - is-typedarray@1.0.0: {} - is-unicode-supported@0.1.0: {} is-unicode-supported@1.3.0: {} @@ -24869,9 +24496,6 @@ snapshots: isarray@0.0.1: {} - isarray@1.0.0: - optional: true - isarray@2.0.5: {} isbinaryfile@4.0.10: {} @@ -24880,8 +24504,6 @@ snapshots: isexe@3.1.1: {} - isstream@0.1.2: {} - istanbul-lib-coverage@3.2.2: {} istanbul-lib-instrument@5.2.1: @@ -24978,6 +24600,25 @@ snapshots: - babel-plugin-macros - supports-color + jest-cli@29.7.0(@types/node@22.15.2): + dependencies: + '@jest/core': 29.7.0 + '@jest/test-result': 29.7.0 + '@jest/types': 29.6.3 + chalk: 4.1.2 + create-jest: 29.7.0(@types/node@22.15.2) + exit: 0.1.2 + import-local: 3.2.0 + jest-config: 29.7.0(@types/node@22.15.2) + jest-util: 29.7.0 + jest-validate: 29.7.0 + yargs: 17.7.2 + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node + jest-cli@29.7.0(@types/node@22.15.2)(ts-node@10.9.2(@types/node@22.15.2)(typescript@5.5.4)): dependencies: '@jest/core': 29.7.0(ts-node@10.9.2(@types/node@22.15.2)(typescript@5.5.4)) @@ -25016,6 +24657,36 @@ snapshots: - supports-color - ts-node + jest-config@29.7.0(@types/node@22.15.2): + dependencies: + '@babel/core': 7.26.10 + '@jest/test-sequencer': 29.7.0 + '@jest/types': 29.6.3 + babel-jest: 29.7.0(@babel/core@7.26.10) + chalk: 4.1.2 + ci-info: 3.9.0 + deepmerge: 4.3.1 + glob: 7.2.3 + graceful-fs: 4.2.11 + jest-circus: 29.7.0 + jest-environment-node: 29.7.0 + jest-get-type: 29.6.3 + jest-regex-util: 29.6.3 + jest-resolve: 29.7.0 + jest-runner: 29.7.0 + jest-util: 29.7.0 + jest-validate: 29.7.0 + micromatch: 4.0.8 + parse-json: 5.2.0 + pretty-format: 29.7.0 + slash: 3.0.0 + strip-json-comments: 3.1.1 + optionalDependencies: + '@types/node': 22.15.2 + transitivePeerDependencies: + - babel-plugin-macros + - supports-color + jest-config@29.7.0(@types/node@22.15.2)(ts-node@10.9.2(@types/node@22.15.2)(typescript@5.5.4)): dependencies: '@babel/core': 7.26.10 @@ -25293,6 +24964,18 @@ snapshots: merge-stream: 2.0.0 supports-color: 8.1.1 + jest@29.7.0(@types/node@22.15.2): + dependencies: + '@jest/core': 29.7.0 + '@jest/types': 29.6.3 + import-local: 3.2.0 + jest-cli: 29.7.0(@types/node@22.15.2) + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node + jest@29.7.0(@types/node@22.15.2)(ts-node@10.9.2(@types/node@22.15.2)(typescript@5.5.4)): dependencies: '@jest/core': 29.7.0(ts-node@10.9.2(@types/node@22.15.2)(typescript@5.5.4)) @@ -25337,8 +25020,6 @@ snapshots: joycon@3.1.1: {} - js-tokens@3.0.2: {} - js-tokens@4.0.0: {} js-yaml@3.14.1: @@ -25354,8 +25035,6 @@ snapshots: dependencies: xmlcreate: 2.0.4 - jsbn@0.1.1: {} - jsbn@1.1.0: {} jsdoc-api@8.1.1: @@ -25434,16 +25113,6 @@ snapshots: json-stable-stringify-without-jsonify@1.0.1: {} - json-stable-stringify@1.2.1: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - isarray: 2.0.5 - jsonify: 0.0.1 - object-keys: 1.1.1 - - json-stringify-safe@5.0.1: {} - json5@1.0.2: dependencies: minimist: 1.2.8 @@ -25462,17 +25131,8 @@ snapshots: optionalDependencies: graceful-fs: 4.2.11 - jsonify@0.0.1: {} - jsonparse@1.3.1: {} - jsprim@1.4.2: - dependencies: - assert-plus: 1.0.0 - extsprintf: 1.3.0 - json-schema: 0.4.0 - verror: 1.10.0 - jsx-ast-utils@3.3.5: dependencies: array-includes: 3.1.8 @@ -26610,12 +26270,6 @@ snapshots: semver: 7.6.3 validate-npm-package-name: 6.0.0 - npm-package-arg@8.1.5: - dependencies: - hosted-git-info: 4.1.0 - semver: 7.6.3 - validate-npm-package-name: 3.0.0 - npm-pick-manifest@9.1.0: dependencies: npm-install-checks: 6.3.0 @@ -26649,14 +26303,6 @@ snapshots: path-key: 4.0.0 unicorn-magic: 0.3.0 - npmlog@4.1.2: - dependencies: - are-we-there-yet: 1.1.7 - console-control-strings: 1.1.0 - gauge: 2.7.4 - set-blocking: 2.0.0 - optional: true - npmlog@5.0.1: dependencies: are-we-there-yet: 2.0.0 @@ -26668,9 +26314,6 @@ snapshots: dependencies: boolbase: 1.0.0 - number-is-nan@1.0.1: - optional: true - nuqs@2.4.3(next@15.4.0-canary.11(babel-plugin-react-compiler@19.1.0-rc.1)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(react@19.1.0): dependencies: mitt: 3.0.1 @@ -26678,8 +26321,6 @@ snapshots: optionalDependencies: next: 15.4.0-canary.11(babel-plugin-react-compiler@19.1.0-rc.1)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) - oauth-sign@0.9.0: {} - object-assign@4.1.1: {} object-get@2.1.1: {} @@ -27010,8 +26651,6 @@ snapshots: perfect-debounce@1.0.0: {} - performance-now@2.1.0: {} - pg-int8@1.0.1: {} pg-numeric@1.0.2: {} @@ -27204,9 +26843,6 @@ snapshots: proc-log@5.0.0: {} - process-nextick-args@2.0.1: - optional: true - process@0.11.10: {} promise-inflight@1.0.1: {} @@ -27248,10 +26884,6 @@ snapshots: proxy-from-env@1.1.0: {} - psl@1.15.0: - dependencies: - punycode: 2.3.1 - punycode.js@2.3.1: {} punycode@2.3.1: {} @@ -27266,8 +26898,6 @@ snapshots: dependencies: side-channel: 1.1.0 - qs@6.5.3: {} - quansync@0.2.10: {} queue-microtask@1.2.3: {} @@ -27514,17 +27144,6 @@ snapshots: type-fest: 4.39.1 unicorn-magic: 0.1.0 - readable-stream@2.3.8: - dependencies: - core-util-is: 1.0.3 - inherits: 2.0.4 - isarray: 1.0.0 - process-nextick-args: 2.0.1 - safe-buffer: 5.1.2 - string_decoder: 1.1.1 - util-deprecate: 1.0.2 - optional: true - readable-stream@3.6.2: dependencies: inherits: 2.0.4 @@ -27727,35 +27346,10 @@ snapshots: transitivePeerDependencies: - supports-color - request@2.88.2: - dependencies: - aws-sign2: 0.7.0 - aws4: 1.13.2 - caseless: 0.12.0 - combined-stream: 1.0.8 - extend: 3.0.2 - forever-agent: 0.6.1 - form-data: 2.3.3 - har-validator: 5.1.5 - http-signature: 1.2.0 - is-typedarray: 1.0.0 - isstream: 0.1.2 - json-stringify-safe: 5.0.1 - mime-types: 2.1.35 - oauth-sign: 0.9.0 - performance-now: 2.1.0 - qs: 6.5.3 - safe-buffer: 5.2.1 - tough-cookie: 2.5.0 - tunnel-agent: 0.6.0 - uuid: 3.4.0 - require-directory@2.1.1: {} require-from-string@2.0.2: {} - require-main-filename@2.0.0: {} - requireindex@1.2.0: {} requizzle@0.2.4: @@ -27889,9 +27483,6 @@ snapshots: has-symbols: 1.1.0 isarray: 2.0.5 - safe-buffer@5.1.2: - optional: true - safe-buffer@5.2.1: {} safe-push-apply@1.0.0: @@ -28098,8 +27689,6 @@ snapshots: ansi-styles: 6.2.1 is-fullwidth-code-point: 5.0.0 - slide@1.1.6: {} - smart-buffer@4.2.0: {} smol-toml@1.3.1: {} @@ -28173,26 +27762,10 @@ snapshots: sprintf-js@1.1.3: {} - sshpk@1.18.0: - dependencies: - asn1: 0.2.6 - assert-plus: 1.0.0 - bcrypt-pbkdf: 1.0.2 - dashdash: 1.14.1 - ecc-jsbn: 0.1.2 - getpass: 0.1.7 - jsbn: 0.1.1 - safer-buffer: 2.1.2 - tweetnacl: 0.14.5 - ssri@12.0.0: dependencies: minipass: 7.1.2 - ssri@8.0.1: - dependencies: - minipass: 3.3.6 - stable-hash@0.0.5: {} stack-utils@2.0.6: @@ -28244,13 +27817,6 @@ snapshots: streamsearch@1.1.0: {} - streamx@2.22.0: - dependencies: - fast-fifo: 1.3.2 - text-decoder: 1.2.3 - optionalDependencies: - bare-events: 2.5.4 - string-argv@0.3.2: {} string-length@4.0.2: @@ -28258,13 +27824,6 @@ snapshots: char-regex: 1.0.2 strip-ansi: 6.0.1 - string-width@1.0.2: - dependencies: - code-point-at: 1.1.0 - is-fullwidth-code-point: 1.0.0 - strip-ansi: 3.0.1 - optional: true - string-width@4.2.3: dependencies: emoji-regex: 8.0.0 @@ -28339,11 +27898,6 @@ snapshots: define-properties: 1.2.1 es-object-atoms: 1.1.1 - string_decoder@1.1.1: - dependencies: - safe-buffer: 5.1.2 - optional: true - string_decoder@1.3.0: dependencies: safe-buffer: 5.2.1 @@ -28353,10 +27907,6 @@ snapshots: character-entities-html4: 2.1.0 character-entities-legacy: 3.0.0 - strip-ansi@3.0.1: - dependencies: - ansi-regex: 2.1.1 - strip-ansi@6.0.1: dependencies: ansi-regex: 5.0.1 @@ -28441,8 +27991,6 @@ snapshots: transitivePeerDependencies: - supports-color - supports-color@2.0.0: {} - supports-color@5.5.0: dependencies: has-flag: 3.0.0 @@ -28506,12 +28054,6 @@ snapshots: tapable@2.2.1: {} - tar-stream@3.1.7: - dependencies: - b4a: 1.6.7 - fast-fifo: 1.3.2 - streamx: 2.22.0 - tar@6.2.1: dependencies: chownr: 2.0.0 @@ -28571,10 +28113,6 @@ snapshots: array-back: 2.0.0 typical: 2.6.1 - text-decoder@1.2.3: - dependencies: - b4a: 1.6.7 - text-extensions@2.4.0: {} thenify-all@1.6.0: @@ -28638,8 +28176,6 @@ snapshots: dependencies: os-tmpdir: 1.0.2 - tmp@0.2.3: {} - tmpl@1.0.5: {} to-regex-range@5.0.1: @@ -28650,11 +28186,6 @@ snapshots: totalist@3.0.1: {} - tough-cookie@2.5.0: - dependencies: - psl: 1.15.0 - punycode: 2.3.1 - tr46@0.0.3: {} tr46@1.0.1: @@ -28776,40 +28307,6 @@ snapshots: tslib@2.8.1: {} - tslint@5.14.0(typescript@5.8.3): - dependencies: - babel-code-frame: 6.26.0 - builtin-modules: 1.1.1 - chalk: 2.4.2 - commander: 2.20.3 - diff: 3.5.0 - glob: 7.2.3 - js-yaml: 3.14.1 - minimatch: 3.1.2 - mkdirp: 0.5.6 - resolve: 1.22.10 - semver: 5.7.2 - tslib: 1.14.1 - tsutils: 2.29.0(typescript@5.8.3) - typescript: 5.8.3 - - tslint@6.1.3(typescript@5.8.3): - dependencies: - '@babel/code-frame': 7.26.2 - builtin-modules: 1.1.1 - chalk: 2.4.2 - commander: 2.20.3 - diff: 4.0.2 - glob: 7.2.3 - js-yaml: 3.14.1 - minimatch: 3.1.2 - mkdirp: 0.5.6 - resolve: 1.22.10 - semver: 5.7.2 - tslib: 1.14.1 - tsutils: 2.29.0(typescript@5.8.3) - typescript: 5.8.3 - tsup@8.4.0(@microsoft/api-extractor@7.52.3(@types/node@18.17.9))(jiti@2.4.2)(postcss@8.5.3)(tsx@4.19.2)(typescript@5.5.4)(yaml@2.7.1): dependencies: bundle-require: 5.1.0(esbuild@0.25.2) @@ -28908,11 +28405,6 @@ snapshots: typescript: 5.8.3 yargs: 17.7.2 - tsutils@2.29.0(typescript@5.8.3): - dependencies: - tslib: 1.14.1 - typescript: 5.8.3 - tsutils@3.21.0(typescript@5.5.4): dependencies: tslib: 1.14.1 @@ -28930,10 +28422,6 @@ snapshots: optionalDependencies: fsevents: 2.3.3 - tunnel-agent@0.6.0: - dependencies: - safe-buffer: 5.2.1 - tunnel@0.0.6: {} turbo-darwin-64@2.5.2: @@ -28965,8 +28453,6 @@ snapshots: tw-animate-css@1.2.8: {} - tweetnacl@0.14.5: {} - twoslash-protocol@0.3.1: {} twoslash@0.3.1(typescript@5.8.3): @@ -29372,8 +28858,6 @@ snapshots: uuid@3.3.2: {} - uuid@3.4.0: {} - uuid@9.0.1: {} uvu@0.5.6: @@ -29396,10 +28880,6 @@ snapshots: spdx-correct: 3.2.0 spdx-expression-parse: 3.0.1 - validate-npm-package-name@3.0.0: - dependencies: - builtins: 1.0.3 - validate-npm-package-name@5.0.1: {} validate-npm-package-name@6.0.0: {} @@ -29428,12 +28908,6 @@ snapshots: - rollup - supports-color - verror@1.10.0: - dependencies: - assert-plus: 1.0.0 - core-util-is: 1.0.2 - extsprintf: 1.3.0 - vfile-matter@5.0.0: dependencies: vfile: 6.0.3 @@ -29732,8 +29206,6 @@ snapshots: is-weakmap: 2.0.2 is-weakset: 2.0.4 - which-module@2.0.1: {} - which-typed-array@1.1.19: dependencies: available-typed-arrays: 1.0.7 @@ -29823,8 +29295,6 @@ snapshots: xmlcreate@2.0.4: {} - y18n@4.0.3: {} - y18n@5.0.8: {} yallist@3.1.1: {} @@ -29835,29 +29305,10 @@ snapshots: yaml@2.7.1: {} - yargs-parser@18.1.3: - dependencies: - camelcase: 5.3.1 - decamelize: 1.2.0 - yargs-parser@20.2.9: {} yargs-parser@21.1.1: {} - yargs@15.4.1: - dependencies: - cliui: 6.0.0 - decamelize: 1.2.0 - find-up: 4.1.0 - get-caller-file: 2.0.5 - require-directory: 2.1.1 - require-main-filename: 2.0.0 - set-blocking: 2.0.0 - string-width: 4.2.3 - which-module: 2.0.1 - y18n: 4.0.3 - yargs-parser: 18.1.3 - yargs@17.7.2: dependencies: cliui: 8.0.1 From 24f9fe8ec7198d1a729cbf01d12a70f7f866579e Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 12:34:08 +0200 Subject: [PATCH 05/38] chore: lint some more --- eslint.config.js | 26 ++++++++++++-- packages/discord.js/src/client/BaseClient.js | 2 +- packages/discord.js/src/client/Client.js | 8 ++--- .../discord.js/src/client/WebhookClient.js | 6 ++-- .../src/client/actions/MessageReactionAdd.js | 2 +- .../websocket/handlers/GUILD_MEMBERS_CHUNK.js | 2 +- .../websocket/handlers/THREAD_LIST_SYNC.js | 4 +-- packages/discord.js/src/errors/ErrorCodes.js | 2 +- .../src/managers/ApplicationCommandManager.js | 4 +-- .../ApplicationCommandPermissionsManager.js | 4 +-- .../src/managers/ApplicationEmojiManager.js | 2 +- .../src/managers/AutoModerationRuleManager.js | 12 +++---- .../managers/CategoryChannelChildManager.js | 2 +- .../src/managers/EntitlementManager.js | 4 +-- .../src/managers/GuildBanManager.js | 6 ++-- .../src/managers/GuildChannelManager.js | 8 ++--- .../src/managers/GuildEmojiManager.js | 2 +- .../src/managers/GuildInviteManager.js | 4 +-- .../discord.js/src/managers/GuildManager.js | 14 ++++---- .../src/managers/GuildMemberManager.js | 14 ++++---- .../managers/GuildScheduledEventManager.js | 14 ++++---- .../managers/GuildSoundboardSoundManager.js | 4 +-- .../src/managers/GuildStickerManager.js | 2 +- .../discord.js/src/managers/MessageManager.js | 4 +-- .../managers/PermissionOverwriteManager.js | 2 +- .../src/managers/ReactionUserManager.js | 2 +- .../discord.js/src/managers/RoleManager.js | 4 +-- .../src/managers/StageInstanceManager.js | 4 +-- .../src/managers/SubscriptionManager.js | 2 +- .../discord.js/src/managers/ThreadManager.js | 4 +-- .../src/managers/ThreadMemberManager.js | 4 +-- packages/discord.js/src/sharding/Shard.js | 4 +-- .../src/sharding/ShardingManager.js | 8 ++--- .../src/structures/ApplicationCommand.js | 34 +++++++++---------- .../src/structures/ApplicationEmoji.js | 2 +- .../ApplicationRoleConnectionMetadata.js | 4 +-- .../discord.js/src/structures/Attachment.js | 2 +- .../src/structures/AttachmentBuilder.js | 2 +- .../src/structures/AutoModerationRule.js | 6 ++-- .../src/structures/BaseGuildTextChannel.js | 2 +- .../src/structures/ClientApplication.js | 16 ++++----- .../discord.js/src/structures/ClientUser.js | 8 ++--- .../src/structures/CommandInteraction.js | 4 +-- .../CommandInteractionOptionResolver.js | 2 +- packages/discord.js/src/structures/Embed.js | 6 ++-- packages/discord.js/src/structures/Guild.js | 22 ++++++------ .../src/structures/GuildAuditLogsEntry.js | 8 ++--- .../discord.js/src/structures/GuildChannel.js | 4 +-- .../discord.js/src/structures/GuildEmoji.js | 2 +- .../src/structures/GuildScheduledEvent.js | 6 ++-- .../src/structures/GuildTemplate.js | 2 +- .../discord.js/src/structures/Integration.js | 2 +- .../structures/InteractionCallbackResource.js | 2 +- packages/discord.js/src/structures/Message.js | 14 ++++---- .../src/structures/MessageMentions.js | 9 ++--- .../src/structures/MessageReaction.js | 2 +- .../src/structures/ModalSubmitFields.js | 2 +- .../src/structures/ModalSubmitInteraction.js | 4 +-- .../src/structures/PartialGroupDMChannel.js | 2 +- .../src/structures/PermissionOverwrites.js | 8 ++--- packages/discord.js/src/structures/Poll.js | 2 +- .../discord.js/src/structures/PollAnswer.js | 2 +- .../discord.js/src/structures/Presence.js | 6 ++-- packages/discord.js/src/structures/Role.js | 4 +-- packages/discord.js/src/structures/Sticker.js | 2 +- .../src/structures/ThreadChannel.js | 2 +- .../src/structures/ThreadOnlyChannel.js | 8 ++--- packages/discord.js/src/structures/User.js | 2 +- .../discord.js/src/structures/VoiceChannel.js | 2 +- .../discord.js/src/structures/VoiceState.js | 2 +- packages/discord.js/src/structures/Webhook.js | 4 +-- .../src/structures/WelcomeChannel.js | 2 +- packages/discord.js/src/structures/Widget.js | 2 +- .../discord.js/src/structures/WidgetMember.js | 2 +- .../src/structures/interfaces/Collector.js | 4 +-- .../interfaces/InteractionResponses.js | 12 +++---- .../structures/interfaces/TextBasedChannel.js | 10 +++--- packages/discord.js/src/util/BitField.js | 4 +-- packages/discord.js/src/util/Channels.js | 2 +- packages/discord.js/src/util/Colors.js | 2 +- packages/discord.js/src/util/Components.js | 6 ++-- packages/discord.js/src/util/Constants.js | 6 ++-- packages/discord.js/src/util/DataResolver.js | 2 +- packages/discord.js/src/util/Events.js | 2 +- .../discord.js/src/util/LimitedCollection.js | 2 +- packages/discord.js/src/util/Options.js | 10 +++--- packages/discord.js/src/util/Partials.js | 2 +- packages/discord.js/src/util/ShardEvents.js | 2 +- packages/discord.js/src/util/Status.js | 2 +- packages/discord.js/src/util/Sweepers.js | 10 +++--- .../src/util/ThreadMemberFlagsBitField.js | 2 +- packages/discord.js/src/util/Util.js | 19 ++++++----- 92 files changed, 264 insertions(+), 240 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 3368f94d4414..2538f346750b 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -146,19 +146,41 @@ export default tseslint.config( }, }, }, + settings: { + jsdoc: { + tagNamePreference: { + augments: 'extends', + return: 'returns', + arg: 'param', + fires: 'emits', + function: 'method', + }, + preferredTypes: { + String: 'string', + Number: 'number', + Boolean: 'boolean', + Symbol: 'symbol', + object: 'Object', + function: 'Function', + array: 'Array', + date: 'Date', + error: 'Error', + null: 'void', + }, + }, + }, rules: { '@typescript-eslint/no-var-requires': 0, '@typescript-eslint/no-require-imports': 0, 'jsdoc/no-undefined-types': 0, '@typescript-eslint/explicit-member-accessibility': 0, '@typescript-eslint/class-literal-property-style': 0, - 'unicorn/no-array-for-each': 0, strict: ['error', 'global'], 'unicorn/consistent-function-scoping': 0, }, }, { - files: [`packages/discord.js/**/*{ts,d.ts,mts,cts}`], + files: [`packages/discord.js/typings/*{d.ts,test-d.ts}`], rules: { 'n/prefer-global/buffer': 0, 'no-restricted-globals': 0, diff --git a/packages/discord.js/src/client/BaseClient.js b/packages/discord.js/src/client/BaseClient.js index fd2ce3f84539..16e431bc445d 100644 --- a/packages/discord.js/src/client/BaseClient.js +++ b/packages/discord.js/src/client/BaseClient.js @@ -74,7 +74,7 @@ class BaseClient extends AsyncEventEmitter { /** * Options used for deleting a webhook. * - * @typedef {object} WebhookDeleteOptions + * @typedef {Object} WebhookDeleteOptions * @property {string} [token] Token of the webhook * @property {string} [reason] The reason for deleting the webhook */ diff --git a/packages/discord.js/src/client/Client.js b/packages/discord.js/src/client/Client.js index 1b7488602fba..d2ee731bd59d 100644 --- a/packages/discord.js/src/client/Client.js +++ b/packages/discord.js/src/client/Client.js @@ -394,7 +394,7 @@ class Client extends BaseClient { /** * Broadcasts a packet to every shard of this client handles. * - * @param {object} packet The packet to send + * @param {Object} packet The packet to send * @private */ async _broadcast(packet) { @@ -458,7 +458,7 @@ class Client extends BaseClient { /** * Options used when fetching an invite from Discord. * - * @typedef {object} ClientFetchInviteOptions + * @typedef {Object} ClientFetchInviteOptions * @property {Snowflake} [guildScheduledEventId] The id of the guild scheduled event to include with * the invite */ @@ -551,7 +551,7 @@ class Client extends BaseClient { /** * Options for fetching sticker packs. * - * @typedef {object} StickerPackFetchOptions + * @typedef {Object} StickerPackFetchOptions * @property {Snowflake} [packId] The id of the sticker pack to fetch */ @@ -623,7 +623,7 @@ class Client extends BaseClient { /** * Options for {@link Client#generateInvite}. * - * @typedef {object} InviteGenerationOptions + * @typedef {Object} InviteGenerationOptions * @property {OAuth2Scopes[]} scopes Scopes that should be requested * @property {PermissionResolvable} [permissions] Permissions to request * @property {GuildResolvable} [guild] Guild to preselect diff --git a/packages/discord.js/src/client/WebhookClient.js b/packages/discord.js/src/client/WebhookClient.js index 7d9b606e57c8..dacc170513ff 100644 --- a/packages/discord.js/src/client/WebhookClient.js +++ b/packages/discord.js/src/client/WebhookClient.js @@ -15,7 +15,7 @@ class WebhookClient extends BaseClient { /** * Represents the credentials used for a webhook in the form of its id and token. * - * @typedef {object} WebhookClientDataIdWithToken + * @typedef {Object} WebhookClientDataIdWithToken * @property {Snowflake} id The webhook's id * @property {string} token The webhook's token */ @@ -23,7 +23,7 @@ class WebhookClient extends BaseClient { /** * Represents the credentials used for a webhook in the form of a URL. * - * @typedef {object} WebhookClientDataURL + * @typedef {Object} WebhookClientDataURL * @property {string} url The full URL for the webhook */ @@ -36,7 +36,7 @@ class WebhookClient extends BaseClient { /** * Options for a webhook client. * - * @typedef {object} WebhookClientOptions + * @typedef {Object} WebhookClientOptions * @property {MessageMentionOptions} [allowedMentions] Default value for {@link BaseMessageOptions#allowedMentions} * @property {RESTOptions} [rest] Options for the REST manager */ diff --git a/packages/discord.js/src/client/actions/MessageReactionAdd.js b/packages/discord.js/src/client/actions/MessageReactionAdd.js index d7fd02878b21..9e9b295b27b6 100644 --- a/packages/discord.js/src/client/actions/MessageReactionAdd.js +++ b/packages/discord.js/src/client/actions/MessageReactionAdd.js @@ -51,7 +51,7 @@ class MessageReactionAddAction extends Action { /** * Provides additional information about altered reaction * - * @typedef {object} MessageReactionEventDetails + * @typedef {Object} MessageReactionEventDetails * @property {ReactionType} type The type of the reaction * @property {boolean} burst Determines whether a super reaction was used */ diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js b/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js index fdcf0b1df708..1d849e244d8c 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js @@ -16,7 +16,7 @@ module.exports = (client, { d: data }) => { /** * Represents the properties of a guild members chunk * - * @typedef {object} GuildMembersChunk + * @typedef {Object} GuildMembersChunk * @property {number} index Index of the received chunk * @property {number} count Number of chunks the client should receive * @property {Array<*>} notFound An array of whatever could not be found diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js index 47bc5e593f09..edb37781cfbf 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js @@ -42,9 +42,9 @@ module.exports = (client, { d: data }) => { }; function removeStaleThreads(client, channel) { - channel.threads?.cache.forEach(thread => { + for (const thread of channel.threads?.cache ?? []) { if (!thread.archived) { client.channels._remove(thread.id); } - }); + } } diff --git a/packages/discord.js/src/errors/ErrorCodes.js b/packages/discord.js/src/errors/ErrorCodes.js index 74fbcaaa9a7a..2e61da8c6188 100644 --- a/packages/discord.js/src/errors/ErrorCodes.js +++ b/packages/discord.js/src/errors/ErrorCodes.js @@ -2,7 +2,7 @@ 'use strict'; /** - * @typedef {object} DiscordjsErrorCodes + * @typedef {Object} DiscordjsErrorCodes * @property {'ClientInvalidOption'} ClientInvalidOption * @property {'ClientInvalidProvidedShards'} ClientInvalidProvidedShards * @property {'ClientMissingIntents'} ClientMissingIntents diff --git a/packages/discord.js/src/managers/ApplicationCommandManager.js b/packages/discord.js/src/managers/ApplicationCommandManager.js index 179c8d7eaa47..e5759860a679 100644 --- a/packages/discord.js/src/managers/ApplicationCommandManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandManager.js @@ -41,7 +41,7 @@ class ApplicationCommandManager extends CachedManager { /** * The APIRouter path to the commands * - * @param {object} [options] The options + * @param {Object} [options] The options * @param {Snowflake} [options.id] The application command's id * @param {Snowflake} [options.guildId] The guild's id to use in the path, * ignored when using a {@link GuildApplicationCommandManager} @@ -81,7 +81,7 @@ class ApplicationCommandManager extends CachedManager { /** * Options used to fetch data from Discord * - * @typedef {object} BaseFetchOptions + * @typedef {Object} BaseFetchOptions * @property {boolean} [cache=true] Whether to cache the fetched data if it wasn't already * @property {boolean} [force=false] Whether to skip the cache check and request the API */ diff --git a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js index b68019fc73a9..bc80aa5b3871 100644 --- a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js @@ -63,7 +63,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * The object returned when fetching permissions for an application command. * - * @typedef {object} ApplicationCommandPermissions + * @typedef {Object} ApplicationCommandPermissions * @property {Snowflake} id The role, user, or channel's id. Can also be a * {@link https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permissions-constants permission constant}. * @property {ApplicationCommandPermissionType} type Whether this permission is for a role or a user @@ -75,7 +75,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { * When passing these options to a manager where `guildId` is `null`, * `guild` is a required parameter * - * @typedef {object} BaseApplicationCommandPermissionsOptions + * @typedef {Object} BaseApplicationCommandPermissionsOptions * @property {GuildResolvable} [guild] The guild to modify / check permissions for * Ignored when the manager has a non-null `guildId` property * @property {ApplicationCommandResolvable} [command] The command to modify / check permissions for diff --git a/packages/discord.js/src/managers/ApplicationEmojiManager.js b/packages/discord.js/src/managers/ApplicationEmojiManager.js index e53c39edae77..97f058da7424 100644 --- a/packages/discord.js/src/managers/ApplicationEmojiManager.js +++ b/packages/discord.js/src/managers/ApplicationEmojiManager.js @@ -31,7 +31,7 @@ class ApplicationEmojiManager extends CachedManager { /** * Options used for creating an emoji of the application * - * @typedef {object} ApplicationEmojiCreateOptions + * @typedef {Object} ApplicationEmojiCreateOptions * @property {BufferResolvable|Base64Resolvable} attachment The image for the emoji * @property {string} name The name for the emoji */ diff --git a/packages/discord.js/src/managers/AutoModerationRuleManager.js b/packages/discord.js/src/managers/AutoModerationRuleManager.js index ffc49d1db01f..947f630cd3fd 100644 --- a/packages/discord.js/src/managers/AutoModerationRuleManager.js +++ b/packages/discord.js/src/managers/AutoModerationRuleManager.js @@ -56,7 +56,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to set the trigger metadata of an auto moderation rule. * - * @typedef {object} AutoModerationTriggerMetadataOptions + * @typedef {Object} AutoModerationTriggerMetadataOptions * @property {string[]} [keywordFilter] The substrings that will be searched for in the content * @property {string[]} [regexPatterns] The regular expression patterns which will be matched against the content * Only Rust-flavored regular expressions are supported. @@ -73,7 +73,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to set the actions of an auto moderation rule. * - * @typedef {object} AutoModerationActionOptions + * @typedef {Object} AutoModerationActionOptions * @property {AutoModerationActionType} type The type of this auto moderation rule action * @property {AutoModerationActionMetadataOptions} [metadata] Additional metadata needed during execution * This property is required if using a `type` of @@ -83,7 +83,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to set the metadata of an auto moderation rule action. * - * @typedef {object} AutoModerationActionMetadataOptions + * @typedef {Object} AutoModerationActionMetadataOptions * @property {GuildTextChannelResolvable|ThreadChannel} [channel] The channel to which content will be logged * @property {number} [durationSeconds] The timeout duration in seconds * @property {string} [customMessage] The custom message that is shown whenever a message is blocked @@ -92,7 +92,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to create an auto moderation rule. * - * @typedef {object} AutoModerationRuleCreateOptions + * @typedef {Object} AutoModerationRuleCreateOptions * @property {string} name The name of the auto moderation rule * @property {AutoModerationRuleEventType} eventType The event type of the auto moderation rule * @property {AutoModerationRuleTriggerType} triggerType The trigger type of the auto moderation rule @@ -163,7 +163,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to edit an auto moderation rule. * - * @typedef {object} AutoModerationRuleEditOptions + * @typedef {Object} AutoModerationRuleEditOptions * @property {string} [name] The name of the auto moderation rule * @property {AutoModerationRuleEventType} [eventType] The event type of the auto moderation rule * @property {AutoModerationTriggerMetadataOptions} [triggerMetadata] The trigger metadata of the auto moderation rule @@ -238,7 +238,7 @@ class AutoModerationRuleManager extends CachedManager { /** * Options used to fetch all auto moderation rules from a guild. * - * @typedef {object} FetchAutoModerationRulesOptions + * @typedef {Object} FetchAutoModerationRulesOptions * @property {boolean} [cache] Whether to cache the fetched auto moderation rules */ diff --git a/packages/discord.js/src/managers/CategoryChannelChildManager.js b/packages/discord.js/src/managers/CategoryChannelChildManager.js index d6a0d355efe2..dbd88cc59c38 100644 --- a/packages/discord.js/src/managers/CategoryChannelChildManager.js +++ b/packages/discord.js/src/managers/CategoryChannelChildManager.js @@ -42,7 +42,7 @@ class CategoryChannelChildManager extends DataManager { /** * Options for creating a channel using {@link CategoryChannelChildManager#create}. * - * @typedef {object} CategoryCreateChannelOptions + * @typedef {Object} CategoryCreateChannelOptions * @property {string} name The name for the new channel * @property {ChannelType} [type=ChannelType.GuildText] The type of the new channel. * @property {string} [topic] The topic for the new channel diff --git a/packages/discord.js/src/managers/EntitlementManager.js b/packages/discord.js/src/managers/EntitlementManager.js index a98c70da9cc3..b86648c2a08d 100644 --- a/packages/discord.js/src/managers/EntitlementManager.js +++ b/packages/discord.js/src/managers/EntitlementManager.js @@ -51,7 +51,7 @@ class EntitlementManager extends CachedManager { /** * Options used to fetch entitlements * - * @typedef {object} FetchEntitlementsOptions + * @typedef {Object} FetchEntitlementsOptions * @property {number} [limit] The maximum number of entitlements to fetch * @property {GuildResolvable} [guild] The guild to fetch entitlements for * @property {UserResolvable} [user] The user to fetch entitlements for @@ -120,7 +120,7 @@ class EntitlementManager extends CachedManager { * Options used to create a test entitlement * Either `guild` or `user` must be provided, but not both * - * @typedef {object} EntitlementCreateOptions + * @typedef {Object} EntitlementCreateOptions * @property {SKUResolvable} sku The id of the SKU to create the entitlement for * @property {GuildResolvable} [guild] The guild to create the entitlement for * @property {UserResolvable} [user] The user to create the entitlement for diff --git a/packages/discord.js/src/managers/GuildBanManager.js b/packages/discord.js/src/managers/GuildBanManager.js index 3098edf52e6d..9f625f777079 100644 --- a/packages/discord.js/src/managers/GuildBanManager.js +++ b/packages/discord.js/src/managers/GuildBanManager.js @@ -63,7 +63,7 @@ class GuildBanManager extends CachedManager { /** * Options used to fetch multiple bans from a guild. * - * @typedef {object} FetchBansOptions + * @typedef {Object} FetchBansOptions * @property {number} [limit] The maximum number of bans to return * @property {Snowflake} [before] Consider only bans before this id * @property {Snowflake} [after] Consider only bans after this id @@ -135,7 +135,7 @@ class GuildBanManager extends CachedManager { /** * Options used to ban a user from a guild. * - * @typedef {object} BanOptions + * @typedef {Object} BanOptions * @property {number} [deleteMessageSeconds] Number of seconds of messages to delete, * must be between 0 and 604800 (7 days), inclusive * @property {string} [reason] The reason for the ban @@ -183,7 +183,7 @@ class GuildBanManager extends CachedManager { /** * Result of bulk banning users from a guild. * - * @typedef {object} BulkBanResult + * @typedef {Object} BulkBanResult * @property {Snowflake[]} bannedUsers IDs of the banned users * @property {Snowflake[]} failedUsers IDs of the users that could not be banned or were already banned */ diff --git a/packages/discord.js/src/managers/GuildChannelManager.js b/packages/discord.js/src/managers/GuildChannelManager.js index 48538cf2f401..231478333ef3 100644 --- a/packages/discord.js/src/managers/GuildChannelManager.js +++ b/packages/discord.js/src/managers/GuildChannelManager.js @@ -116,7 +116,7 @@ class GuildChannelManager extends CachedManager { /** * Represents the followed channel data. * - * @typedef {object} FollowedChannelData + * @typedef {Object} FollowedChannelData * @property {Snowflake} channelId Source channel id * @property {Snowflake} webhookId Created webhook id in the target channel */ @@ -268,7 +268,7 @@ class GuildChannelManager extends CachedManager { /** * Options used to edit a guild channel. * - * @typedef {object} GuildChannelEditOptions + * @typedef {Object} GuildChannelEditOptions * @property {string} [name] The name of the channel * @property {ChannelType} [type] The type of the channel (only conversion between text and announcement is supported) * @property {number} [position] The position of the channel @@ -465,7 +465,7 @@ class GuildChannelManager extends CachedManager { /** * The data needed for updating a channel's position. * - * @typedef {object} ChannelPosition + * @typedef {Object} ChannelPosition * @property {GuildChannel|Snowflake} channel Channel to update * @property {number} [position] New position for the channel * @property {CategoryChannelResolvable} [parent] Parent channel for this channel @@ -502,7 +502,7 @@ class GuildChannelManager extends CachedManager { /** * Data returned from fetching threads. * - * @typedef {object} FetchedThreads + * @typedef {Object} FetchedThreads * @property {Collection} threads The threads that were fetched * @property {Collection} members The thread members in the received threads */ diff --git a/packages/discord.js/src/managers/GuildEmojiManager.js b/packages/discord.js/src/managers/GuildEmojiManager.js index 3937c7c7a705..ec39228ecd90 100644 --- a/packages/discord.js/src/managers/GuildEmojiManager.js +++ b/packages/discord.js/src/managers/GuildEmojiManager.js @@ -108,7 +108,7 @@ class GuildEmojiManager extends CachedManager { /** * Options used for creating an emoji in a guild. * - * @typedef {object} GuildEmojiCreateOptions + * @typedef {Object} GuildEmojiCreateOptions * @property {BufferResolvable|Base64Resolvable} attachment The image for the emoji * @property {string} name The name for the emoji * @property {Collection|RoleResolvable[]} [roles] The roles to limit the emoji to diff --git a/packages/discord.js/src/managers/GuildInviteManager.js b/packages/discord.js/src/managers/GuildInviteManager.js index ea8f4394b93f..e71d4e584986 100644 --- a/packages/discord.js/src/managers/GuildInviteManager.js +++ b/packages/discord.js/src/managers/GuildInviteManager.js @@ -80,7 +80,7 @@ class GuildInviteManager extends CachedManager { /** * Options used to fetch a single invite from a guild. * - * @typedef {object} FetchInviteOptions + * @typedef {Object} FetchInviteOptions * @property {InviteResolvable} code The invite to fetch * @property {boolean} [cache=true] Whether or not to cache the fetched invite * @property {boolean} [force=false] Whether to skip the cache check and request the API @@ -89,7 +89,7 @@ class GuildInviteManager extends CachedManager { /** * Options used to fetch all invites from a guild. * - * @typedef {object} FetchInvitesOptions + * @typedef {Object} FetchInvitesOptions * @property {GuildInvitableChannelResolvable} [channelId] * The channel to fetch all invites from * @property {boolean} [cache=true] Whether or not to cache the fetched invites diff --git a/packages/discord.js/src/managers/GuildManager.js b/packages/discord.js/src/managers/GuildManager.js index 42739d37c14a..075f801a7aa3 100644 --- a/packages/discord.js/src/managers/GuildManager.js +++ b/packages/discord.js/src/managers/GuildManager.js @@ -63,7 +63,7 @@ class GuildManager extends CachedManager { /** * Partial data for a Role. * - * @typedef {object} PartialRoleData + * @typedef {Object} PartialRoleData * @property {Snowflake|number} [id] The role's id, used to set channel overrides. * This is a placeholder and will be replaced by the API after consumption * @property {string} [name] The name of the role @@ -77,7 +77,7 @@ class GuildManager extends CachedManager { /** * Partial overwrite data. * - * @typedef {object} PartialOverwriteData + * @typedef {Object} PartialOverwriteData * @property {Snowflake|number} id The id of the {@link Role} or {@link User} this overwrite belongs to * @property {OverwriteType} [type] The type of this overwrite * @property {PermissionResolvable} [allow] The permissions to allow @@ -87,7 +87,7 @@ class GuildManager extends CachedManager { /** * Partial data for a Channel. * - * @typedef {object} PartialChannelData + * @typedef {Object} PartialChannelData * @property {Snowflake|number} [id] The channel's id, used to set its parent. * This is a placeholder and will be replaced by the API after consumption * @property {Snowflake|number} [parentId] The parent id for this channel @@ -153,7 +153,7 @@ class GuildManager extends CachedManager { /** * Options used to create a guild. * - * @typedef {object} GuildCreateOptions + * @typedef {Object} GuildCreateOptions * @property {string} name The name of the guild * @property {?(BufferResolvable|Base64Resolvable)} [icon=null] The icon for the guild * @property {GuildVerificationLevel} [verificationLevel] The verification level for the guild @@ -267,7 +267,7 @@ class GuildManager extends CachedManager { /** * Options used to fetch multiple guilds. * - * @typedef {object} FetchGuildsOptions + * @typedef {Object} FetchGuildsOptions * @property {Snowflake} [before] Get guilds before this guild id * @property {Snowflake} [after] Get guilds after this guild id * @property {number} [limit] Maximum number of guilds to request (1-200) @@ -300,7 +300,7 @@ class GuildManager extends CachedManager { } /** - * @typedef {object} FetchSoundboardSoundsOptions + * @typedef {Object} FetchSoundboardSoundsOptions * @property {Snowflake[]} guildIds The ids of the guilds to fetch soundboard sounds for * @property {number} [time=10_000] The timeout for receipt of the soundboard sounds */ @@ -371,7 +371,7 @@ class GuildManager extends CachedManager { /** * Options used to set incident actions. Supplying `null` to any option will disable the action. * - * @typedef {object} IncidentActionsEditOptions + * @typedef {Object} IncidentActionsEditOptions * @property {?DateResolvable} [invitesDisabledUntil] When invites should be enabled again * @property {?DateResolvable} [dmsDisabledUntil] When direct messages should be enabled again */ diff --git a/packages/discord.js/src/managers/GuildMemberManager.js b/packages/discord.js/src/managers/GuildMemberManager.js index 3f884da886fc..294fe159fbd1 100644 --- a/packages/discord.js/src/managers/GuildMemberManager.js +++ b/packages/discord.js/src/managers/GuildMemberManager.js @@ -72,7 +72,7 @@ class GuildMemberManager extends CachedManager { /** * Options used to add a user to a guild using OAuth2. * - * @typedef {object} AddGuildMemberOptions + * @typedef {Object} AddGuildMemberOptions * @property {string} accessToken An OAuth2 access token for the user with the {@link OAuth2Scopes.GuildsJoin} * scope granted to the bot's application * @property {string} [nick] The nickname to give to the member @@ -167,7 +167,7 @@ class GuildMemberManager extends CachedManager { /** * Options used to fetch multiple members from a guild. * - * @typedef {object} FetchMembersOptions + * @typedef {Object} FetchMembersOptions * @property {UserResolvable|UserResolvable[]} [user] The user(s) to fetch * @property {?string} [query] Limit fetch to members with similar usernames * @property {number} [limit=0] Maximum number of members to request @@ -300,7 +300,7 @@ class GuildMemberManager extends CachedManager { /** * Options used for searching guild members. * - * @typedef {object} GuildSearchMembersOptions + * @typedef {Object} GuildSearchMembersOptions * @property {string} query Filter members whose username or nickname start with this query * @property {number} [limit] Maximum number of members to search * @property {boolean} [cache=true] Whether or not to cache the fetched member(s) @@ -322,7 +322,7 @@ class GuildMemberManager extends CachedManager { /** * Options used for listing guild members. * - * @typedef {object} GuildListMembersOptions + * @typedef {Object} GuildListMembersOptions * @property {Snowflake} [after] Limit fetching members to those with an id greater than the supplied id * @property {number} [limit] Maximum number of members to list * @property {boolean} [cache=true] Whether or not to cache the fetched member(s) @@ -343,7 +343,7 @@ class GuildMemberManager extends CachedManager { /** * The data for editing a guild member. * - * @typedef {object} GuildMemberEditOptions + * @typedef {Object} GuildMemberEditOptions * @property {?string} [nick] The nickname to set for the member * @property {Collection|RoleResolvable[]} [roles] The roles or role ids to apply * @property {boolean} [mute] Whether or not the member should be muted @@ -416,7 +416,7 @@ class GuildMemberManager extends CachedManager { * It's recommended to set {@link GuildPruneMembersOptions#count options.count} * to `false` for large guilds. * - * @typedef {object} GuildPruneMembersOptions + * @typedef {Object} GuildPruneMembersOptions * @property {number} [days] Number of days of inactivity required to kick * @property {boolean} [dry=false] Get the number of users that will be kicked, without actually kicking them * @property {boolean} [count] Whether or not to return the number of users that have been kicked. @@ -542,7 +542,7 @@ class GuildMemberManager extends CachedManager { /** * Options used for adding or removing a role from a member. * - * @typedef {object} AddOrRemoveGuildMemberRoleOptions + * @typedef {Object} AddOrRemoveGuildMemberRoleOptions * @property {UserResolvable} user The user to add/remove the role from * @property {RoleResolvable} role The role to add/remove * @property {string} [reason] Reason for adding/removing the role diff --git a/packages/discord.js/src/managers/GuildScheduledEventManager.js b/packages/discord.js/src/managers/GuildScheduledEventManager.js index feb92bb3de71..d29792b20d4c 100644 --- a/packages/discord.js/src/managers/GuildScheduledEventManager.js +++ b/packages/discord.js/src/managers/GuildScheduledEventManager.js @@ -44,7 +44,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Options for setting a recurrence rule for a guild scheduled event. * - * @typedef {object} GuildScheduledEventRecurrenceRuleOptions + * @typedef {Object} GuildScheduledEventRecurrenceRuleOptions * @property {DateResolvable} startAt The time the recurrence rule interval starts at * @property {GuildScheduledEventRecurrenceRuleFrequency} frequency How often the event occurs * @property {number} interval The spacing between the events @@ -57,7 +57,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to create a guild scheduled event. * - * @typedef {object} GuildScheduledEventCreateOptions + * @typedef {Object} GuildScheduledEventCreateOptions * @property {string} name The name of the guild scheduled event * @property {DateResolvable} scheduledStartTime The time to schedule the event at * @property {DateResolvable} [scheduledEndTime] The time to end the event at @@ -80,7 +80,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to set entity metadata of a guild scheduled event. * - * @typedef {object} GuildScheduledEventEntityMetadataOptions + * @typedef {Object} GuildScheduledEventEntityMetadataOptions * @property {string} [location] The location of the guild scheduled event * This is required if `entityType` is {@link GuildScheduledEventEntityType.External} */ @@ -148,7 +148,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to fetch multiple guild scheduled events from a guild. * - * @typedef {object} FetchGuildScheduledEventsOptions + * @typedef {Object} FetchGuildScheduledEventsOptions * @property {boolean} [cache] Whether or not to cache the fetched guild scheduled events * @property {boolean} [withUserCount=true] Whether to fetch the number of users subscribed to each scheduled event * should be returned @@ -190,7 +190,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to edit a guild scheduled event. * - * @typedef {object} GuildScheduledEventEditOptions + * @typedef {Object} GuildScheduledEventEditOptions * @property {string} [name] The name of the guild scheduled event * @property {DateResolvable} [scheduledStartTime] The time to schedule the event at * @property {DateResolvable} [scheduledEndTime] The time to end the event at @@ -279,7 +279,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Options used to fetch subscribers of a guild scheduled event * - * @typedef {object} FetchGuildScheduledEventSubscribersOptions + * @typedef {Object} FetchGuildScheduledEventSubscribersOptions * @property {number} [limit] The maximum numbers of users to fetch * @property {boolean} [withMember] Whether to fetch guild member data of the users * @property {Snowflake} [before] Consider only users before this user id @@ -290,7 +290,7 @@ class GuildScheduledEventManager extends CachedManager { /** * Represents a subscriber of a {@link GuildScheduledEvent} * - * @typedef {object} GuildScheduledEventUser + * @typedef {Object} GuildScheduledEventUser * @property {Snowflake} guildScheduledEventId The id of the guild scheduled event which the user subscribed to * @property {User} user The user that subscribed to the guild scheduled event * @property {?GuildMember} member The guild member associated with the user, if any diff --git a/packages/discord.js/src/managers/GuildSoundboardSoundManager.js b/packages/discord.js/src/managers/GuildSoundboardSoundManager.js index f802ceb7db27..d4fdaf011f79 100644 --- a/packages/discord.js/src/managers/GuildSoundboardSoundManager.js +++ b/packages/discord.js/src/managers/GuildSoundboardSoundManager.js @@ -71,7 +71,7 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Options used to create a soundboard sound in a guild. * - * @typedef {object} GuildSoundboardSoundCreateOptions + * @typedef {Object} GuildSoundboardSoundCreateOptions * @property {BufferResolvable|Stream} file The file for the soundboard sound * @property {string} name The name for the soundboard sound * @property {string} [contentType] The content type for the soundboard sound file @@ -112,7 +112,7 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Data for editing a soundboard sound. * - * @typedef {object} GuildSoundboardSoundEditOptions + * @typedef {Object} GuildSoundboardSoundEditOptions * @property {string} [name] The name of the soundboard sound * @property {?number} [volume] The volume of the soundboard sound, from 0 to 1 * @property {?Snowflake} [emojiId] The emoji id of the soundboard sound diff --git a/packages/discord.js/src/managers/GuildStickerManager.js b/packages/discord.js/src/managers/GuildStickerManager.js index 929ba30c2db4..bacc23bf3e00 100644 --- a/packages/discord.js/src/managers/GuildStickerManager.js +++ b/packages/discord.js/src/managers/GuildStickerManager.js @@ -38,7 +38,7 @@ class GuildStickerManager extends CachedManager { /** * Options used to create a guild sticker. * - * @typedef {object} GuildStickerCreateOptions + * @typedef {Object} GuildStickerCreateOptions * @property {AttachmentPayload|BufferResolvable|Stream} file The file for the sticker * @property {string} name The name for the sticker * @property {string} tags The Discord name of a unicode emoji representing the sticker's expression diff --git a/packages/discord.js/src/managers/MessageManager.js b/packages/discord.js/src/managers/MessageManager.js index ba175cbdaad6..c79050eace4b 100644 --- a/packages/discord.js/src/managers/MessageManager.js +++ b/packages/discord.js/src/managers/MessageManager.js @@ -60,7 +60,7 @@ class MessageManager extends CachedManager { * Options used to fetch multiple messages. * The `before`, `after`, and `around` parameters are mutually exclusive. * - * @typedef {object} FetchMessagesOptions + * @typedef {Object} FetchMessagesOptions * @property {number} [limit] The maximum number of messages to return * @property {Snowflake} [before] Consider only messages before this id * @property {Snowflake} [after] Consider only messages after this id @@ -166,7 +166,7 @@ class MessageManager extends CachedManager { /** * Data used to reference an attachment. * - * @typedef {object} MessageEditAttachmentData + * @typedef {Object} MessageEditAttachmentData * @property {Snowflake} id The id of the attachment */ diff --git a/packages/discord.js/src/managers/PermissionOverwriteManager.js b/packages/discord.js/src/managers/PermissionOverwriteManager.js index e6bd44d7a348..83d98b9433de 100644 --- a/packages/discord.js/src/managers/PermissionOverwriteManager.js +++ b/packages/discord.js/src/managers/PermissionOverwriteManager.js @@ -82,7 +82,7 @@ class PermissionOverwriteManager extends CachedManager { /** * Extra information about the overwrite. * - * @typedef {object} GuildChannelOverwriteOptions + * @typedef {Object} GuildChannelOverwriteOptions * @property {string} [reason] The reason for creating/editing this overwrite * @property {OverwriteType} [type] The type of overwrite. Use this to bypass automatic resolution of `type` * that results in an error for an uncached structure diff --git a/packages/discord.js/src/managers/ReactionUserManager.js b/packages/discord.js/src/managers/ReactionUserManager.js index e3cc7467cd11..aa8f0e31220e 100644 --- a/packages/discord.js/src/managers/ReactionUserManager.js +++ b/packages/discord.js/src/managers/ReactionUserManager.js @@ -34,7 +34,7 @@ class ReactionUserManager extends CachedManager { /** * Options used to fetch users who gave a reaction. * - * @typedef {object} FetchReactionUsersOptions + * @typedef {Object} FetchReactionUsersOptions * @property {ReactionType} [type=ReactionType.Normal] The reaction type to fetch * @property {number} [limit=100] The maximum amount of users to fetch, defaults to `100` * @property {Snowflake} [after] Limit fetching users to those with an id greater than the supplied id diff --git a/packages/discord.js/src/managers/RoleManager.js b/packages/discord.js/src/managers/RoleManager.js index 3fb9f8ff5568..4f8b1407454d 100644 --- a/packages/discord.js/src/managers/RoleManager.js +++ b/packages/discord.js/src/managers/RoleManager.js @@ -112,7 +112,7 @@ class RoleManager extends CachedManager { /** * Options used to create a new role. * - * @typedef {object} RoleCreateOptions + * @typedef {Object} RoleCreateOptions * @property {string} [name] The name of the new role * @property {ColorResolvable} [color] The data to create the role with * @property {boolean} [hoist] Whether or not the new role should be hoisted @@ -286,7 +286,7 @@ class RoleManager extends CachedManager { /** * The data needed for updating a guild role's position * - * @typedef {object} GuildRolePosition + * @typedef {Object} GuildRolePosition * @property {RoleResolvable} role The role's id * @property {number} position The position to update */ diff --git a/packages/discord.js/src/managers/StageInstanceManager.js b/packages/discord.js/src/managers/StageInstanceManager.js index 5d0f21b4e4e3..baf6b1cbbed4 100644 --- a/packages/discord.js/src/managers/StageInstanceManager.js +++ b/packages/discord.js/src/managers/StageInstanceManager.js @@ -32,7 +32,7 @@ class StageInstanceManager extends CachedManager { /** * Options used to create a stage instance. * - * @typedef {object} StageInstanceCreateOptions + * @typedef {Object} StageInstanceCreateOptions * @property {string} topic The topic of the stage instance * @property {StageInstancePrivacyLevel} [privacyLevel] The privacy level of the stage instance * @property {boolean} [sendStartNotification] Whether to notify `@everyone` that the stage instance has started @@ -112,7 +112,7 @@ class StageInstanceManager extends CachedManager { /** * Options used to edit an existing stage instance. * - * @typedef {object} StageInstanceEditOptions + * @typedef {Object} StageInstanceEditOptions * @property {string} [topic] The new topic of the stage instance * @property {StageInstancePrivacyLevel} [privacyLevel] The new privacy level of the stage instance */ diff --git a/packages/discord.js/src/managers/SubscriptionManager.js b/packages/discord.js/src/managers/SubscriptionManager.js index cfb2e1b35815..8c08e81d26f5 100644 --- a/packages/discord.js/src/managers/SubscriptionManager.js +++ b/packages/discord.js/src/managers/SubscriptionManager.js @@ -36,7 +36,7 @@ class SubscriptionManager extends CachedManager { /** * Options used to fetch subscriptions * - * @typedef {object} FetchSubscriptionsOptions + * @typedef {Object} FetchSubscriptionsOptions * @property {Snowflake} [after] Consider only subscriptions after this subscription id * @property {Snowflake} [before] Consider only subscriptions before this subscription id * @property {number} [limit] The maximum number of subscriptions to fetch diff --git a/packages/discord.js/src/managers/ThreadManager.js b/packages/discord.js/src/managers/ThreadManager.js index 7eea8b8ab8f4..212f1e435ceb 100644 --- a/packages/discord.js/src/managers/ThreadManager.js +++ b/packages/discord.js/src/managers/ThreadManager.js @@ -72,7 +72,7 @@ class ThreadManager extends CachedManager { /** * Options for fetching multiple threads. * - * @typedef {object} FetchThreadsOptions + * @typedef {Object} FetchThreadsOptions * @property {FetchArchivedThreadOptions} [archived] Options used to fetch archived threads */ @@ -119,7 +119,7 @@ class ThreadManager extends CachedManager { /** * The options used to fetch archived threads. * - * @typedef {object} FetchArchivedThreadOptions + * @typedef {Object} FetchArchivedThreadOptions * @property {string} [type='public'] The type of threads to fetch (`public` or `private`) * @property {boolean} [fetchAll=false] Whether to fetch **all** archived threads when `type` is `private` * This property requires the {@link PermissionFlagsBits.ManageThreads} permission if `true`. diff --git a/packages/discord.js/src/managers/ThreadMemberManager.js b/packages/discord.js/src/managers/ThreadMemberManager.js index e024169064c2..4bd1d459d8d1 100644 --- a/packages/discord.js/src/managers/ThreadMemberManager.js +++ b/packages/discord.js/src/managers/ThreadMemberManager.js @@ -134,7 +134,7 @@ class ThreadMemberManager extends CachedManager { * Options used to fetch multiple thread members with guild member data. * With `withMember` set to `true`, pagination is enabled. * - * @typedef {object} FetchThreadMembersWithGuildMemberDataOptions + * @typedef {Object} FetchThreadMembersWithGuildMemberDataOptions * @property {true} withMember Whether to also return the guild member data * @property {Snowflake} [after] Consider only thread members after this id * @property {number} [limit] The maximum number of thread members to return @@ -144,7 +144,7 @@ class ThreadMemberManager extends CachedManager { /** * Options used to fetch multiple thread members without guild member data. * - * @typedef {object} FetchThreadMembersWithoutGuildMemberDataOptions + * @typedef {Object} FetchThreadMembersWithoutGuildMemberDataOptions * @property {false} [withMember] Whether to also return the guild member data * @property {boolean} [cache] Whether to cache the fetched thread members */ diff --git a/packages/discord.js/src/sharding/Shard.js b/packages/discord.js/src/sharding/Shard.js index d43b59831e5e..48b33bd9a101 100644 --- a/packages/discord.js/src/sharding/Shard.js +++ b/packages/discord.js/src/sharding/Shard.js @@ -74,7 +74,7 @@ class Shard extends AsyncEventEmitter { /** * Environment variables for the shard's process, or workerData for the shard's worker * - * @type {object} + * @type {Object} */ this.env = { ...process.env, @@ -234,7 +234,7 @@ class Shard extends AsyncEventEmitter { /** * Options used to respawn a shard. * - * @typedef {object} ShardRespawnOptions + * @typedef {Object} ShardRespawnOptions * @property {number} [delay=500] How long to wait between killing the process/worker and * restarting it (in milliseconds) * @property {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} diff --git a/packages/discord.js/src/sharding/ShardingManager.js b/packages/discord.js/src/sharding/ShardingManager.js index 3363929336d2..ded3c83c8f11 100644 --- a/packages/discord.js/src/sharding/ShardingManager.js +++ b/packages/discord.js/src/sharding/ShardingManager.js @@ -32,7 +32,7 @@ class ShardingManager extends AsyncEventEmitter { /** * The options to spawn shards with for a {@link ShardingManager}. * - * @typedef {object} ShardingManagerOptions + * @typedef {Object} ShardingManagerOptions * @property {string|number} [totalShards='auto'] Number of total shards of all shard managers or "auto" * @property {string|number[]} [shardList='auto'] List of shards to spawn or "auto" * @property {ShardingManagerMode} [mode='process'] Which mode to use for shards @@ -199,7 +199,7 @@ class ShardingManager extends AsyncEventEmitter { /** * Options used to spawn multiple shards. * - * @typedef {object} MultipleShardSpawnOptions + * @typedef {Object} MultipleShardSpawnOptions * @property {number|string} [amount=this.totalShards] Number of shards to spawn * @property {number} [delay=5500] How long to wait in between spawning each shard (in milliseconds) * @property {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready @@ -276,7 +276,7 @@ class ShardingManager extends AsyncEventEmitter { /** * Options for {@link ShardingManager#broadcastEval} and {@link ShardClientUtil#broadcastEval}. * - * @typedef {object} BroadcastEvalOptions + * @typedef {Object} BroadcastEvalOptions * @property {number} [shard] Shard to run script on, all if undefined * @property {*} [context] The JSON-serializable values to call the script with */ @@ -340,7 +340,7 @@ class ShardingManager extends AsyncEventEmitter { /** * Options used to respawn all shards. * - * @typedef {object} MultipleShardRespawnOptions + * @typedef {Object} MultipleShardRespawnOptions * @property {number} [shardDelay=5000] How long to wait between shards (in milliseconds) * @property {number} [respawnDelay=500] How long to wait between killing a shard's process and restarting it * (in milliseconds) diff --git a/packages/discord.js/src/structures/ApplicationCommand.js b/packages/discord.js/src/structures/ApplicationCommand.js index e06d57461995..adce7eeed298 100644 --- a/packages/discord.js/src/structures/ApplicationCommand.js +++ b/packages/discord.js/src/structures/ApplicationCommand.js @@ -83,7 +83,7 @@ class ApplicationCommand extends Base { /** * The name localizations for this command * - * @type {?Record} + * @type {?Object} */ this.nameLocalizations = data.name_localizations; } else { @@ -114,7 +114,7 @@ class ApplicationCommand extends Base { /** * The description localizations for this command * - * @type {?Record} + * @type {?Object} */ this.descriptionLocalizations = data.description_localizations; } else { @@ -236,14 +236,14 @@ class ApplicationCommand extends Base { /** * Data for creating or editing an application command. * - * @typedef {object} ApplicationCommandData + * @typedef {Object} ApplicationCommandData * @property {string} name The name of the command, must be in all lowercase if type is * {@link ApplicationCommandType.ChatInput} - * @property {Record} [nameLocalizations] The localizations for the command name + * @property {Object} [nameLocalizations] The localizations for the command name * @property {string} description The description of the command, * if type is {@link ApplicationCommandType.ChatInput} or {@link ApplicationCommandType.PrimaryEntryPoint} * @property {boolean} [nsfw] Whether the command is age-restricted - * @property {Record} [descriptionLocalizations] The localizations for the command description, + * @property {Object} [descriptionLocalizations] The localizations for the command description, * if type is {@link ApplicationCommandType.ChatInput} or {@link ApplicationCommandType.PrimaryEntryPoint} * @property {ApplicationCommandType} [type=ApplicationCommandType.ChatInput] The type of the command * @property {ApplicationCommandOptionData[]} [options] Options for the command @@ -262,12 +262,12 @@ class ApplicationCommand extends Base { * Note that providing a value for the `camelCase` counterpart for any `snake_case` property * will discard the provided `snake_case` property. * - * @typedef {object} ApplicationCommandOptionData + * @typedef {Object} ApplicationCommandOptionData * @property {ApplicationCommandOptionType} type The type of the option * @property {string} name The name of the option - * @property {Record} [nameLocalizations] The name localizations for the option + * @property {Object} [nameLocalizations] The name localizations for the option * @property {string} description The description of the option - * @property {Record} [descriptionLocalizations] The description localizations for the option + * @property {Object} [descriptionLocalizations] The description localizations for the option * @property {boolean} [autocomplete] Whether the autocomplete interaction is enabled for a * {@link ApplicationCommandOptionType.String}, {@link ApplicationCommandOptionType.Integer} or * {@link ApplicationCommandOptionType.Number} option @@ -287,9 +287,9 @@ class ApplicationCommand extends Base { */ /** - * @typedef {object} ApplicationCommandOptionChoiceData + * @typedef {Object} ApplicationCommandOptionChoiceData * @property {string} name The name of the choice - * @property {Record} [nameLocalizations] The localized names for this choice + * @property {Object} [nameLocalizations] The localized names for this choice * @property {string|number} value The value of the choice */ @@ -323,7 +323,7 @@ class ApplicationCommand extends Base { /** * Edits the localized names of this ApplicationCommand * - * @param {Record} nameLocalizations The new localized names for the command + * @param {Object} nameLocalizations The new localized names for the command * @returns {Promise} * @example * // Edit the name localizations of this command @@ -351,7 +351,7 @@ class ApplicationCommand extends Base { /** * Edits the localized descriptions of this ApplicationCommand * - * @param {Record} descriptionLocalizations The new localized descriptions for the command + * @param {Object} descriptionLocalizations The new localized descriptions for the command * @returns {Promise} * @example * // Edit the description localizations of this command @@ -565,13 +565,13 @@ class ApplicationCommand extends Base { /** * An option for an application command or subcommand. * - * @typedef {object} ApplicationCommandOption + * @typedef {Object} ApplicationCommandOption * @property {ApplicationCommandOptionType} type The type of the option * @property {string} name The name of the option - * @property {Record} [nameLocalizations] The localizations for the option name + * @property {Object} [nameLocalizations] The localizations for the option name * @property {string} [nameLocalized] The localized name for this option * @property {string} description The description of the option - * @property {Record} [descriptionLocalizations] The localizations for the option description + * @property {Object} [descriptionLocalizations] The localizations for the option description * @property {string} [descriptionLocalized] The localized description for this option * @property {boolean} [required] Whether the option is required * @property {boolean} [autocomplete] Whether the autocomplete interaction is enabled for a @@ -594,10 +594,10 @@ class ApplicationCommand extends Base { /** * A choice for an application command option. * - * @typedef {object} ApplicationCommandOptionChoice + * @typedef {Object} ApplicationCommandOptionChoice * @property {string} name The name of the choice * @property {?string} nameLocalized The localized name of the choice in the provided locale, if any - * @property {?Record} [nameLocalizations] The localized names for this choice + * @property {?Object} [nameLocalizations] The localized names for this choice * @property {string|number} value The value of the choice */ diff --git a/packages/discord.js/src/structures/ApplicationEmoji.js b/packages/discord.js/src/structures/ApplicationEmoji.js index 8b47eb3190cc..b4626054bf4e 100644 --- a/packages/discord.js/src/structures/ApplicationEmoji.js +++ b/packages/discord.js/src/structures/ApplicationEmoji.js @@ -66,7 +66,7 @@ class ApplicationEmoji extends Emoji { /** * Data for editing an emoji. * - * @typedef {object} ApplicationEmojiEditOptions + * @typedef {Object} ApplicationEmojiEditOptions * @property {string} [name] The name of the emoji */ diff --git a/packages/discord.js/src/structures/ApplicationRoleConnectionMetadata.js b/packages/discord.js/src/structures/ApplicationRoleConnectionMetadata.js index 64ea3bb7c618..d19624917994 100644 --- a/packages/discord.js/src/structures/ApplicationRoleConnectionMetadata.js +++ b/packages/discord.js/src/structures/ApplicationRoleConnectionMetadata.js @@ -15,7 +15,7 @@ class ApplicationRoleConnectionMetadata { /** * The name localizations for this metadata field * - * @type {?Record} + * @type {?Object} */ this.nameLocalizations = data.name_localizations ?? null; @@ -29,7 +29,7 @@ class ApplicationRoleConnectionMetadata { /** * The description localizations for this metadata field * - * @type {?Record} + * @type {?Object} */ this.descriptionLocalizations = data.description_localizations ?? null; diff --git a/packages/discord.js/src/structures/Attachment.js b/packages/discord.js/src/structures/Attachment.js index 1bcd7cfa347a..0e502a064127 100644 --- a/packages/discord.js/src/structures/Attachment.js +++ b/packages/discord.js/src/structures/Attachment.js @@ -4,7 +4,7 @@ const { AttachmentFlagsBitField } = require('../util/AttachmentFlagsBitField.js' const { basename, flatten } = require('../util/Util.js'); /** - * @typedef {object} AttachmentPayload + * @typedef {Object} AttachmentPayload * @property {?string} name The name of the attachment * @property {Stream|BufferResolvable} attachment The attachment in this payload * @property {?string} description The description of the attachment diff --git a/packages/discord.js/src/structures/AttachmentBuilder.js b/packages/discord.js/src/structures/AttachmentBuilder.js index 1ff35601792a..031c3c4ff00e 100644 --- a/packages/discord.js/src/structures/AttachmentBuilder.js +++ b/packages/discord.js/src/structures/AttachmentBuilder.js @@ -116,7 +116,7 @@ class AttachmentBuilder { exports.AttachmentBuilder = AttachmentBuilder; /** - * @typedef {object} AttachmentData + * @typedef {Object} AttachmentData * @property {string} [name] The name of the attachment * @property {string} [description] The description of the attachment */ diff --git a/packages/discord.js/src/structures/AutoModerationRule.js b/packages/discord.js/src/structures/AutoModerationRule.js index ec12bcf2de2d..41642d145e1c 100644 --- a/packages/discord.js/src/structures/AutoModerationRule.js +++ b/packages/discord.js/src/structures/AutoModerationRule.js @@ -67,7 +67,7 @@ class AutoModerationRule extends Base { /** * Additional data used to determine whether an auto moderation rule should be triggered. * - * @typedef {object} AutoModerationTriggerMetadata + * @typedef {Object} AutoModerationTriggerMetadata * @property {string[]} keywordFilter The substrings that will be searched for in the content * @property {string[]} regexPatterns The regular expression patterns which will be matched against the content * Only Rust-flavored regular expressions are supported. @@ -100,7 +100,7 @@ class AutoModerationRule extends Base { /** * An object containing information about an auto moderation rule action. * - * @typedef {object} AutoModerationAction + * @typedef {Object} AutoModerationAction * @property {AutoModerationActionType} type The type of this auto moderation rule action * @property {AutoModerationActionMetadata} metadata Additional metadata needed during execution */ @@ -108,7 +108,7 @@ class AutoModerationRule extends Base { /** * Additional data used when an auto moderation rule is executed. * - * @typedef {object} AutoModerationActionMetadata + * @typedef {Object} AutoModerationActionMetadata * @property {?Snowflake} channelId The id of the channel to which content will be logged * @property {?number} durationSeconds The timeout duration in seconds * @property {?string} customMessage The custom message that is shown whenever a message is blocked diff --git a/packages/discord.js/src/structures/BaseGuildTextChannel.js b/packages/discord.js/src/structures/BaseGuildTextChannel.js index 9cf80ac84a98..5f365fcefd9f 100644 --- a/packages/discord.js/src/structures/BaseGuildTextChannel.js +++ b/packages/discord.js/src/structures/BaseGuildTextChannel.js @@ -149,7 +149,7 @@ class BaseGuildTextChannel extends GuildChannel { /** * Options used to create an invite to a guild channel. * - * @typedef {object} InviteCreateOptions + * @typedef {Object} InviteCreateOptions * @property {boolean} [temporary] Whether members that joined via the invite should be automatically * kicked after 24 hours if they have not yet received a role * @property {number} [maxAge] How long the invite should last (in seconds, 0 for forever) diff --git a/packages/discord.js/src/structures/ClientApplication.js b/packages/discord.js/src/structures/ClientApplication.js index 9f7dd4ae1c4e..d3ace855ef5f 100644 --- a/packages/discord.js/src/structures/ClientApplication.js +++ b/packages/discord.js/src/structures/ClientApplication.js @@ -15,7 +15,7 @@ const { Team } = require('./Team.js'); const { Application } = require('./interfaces/Application.js'); /** - * @typedef {object} ClientApplicationInstallParams + * @typedef {Object} ClientApplicationInstallParams * @property {OAuth2Scopes[]} scopes Scopes that will be set upon adding this application * @property {Readonly} permissions Permissions that will be requested for the integrated role */ @@ -85,7 +85,7 @@ class ClientApplication extends Application { /** * OAuth2 installation parameters. * - * @typedef {object} IntegrationTypesConfigurationParameters + * @typedef {Object} IntegrationTypesConfigurationParameters * @property {OAuth2Scopes[]} scopes Scopes that will be set upon adding this application * @property {Readonly} permissions Permissions that will be requested for the integrated role */ @@ -93,7 +93,7 @@ class ClientApplication extends Application { /** * The application's supported installation context data. * - * @typedef {object} IntegrationTypesConfigurationContext + * @typedef {Object} IntegrationTypesConfigurationContext * @property {?IntegrationTypesConfigurationParameters} oauth2InstallParams * Scopes and permissions regarding the installation context */ @@ -101,7 +101,7 @@ class ClientApplication extends Application { /** * The application's supported installation context data. * - * @typedef {object} IntegrationTypesConfiguration + * @typedef {Object} IntegrationTypesConfiguration * @property {IntegrationTypesConfigurationContext} [0] Scopes and permissions * regarding the guild-installation context * @property {IntegrationTypesConfigurationContext} [1] Scopes and permissions @@ -312,7 +312,7 @@ class ClientApplication extends Application { /** * Options used for editing an application. * - * @typedef {object} ClientApplicationEditOptions + * @typedef {Object} ClientApplicationEditOptions * @property {string} [customInstallURL] The application's custom installation URL * @property {string} [description] The application's description * @property {string} [roleConnectionsVerificationURL] The application's role connection verification URL @@ -394,11 +394,11 @@ class ClientApplication extends Application { /** * Data for creating or editing an application role connection metadata. * - * @typedef {object} ApplicationRoleConnectionMetadataEditOptions + * @typedef {Object} ApplicationRoleConnectionMetadataEditOptions * @property {string} name The name of the metadata field - * @property {?Record} [nameLocalizations] The name localizations for the metadata field + * @property {?Object} [nameLocalizations] The name localizations for the metadata field * @property {string} description The description of the metadata field - * @property {?Record} [descriptionLocalizations] The description localizations for the metadata field + * @property {?Object} [descriptionLocalizations] The description localizations for the metadata field * @property {string} key The dictionary key of the metadata field * @property {ApplicationRoleConnectionMetadataType} type The type of the metadata field */ diff --git a/packages/discord.js/src/structures/ClientUser.js b/packages/discord.js/src/structures/ClientUser.js index 83d38852997e..8a450afe6e48 100644 --- a/packages/discord.js/src/structures/ClientUser.js +++ b/packages/discord.js/src/structures/ClientUser.js @@ -49,7 +49,7 @@ class ClientUser extends User { /** * Data used to edit the logged in client * - * @typedef {object} ClientUserEditOptions + * @typedef {Object} ClientUserEditOptions * @property {string} [username] The new username * @property {?(BufferResolvable|Base64Resolvable)} [avatar] The new avatar * @property {?(BufferResolvable|Base64Resolvable)} [banner] The new banner @@ -126,7 +126,7 @@ class ClientUser extends User { /** * Options for setting activities * - * @typedef {object} ActivitiesOptions + * @typedef {Object} ActivitiesOptions * @property {string} name Name of the activity * @property {string} [state] State of the activity * @property {ActivityType} [type] Type of the activity @@ -136,7 +136,7 @@ class ClientUser extends User { /** * Data resembling a raw Discord presence. * - * @typedef {object} PresenceData + * @typedef {Object} PresenceData * @property {PresenceStatusData} [status] Status of the user * @property {boolean} [afk] Whether the user is AFK * @property {ActivitiesOptions[]} [activities] Activity the user is playing @@ -183,7 +183,7 @@ class ClientUser extends User { /** * Options for setting an activity. * - * @typedef {object} ActivityOptions + * @typedef {Object} ActivityOptions * @property {string} name Name of the activity * @property {string} [state] State of the activity * @property {string} [url] Twitch / YouTube stream URL diff --git a/packages/discord.js/src/structures/CommandInteraction.js b/packages/discord.js/src/structures/CommandInteraction.js index fa920cbe9f50..b30ce72d8b44 100644 --- a/packages/discord.js/src/structures/CommandInteraction.js +++ b/packages/discord.js/src/structures/CommandInteraction.js @@ -93,7 +93,7 @@ class CommandInteraction extends BaseInteraction { /** * Represents the resolved data of a received command interaction. * - * @typedef {object} CommandInteractionResolvedData + * @typedef {Object} CommandInteractionResolvedData * @property {Collection} [users] The resolved users * @property {Collection} [members] The resolved guild members * @property {Collection} [roles] The resolved roles @@ -105,7 +105,7 @@ class CommandInteraction extends BaseInteraction { /** * Represents an option of a received command interaction. * - * @typedef {object} CommandInteractionOption + * @typedef {Object} CommandInteractionOption * @property {string} name The name of the option * @property {ApplicationCommandOptionType} type The type of the option * @property {boolean} [autocomplete] Whether the autocomplete interaction is enabled for a diff --git a/packages/discord.js/src/structures/CommandInteractionOptionResolver.js b/packages/discord.js/src/structures/CommandInteractionOptionResolver.js index 79252454fded..66191e8597c1 100644 --- a/packages/discord.js/src/structures/CommandInteractionOptionResolver.js +++ b/packages/discord.js/src/structures/CommandInteractionOptionResolver.js @@ -313,7 +313,7 @@ class CommandInteractionOptionResolver { /** * The full autocomplete option object. * - * @typedef {object} AutocompleteFocusedOption + * @typedef {Object} AutocompleteFocusedOption * @property {string} name The name of the option * @property {ApplicationCommandOptionType} type The type of the application command option * @property {string} value The value of the option diff --git a/packages/discord.js/src/structures/Embed.js b/packages/discord.js/src/structures/Embed.js index 517958d50c19..165febd5e03b 100644 --- a/packages/discord.js/src/structures/Embed.js +++ b/packages/discord.js/src/structures/Embed.js @@ -78,7 +78,7 @@ class Embed { } /** - * @typedef {object} EmbedAssetData + * @typedef {Object} EmbedAssetData * @property {?string} url The URL of the image * @property {?string} proxyURL The proxy URL of the image * @property {?number} height The height of the image @@ -134,7 +134,7 @@ class Embed { } /** - * @typedef {object} EmbedAuthorData + * @typedef {Object} EmbedAuthorData * @property {string} name The name of the author * @property {?string} url The URL of the author * @property {?string} iconURL The icon URL of the author @@ -168,7 +168,7 @@ class Embed { } /** - * @typedef {object} EmbedFooterData + * @typedef {Object} EmbedFooterData * @property {string} text The text of the footer * @property {?string} iconURL The URL of the icon * @property {?string} proxyIconURL The proxy URL of the icon diff --git a/packages/discord.js/src/structures/Guild.js b/packages/discord.js/src/structures/Guild.js index 636c2e0384fd..ad9d8a2d6f8c 100644 --- a/packages/discord.js/src/structures/Guild.js +++ b/packages/discord.js/src/structures/Guild.js @@ -518,7 +518,7 @@ class Guild extends AnonymousGuild { /** * Incident actions of a guild. * - * @typedef {object} IncidentActions + * @typedef {Object} IncidentActions * @property {?Date} invitesDisabledUntil When invites would be enabled again * @property {?Date} dmsDisabledUntil When direct messages would be enabled again * @property {?Date} dmSpamDetectedAt When direct message spam was detected @@ -722,7 +722,7 @@ class Guild extends AnonymousGuild { /** * An object containing information about a guild's vanity invite. * - * @typedef {object} Vanity + * @typedef {Object} Vanity * @property {?string} code Vanity invite code * @property {number} uses How many times this invite has been used */ @@ -782,7 +782,7 @@ class Guild extends AnonymousGuild { /** * Data for the Guild Widget Settings object * - * @typedef {object} GuildWidgetSettings + * @typedef {Object} GuildWidgetSettings * @property {boolean} enabled Whether the widget is enabled * @property {?(TextChannel|AnnouncementChannel|VoiceChannel|StageChannel|ForumChannel|MediaChannel)} channel * The widget invite channel @@ -791,7 +791,7 @@ class Guild extends AnonymousGuild { /** * The Guild Widget Settings object * - * @typedef {object} GuildWidgetSettingsData + * @typedef {Object} GuildWidgetSettingsData * @property {boolean} enabled Whether the widget is enabled * @property {?(TextChannel|AnnouncementChannel|VoiceChannel|StageChannel|ForumChannel| * MediaChannel|Snowflake)} channel The widget invite channel @@ -830,7 +830,7 @@ class Guild extends AnonymousGuild { /** * Options used to fetch audit logs. * - * @typedef {object} GuildAuditLogsFetchOptions + * @typedef {Object} GuildAuditLogsFetchOptions * @property {Snowflake|GuildAuditLogsEntry} [before] Consider only entries before this entry * @property {Snowflake|GuildAuditLogsEntry} [after] Consider only entries after this entry * @property {number} [limit] The number of entries to return @@ -880,7 +880,7 @@ class Guild extends AnonymousGuild { /** * The data for editing a guild. * - * @typedef {object} GuildEditOptions + * @typedef {Object} GuildEditOptions * @property {string} [name] The name of the guild * @property {?GuildVerificationLevel} [verificationLevel] The verification level of the guild * @property {?GuildDefaultMessageNotifications} [defaultMessageNotifications] The default message @@ -985,7 +985,7 @@ class Guild extends AnonymousGuild { /** * Options used to edit the guild onboarding. * - * @typedef {object} GuildOnboardingEditOptions + * @typedef {Object} GuildOnboardingEditOptions * @property {GuildOnboardingPromptData[]|Collection} [prompts] * The prompts shown during onboarding and in customize community * @property {ChannelResolvable[]|Collection} [defaultChannels] @@ -998,7 +998,7 @@ class Guild extends AnonymousGuild { /** * Data for editing a guild onboarding prompt. * - * @typedef {object} GuildOnboardingPromptData + * @typedef {Object} GuildOnboardingPromptData * @property {Snowflake} [id] The id of the prompt * @property {string} title The title for the prompt * @property {boolean} [singleSelect] Whether users are limited to selecting one option for the prompt @@ -1012,7 +1012,7 @@ class Guild extends AnonymousGuild { /** * Data for editing a guild onboarding prompt option. * - * @typedef {object} GuildOnboardingPromptOptionData + * @typedef {Object} GuildOnboardingPromptOptionData * @property {?Snowflake} [id] The id of the option * @property {ChannelResolvable[]|Collection} [channels] * The channels a member is added to when the option is selected @@ -1068,7 +1068,7 @@ class Guild extends AnonymousGuild { /** * Welcome channel data * - * @typedef {object} WelcomeChannelData + * @typedef {Object} WelcomeChannelData * @property {string} description The description to show for this welcome channel * @property {TextChannel|AnnouncementChannel|ForumChannel|MediaChannel|Snowflake} channel * The channel to link for this welcome channel @@ -1078,7 +1078,7 @@ class Guild extends AnonymousGuild { /** * Welcome screen edit data * - * @typedef {object} WelcomeScreenEditOptions + * @typedef {Object} WelcomeScreenEditOptions * @property {boolean} [enabled] Whether the welcome screen is enabled * @property {string} [description] The description for the welcome screen * @property {WelcomeChannelData[]} [welcomeChannels] The welcome channel data for the welcome screen diff --git a/packages/discord.js/src/structures/GuildAuditLogsEntry.js b/packages/discord.js/src/structures/GuildAuditLogsEntry.js index e19c2ca35355..ee04c9412caf 100644 --- a/packages/discord.js/src/structures/GuildAuditLogsEntry.js +++ b/packages/discord.js/src/structures/GuildAuditLogsEntry.js @@ -97,8 +97,8 @@ const Targets = { * Constructs an object of known properties for a structure from an array of changes. * * @param {AuditLogChange[]} changes The array of changes - * @param {object} [initialData] The initial data passed to the function - * @returns {object} + * @param {Object} [initialData] The initial data passed to the function + * @returns {Object} * @ignore */ function changesReduce(changes, initialData = {}) { @@ -115,7 +115,7 @@ class GuildAuditLogsEntry { /** * Key mirror of all available audit log targets. * - * @type {Record} + * @type {Object} * @memberof GuildAuditLogsEntry */ static Targets = Targets; @@ -171,7 +171,7 @@ class GuildAuditLogsEntry { /** * An entry in the audit log representing a specific change. * - * @typedef {object} AuditLogChange + * @typedef {Object} AuditLogChange * @property {string} key The property that was changed, e.g. `nick` for nickname changes * For application command permissions updates the key is the id of the user, channel, * role, or a permission constant that was updated instead of an actual property name diff --git a/packages/discord.js/src/structures/GuildChannel.js b/packages/discord.js/src/structures/GuildChannel.js index 857d27508772..c6f55a910f48 100644 --- a/packages/discord.js/src/structures/GuildChannel.js +++ b/packages/discord.js/src/structures/GuildChannel.js @@ -333,7 +333,7 @@ class GuildChannel extends BaseChannel { /** * Options used to set the parent of a channel. * - * @typedef {object} SetParentOptions + * @typedef {Object} SetParentOptions * @property {boolean} [lockPermissions=false] Whether to lock the permissions to what the parent's permissions are * @property {string} [reason] The reason for modifying the parent of the channel */ @@ -366,7 +366,7 @@ class GuildChannel extends BaseChannel { /** * Options used to set the position of a channel. * - * @typedef {object} SetChannelPositionOptions + * @typedef {Object} SetChannelPositionOptions * @property {boolean} [relative=false] Whether or not to change the position relative to its current value * @property {string} [reason] The reason for changing the position */ diff --git a/packages/discord.js/src/structures/GuildEmoji.js b/packages/discord.js/src/structures/GuildEmoji.js index d20241c9f95b..2e673e8dd0f5 100644 --- a/packages/discord.js/src/structures/GuildEmoji.js +++ b/packages/discord.js/src/structures/GuildEmoji.js @@ -86,7 +86,7 @@ class GuildEmoji extends BaseGuildEmoji { /** * Data for editing an emoji. * - * @typedef {object} GuildEmojiEditOptions + * @typedef {Object} GuildEmojiEditOptions * @property {string} [name] The name of the emoji * @property {Collection|RoleResolvable[]} [roles] Roles to restrict emoji to * @property {string} [reason] Reason for editing this emoji diff --git a/packages/discord.js/src/structures/GuildScheduledEvent.js b/packages/discord.js/src/structures/GuildScheduledEvent.js index f01befd7a3b4..48fa135947c0 100644 --- a/packages/discord.js/src/structures/GuildScheduledEvent.js +++ b/packages/discord.js/src/structures/GuildScheduledEvent.js @@ -174,7 +174,7 @@ class GuildScheduledEvent extends Base { * Represents the additional metadata for a {@link GuildScheduledEvent} * * @see {@link https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-entity-metadata} - * @typedef {object} GuildScheduledEventEntityMetadata + * @typedef {Object} GuildScheduledEventEntityMetadata * @property {?string} location The location of the guild scheduled event */ @@ -209,7 +209,7 @@ class GuildScheduledEvent extends Base { /** * Represents the recurrence rule for a {@link GuildScheduledEvent}. * - * @typedef {object} GuildScheduledEventRecurrenceRule + * @typedef {Object} GuildScheduledEventRecurrenceRule * @property {number} startTimestamp The timestamp the recurrence rule interval starts at * @property {Date} startAt The time the recurrence rule interval starts at * @property {?number} endTimestamp The timestamp the recurrence rule interval ends at @@ -225,7 +225,7 @@ class GuildScheduledEvent extends Base { */ /** - * @typedef {object} GuildScheduledEventRecurrenceRuleNWeekday + * @typedef {Object} GuildScheduledEventRecurrenceRuleNWeekday * @property {number} n The week to recur on * @property {GuildScheduledEventRecurrenceRuleWeekday} day The day within the week to recur on */ diff --git a/packages/discord.js/src/structures/GuildTemplate.js b/packages/discord.js/src/structures/GuildTemplate.js index d022039d2002..c3e13fe07035 100644 --- a/packages/discord.js/src/structures/GuildTemplate.js +++ b/packages/discord.js/src/structures/GuildTemplate.js @@ -172,7 +172,7 @@ class GuildTemplate extends Base { /** * Options used to edit a guild template. * - * @typedef {object} GuildTemplateEditOptions + * @typedef {Object} GuildTemplateEditOptions * @property {string} [name] The name of this template * @property {string} [description] The description of this template */ diff --git a/packages/discord.js/src/structures/Integration.js b/packages/discord.js/src/structures/Integration.js index 4706bda7c590..b154c934152a 100644 --- a/packages/discord.js/src/structures/Integration.js +++ b/packages/discord.js/src/structures/Integration.js @@ -7,7 +7,7 @@ const { IntegrationApplication } = require('./IntegrationApplication.js'); /** * The information account for an integration * - * @typedef {object} IntegrationAccount + * @typedef {Object} IntegrationAccount * @property {Snowflake|string} id The id of the account * @property {string} name The name of the account */ diff --git a/packages/discord.js/src/structures/InteractionCallbackResource.js b/packages/discord.js/src/structures/InteractionCallbackResource.js index 65c7cb1a03e4..214f77d86695 100644 --- a/packages/discord.js/src/structures/InteractionCallbackResource.js +++ b/packages/discord.js/src/structures/InteractionCallbackResource.js @@ -28,7 +28,7 @@ class InteractionCallbackResource { /** * The Activity launched by an interaction * - * @typedef {object} ActivityInstance + * @typedef {Object} ActivityInstance * @property {string} id The instance id of the Activity */ diff --git a/packages/discord.js/src/structures/Message.js b/packages/discord.js/src/structures/Message.js index 27439c12c28b..d51e5c9eebcc 100644 --- a/packages/discord.js/src/structures/Message.js +++ b/packages/discord.js/src/structures/Message.js @@ -222,7 +222,7 @@ class Message extends Base { /** * Role subscription data found on {@link MessageType.RoleSubscriptionPurchase} messages. * - * @typedef {object} RoleSubscriptionData + * @typedef {Object} RoleSubscriptionData * @property {Snowflake} roleSubscriptionListingId The id of the SKU and listing the user is subscribed to * @property {string} tierName The name of the tier the user is subscribed to * @property {number} totalMonthsSubscribed The total number of months the user has been subscribed for @@ -249,7 +249,7 @@ class Message extends Base { /** * Resolved data from auto-populated select menus. * - * @typedef {object} CommandInteractionResolvedData + * @typedef {Object} CommandInteractionResolvedData * @property {Collection} attachments attachments * @property {Collection} channels channels * @property {Collection} members members @@ -396,7 +396,7 @@ class Message extends Base { * {@link MessageType.ThreadStarterMessage} * * @see {@link https://discord.com/developers/docs/resources/message#message-object-message-types} - * @typedef {object} MessageReference + * @typedef {Object} MessageReference * @property {Snowflake} channelId The channel id that was referenced * @property {Snowflake|undefined} guildId The guild id that was referenced * @property {Snowflake|undefined} messageId The message id that was referenced @@ -427,7 +427,7 @@ class Message extends Base { /** * Partial data of the interaction that a message is a result of * - * @typedef {object} MessageInteractionMetadata + * @typedef {Object} MessageInteractionMetadata * @property {Snowflake} id The interaction's id * @property {InteractionType} type The type of the interaction * @property {User} user The user that invoked the interaction @@ -494,7 +494,7 @@ class Message extends Base { /** * A call associated with a message * - * @typedef {object} MessageCall + * @typedef {Object} MessageCall * @property {Readonly} endedAt The time the call ended * @property {?number} endedTimestamp The timestamp the call ended * @property {Snowflake[]} participants The ids of the users that participated in the call @@ -700,7 +700,7 @@ class Message extends Base { /** * An object containing the same properties as CollectorOptions, but a few more: * - * @typedef {object} AwaitMessageComponentOptions + * @typedef {Object} AwaitMessageComponentOptions * @property {CollectorFilter} [filter] The filter applied to this collector * @property {number} [time] Time to wait for an interaction before rejecting * @property {ComponentType} [componentType] The type of component interaction to collect @@ -1033,7 +1033,7 @@ class Message extends Base { /** * Options for starting a thread on a message. * - * @typedef {object} StartThreadOptions + * @typedef {Object} StartThreadOptions * @property {string} name The name of the new thread * @property {ThreadAutoArchiveDuration} [autoArchiveDuration=this.channel.defaultAutoArchiveDuration] The amount of * time after which the thread should automatically archive in case of no recent activity diff --git a/packages/discord.js/src/structures/MessageMentions.js b/packages/discord.js/src/structures/MessageMentions.js index ff215abf3dc8..c1c32516ff95 100644 --- a/packages/discord.js/src/structures/MessageMentions.js +++ b/packages/discord.js/src/structures/MessageMentions.js @@ -167,7 +167,7 @@ class MessageMentions { /** * Crossposted channel data. * - * @typedef {object} CrosspostedChannel + * @typedef {Object} CrosspostedChannel * @property {Snowflake} channelId The mentioned channel's id * @property {Snowflake} guildId The id of the guild that has the channel * @property {ChannelType} type The channel's type @@ -217,10 +217,11 @@ class MessageMentions { if (this._members) return this._members; if (!this.guild) return null; this._members = new Collection(); - this.users.forEach(user => { + for (const user of this.users) { const member = this.guild.members.resolve(user); if (member) this._members.set(member.user.id, member); - }); + } + return this._members; } @@ -266,7 +267,7 @@ class MessageMentions { /** * Options used to check for a mention. * - * @typedef {object} MessageMentionsHasOptions + * @typedef {Object} MessageMentionsHasOptions * @property {boolean} [ignoreDirect=false] Whether to ignore direct mentions to the item * @property {boolean} [ignoreRoles=false] Whether to ignore role mentions to a guild member * @property {boolean} [ignoreRepliedUser=false] Whether to ignore replied user mention to an user diff --git a/packages/discord.js/src/structures/MessageReaction.js b/packages/discord.js/src/structures/MessageReaction.js index bfe910ec7e41..0328decd0fbc 100644 --- a/packages/discord.js/src/structures/MessageReaction.js +++ b/packages/discord.js/src/structures/MessageReaction.js @@ -79,7 +79,7 @@ class MessageReaction { /** * The reaction count details object contains information about super and normal reaction counts. * - * @typedef {object} ReactionCountDetailsData + * @typedef {Object} ReactionCountDetailsData * @property {number} burst Count of super reactions * @property {number} normal Count of normal reactions */ diff --git a/packages/discord.js/src/structures/ModalSubmitFields.js b/packages/discord.js/src/structures/ModalSubmitFields.js index e2c4e12be08e..15484d7befc5 100644 --- a/packages/discord.js/src/structures/ModalSubmitFields.js +++ b/packages/discord.js/src/structures/ModalSubmitFields.js @@ -22,7 +22,7 @@ class ModalSubmitFields { * @type {Collection} */ this.fields = components.reduce((accumulator, next) => { - next.components.forEach(component => accumulator.set(component.customId, component)); + for (const component of next.components) accumulator.set(component.customId, component); return accumulator; }, new Collection()); } diff --git a/packages/discord.js/src/structures/ModalSubmitInteraction.js b/packages/discord.js/src/structures/ModalSubmitInteraction.js index 485cdc0bde84..8c6f27ed17ac 100644 --- a/packages/discord.js/src/structures/ModalSubmitInteraction.js +++ b/packages/discord.js/src/structures/ModalSubmitInteraction.js @@ -9,14 +9,14 @@ const { InteractionResponses } = require('./interfaces/InteractionResponses.js') const getMessage = lazy(() => require('./Message.js').Message); /** - * @typedef {object} ModalData + * @typedef {Object} ModalData * @property {string} value The value of the field * @property {ComponentType} type The component type of the field * @property {string} customId The custom id of the field */ /** - * @typedef {object} ActionRowModalData + * @typedef {Object} ActionRowModalData * @property {ModalData[]} components The components of this action row * @property {ComponentType} type The component type of the action row */ diff --git a/packages/discord.js/src/structures/PartialGroupDMChannel.js b/packages/discord.js/src/structures/PartialGroupDMChannel.js index 8768e131f012..ab3c1cbd070e 100644 --- a/packages/discord.js/src/structures/PartialGroupDMChannel.js +++ b/packages/discord.js/src/structures/PartialGroupDMChannel.js @@ -35,7 +35,7 @@ class PartialGroupDMChannel extends BaseChannel { /** * Recipient data received in a {@link PartialGroupDMChannel}. * - * @typedef {object} PartialRecipient + * @typedef {Object} PartialRecipient * @property {string} username The username of the recipient */ diff --git a/packages/discord.js/src/structures/PermissionOverwrites.js b/packages/discord.js/src/structures/PermissionOverwrites.js index 3dbc49ef49a1..969027649840 100644 --- a/packages/discord.js/src/structures/PermissionOverwrites.js +++ b/packages/discord.js/src/structures/PermissionOverwrites.js @@ -112,11 +112,11 @@ class PermissionOverwrites extends Base { * } * ``` * - * @typedef {Record} PermissionOverwriteOptions + * @typedef {Object} PermissionOverwriteOptions */ /** - * @typedef {object} ResolvedOverwriteOptions + * @typedef {Object} ResolvedOverwriteOptions * @property {PermissionsBitField} allow The allowed permissions * @property {PermissionsBitField} deny The denied permissions */ @@ -151,7 +151,7 @@ class PermissionOverwrites extends Base { /** * The raw data for a permission overwrite * - * @typedef {object} RawOverwriteData + * @typedef {Object} RawOverwriteData * @property {Snowflake} id The id of the {@link Role} or {@link User} this overwrite belongs to * @property {string} allow The permissions to allow * @property {string} deny The permissions to deny @@ -169,7 +169,7 @@ class PermissionOverwrites extends Base { /** * Data that can be used for a permission overwrite * - * @typedef {object} OverwriteData + * @typedef {Object} OverwriteData * @property {UserResolvable|RoleResolvable} id Member or role this overwrite is for * @property {PermissionResolvable} [allow] The permissions to allow * @property {PermissionResolvable} [deny] The permissions to deny diff --git a/packages/discord.js/src/structures/Poll.js b/packages/discord.js/src/structures/Poll.js index 2d7b9e2eaf75..3378832014d4 100644 --- a/packages/discord.js/src/structures/Poll.js +++ b/packages/discord.js/src/structures/Poll.js @@ -123,7 +123,7 @@ class Poll extends Base { /** * The media for a poll's question * - * @typedef {object} PollQuestionMedia + * @typedef {Object} PollQuestionMedia * @property {?string} text The text of this question */ diff --git a/packages/discord.js/src/structures/PollAnswer.js b/packages/discord.js/src/structures/PollAnswer.js index b20e9568ee37..5e208d073c0e 100644 --- a/packages/discord.js/src/structures/PollAnswer.js +++ b/packages/discord.js/src/structures/PollAnswer.js @@ -97,7 +97,7 @@ class PollAnswer extends Base { /** * Options used for fetching voters of a poll answer. * - * @typedef {object} BaseFetchPollAnswerVotersOptions + * @typedef {Object} BaseFetchPollAnswerVotersOptions * @property {number} [limit] The maximum number of voters to fetch * @property {Snowflake} [after] The user id to fetch voters after */ diff --git a/packages/discord.js/src/structures/Presence.js b/packages/discord.js/src/structures/Presence.js index 6495fb0abe98..f3de71ab5a1f 100644 --- a/packages/discord.js/src/structures/Presence.js +++ b/packages/discord.js/src/structures/Presence.js @@ -9,7 +9,7 @@ const { Emoji } = require('./Emoji.js'); /** * Activity sent in a message. * - * @typedef {object} MessageActivity + * @typedef {Object} MessageActivity * @property {string} [partyId] Id of the party represented in activity * @property {MessageActivityType} type Type of activity sent */ @@ -208,7 +208,7 @@ class Activity { /** * Represents timestamps of an activity * - * @typedef {object} ActivityTimestamps + * @typedef {Object} ActivityTimestamps * @property {?Date} start When the activity started * @property {?Date} end When the activity will end */ @@ -228,7 +228,7 @@ class Activity { /** * Represents a party of an activity * - * @typedef {object} ActivityParty + * @typedef {Object} ActivityParty * @property {?string} id The party's id * @property {number[]} size Size of the party as `[current, max]` */ diff --git a/packages/discord.js/src/structures/Role.js b/packages/discord.js/src/structures/Role.js index 0d8bae75069f..d2a5d7a63b98 100644 --- a/packages/discord.js/src/structures/Role.js +++ b/packages/discord.js/src/structures/Role.js @@ -255,7 +255,7 @@ class Role extends Base { /** * The data for a role. * - * @typedef {object} RoleData + * @typedef {Object} RoleData * @property {string} [name] The name of the role * @property {ColorResolvable} [color] The color of the role, either a hex string or a base 10 number * @property {boolean} [hoist] Whether or not the role should be hoisted @@ -415,7 +415,7 @@ class Role extends Base { /** * Options used to set the position of a role. * - * @typedef {object} SetRolePositionOptions + * @typedef {Object} SetRolePositionOptions * @property {boolean} [relative=false] Whether to change the position relative to its current value or not * @property {string} [reason] The reason for changing the position */ diff --git a/packages/discord.js/src/structures/Sticker.js b/packages/discord.js/src/structures/Sticker.js index 5b3fa49a1780..a181cf6af4de 100644 --- a/packages/discord.js/src/structures/Sticker.js +++ b/packages/discord.js/src/structures/Sticker.js @@ -220,7 +220,7 @@ class Sticker extends Base { /** * Data for editing a sticker. * - * @typedef {object} GuildStickerEditOptions + * @typedef {Object} GuildStickerEditOptions * @property {string} [name] The name of the sticker * @property {?string} [description] The description of the sticker * @property {string} [tags] The Discord name of a unicode emoji representing the sticker's expression diff --git a/packages/discord.js/src/structures/ThreadChannel.js b/packages/discord.js/src/structures/ThreadChannel.js index 07c13771b309..48d76a2c0b2b 100644 --- a/packages/discord.js/src/structures/ThreadChannel.js +++ b/packages/discord.js/src/structures/ThreadChannel.js @@ -347,7 +347,7 @@ class ThreadChannel extends BaseChannel { /** * The options used to edit a thread channel * - * @typedef {object} ThreadEditOptions + * @typedef {Object} ThreadEditOptions * @property {string} [name] The new name for the thread * @property {boolean} [archived] Whether the thread is archived * @property {ThreadAutoArchiveDuration} [autoArchiveDuration] The amount of time after which the thread diff --git a/packages/discord.js/src/structures/ThreadOnlyChannel.js b/packages/discord.js/src/structures/ThreadOnlyChannel.js index 6955ba7a845b..c94d5e4bc0eb 100644 --- a/packages/discord.js/src/structures/ThreadOnlyChannel.js +++ b/packages/discord.js/src/structures/ThreadOnlyChannel.js @@ -6,13 +6,13 @@ const { GuildChannel } = require('./GuildChannel.js'); const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); /** - * @typedef {object} GuildForumTagEmoji + * @typedef {Object} GuildForumTagEmoji * @property {?Snowflake} id The id of a guild's custom emoji * @property {?string} name The unicode character of the emoji */ /** - * @typedef {object} GuildForumTag + * @typedef {Object} GuildForumTag * @property {Snowflake} id The id of the tag * @property {string} name The name of the tag * @property {boolean} moderated Whether this tag can only be added to or removed from threads @@ -21,7 +21,7 @@ const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); */ /** - * @typedef {object} GuildForumTagData + * @typedef {Object} GuildForumTagData * @property {Snowflake} [id] The id of the tag * @property {string} name The name of the tag * @property {boolean} [moderated] Whether this tag can only be added to or removed from threads @@ -30,7 +30,7 @@ const { TextBasedChannel } = require('./interfaces/TextBasedChannel.js'); */ /** - * @typedef {object} DefaultReactionEmoji + * @typedef {Object} DefaultReactionEmoji * @property {?Snowflake} id The id of a guild's custom emoji * @property {?string} name The unicode character of the emoji */ diff --git a/packages/discord.js/src/structures/User.js b/packages/discord.js/src/structures/User.js index 4bcd228a63b1..2851179e5619 100644 --- a/packages/discord.js/src/structures/User.js +++ b/packages/discord.js/src/structures/User.js @@ -133,7 +133,7 @@ class User extends Base { } /** - * @typedef {object} AvatarDecorationData + * @typedef {Object} AvatarDecorationData * @property {string} asset The avatar decoration hash * @property {Snowflake} skuId The id of the avatar decoration's SKU */ diff --git a/packages/discord.js/src/structures/VoiceChannel.js b/packages/discord.js/src/structures/VoiceChannel.js index 5b56a67e724c..c5dd819a6ede 100644 --- a/packages/discord.js/src/structures/VoiceChannel.js +++ b/packages/discord.js/src/structures/VoiceChannel.js @@ -39,7 +39,7 @@ class VoiceChannel extends BaseGuildVoiceChannel { } /** - * @typedef {object} SendSoundboardSoundOptions + * @typedef {Object} SendSoundboardSoundOptions * @property {string} soundId The id of the soundboard sound to send * @property {string} [guildId] The id of the guild the soundboard sound is a part of */ diff --git a/packages/discord.js/src/structures/VoiceState.js b/packages/discord.js/src/structures/VoiceState.js index df41f69e14a4..6661314a3ff9 100644 --- a/packages/discord.js/src/structures/VoiceState.js +++ b/packages/discord.js/src/structures/VoiceState.js @@ -231,7 +231,7 @@ class VoiceState extends Base { /** * Data to edit the logged in user's own voice state with, when in a stage channel * - * @typedef {object} VoiceStateEditOptions + * @typedef {Object} VoiceStateEditOptions * @property {boolean} [requestToSpeak] Whether or not the client is requesting to become a speaker. * Only available to the logged in user's own voice state. * @property {boolean} [suppressed] Whether or not the user should be suppressed. diff --git a/packages/discord.js/src/structures/Webhook.js b/packages/discord.js/src/structures/Webhook.js index 3debd06eddc9..fc179629daf2 100644 --- a/packages/discord.js/src/structures/Webhook.js +++ b/packages/discord.js/src/structures/Webhook.js @@ -257,7 +257,7 @@ class Webhook { /** * Sends a raw slack message with this webhook. * - * @param {object} body The raw body to send + * @param {Object} body The raw body to send * @returns {Promise} * @example * // Send a slack message @@ -287,7 +287,7 @@ class Webhook { /** * Options used to edit a {@link Webhook}. * - * @typedef {object} WebhookEditOptions + * @typedef {Object} WebhookEditOptions * @property {string} [name=this.name] The new name for the webhook * @property {?(BufferResolvable)} [avatar] The new avatar for the webhook * @property {GuildTextChannelResolvable|VoiceChannel|StageChannel|ForumChannel|MediaChannel} [channel] diff --git a/packages/discord.js/src/structures/WelcomeChannel.js b/packages/discord.js/src/structures/WelcomeChannel.js index 4caf536bf41f..93b9c22aff3c 100644 --- a/packages/discord.js/src/structures/WelcomeChannel.js +++ b/packages/discord.js/src/structures/WelcomeChannel.js @@ -29,7 +29,7 @@ class WelcomeChannel extends Base { /** * The raw emoji data * - * @type {object} + * @type {Object} * @private */ this._emoji = { diff --git a/packages/discord.js/src/structures/Widget.js b/packages/discord.js/src/structures/Widget.js index 12fbadf80617..362eb5896739 100644 --- a/packages/discord.js/src/structures/Widget.js +++ b/packages/discord.js/src/structures/Widget.js @@ -19,7 +19,7 @@ class Widget extends Base { /** * Represents a channel in a Widget * - * @typedef {object} WidgetChannel + * @typedef {Object} WidgetChannel * @property {Snowflake} id Id of the channel * @property {string} name Name of the channel * @property {number} position Position of the channel diff --git a/packages/discord.js/src/structures/WidgetMember.js b/packages/discord.js/src/structures/WidgetMember.js index 6df17a8460fd..36040780edb7 100644 --- a/packages/discord.js/src/structures/WidgetMember.js +++ b/packages/discord.js/src/structures/WidgetMember.js @@ -11,7 +11,7 @@ class WidgetMember extends Base { /** * Activity sent in a {@link WidgetMember}. * - * @typedef {object} WidgetActivity + * @typedef {Object} WidgetActivity * @property {string} name The name of the activity */ diff --git a/packages/discord.js/src/structures/interfaces/Collector.js b/packages/discord.js/src/structures/interfaces/Collector.js index 8c49c09b8836..c314c640bd05 100644 --- a/packages/discord.js/src/structures/interfaces/Collector.js +++ b/packages/discord.js/src/structures/interfaces/Collector.js @@ -18,7 +18,7 @@ const { flatten } = require('../../util/Util.js'); /** * Options to be applied to the collector. * - * @typedef {object} CollectorOptions + * @typedef {Object} CollectorOptions * @property {CollectorFilter} [filter] The filter applied to this collector * @property {number} [time] How long to run the collector for in milliseconds * @property {number} [idle] How long to stop the collector after inactivity in milliseconds @@ -261,7 +261,7 @@ class Collector extends AsyncEventEmitter { /** * Options used to reset the timeout and idle timer of a {@link Collector}. * - * @typedef {object} CollectorResetTimerOptions + * @typedef {Object} CollectorResetTimerOptions * @property {number} [time] How long to run the collector for (in milliseconds) * @property {number} [idle] How long to wait to stop the collector after inactivity (in milliseconds) */ diff --git a/packages/discord.js/src/structures/interfaces/InteractionResponses.js b/packages/discord.js/src/structures/interfaces/InteractionResponses.js index 8a79a3b2c688..c10606d379ab 100644 --- a/packages/discord.js/src/structures/interfaces/InteractionResponses.js +++ b/packages/discord.js/src/structures/interfaces/InteractionResponses.js @@ -10,7 +10,7 @@ const { InteractionCollector } = require('../InteractionCollector.js'); const { MessagePayload } = require('../MessagePayload.js'); /** - * @typedef {object} ModalComponentData + * @typedef {Object} ModalComponentData * @property {string} title The title of the modal * @property {string} customId The custom id of the modal * @property {ActionRow[]} components The components within this modal @@ -25,7 +25,7 @@ class InteractionResponses { /** * Options for deferring the reply to an {@link BaseInteraction}. * - * @typedef {object} InteractionDeferReplyOptions + * @typedef {Object} InteractionDeferReplyOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response * @property {MessageFlagsResolvable} [flags] Flags for the reply. * Only `MessageFlags.Ephemeral` can be set. @@ -34,7 +34,7 @@ class InteractionResponses { /** * Options for deferring and updating the reply to a {@link MessageComponentInteraction}. * - * @typedef {object} InteractionDeferUpdateOptions + * @typedef {Object} InteractionDeferUpdateOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response */ @@ -59,14 +59,14 @@ class InteractionResponses { /** * Options for launching activity in response to a {@link BaseInteraction} * - * @typedef {object} LaunchActivityOptions + * @typedef {Object} LaunchActivityOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response */ /** * Options for showing a modal in response to a {@link BaseInteraction} * - * @typedef {object} ShowModalOptions + * @typedef {Object} ShowModalOptions * @property {boolean} [withResponse] Whether to return an {@link InteractionCallbackResponse} as the response */ @@ -332,7 +332,7 @@ class InteractionResponses { /** * An object containing the same properties as {@link CollectorOptions}, but a few less: * - * @typedef {object} AwaitModalSubmitOptions + * @typedef {Object} AwaitModalSubmitOptions * @property {CollectorFilter} [filter] The filter applied to this collector * @property {number} time Time in milliseconds to wait for an interaction before rejecting */ diff --git a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js index a7564130d722..9883a75779d2 100644 --- a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js +++ b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js @@ -62,7 +62,7 @@ class TextBasedChannel { /** * Represents the data for a poll answer. * - * @typedef {object} PollAnswerData + * @typedef {Object} PollAnswerData * @property {string} text The text for the poll answer * @property {EmojiIdentifierResolvable} [emoji] The emoji for the poll answer */ @@ -70,7 +70,7 @@ class TextBasedChannel { /** * Represents the data for a poll. * - * @typedef {object} PollData + * @typedef {Object} PollData * @property {PollQuestionMedia} question The question for the poll * @property {PollAnswerData[]} answers The answers for the poll * @property {number} duration The duration in hours for the poll @@ -81,7 +81,7 @@ class TextBasedChannel { /** * The base message options for messages. * - * @typedef {object} BaseMessageOptions + * @typedef {Object} BaseMessageOptions * @property {?string} [content=''] The content for the message. This can only be `null` when editing a message. * @property {Array<(EmbedBuilder|Embed|APIEmbed)>} [embeds] The embeds for the message * @property {MessageMentionOptions} [allowedMentions] Which mentions should be parsed from the message content @@ -130,7 +130,7 @@ class TextBasedChannel { /** * Options provided to control parsing of mentions by Discord * - * @typedef {object} MessageMentionOptions + * @typedef {Object} MessageMentionOptions * @property {MessageMentionTypes[]} [parse] Types of mentions to be parsed * @property {Snowflake[]} [users] Snowflakes of Users to be parsed as mentions * @property {Snowflake[]} [roles] Snowflakes of Roles to be parsed as mentions @@ -346,7 +346,7 @@ class TextBasedChannel { /** * Options used to create a {@link Webhook}. * - * @typedef {object} ChannelWebhookCreateOptions + * @typedef {Object} ChannelWebhookCreateOptions * @property {string} name The name of the webhook * @property {?(BufferResolvable|Base64Resolvable)} [avatar] Avatar for the webhook * @property {string} [reason] Reason for creating the webhook diff --git a/packages/discord.js/src/util/BitField.js b/packages/discord.js/src/util/BitField.js index ca9379e6d8fa..a8aa2dbd1a09 100644 --- a/packages/discord.js/src/util/BitField.js +++ b/packages/discord.js/src/util/BitField.js @@ -10,7 +10,7 @@ class BitField { * Numeric bitfield flags. * Defined in extension classes * - * @type {object} + * @type {Object} * @memberof BitField * @abstract */ @@ -125,7 +125,7 @@ class BitField { * bit is available. * * @param {...*} hasParams Additional parameters for the has method, if any - * @returns {object} + * @returns {Object} */ serialize(...hasParams) { const serialized = {}; diff --git a/packages/discord.js/src/util/Channels.js b/packages/discord.js/src/util/Channels.js index 2a05235b0ae8..7d28302eadaa 100644 --- a/packages/discord.js/src/util/Channels.js +++ b/packages/discord.js/src/util/Channels.js @@ -18,7 +18,7 @@ const getMediaChannel = lazy(() => require('../structures/MediaChannel.js').Medi /** * Extra options for creating a channel. * - * @typedef {object} CreateChannelOptions + * @typedef {Object} CreateChannelOptions * @property {boolean} [allowFromUnknownGuild] Whether to allow creating a channel from an unknown guild * @private */ diff --git a/packages/discord.js/src/util/Colors.js b/packages/discord.js/src/util/Colors.js index 4f5bb1cec92f..eecda00ea15d 100644 --- a/packages/discord.js/src/util/Colors.js +++ b/packages/discord.js/src/util/Colors.js @@ -1,7 +1,7 @@ 'use strict'; /** - * @typedef {object} Colors + * @typedef {Object} Colors * @property {number} Aqua 0x1ABC9C | rgb(26,188,156) * @property {number} Blue 0x3498DB | rgb(52,152,219) * @property {number} Blurple 0x5865F2 | rgb(88,101,242) diff --git a/packages/discord.js/src/util/Components.js b/packages/discord.js/src/util/Components.js index 1c66ef21dce5..5b57261f00ea 100644 --- a/packages/discord.js/src/util/Components.js +++ b/packages/discord.js/src/util/Components.js @@ -1,11 +1,11 @@ /* eslint-disable @typescript-eslint/no-use-before-define */ -/* eslint-disable import-x/order */ 'use strict'; +// eslint-disable-next-line import-x/order const { ComponentType } = require('discord-api-types/v10'); /** - * @typedef {object} BaseComponentData + * @typedef {Object} BaseComponentData * @property {ComponentType} type The type of component */ @@ -25,7 +25,7 @@ const { ComponentType } = require('discord-api-types/v10'); */ /** - * @typedef {object} SelectMenuComponentOptionData + * @typedef {Object} SelectMenuComponentOptionData * @property {string} label The label of the option * @property {string} value The value of the option * @property {?string} description The description of the option diff --git a/packages/discord.js/src/util/Constants.js b/packages/discord.js/src/util/Constants.js index b6413285672b..1469c413c2d5 100644 --- a/packages/discord.js/src/util/Constants.js +++ b/packages/discord.js/src/util/Constants.js @@ -209,7 +209,7 @@ exports.UndeletableMessageTypes = [ * {@link StickerFormatType.Lottie} -> {@link ImageFormat.Lottie} * {@link StickerFormatType.GIF} -> {@link ImageFormat.GIF} * - * @typedef {object} StickerFormatExtensionMap + * @typedef {Object} StickerFormatExtensionMap * @property {"png"} 1 PNG * @property {"png"} 2 APNG * @property {"json"} 3 Lottie @@ -223,7 +223,7 @@ exports.StickerFormatExtensionMap = { }; /** - * @typedef {object} Constants Constants that can be used in an enum or object-like way. + * @typedef {Object} Constants Constants that can be used in an enum or object-like way. * @property {number} MaxBulkDeletableMessageAge Max bulk deletable message age * @property {SweeperKey[]} SweeperKeys The possible names of items that can be swept in sweepers * @property {NonSystemMessageTypes} NonSystemMessageTypes The types of messages that are not deemed a system type @@ -231,5 +231,5 @@ exports.StickerFormatExtensionMap = { * @property {ThreadChannelTypes} ThreadChannelTypes The types of channels that are threads * @property {VoiceBasedChannelTypes} VoiceBasedChannelTypes The types of channels that are voice-based * @property {SelectMenuTypes} SelectMenuTypes The types of components that are select menus. - * @property {object} StickerFormatExtensionMap A mapping between sticker formats and their respective image formats. + * @property {Object} StickerFormatExtensionMap A mapping between sticker formats and their respective image formats. */ diff --git a/packages/discord.js/src/util/DataResolver.js b/packages/discord.js/src/util/DataResolver.js index 0df2886177f1..c081977ab892 100644 --- a/packages/discord.js/src/util/DataResolver.js +++ b/packages/discord.js/src/util/DataResolver.js @@ -74,7 +74,7 @@ function resolveGuildTemplateCode(data) { */ /** - * @typedef {object} ResolvedFile + * @typedef {Object} ResolvedFile * @property {Buffer} data Buffer containing the file data * @property {string} [contentType] Content-Type of the file * @private diff --git a/packages/discord.js/src/util/Events.js b/packages/discord.js/src/util/Events.js index 92ab18111e78..c546055e755b 100644 --- a/packages/discord.js/src/util/Events.js +++ b/packages/discord.js/src/util/Events.js @@ -1,7 +1,7 @@ 'use strict'; /** - * @typedef {object} Events + * @typedef {Object} Events * @property {string} ApplicationCommandPermissionsUpdate applicationCommandPermissionsUpdate * @property {string} AutoModerationActionExecution autoModerationActionExecution * @property {string} AutoModerationRuleCreate autoModerationRuleCreate diff --git a/packages/discord.js/src/util/LimitedCollection.js b/packages/discord.js/src/util/LimitedCollection.js index 2272a8f9d566..214d7e5c224a 100644 --- a/packages/discord.js/src/util/LimitedCollection.js +++ b/packages/discord.js/src/util/LimitedCollection.js @@ -6,7 +6,7 @@ const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); /** * Options for defining the behavior of a LimitedCollection * - * @typedef {object} LimitedCollectionOptions + * @typedef {Object} LimitedCollectionOptions * @property {?number} [maxSize=Infinity] The maximum size of the Collection * @property {?Function} [keepOverLimit=null] A function, which is passed the value and key of an entry, ran to decide * to keep an entry past the maximum size diff --git a/packages/discord.js/src/util/Options.js b/packages/discord.js/src/util/Options.js index 58728ab9d300..fda896b0d7f3 100644 --- a/packages/discord.js/src/util/Options.js +++ b/packages/discord.js/src/util/Options.js @@ -17,7 +17,7 @@ const { toSnakeCase } = require('./Transformers.js'); /** * Options for a client. * - * @typedef {object} ClientOptions + * @typedef {Object} ClientOptions * @property {number} [closeTimeout=5_000] The amount of time in milliseconds to wait for the close frame to be received * from the WebSocket. Don't have this too high/low. It's best to have it between 2_000-6_000 ms. * @property {CacheFactory} [makeCache] Function to create a cache. @@ -44,13 +44,13 @@ const { toSnakeCase } = require('./Transformers.js'); /** * Options for {@link Sweepers} defining the behavior of cache sweeping * - * @typedef {Record} SweeperOptions + * @typedef {Object} SweeperOptions */ /** * Options for sweeping a single type of item from cache * - * @typedef {object} SweepOptions + * @typedef {Object} SweepOptions * @property {number} interval The interval (in seconds) at which to perform sweeping of the item * @property {number} [lifetime] How long an item should stay in cache until it is considered sweepable. * This property is only valid for the `invites`, `messages`, and `threads` keys. The `filter` property @@ -102,7 +102,7 @@ class Options extends null { /** * Create a cache factory using predefined settings to sweep or limit. * - * @param {Record} [settings] Settings passed to the relevant constructor. + * @param {Object} [settings] Settings passed to the relevant constructor. * If no setting is provided for a manager, it uses Collection. * If a number is provided for a manager, it uses that number as the max size for a LimitedCollection. * If LimitedCollectionOptions are provided for a manager, it uses those settings to form a LimitedCollection. @@ -163,7 +163,7 @@ class Options extends null { * If you want to keep default behavior and add on top of it you can use this object and add on to it, e.g. * `makeCache: Options.cacheWithLimits({ ...Options.DefaultMakeCacheSettings, ReactionManager: 0 })` * - * @type {Record} + * @type {Object} */ static get DefaultMakeCacheSettings() { return { diff --git a/packages/discord.js/src/util/Partials.js b/packages/discord.js/src/util/Partials.js index e671adcb9a8f..abbfc7f1e3f1 100644 --- a/packages/discord.js/src/util/Partials.js +++ b/packages/discord.js/src/util/Partials.js @@ -18,7 +18,7 @@ const { createEnum } = require('./Enums.js'); * }); * ``` * - * @typedef {object} Partials + * @typedef {Object} Partials * @property {number} User The partial to receive uncached users. * @property {number} Channel The partial to receive uncached channels. * This is required to receive direct messages! diff --git a/packages/discord.js/src/util/ShardEvents.js b/packages/discord.js/src/util/ShardEvents.js index 4b079db90527..831e44913df9 100644 --- a/packages/discord.js/src/util/ShardEvents.js +++ b/packages/discord.js/src/util/ShardEvents.js @@ -1,7 +1,7 @@ 'use strict'; /** - * @typedef {object} ShardEvents + * @typedef {Object} ShardEvents * @property {string} Death death * @property {string} Disconnect disconnect * @property {string} Error error diff --git a/packages/discord.js/src/util/Status.js b/packages/discord.js/src/util/Status.js index d603751ddd55..9f67d09c5320 100644 --- a/packages/discord.js/src/util/Status.js +++ b/packages/discord.js/src/util/Status.js @@ -3,7 +3,7 @@ const { createEnum } = require('./Enums.js'); /** - * @typedef {object} Status + * @typedef {Object} Status * @property {number} Ready ready * @property {number} Idle idle * @property {number} WaitingForGuilds waiting for guilds diff --git a/packages/discord.js/src/util/Sweepers.js b/packages/discord.js/src/util/Sweepers.js index a256bd7b21ed..837e7fd4d1b1 100644 --- a/packages/discord.js/src/util/Sweepers.js +++ b/packages/discord.js/src/util/Sweepers.js @@ -35,7 +35,7 @@ class Sweepers { /** * A record of interval timeout that is used to sweep the indicated items, or null if not being swept * - * @type {Record} + * @type {Object} */ this.intervals = Object.fromEntries(SweeperKeys.map(key => [key, null])); @@ -347,7 +347,7 @@ class Sweepers { /** * Options for generating a filter function based on lifetime * - * @typedef {object} LifetimeFilterOptions + * @typedef {Object} LifetimeFilterOptions * @property {number} [lifetime=14400] How long, in seconds, an entry should stay in the collection * before it is considered sweepable. * @property {Function} [getComparisonTimestamp=e => e?.createdTimestamp] A function that takes an entry, key, @@ -438,7 +438,7 @@ class Sweepers { /** * Configuration options for emitting the cache sweep client event * - * @typedef {object} SweepEventOptions + * @typedef {Object} SweepEventOptions * @property {boolean} [emit=true] Whether to emit the client event in this method * @property {string} [outputName] A name to output in the client event if it should differ from the key * @private @@ -450,7 +450,7 @@ class Sweepers { * @param {string} key The name of the property * @param {Function} filter Filter function passed to sweep * @param {SweepEventOptions} [eventOptions] Options for the Client event emitted here - * @returns {object} Object containing the number of guilds swept and the number of items swept + * @returns {Object} Object containing the number of guilds swept and the number of items swept * @private */ _sweepGuildDirectProp(key, filter, { emit = true, outputName } = {}) { @@ -513,7 +513,7 @@ class Sweepers { * * @param {string} intervalKey The name of the property that stores the interval for this sweeper * @param {string} sweepKey The name of the function that sweeps the desired caches - * @param {object} opts Validated options for a sweep + * @param {Object} opts Validated options for a sweep * @private */ _initInterval(intervalKey, sweepKey, opts) { diff --git a/packages/discord.js/src/util/ThreadMemberFlagsBitField.js b/packages/discord.js/src/util/ThreadMemberFlagsBitField.js index 1aec66e402a0..1b38c504d24a 100644 --- a/packages/discord.js/src/util/ThreadMemberFlagsBitField.js +++ b/packages/discord.js/src/util/ThreadMemberFlagsBitField.js @@ -11,7 +11,7 @@ class ThreadMemberFlagsBitField extends BitField { /** * Numeric thread member flags. There are currently no bitflags relevant to bots for this. * - * @type {Record} + * @type {Object} * @memberof ThreadMemberFlagsBitField */ static Flags = {}; diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index a8a76a580016..c45c8b62ea25 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -1,4 +1,3 @@ -/* eslint-disable import-x/order */ 'use strict'; // eslint-disable-next-line @typescript-eslint/unbound-method @@ -6,7 +5,9 @@ const { parse } = require('node:path'); const { Collection } = require('@discordjs/collection'); const { ChannelType, RouteBases, Routes } = require('discord-api-types/v10'); const { fetch } = require('undici'); +// eslint-disable-next-line import-x/order const { Colors } = require('./Colors.js'); +// eslint-disable-next-line import-x/order const { DiscordjsError, DiscordjsRangeError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); const isObject = data => typeof data === 'object' && data !== null; @@ -14,9 +15,9 @@ const isObject = data => typeof data === 'object' && data !== null; /** * Flatten an object. Any properties that are collections will get converted to an array of keys. * - * @param {object} obj The object to flatten. - * @param {...Record} [props] Specific properties to include/exclude. - * @returns {object} + * @param {Object} obj The object to flatten. + * @param {...Object} [props] Specific properties to include/exclude. + * @returns {Object} */ function flatten(obj, ...props) { if (!isObject(obj)) return obj; @@ -59,7 +60,7 @@ function flatten(obj, ...props) { } /** - * @typedef {object} FetchRecommendedShardCountOptions + * @typedef {Object} FetchRecommendedShardCountOptions * @property {number} [guildsPerShard=1000] Number of guilds assigned per shard * @property {number} [multipleOf=1] The multiple the shard count should round up to. (16 for large bot sharding) */ @@ -90,7 +91,7 @@ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multi /** * A partial emoji object. * - * @typedef {object} PartialEmoji + * @typedef {Object} PartialEmoji * @property {boolean} animated Whether the emoji is animated * @property {Snowflake|undefined} id The id of the emoji * @property {string} name The name of the emoji @@ -115,7 +116,7 @@ function parseEmoji(text) { /** * A partial emoji object with only an id. * - * @typedef {object} PartialEmojiOnlyId + * @typedef {Object} PartialEmojiOnlyId * @property {Snowflake} id The id of the emoji */ @@ -160,7 +161,7 @@ function resolveGuildEmoji(client, emojiId) { /** * Options used to make an error object. * - * @typedef {object} MakeErrorOptions + * @typedef {Object} MakeErrorOptions * @property {string} name Error type * @property {string} message Message for the error * @property {string} stack Stack for the error @@ -477,7 +478,7 @@ function parseWebhookURL(url) { /** * Supportive data for interaction resolved data. * - * @typedef {object} SupportingInteractionResolvedData + * @typedef {Object} SupportingInteractionResolvedData * @property {Client} client The client * @property {Guild} [guild] A guild * @property {GuildTextBasedChannel} [channel] A channel From 45dcff97008482b69d9aeac99e8284d8d1f61f93 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 13:09:36 +0200 Subject: [PATCH 06/38] fix: more lint changes --- eslint.config.js | 44 +++++++++++++++++--------- packages/discord.js/typings/index.d.ts | 9 ++++-- 2 files changed, 36 insertions(+), 17 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 2538f346750b..e0688fbc0366 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -148,23 +148,8 @@ export default tseslint.config( }, settings: { jsdoc: { - tagNamePreference: { - augments: 'extends', - return: 'returns', - arg: 'param', - fires: 'emits', - function: 'method', - }, preferredTypes: { - String: 'string', - Number: 'number', - Boolean: 'boolean', - Symbol: 'symbol', object: 'Object', - function: 'Function', - array: 'Array', - date: 'Date', - error: 'Error', null: 'void', }, }, @@ -187,6 +172,35 @@ export default tseslint.config( '@typescript-eslint/no-unsafe-declaration-merging': 0, '@typescript-eslint/no-empty-object-type': 0, '@typescript-eslint/no-use-before-define': 0, + 'no-restricted-syntax': [ + 2, + { + selector: + 'MethodDefinition[key.name!=on][key.name!=once][key.name!=off] > TSEmptyBodyFunctionExpression > Identifier :not(TSTypeOperator[operator=readonly]) > TSArrayType', + message: 'Array parameters on methods must be readonly', + }, + { + selector: + 'MethodDefinition > TSEmptyBodyFunctionExpression > Identifier TSTypeReference > Identifier[name=Collection]', + message: 'Parameters of type Collection on methods must use ReadonlyCollection', + }, + { + selector: 'TSDeclareFunction > Identifier :not(TSTypeOperator[operator=readonly]) > TSArrayType', + message: 'Array parameters on functions must be readonly', + }, + { + selector: 'TSDeclareFunction Identifier TSTypeReference > Identifier[name=Collection]', + message: 'Parameters of type Collection on functions must use ReadonlyCollection', + }, + { + selector: 'TSInterfaceDeclaration TSPropertySignature :not(TSTypeOperator[operator=readonly]) > TSArrayType', + message: 'Array properties on interfaces must be readonly', + }, + { + selector: 'TSInterfaceDeclaration TSPropertySignature TSTypeReference > Identifier[name=Collection]', + message: 'Interface properties of type Collection must use ReadonlyCollection', + }, + ], }, }, { diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index ea0c84468045..41a151cb6924 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -4097,7 +4097,12 @@ export function makePlainError(err: Error): MakeErrorOptions; /** * @internal */ -export function moveElementInArray(array: unknown[], element: unknown, newIndex: number, offset?: boolean): number; +export function moveElementInArray( + array: readonly unknown[], + element: unknown, + newIndex: number, + offset?: boolean, +): number; export function parseEmoji(text: string): PartialEmoji | null; export function resolveColor(color: ColorResolvable): number; export function resolvePartialEmoji(emoji: Snowflake): PartialEmojiOnlyId; @@ -7338,7 +7343,7 @@ export interface PartialPoll null, 'answers' | 'message' | 'question' > { - answers: Collection; + answers: ReadonlyCollection; message: PartialMessage; question: { text: null }; } From 6b46d98e4ecb897edcb531a7c6002ae432596f94 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 13:33:42 +0200 Subject: [PATCH 07/38] fix: type tests --- packages/discord.js/typings/index.test-d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/discord.js/typings/index.test-d.ts b/packages/discord.js/typings/index.test-d.ts index 5b759ea25f3c..60e9cd60175d 100644 --- a/packages/discord.js/typings/index.test-d.ts +++ b/packages/discord.js/typings/index.test-d.ts @@ -2756,7 +2756,7 @@ if (partialPoll.partial) { expectType(partialPoll.allowMultiselect); expectType(partialPoll.layoutType); expectType(partialPoll.expiresTimestamp); - expectType>(partialPoll.answers); + expectType>(partialPoll.answers); } declare const partialPollAnswer: PartialPollAnswer; From 9bb0a5d1091d9a027a5192544001010487b6cb3f Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 13:54:56 +0200 Subject: [PATCH 08/38] chore: port eslint rule --- eslint.config.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/eslint.config.js b/eslint.config.js index e0688fbc0366..18842dd2c15c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -162,6 +162,32 @@ export default tseslint.config( '@typescript-eslint/class-literal-property-style': 0, strict: ['error', 'global'], 'unicorn/consistent-function-scoping': 0, + + 'no-restricted-syntax': [ + 'error', + { + selector: "AssignmentExpression[left.object.name='module'][left.property.name='exports']", + message: 'Use named exports instead of module.exports', + }, + { + selector: + "VariableDeclarator[init.callee.name='require'][init.arguments.0.value=/^\\./]:not([id.type='ObjectPattern'])", + message: 'Use object destructuring when requiring local modules', + }, + ], + }, + }, + { + files: [`packages/discord.js/src/client/websocket/handlers/*.js`], + rules: { + 'no-restricted-syntax': [ + 'error', + { + selector: + "VariableDeclarator[init.callee.name='require'][init.arguments.0.value=/^\\./]:not([id.type='ObjectPattern'])", + message: 'Use object destructuring when requiring local modules', + }, + ], }, }, { From 99ab57d4ff81e6d60703220418c33c87ef3e7141 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 16:47:15 +0200 Subject: [PATCH 09/38] refactor: lintstaged doesn't need this --- packages/discord.js/.lintstagedrc.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/discord.js/.lintstagedrc.json b/packages/discord.js/.lintstagedrc.json index 55af9a21847e..2b5149872266 100644 --- a/packages/discord.js/.lintstagedrc.json +++ b/packages/discord.js/.lintstagedrc.json @@ -1,5 +1,5 @@ { "$schema": "https://json.schemastore.org/lintstagedrc.schema.json", "*": "prettier --ignore-unknown --write", - "{src/**,test/**,typings/**,scripts/**}.{mjs,js,ts}": "cross-env TIMING=1 eslint --fix --format=pretty" + "{src/**,test/**,typings/**,scripts/**}.{mjs,js,ts}": "cross-env eslint --fix" } From 0e3e3917bd04d1206c972aef74fd88344ecb35d0 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 19:20:32 +0200 Subject: [PATCH 10/38] fix: eslint was a bit too eager --- eslint.config.js | 3 +- .../src/managers/ApplicationCommandManager.js | 4 +- .../ApplicationCommandPermissionsManager.js | 2 +- .../src/managers/AutoModerationRuleManager.js | 4 +- .../discord.js/src/managers/ChannelManager.js | 4 +- .../src/managers/EntitlementManager.js | 8 +- .../src/managers/GuildBanManager.js | 6 +- .../src/managers/GuildChannelManager.js | 14 +- .../src/managers/GuildEmojiManager.js | 14 +- .../src/managers/GuildInviteManager.js | 20 +-- .../discord.js/src/managers/GuildManager.js | 12 +- .../managers/GuildScheduledEventManager.js | 6 +- .../managers/GuildSoundboardSoundManager.js | 6 +- .../src/managers/GuildStickerManager.js | 6 +- .../discord.js/src/managers/MessageManager.js | 6 +- .../src/managers/PollAnswerVoterManager.js | 2 +- .../src/managers/PresenceManager.js | 6 +- .../src/managers/ReactionManager.js | 6 +- .../src/managers/ReactionUserManager.js | 2 +- .../discord.js/src/managers/RoleManager.js | 4 +- .../src/managers/StageInstanceManager.js | 4 +- .../src/managers/SubscriptionManager.js | 2 +- .../discord.js/src/managers/ThreadManager.js | 14 +- .../src/managers/ThreadMemberManager.js | 4 +- .../discord.js/src/managers/UserManager.js | 10 +- packages/discord.js/src/sharding/Shard.js | 4 +- .../src/sharding/ShardClientUtil.js | 2 +- .../src/sharding/ShardingManager.js | 8 +- .../src/structures/AnonymousGuild.js | 4 +- .../src/structures/ApplicationCommand.js | 6 +- .../src/structures/AttachmentBuilder.js | 2 +- .../src/structures/AutoModerationRule.js | 2 +- .../discord.js/src/structures/BaseChannel.js | 2 +- .../discord.js/src/structures/BaseGuild.js | 2 +- .../src/structures/BaseGuildTextChannel.js | 8 +- .../src/structures/BaseGuildVoiceChannel.js | 4 +- .../discord.js/src/structures/ClientUser.js | 10 +- .../CommandInteractionOptionResolver.js | 28 ++-- .../discord.js/src/structures/DMChannel.js | 2 +- packages/discord.js/src/structures/Emoji.js | 2 +- packages/discord.js/src/structures/Guild.js | 28 ++-- .../src/structures/GuildAuditLogsEntry.js | 82 +++++------ .../discord.js/src/structures/GuildBan.js | 2 +- .../discord.js/src/structures/GuildChannel.js | 2 +- .../discord.js/src/structures/GuildMember.js | 12 +- .../discord.js/src/structures/GuildPreview.js | 6 +- .../src/structures/GuildScheduledEvent.js | 4 +- .../discord.js/src/structures/Integration.js | 8 +- .../src/structures/InteractionCollector.js | 2 +- packages/discord.js/src/structures/Invite.js | 3 +- packages/discord.js/src/structures/Message.js | 22 +-- .../structures/MessageComponentInteraction.js | 12 +- .../src/structures/MessagePayload.js | 2 +- .../src/structures/PartialGroupDMChannel.js | 2 +- .../src/structures/PermissionOverwrites.js | 4 +- .../discord.js/src/structures/PollAnswer.js | 2 +- .../discord.js/src/structures/Presence.js | 18 +-- .../src/structures/ReactionCollector.js | 2 +- packages/discord.js/src/structures/Role.js | 8 +- .../discord.js/src/structures/StickerPack.js | 2 +- packages/discord.js/src/structures/Team.js | 2 +- .../src/structures/ThreadChannel.js | 8 +- .../src/structures/ThreadOnlyChannel.js | 2 +- packages/discord.js/src/structures/User.js | 10 +- .../discord.js/src/structures/VoiceState.js | 8 +- packages/discord.js/src/structures/Webhook.js | 4 +- .../src/structures/interfaces/Application.js | 4 +- .../src/structures/interfaces/Collector.js | 2 +- .../interfaces/InteractionResponses.js | 8 +- .../structures/interfaces/TextBasedChannel.js | 12 +- .../src/util/ApplicationFlagsBitField.js | 8 +- packages/discord.js/src/util/BitField.js | 17 ++- .../src/util/ChannelFlagsBitField.js | 8 +- packages/discord.js/src/util/Constants.js | 138 +++++++++--------- packages/discord.js/src/util/DataResolver.js | 22 +-- .../src/util/GuildMemberFlagsBitField.js | 8 +- .../discord.js/src/util/IntentsBitField.js | 8 +- .../discord.js/src/util/LimitedCollection.js | 2 +- .../src/util/MessageFlagsBitField.js | 8 +- packages/discord.js/src/util/Options.js | 6 +- .../src/util/PermissionsBitField.js | 14 +- packages/discord.js/src/util/Sweepers.js | 10 +- .../src/util/SystemChannelFlagsBitField.js | 8 +- packages/discord.js/src/util/Util.js | 14 +- packages/discord.js/typings/index.d.ts | 1 + 85 files changed, 406 insertions(+), 404 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 18842dd2c15c..aca2a321a2cc 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -158,6 +158,7 @@ export default tseslint.config( '@typescript-eslint/no-var-requires': 0, '@typescript-eslint/no-require-imports': 0, 'jsdoc/no-undefined-types': 0, + 'jsdoc/no-defaults': 0, '@typescript-eslint/explicit-member-accessibility': 0, '@typescript-eslint/class-literal-property-style': 0, strict: ['error', 'global'], @@ -193,8 +194,6 @@ export default tseslint.config( { files: [`packages/discord.js/typings/*{d.ts,test-d.ts}`], rules: { - 'n/prefer-global/buffer': 0, - 'no-restricted-globals': 0, '@typescript-eslint/no-unsafe-declaration-merging': 0, '@typescript-eslint/no-empty-object-type': 0, '@typescript-eslint/no-use-before-define': 0, diff --git a/packages/discord.js/src/managers/ApplicationCommandManager.js b/packages/discord.js/src/managers/ApplicationCommandManager.js index e5759860a679..cbf7672ef013 100644 --- a/packages/discord.js/src/managers/ApplicationCommandManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandManager.js @@ -66,8 +66,8 @@ class ApplicationCommandManager extends CachedManager { /** * Data that resolves to give an ApplicationCommand object. This can be: - * An ApplicationCommand object - * A Snowflake + * - An ApplicationCommand object + * - A Snowflake * * @typedef {ApplicationCommand|Snowflake} ApplicationCommandResolvable */ diff --git a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js index bc80aa5b3871..517efdf93fa8 100644 --- a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js @@ -84,7 +84,7 @@ class ApplicationCommandPermissionsManager extends BaseManager { /** * Fetches the permissions for one or multiple commands. Providing the client's id as the "command id" will fetch - * only* the guild level permissions + * _only_ the guild level permissions * * @param {BaseApplicationCommandPermissionsOptions} [options] Options used to fetch permissions * @returns {Promise>} diff --git a/packages/discord.js/src/managers/AutoModerationRuleManager.js b/packages/discord.js/src/managers/AutoModerationRuleManager.js index 947f630cd3fd..c19414e4dfcf 100644 --- a/packages/discord.js/src/managers/AutoModerationRuleManager.js +++ b/packages/discord.js/src/managers/AutoModerationRuleManager.js @@ -222,8 +222,8 @@ class AutoModerationRuleManager extends CachedManager { /** * Data that can be resolved to give an AutoModerationRule object. This can be: - * An AutoModerationRule - * A Snowflake + * - An AutoModerationRule + * - A Snowflake * * @typedef {AutoModerationRule|Snowflake} AutoModerationRuleResolvable */ diff --git a/packages/discord.js/src/managers/ChannelManager.js b/packages/discord.js/src/managers/ChannelManager.js index ca93e50b3721..508d4010b208 100644 --- a/packages/discord.js/src/managers/ChannelManager.js +++ b/packages/discord.js/src/managers/ChannelManager.js @@ -80,8 +80,8 @@ class ChannelManager extends CachedManager { /** * Data that can be resolved to give a Channel object. This can be: - * A Channel object - * A Snowflake + * - A Channel object + * - A Snowflake * * @typedef {BaseChannel|Snowflake} ChannelResolvable */ diff --git a/packages/discord.js/src/managers/EntitlementManager.js b/packages/discord.js/src/managers/EntitlementManager.js index b86648c2a08d..70cd518f94cb 100644 --- a/packages/discord.js/src/managers/EntitlementManager.js +++ b/packages/discord.js/src/managers/EntitlementManager.js @@ -27,16 +27,16 @@ class EntitlementManager extends CachedManager { /** * Data that resolves to give an Entitlement object. This can be: - * An Entitlement object - * A Snowflake + * - An Entitlement object + * - A Snowflake * * @typedef {Entitlement|Snowflake} EntitlementResolvable */ /** * Data that resolves to give a SKU object. This can be: - * A SKU object - * A Snowflake + * - A SKU object + * - A Snowflake * * @typedef {SKU|Snowflake} SKUResolvable */ diff --git a/packages/discord.js/src/managers/GuildBanManager.js b/packages/discord.js/src/managers/GuildBanManager.js index 9f625f777079..4abb65a75e4a 100644 --- a/packages/discord.js/src/managers/GuildBanManager.js +++ b/packages/discord.js/src/managers/GuildBanManager.js @@ -37,8 +37,8 @@ class GuildBanManager extends CachedManager { /** * Data that resolves to give a GuildBan object. This can be: - * A GuildBan object - * A User resolvable + * - A GuildBan object + * - A User resolvable * * @typedef {GuildBan|UserResolvable} GuildBanResolvable */ @@ -145,7 +145,7 @@ class GuildBanManager extends CachedManager { * Bans a user from the guild. * * @param {UserResolvable} user The user to ban - * @param {BanOptions} [options] Options for the ban + * @param {BanOptions} [options={}] Options for the ban * @returns {Promise} * @example * // Ban a user by id (or with a user/guild member object) diff --git a/packages/discord.js/src/managers/GuildChannelManager.js b/packages/discord.js/src/managers/GuildChannelManager.js index 231478333ef3..df5dae6accad 100644 --- a/packages/discord.js/src/managers/GuildChannelManager.js +++ b/packages/discord.js/src/managers/GuildChannelManager.js @@ -76,9 +76,9 @@ class GuildChannelManager extends CachedManager { /** * Data that can be resolved to give a Guild Channel object. This can be: - * A GuildChannel object - * A ThreadChannel object - * A Snowflake + * - A GuildChannel object + * - A ThreadChannel object + * - A Snowflake * * @typedef {GuildChannel|ThreadChannel|Snowflake} GuildChannelResolvable */ @@ -107,8 +107,8 @@ class GuildChannelManager extends CachedManager { /** * Data that can be resolved to an Announcement Channel object. This can be: - * An Announcement Channel object - * A Snowflake + * - An Announcement Channel object + * - A Snowflake * * @typedef {AnnouncementChannel|Snowflake} AnnouncementChannelResolvable */ @@ -456,8 +456,8 @@ class GuildChannelManager extends CachedManager { /** * Data that can be resolved to give a Category Channel object. This can be: - * A CategoryChannel object - * A Snowflake + * - A CategoryChannel object + * - A Snowflake * * @typedef {CategoryChannel|Snowflake} CategoryChannelResolvable */ diff --git a/packages/discord.js/src/managers/GuildEmojiManager.js b/packages/discord.js/src/managers/GuildEmojiManager.js index ec39228ecd90..83ef0e490916 100644 --- a/packages/discord.js/src/managers/GuildEmojiManager.js +++ b/packages/discord.js/src/managers/GuildEmojiManager.js @@ -39,10 +39,10 @@ class GuildEmojiManager extends CachedManager { /** * Data that can be resolved into a GuildEmoji object. This can be: - * A Snowflake - * A GuildEmoji object - * A ReactionEmoji object - * An ApplicationEmoji object + * - A Snowflake + * - A GuildEmoji object + * - A ReactionEmoji object + * - An ApplicationEmoji object * * @typedef {Snowflake|GuildEmoji|ReactionEmoji|ApplicationEmoji} EmojiResolvable */ @@ -73,9 +73,9 @@ class GuildEmojiManager extends CachedManager { /** * Data that can be resolved to give an emoji identifier. This can be: - * An EmojiResolvable - * The ``, `<:name:id>`, `a:name:id` or `name:id` emoji identifier string of an emoji - * The Unicode representation of an emoji + * - An EmojiResolvable + * - The ``, `<:name:id>`, `a:name:id` or `name:id` emoji identifier string of an emoji + * - The Unicode representation of an emoji * * @typedef {string|EmojiResolvable} EmojiIdentifierResolvable */ diff --git a/packages/discord.js/src/managers/GuildInviteManager.js b/packages/discord.js/src/managers/GuildInviteManager.js index e71d4e584986..69b8b04588dd 100644 --- a/packages/discord.js/src/managers/GuildInviteManager.js +++ b/packages/discord.js/src/managers/GuildInviteManager.js @@ -37,21 +37,21 @@ class GuildInviteManager extends CachedManager { /** * Data that resolves to give an Invite object. This can be: - * An invite code - * An invite URL + * - An invite code + * - An invite URL * * @typedef {string} InviteResolvable */ /** * Data that can be resolved to a channel that an invite can be created on. This can be: - * TextChannel - * VoiceChannel - * AnnouncementChannel - * StageChannel - * ForumChannel - * MediaChannel - * Snowflake + * - TextChannel + * - VoiceChannel + * - AnnouncementChannel + * - StageChannel + * - ForumChannel + * - MediaChannel + * - Snowflake * * @typedef {TextChannel|VoiceChannel|AnnouncementChannel|StageChannel|ForumChannel|MediaChannel|Snowflake} * GuildInvitableChannelResolvable @@ -182,7 +182,7 @@ class GuildInviteManager extends CachedManager { * Create an invite to the guild from the provided channel. * * @param {GuildInvitableChannelResolvable} channel The options for creating the invite from a channel. - * @param {InviteCreateOptions} [options] The options for creating the invite from a channel. + * @param {InviteCreateOptions} [options={}] The options for creating the invite from a channel. * @returns {Promise} * @example * // Create an invite to a selected channel diff --git a/packages/discord.js/src/managers/GuildManager.js b/packages/discord.js/src/managers/GuildManager.js index 075f801a7aa3..35b1114e9326 100644 --- a/packages/discord.js/src/managers/GuildManager.js +++ b/packages/discord.js/src/managers/GuildManager.js @@ -50,12 +50,12 @@ class GuildManager extends CachedManager { /** * Data that resolves to give a Guild object. This can be: - * A Guild object - * A GuildChannel object - * A GuildEmoji object - * A Role object - * A Snowflake - * An Invite object + * - A Guild object + * - A GuildChannel object + * - A GuildEmoji object + * - A Role object + * - A Snowflake + * - An Invite object * * @typedef {Guild|GuildChannel|GuildMember|GuildEmoji|Role|Snowflake|Invite} GuildResolvable */ diff --git a/packages/discord.js/src/managers/GuildScheduledEventManager.js b/packages/discord.js/src/managers/GuildScheduledEventManager.js index d29792b20d4c..e0423e5b47b0 100644 --- a/packages/discord.js/src/managers/GuildScheduledEventManager.js +++ b/packages/discord.js/src/managers/GuildScheduledEventManager.js @@ -35,8 +35,8 @@ class GuildScheduledEventManager extends CachedManager { /** * Data that resolves to give a GuildScheduledEvent object. This can be: - * A Snowflake - * A GuildScheduledEvent object + * - A Snowflake + * - A GuildScheduledEvent object * * @typedef {Snowflake|GuildScheduledEvent} GuildScheduledEventResolvable */ @@ -300,7 +300,7 @@ class GuildScheduledEventManager extends CachedManager { * Fetches subscribers of a guild scheduled event. * * @param {GuildScheduledEventResolvable} guildScheduledEvent The guild scheduled event to fetch subscribers of - * @param {FetchGuildScheduledEventSubscribersOptions} [options] Options for fetching the subscribers + * @param {FetchGuildScheduledEventSubscribersOptions} [options={}] Options for fetching the subscribers * @returns {Promise>} */ async fetchSubscribers(guildScheduledEvent, options = {}) { diff --git a/packages/discord.js/src/managers/GuildSoundboardSoundManager.js b/packages/discord.js/src/managers/GuildSoundboardSoundManager.js index d4fdaf011f79..2170e28e559b 100644 --- a/packages/discord.js/src/managers/GuildSoundboardSoundManager.js +++ b/packages/discord.js/src/managers/GuildSoundboardSoundManager.js @@ -40,8 +40,8 @@ class GuildSoundboardSoundManager extends CachedManager { /** * Data that resolves to give a SoundboardSound object. This can be: - * A SoundboardSound object - * A Snowflake + * - A SoundboardSound object + * - A Snowflake * * @typedef {SoundboardSound|Snowflake} SoundboardSoundResolvable */ @@ -124,7 +124,7 @@ class GuildSoundboardSoundManager extends CachedManager { * Edits a soundboard sound. * * @param {SoundboardSoundResolvable} soundboardSound The soundboard sound to edit - * @param {GuildSoundboardSoundEditOptions} [options] The new data for the soundboard sound + * @param {GuildSoundboardSoundEditOptions} [options={}] The new data for the soundboard sound * @returns {Promise} */ async edit(soundboardSound, options = {}) { diff --git a/packages/discord.js/src/managers/GuildStickerManager.js b/packages/discord.js/src/managers/GuildStickerManager.js index bacc23bf3e00..e8bd50f76db4 100644 --- a/packages/discord.js/src/managers/GuildStickerManager.js +++ b/packages/discord.js/src/managers/GuildStickerManager.js @@ -79,8 +79,8 @@ class GuildStickerManager extends CachedManager { /** * Data that resolves to give a Sticker object. This can be: - * A Sticker object - * A Snowflake + * - A Sticker object + * - A Snowflake * * @typedef {Sticker|Snowflake} StickerResolvable */ @@ -109,7 +109,7 @@ class GuildStickerManager extends CachedManager { * Edits a sticker. * * @param {StickerResolvable} sticker The sticker to edit - * @param {GuildStickerEditOptions} [options] The new data for the sticker + * @param {GuildStickerEditOptions} [options={}] The new data for the sticker * @returns {Promise} */ async edit(sticker, options = {}) { diff --git a/packages/discord.js/src/managers/MessageManager.js b/packages/discord.js/src/managers/MessageManager.js index c79050eace4b..284e15cf8545 100644 --- a/packages/discord.js/src/managers/MessageManager.js +++ b/packages/discord.js/src/managers/MessageManager.js @@ -43,8 +43,8 @@ class MessageManager extends CachedManager { /** * Data that can be resolved to a Message object. This can be: - * A Message - * A Snowflake + * - A Message + * - A Snowflake * * @typedef {Message|Snowflake} MessageResolvable */ @@ -128,7 +128,7 @@ class MessageManager extends CachedManager { * The returned Collection does not contain any reaction data of the messages. * Those need to be fetched separately. * - * @param {boolean} [cache] Whether to cache the message(s) + * @param {boolean} [cache=true] Whether to cache the message(s) * @returns {Promise>} * @example * // Get pinned messages diff --git a/packages/discord.js/src/managers/PollAnswerVoterManager.js b/packages/discord.js/src/managers/PollAnswerVoterManager.js index 93d37cba9ac7..f904dd7a5339 100644 --- a/packages/discord.js/src/managers/PollAnswerVoterManager.js +++ b/packages/discord.js/src/managers/PollAnswerVoterManager.js @@ -33,7 +33,7 @@ class PollAnswerVoterManager extends CachedManager { /** * Fetches the users that voted on this poll answer. Resolves with a collection of users, mapped by their ids. * - * @param {BaseFetchPollAnswerVotersOptions} [options] Options for fetching the users + * @param {BaseFetchPollAnswerVotersOptions} [options={}] Options for fetching the users * @returns {Promise>} */ async fetch({ after, limit } = {}) { diff --git a/packages/discord.js/src/managers/PresenceManager.js b/packages/discord.js/src/managers/PresenceManager.js index 3689f875115b..ad42176257a5 100644 --- a/packages/discord.js/src/managers/PresenceManager.js +++ b/packages/discord.js/src/managers/PresenceManager.js @@ -26,9 +26,9 @@ class PresenceManager extends CachedManager { /** * Data that can be resolved to a Presence object. This can be: - * A Presence - * A UserResolvable - * A Snowflake + * - A Presence + * - A UserResolvable + * - A Snowflake * * @typedef {Presence|UserResolvable|Snowflake} PresenceResolvable */ diff --git a/packages/discord.js/src/managers/ReactionManager.js b/packages/discord.js/src/managers/ReactionManager.js index 3b776f873c6f..315641b83e64 100644 --- a/packages/discord.js/src/managers/ReactionManager.js +++ b/packages/discord.js/src/managers/ReactionManager.js @@ -34,9 +34,9 @@ class ReactionManager extends CachedManager { /** * Data that can be resolved to a MessageReaction object. This can be: - * A MessageReaction - * A Snowflake - * The Unicode representation of an emoji + * - A MessageReaction + * - A Snowflake + * - The Unicode representation of an emoji * * @typedef {MessageReaction|Snowflake} MessageReactionResolvable */ diff --git a/packages/discord.js/src/managers/ReactionUserManager.js b/packages/discord.js/src/managers/ReactionUserManager.js index aa8f0e31220e..378677519154 100644 --- a/packages/discord.js/src/managers/ReactionUserManager.js +++ b/packages/discord.js/src/managers/ReactionUserManager.js @@ -66,7 +66,7 @@ class ReactionUserManager extends CachedManager { /** * Removes a user from this reaction. * - * @param {UserResolvable} [user] The user to remove the reaction of + * @param {UserResolvable} [user=this.client.user] The user to remove the reaction of * @returns {Promise} */ async remove(user = this.client.user) { diff --git a/packages/discord.js/src/managers/RoleManager.js b/packages/discord.js/src/managers/RoleManager.js index 4f8b1407454d..15a02a020997 100644 --- a/packages/discord.js/src/managers/RoleManager.js +++ b/packages/discord.js/src/managers/RoleManager.js @@ -83,8 +83,8 @@ class RoleManager extends CachedManager { /** * Data that can be resolved to a Role object. This can be: - * A Role - * A Snowflake + * - A Role + * - A Snowflake * * @typedef {Role|Snowflake} RoleResolvable */ diff --git a/packages/discord.js/src/managers/StageInstanceManager.js b/packages/discord.js/src/managers/StageInstanceManager.js index baf6b1cbbed4..53c152d5248f 100644 --- a/packages/discord.js/src/managers/StageInstanceManager.js +++ b/packages/discord.js/src/managers/StageInstanceManager.js @@ -42,8 +42,8 @@ class StageInstanceManager extends CachedManager { /** * Data that can be resolved to a Stage Channel object. This can be: - * A StageChannel - * A Snowflake + * - A StageChannel + * - A Snowflake * * @typedef {StageChannel|Snowflake} StageChannelResolvable */ diff --git a/packages/discord.js/src/managers/SubscriptionManager.js b/packages/discord.js/src/managers/SubscriptionManager.js index 8c08e81d26f5..595704f0911b 100644 --- a/packages/discord.js/src/managers/SubscriptionManager.js +++ b/packages/discord.js/src/managers/SubscriptionManager.js @@ -48,7 +48,7 @@ class SubscriptionManager extends CachedManager { /** * Fetches subscriptions for this application * - * @param {FetchSubscriptionOptions|FetchSubscriptionsOptions} [options] Options for fetching the subscriptions + * @param {FetchSubscriptionOptions|FetchSubscriptionsOptions} [options={}] Options for fetching the subscriptions * @returns {Promise>} */ async fetch(options = {}) { diff --git a/packages/discord.js/src/managers/ThreadManager.js b/packages/discord.js/src/managers/ThreadManager.js index 212f1e435ceb..171a0969fba6 100644 --- a/packages/discord.js/src/managers/ThreadManager.js +++ b/packages/discord.js/src/managers/ThreadManager.js @@ -29,8 +29,8 @@ class ThreadManager extends CachedManager { /** * Data that can be resolved to a Thread Channel object. This can be: - * A ThreadChannel object - * A Snowflake + * - A ThreadChannel object + * - A Snowflake * * @typedef {ThreadChannel|Snowflake} ThreadChannelResolvable */ @@ -109,9 +109,9 @@ class ThreadManager extends CachedManager { /** * Data that can be resolved to a Date object. This can be: - * A Date object - * A number representing a timestamp - * An {@link https://en.wikipedia.org/wiki/ISO_8601 ISO 8601} string + * - A Date object + * - A number representing a timestamp + * - An {@link https://en.wikipedia.org/wiki/ISO_8601 ISO 8601} string * * @typedef {Date|number|string} DateResolvable */ @@ -142,7 +142,7 @@ class ThreadManager extends CachedManager { * in the parent channel. * * @param {FetchArchivedThreadOptions} [options] The options to fetch archived threads - * @param {boolean} [cache] Whether to cache the new thread objects if they aren't already + * @param {boolean} [cache=true] Whether to cache the new thread objects if they aren't already * @returns {Promise} */ async fetchArchived({ type = 'public', fetchAll = false, before, limit } = {}, cache = true) { @@ -181,7 +181,7 @@ class ThreadManager extends CachedManager { /** * Obtains all active threads in the channel. * - * @param {boolean} [cache] Whether to cache the fetched data + * @param {boolean} [cache=true] Whether to cache the fetched data * @returns {Promise} */ async fetchActive(cache = true) { diff --git a/packages/discord.js/src/managers/ThreadMemberManager.js b/packages/discord.js/src/managers/ThreadMemberManager.js index 4bd1d459d8d1..e96a4a2899e8 100644 --- a/packages/discord.js/src/managers/ThreadMemberManager.js +++ b/packages/discord.js/src/managers/ThreadMemberManager.js @@ -63,8 +63,8 @@ class ThreadMemberManager extends CachedManager { /** * Data that resolves to give a ThreadMember object. This can be: - * A ThreadMember object - * A User resolvable + * - A ThreadMember object + * - A User resolvable * * @typedef {ThreadMember|UserResolvable} ThreadMemberResolvable */ diff --git a/packages/discord.js/src/managers/UserManager.js b/packages/discord.js/src/managers/UserManager.js index 7f91be28b1cf..748c5181fac2 100644 --- a/packages/discord.js/src/managers/UserManager.js +++ b/packages/discord.js/src/managers/UserManager.js @@ -27,11 +27,11 @@ class UserManager extends CachedManager { /** * Data that resolves to give a User object. This can be: - * A User object - * A Snowflake - * A Message object (resolves to the message author) - * A GuildMember object - * A ThreadMember object + * - A User object + * - A Snowflake + * - A Message object (resolves to the message author) + * - A GuildMember object + * - A ThreadMember object * * @typedef {User|Snowflake|Message|GuildMember|ThreadMember} UserResolvable */ diff --git a/packages/discord.js/src/sharding/Shard.js b/packages/discord.js/src/sharding/Shard.js index 48b33bd9a101..d1d6fc1d1b8c 100644 --- a/packages/discord.js/src/sharding/Shard.js +++ b/packages/discord.js/src/sharding/Shard.js @@ -134,7 +134,7 @@ class Shard extends AsyncEventEmitter { * Forks a child process or creates a worker thread for the shard. * You should not need to call this manually. * - * @param {number} [timeout] The amount in milliseconds to wait until the {@link Client} has become ready + * @param {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready * before resolving (`-1` or `Infinity` for no wait) * @returns {Promise} */ @@ -451,7 +451,7 @@ class Shard extends AsyncEventEmitter { /** * Handles the shard's process/worker exiting. * - * @param {boolean} [respawn] Whether to spawn the shard again + * @param {boolean} [respawn=this.manager.respawn] Whether to spawn the shard again * @param {number} [timeout] The amount in milliseconds to wait until the {@link Client} * has become ready (`-1` or `Infinity` for no wait) * @private diff --git a/packages/discord.js/src/sharding/ShardClientUtil.js b/packages/discord.js/src/sharding/ShardClientUtil.js index 7057bd53b6c9..716410664e8f 100644 --- a/packages/discord.js/src/sharding/ShardClientUtil.js +++ b/packages/discord.js/src/sharding/ShardClientUtil.js @@ -128,7 +128,7 @@ class ShardClientUtil { * Evaluates a script or function on all shards, or a given shard, in the context of the {@link Client}s. * * @param {Function} script JavaScript to run on each shard - * @param {BroadcastEvalOptions} [options] The options for the broadcast + * @param {BroadcastEvalOptions} [options={}] The options for the broadcast * @returns {Promise<*|Array<*>>} Results of the script execution * @example * client.shard.broadcastEval(client => client.guilds.cache.size) diff --git a/packages/discord.js/src/sharding/ShardingManager.js b/packages/discord.js/src/sharding/ShardingManager.js index ded3c83c8f11..2ad4039fc24b 100644 --- a/packages/discord.js/src/sharding/ShardingManager.js +++ b/packages/discord.js/src/sharding/ShardingManager.js @@ -23,8 +23,8 @@ const { Shard } = require('./Shard.js'); class ShardingManager extends AsyncEventEmitter { /** * The mode to spawn shards with for a {@link ShardingManager}. Can be either one of: - * 'process' to use child processes - * 'worker' to use {@link Worker} threads + * - 'process' to use child processes + * - 'worker' to use {@link Worker} threads * * @typedef {string} ShardingManagerMode */ @@ -179,7 +179,7 @@ class ShardingManager extends AsyncEventEmitter { * Creates a single shard. * Using this method is usually not necessary if you use the spawn method. * - * @param {number} [id] Id of the shard to create + * @param {number} [id=this.shards.size] Id of the shard to create * This is usually not necessary to manually specify. * @returns {Shard} Note that the created shard needs to be explicitly spawned using its spawn method. */ @@ -285,7 +285,7 @@ class ShardingManager extends AsyncEventEmitter { * Evaluates a script on all shards, or a given shard, in the context of the {@link Client}s. * * @param {Function} script JavaScript to run on each shard - * @param {BroadcastEvalOptions} [options] The options for the broadcast + * @param {BroadcastEvalOptions} [options={}] The options for the broadcast * @returns {Promise<*|Array<*>>} Results of the script execution */ async broadcastEval(script, options = {}) { diff --git a/packages/discord.js/src/structures/AnonymousGuild.js b/packages/discord.js/src/structures/AnonymousGuild.js index 3aae65f64874..7738e29216b9 100644 --- a/packages/discord.js/src/structures/AnonymousGuild.js +++ b/packages/discord.js/src/structures/AnonymousGuild.js @@ -86,7 +86,7 @@ class AnonymousGuild extends BaseGuild { /** * The URL to this guild's banner. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ bannerURL(options = {}) { @@ -96,7 +96,7 @@ class AnonymousGuild extends BaseGuild { /** * The URL to this guild's invite splash image. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ splashURL(options = {}) { diff --git a/packages/discord.js/src/structures/ApplicationCommand.js b/packages/discord.js/src/structures/ApplicationCommand.js index adce7eeed298..0403af955b44 100644 --- a/packages/discord.js/src/structures/ApplicationCommand.js +++ b/packages/discord.js/src/structures/ApplicationCommand.js @@ -406,7 +406,7 @@ class ApplicationCommand extends Base { * what most users need. * * @param {ApplicationCommand|ApplicationCommandData|APIApplicationCommand} command The command to compare with - * @param {boolean} [enforceOptionOrder] Whether to strictly check that options and choices are in the same + * @param {boolean} [enforceOptionOrder=false] Whether to strictly check that options and choices are in the same * order in the array The client may not always respect this ordering! * @returns {boolean} */ @@ -466,7 +466,7 @@ class ApplicationCommand extends Base { * @param {ApplicationCommandOptionData[]} existing The options on the existing command, * should be {@link ApplicationCommand#options} * @param {ApplicationCommandOptionData[]|APIApplicationCommandOption[]} options The options to compare against - * @param {boolean} [enforceOptionOrder] Whether to strictly check that options and choices are in the same + * @param {boolean} [enforceOptionOrder=false] Whether to strictly check that options and choices are in the same * order in the array The client may not always respect this ordering! * @returns {boolean} */ @@ -492,7 +492,7 @@ class ApplicationCommand extends Base { * @param {ApplicationCommandOptionData} existing The option on the existing command, * should be from {@link ApplicationCommand#options} * @param {ApplicationCommandOptionData|APIApplicationCommandOption} option The option to compare against - * @param {boolean} [enforceOptionOrder] Whether to strictly check that options or choices are in the same + * @param {boolean} [enforceOptionOrder=false] Whether to strictly check that options or choices are in the same * order in their array The client may not always respect this ordering! * @returns {boolean} * @private diff --git a/packages/discord.js/src/structures/AttachmentBuilder.js b/packages/discord.js/src/structures/AttachmentBuilder.js index 031c3c4ff00e..f5489c7f07a4 100644 --- a/packages/discord.js/src/structures/AttachmentBuilder.js +++ b/packages/discord.js/src/structures/AttachmentBuilder.js @@ -67,7 +67,7 @@ class AttachmentBuilder { /** * Sets whether this attachment is a spoiler * - * @param {boolean} [spoiler] Whether the attachment should be marked as a spoiler + * @param {boolean} [spoiler=true] Whether the attachment should be marked as a spoiler * @returns {AttachmentBuilder} This attachment */ setSpoiler(spoiler = true) { diff --git a/packages/discord.js/src/structures/AutoModerationRule.js b/packages/discord.js/src/structures/AutoModerationRule.js index 41642d145e1c..d4899f00ec52 100644 --- a/packages/discord.js/src/structures/AutoModerationRule.js +++ b/packages/discord.js/src/structures/AutoModerationRule.js @@ -281,7 +281,7 @@ class AutoModerationRule extends Base { /** * Sets whether this auto moderation rule should be enabled. * - * @param {boolean} [enabled] Whether to enable this auto moderation rule + * @param {boolean} [enabled=true] Whether to enable this auto moderation rule * @param {string} [reason] The reason for enabling or disabling this auto moderation rule * @returns {Promise} */ diff --git a/packages/discord.js/src/structures/BaseChannel.js b/packages/discord.js/src/structures/BaseChannel.js index d71680efe7a9..416d2c434e77 100644 --- a/packages/discord.js/src/structures/BaseChannel.js +++ b/packages/discord.js/src/structures/BaseChannel.js @@ -119,7 +119,7 @@ class BaseChannel extends Base { /** * Fetches this channel. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=true] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { diff --git a/packages/discord.js/src/structures/BaseGuild.js b/packages/discord.js/src/structures/BaseGuild.js index b07415c8cbb5..b7c6124e27d2 100644 --- a/packages/discord.js/src/structures/BaseGuild.js +++ b/packages/discord.js/src/structures/BaseGuild.js @@ -100,7 +100,7 @@ class BaseGuild extends Base { /** * The URL to this guild's icon. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ iconURL(options = {}) { diff --git a/packages/discord.js/src/structures/BaseGuildTextChannel.js b/packages/discord.js/src/structures/BaseGuildTextChannel.js index 5f365fcefd9f..b8ca6b51cc56 100644 --- a/packages/discord.js/src/structures/BaseGuildTextChannel.js +++ b/packages/discord.js/src/structures/BaseGuildTextChannel.js @@ -139,9 +139,9 @@ class BaseGuildTextChannel extends GuildChannel { /** * Data that can be resolved to an Application. This can be: - * An Application - * An Activity with associated Application - * A Snowflake + * - An Application + * - An Activity with associated Application + * - A Snowflake * * @typedef {Application|Snowflake} ApplicationResolvable */ @@ -183,7 +183,7 @@ class BaseGuildTextChannel extends GuildChannel { * Fetches a collection of invites to this guild channel. * Resolves with a collection mapping invites by their codes. * - * @param {boolean} [cache] Whether or not to cache the fetched invites + * @param {boolean} [cache=true] Whether or not to cache the fetched invites * @returns {Promise>} */ async fetchInvites(cache = true) { diff --git a/packages/discord.js/src/structures/BaseGuildVoiceChannel.js b/packages/discord.js/src/structures/BaseGuildVoiceChannel.js index eabc1b4708f9..b17a90fa3590 100644 --- a/packages/discord.js/src/structures/BaseGuildVoiceChannel.js +++ b/packages/discord.js/src/structures/BaseGuildVoiceChannel.js @@ -150,7 +150,7 @@ class BaseGuildVoiceChannel extends GuildChannel { /** * Creates an invite to this guild channel. * - * @param {InviteCreateOptions} [options] The options for creating the invite + * @param {InviteCreateOptions} [options={}] The options for creating the invite * @returns {Promise} * @example * // Create an invite to a channel @@ -165,7 +165,7 @@ class BaseGuildVoiceChannel extends GuildChannel { /** * Fetches a collection of invites to this guild channel. * - * @param {boolean} [cache] Whether to cache the fetched invites + * @param {boolean} [cache=true] Whether to cache the fetched invites * @returns {Promise>} */ async fetchInvites(cache = true) { diff --git a/packages/discord.js/src/structures/ClientUser.js b/packages/discord.js/src/structures/ClientUser.js index 8a450afe6e48..a075ef1ec045 100644 --- a/packages/discord.js/src/structures/ClientUser.js +++ b/packages/discord.js/src/structures/ClientUser.js @@ -158,10 +158,10 @@ class ClientUser extends User { /** * A user's status. Must be one of: - * `online` - * `idle` - * `invisible` - * `dnd` (do not disturb) + * - `online` + * - `idle` + * - `invisible` + * - `dnd` (do not disturb) * * @typedef {string} PresenceStatusData */ @@ -211,7 +211,7 @@ class ClientUser extends User { /** * Sets/removes the AFK flag for the client user. * - * @param {boolean} [afk] Whether or not the user is AFK + * @param {boolean} [afk=true] Whether or not the user is AFK * @param {number|number[]} [shardId] Shard Id(s) to have the AFK flag set on * @returns {Promise} */ diff --git a/packages/discord.js/src/structures/CommandInteractionOptionResolver.js b/packages/discord.js/src/structures/CommandInteractionOptionResolver.js index 66191e8597c1..a434510ff8b2 100644 --- a/packages/discord.js/src/structures/CommandInteractionOptionResolver.js +++ b/packages/discord.js/src/structures/CommandInteractionOptionResolver.js @@ -76,7 +76,7 @@ class CommandInteractionOptionResolver { * Gets an option by its name. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?CommandInteractionOption} The option, if found. */ get(name, required = false) { @@ -118,7 +118,7 @@ class CommandInteractionOptionResolver { /** * Gets the selected subcommand. * - * @param {boolean} [required] Whether to throw an error if there is no subcommand. + * @param {boolean} [required=true] Whether to throw an error if there is no subcommand. * @returns {?string} The name of the selected subcommand, or null if not set and not required. */ getSubcommand(required = true) { @@ -132,7 +132,7 @@ class CommandInteractionOptionResolver { /** * Gets the selected subcommand group. * - * @param {boolean} [required] Whether to throw an error if there is no subcommand group. + * @param {boolean} [required=false] Whether to throw an error if there is no subcommand group. * @returns {?string} The name of the selected subcommand group, or null if not set and not required. */ getSubcommandGroup(required = false) { @@ -147,7 +147,7 @@ class CommandInteractionOptionResolver { * Gets a boolean option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?boolean} The value of the option, or null if not set and not required. */ getBoolean(name, required = false) { @@ -159,8 +159,8 @@ class CommandInteractionOptionResolver { * Gets a channel option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. - * @param {ChannelType[]} [channelTypes] The allowed types of channels. If empty, all channel types are allowed. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. + * @param {ChannelType[]} [channelTypes=[]] The allowed types of channels. If empty, all channel types are allowed. * @returns {?(GuildChannel|ThreadChannel|APIChannel)} * The value of the option, or null if not set and not required. */ @@ -184,7 +184,7 @@ class CommandInteractionOptionResolver { * Gets a string option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?string} The value of the option, or null if not set and not required. */ getString(name, required = false) { @@ -196,7 +196,7 @@ class CommandInteractionOptionResolver { * Gets an integer option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?number} The value of the option, or null if not set and not required. */ getInteger(name, required = false) { @@ -208,7 +208,7 @@ class CommandInteractionOptionResolver { * Gets a number option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?number} The value of the option, or null if not set and not required. */ getNumber(name, required = false) { @@ -220,7 +220,7 @@ class CommandInteractionOptionResolver { * Gets a user option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?User} The value of the option, or null if not set and not required. */ getUser(name, required = false) { @@ -254,7 +254,7 @@ class CommandInteractionOptionResolver { * Gets a role option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?(Role|APIRole)} The value of the option, or null if not set and not required. */ getRole(name, required = false) { @@ -271,7 +271,7 @@ class CommandInteractionOptionResolver { * Gets an attachment option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?Attachment} The value of the option, or null if not set and not required. */ getAttachment(name, required = false) { @@ -283,7 +283,7 @@ class CommandInteractionOptionResolver { * Gets a mentionable option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?(User|GuildMember|APIGuildMember|Role|APIRole)} * The value of the option, or null if not set and not required. */ @@ -301,7 +301,7 @@ class CommandInteractionOptionResolver { * Gets a message option. * * @param {string} name The name of the option. - * @param {boolean} [required] Whether to throw an error if the option is not found. + * @param {boolean} [required=false] Whether to throw an error if the option is not found. * @returns {?Message} * The value of the option, or null if not set and not required. */ diff --git a/packages/discord.js/src/structures/DMChannel.js b/packages/discord.js/src/structures/DMChannel.js index d568070e8df1..0bb1935999dc 100644 --- a/packages/discord.js/src/structures/DMChannel.js +++ b/packages/discord.js/src/structures/DMChannel.js @@ -90,7 +90,7 @@ class DMChannel extends BaseChannel { /** * Fetch this DMChannel. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=true] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { diff --git a/packages/discord.js/src/structures/Emoji.js b/packages/discord.js/src/structures/Emoji.js index f410773fde88..bd6a7246db6c 100644 --- a/packages/discord.js/src/structures/Emoji.js +++ b/packages/discord.js/src/structures/Emoji.js @@ -48,7 +48,7 @@ class Emoji extends Base { /** * Returns a URL for the emoji or `null` if this is not a custom emoji. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ imageURL(options = {}) { diff --git a/packages/discord.js/src/structures/Guild.js b/packages/discord.js/src/structures/Guild.js index ad9d8a2d6f8c..2eb33a6f413b 100644 --- a/packages/discord.js/src/structures/Guild.js +++ b/packages/discord.js/src/structures/Guild.js @@ -551,7 +551,7 @@ class Guild extends AnonymousGuild { /** * The URL to this guild's discovery splash image. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ discoverySplashURL(options = {}) { @@ -841,7 +841,7 @@ class Guild extends AnonymousGuild { /** * Fetches audit logs for this guild. * - * @param {GuildAuditLogsFetchOptions} [options] Options for fetching audit logs + * @param {GuildAuditLogsFetchOptions} [options={}] Options for fetching audit logs * @returns {Promise} * @example * // Output audit log entries @@ -907,16 +907,16 @@ class Guild extends AnonymousGuild { /** * Data that can be resolved to a Text Channel object. This can be: - * A TextChannel - * A Snowflake + * - A TextChannel + * - A Snowflake * * @typedef {TextChannel|Snowflake} TextChannelResolvable */ /** * Data that can be resolved to a Voice Channel object. This can be: - * A VoiceChannel - * A Snowflake + * - A VoiceChannel + * - A Snowflake * * @typedef {VoiceChannel|Snowflake} VoiceChannelResolvable */ @@ -1086,18 +1086,18 @@ class Guild extends AnonymousGuild { /** * Data that can be resolved to a GuildTextChannel object. This can be: - * A TextChannel - * A AnnouncementChannel - * A Snowflake + * - A TextChannel + * - A AnnouncementChannel + * - A Snowflake * * @typedef {TextChannel|AnnouncementChannel|Snowflake} GuildTextChannelResolvable */ /** * Data that can be resolved to a GuildVoiceChannel object. This can be: - * A VoiceChannel - * A StageChannel - * A Snowflake + * - A VoiceChannel + * - A StageChannel + * - A Snowflake * * @typedef {VoiceChannel|StageChannel|Snowflake} GuildVoiceChannelResolvable */ @@ -1386,7 +1386,7 @@ class Guild extends AnonymousGuild { /** * Edits the enabled state of the guild's premium progress bar * - * @param {boolean} [enabled] The new enabled state of the guild's premium progress bar + * @param {boolean} [enabled=true] The new enabled state of the guild's premium progress bar * @param {string} [reason] Reason for changing the state of the guild's premium progress bar * @returns {Promise} */ @@ -1485,7 +1485,7 @@ class Guild extends AnonymousGuild { /** * Sets whether this guild's invites are disabled. * - * @param {boolean} [disabled] Whether the invites are disabled + * @param {boolean} [disabled=true] Whether the invites are disabled * @returns {Promise} */ async disableInvites(disabled = true) { diff --git a/packages/discord.js/src/structures/GuildAuditLogsEntry.js b/packages/discord.js/src/structures/GuildAuditLogsEntry.js index ee04c9412caf..2b561cc80973 100644 --- a/packages/discord.js/src/structures/GuildAuditLogsEntry.js +++ b/packages/discord.js/src/structures/GuildAuditLogsEntry.js @@ -36,24 +36,24 @@ const Targets = { /** * The target of a guild audit log entry. It can be one of: - * A guild - * A channel - * A user - * A role - * An invite - * A webhook - * A guild emoji - * An integration - * A stage instance - * A sticker - * A guild scheduled event - * A thread - * An application command - * An auto moderation rule - * A guild onboarding prompt - * A soundboard sound - * An object with an id key if target was deleted or fake entity - * An object where the keys represent either the new value or the old value + * - A guild + * - A channel + * - A user + * - A role + * - An invite + * - A webhook + * - A guild emoji + * - An integration + * - A stage instance + * - A sticker + * - A guild scheduled event + * - A thread + * - An application command + * - An auto moderation rule + * - A guild onboarding prompt + * - A soundboard sound + * - An object with an id key if target was deleted or fake entity + * - An object where the keys represent either the new value or the old value * * @typedef {?(object|Guild|BaseChannel|User|Role|Invite|Webhook|GuildEmoji|Integration|StageInstance|Sticker| * GuildScheduledEvent|ApplicationCommand|AutoModerationRule|GuildOnboardingPrompt|SoundboardSound)} AuditLogEntryTarget @@ -61,34 +61,34 @@ const Targets = { /** * The action type of an entry, e.g. `Create`. Here are the available types: - * Create - * Delete - * Update - * All + * - Create + * - Delete + * - Update + * - All * * @typedef {string} AuditLogActionType */ /** * The target type of an entry. Here are the available types: - * Guild - * Channel - * User - * Role - * Invite - * Webhook - * Emoji - * Message - * Integration - * StageInstance - * Sticker - * Thread - * GuildScheduledEvent - * ApplicationCommand - * GuildOnboardingPrompt - * SoundboardSound - * AutoModeration - * Unknown + * - Guild + * - Channel + * - User + * - Role + * - Invite + * - Webhook + * - Emoji + * - Message + * - Integration + * - StageInstance + * - Sticker + * - Thread + * - GuildScheduledEvent + * - ApplicationCommand + * - GuildOnboardingPrompt + * - SoundboardSound + * - AutoModeration + * - Unknown * * @typedef {string} AuditLogTargetType */ @@ -97,7 +97,7 @@ const Targets = { * Constructs an object of known properties for a structure from an array of changes. * * @param {AuditLogChange[]} changes The array of changes - * @param {Object} [initialData] The initial data passed to the function + * @param {Object} [initialData={}] The initial data passed to the function * @returns {Object} * @ignore */ diff --git a/packages/discord.js/src/structures/GuildBan.js b/packages/discord.js/src/structures/GuildBan.js index 3a0636ae2b85..ffb63bc62da1 100644 --- a/packages/discord.js/src/structures/GuildBan.js +++ b/packages/discord.js/src/structures/GuildBan.js @@ -54,7 +54,7 @@ class GuildBan extends Base { /** * Fetches this GuildBan. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=true] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { diff --git a/packages/discord.js/src/structures/GuildChannel.js b/packages/discord.js/src/structures/GuildChannel.js index c6f55a910f48..0ad9135d5277 100644 --- a/packages/discord.js/src/structures/GuildChannel.js +++ b/packages/discord.js/src/structures/GuildChannel.js @@ -179,7 +179,7 @@ class GuildChannel extends BaseChannel { * Gets the overall set of permissions for a member or role in this channel, taking into account channel overwrites. * * @param {UserResolvable|RoleResolvable} memberOrRole The member or role to obtain the overall permissions for - * @param {boolean} [checkAdmin] Whether having the {@link PermissionFlagsBits.Administrator} permission + * @param {boolean} [checkAdmin=true] Whether having the {@link PermissionFlagsBits.Administrator} permission * will return all permissions * @returns {?Readonly} */ diff --git a/packages/discord.js/src/structures/GuildMember.js b/packages/discord.js/src/structures/GuildMember.js index c8e933721bcb..6c428284cb85 100644 --- a/packages/discord.js/src/structures/GuildMember.js +++ b/packages/discord.js/src/structures/GuildMember.js @@ -174,7 +174,7 @@ class GuildMember extends Base { /** * A link to the member's guild avatar. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ avatarURL(options = {}) { @@ -184,7 +184,7 @@ class GuildMember extends Base { /** * A link to the member's banner. * - * @param {ImageURLOptions} [options] Options for the banner URL + * @param {ImageURLOptions} [options={}] Options for the banner URL * @returns {?string} */ bannerURL(options = {}) { @@ -195,7 +195,7 @@ class GuildMember extends Base { * A link to the member's guild avatar if they have one. * Otherwise, a link to their {@link User#displayAvatarURL} will be returned. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {string} */ displayAvatarURL(options) { @@ -206,7 +206,7 @@ class GuildMember extends Base { * A link to the member's guild banner if they have one. * Otherwise, a link to their {@link User#bannerURL} will be returned. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ displayBannerURL(options) { @@ -432,7 +432,7 @@ class GuildMember extends Base { /** * Creates a DM channel between the client and this member. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=false] Whether to skip the cache check and request the API * @returns {Promise} */ async createDM(force = false) { @@ -513,7 +513,7 @@ class GuildMember extends Base { /** * Fetches this GuildMember. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=true] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { diff --git a/packages/discord.js/src/structures/GuildPreview.js b/packages/discord.js/src/structures/GuildPreview.js index 87f6163e46d8..08e0fbbfcde3 100644 --- a/packages/discord.js/src/structures/GuildPreview.js +++ b/packages/discord.js/src/structures/GuildPreview.js @@ -152,7 +152,7 @@ class GuildPreview extends Base { /** * The URL to this guild's splash. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ splashURL(options = {}) { @@ -162,7 +162,7 @@ class GuildPreview extends Base { /** * The URL to this guild's discovery splash. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ discoverySplashURL(options = {}) { @@ -172,7 +172,7 @@ class GuildPreview extends Base { /** * The URL to this guild's icon. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ iconURL(options = {}) { diff --git a/packages/discord.js/src/structures/GuildScheduledEvent.js b/packages/discord.js/src/structures/GuildScheduledEvent.js index 48fa135947c0..50914fc283c2 100644 --- a/packages/discord.js/src/structures/GuildScheduledEvent.js +++ b/packages/discord.js/src/structures/GuildScheduledEvent.js @@ -272,7 +272,7 @@ class GuildScheduledEvent extends Base { /** * The URL of this scheduled event's cover image * - * @param {BaseImageURLOptions} [options] Options for image URL + * @param {BaseImageURLOptions} [options={}] Options for image URL * @returns {?string} */ coverImageURL(options = {}) { @@ -396,7 +396,7 @@ class GuildScheduledEvent extends Base { /** * Fetches this guild scheduled event. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=true] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { diff --git a/packages/discord.js/src/structures/Integration.js b/packages/discord.js/src/structures/Integration.js index b154c934152a..156c8dac768b 100644 --- a/packages/discord.js/src/structures/Integration.js +++ b/packages/discord.js/src/structures/Integration.js @@ -14,10 +14,10 @@ const { IntegrationApplication } = require('./IntegrationApplication.js'); /** * The type of an {@link Integration}. This can be: - * `twitch` - * `youtube` - * `discord` - * `guild_subscription` + * - `twitch` + * - `youtube` + * - `discord` + * - `guild_subscription` * * @typedef {string} IntegrationType */ diff --git a/packages/discord.js/src/structures/InteractionCollector.js b/packages/discord.js/src/structures/InteractionCollector.js index 41eeb71d7534..d0e925c52115 100644 --- a/packages/discord.js/src/structures/InteractionCollector.js +++ b/packages/discord.js/src/structures/InteractionCollector.js @@ -31,7 +31,7 @@ const { Collector } = require('./interfaces/Collector.js'); class InteractionCollector extends Collector { /** * @param {Client} client The client on which to collect interactions - * @param {InteractionCollectorOptions} [options] The options to apply to this collector + * @param {InteractionCollectorOptions} [options={}] The options to apply to this collector */ constructor(client, options = {}) { super(client, options); diff --git a/packages/discord.js/src/structures/Invite.js b/packages/discord.js/src/structures/Invite.js index 2e426a522303..2da88ca0b5b3 100644 --- a/packages/discord.js/src/structures/Invite.js +++ b/packages/discord.js/src/structures/Invite.js @@ -252,7 +252,8 @@ class Invite extends Base { if (!guild || !this.client.guilds.cache.has(guild.id)) return false; if (!guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); return Boolean( - this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) ?? + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) || guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild), ); } diff --git a/packages/discord.js/src/structures/Message.js b/packages/discord.js/src/structures/Message.js index d51e5c9eebcc..dc9212c3aea8 100644 --- a/packages/discord.js/src/structures/Message.js +++ b/packages/discord.js/src/structures/Message.js @@ -389,11 +389,11 @@ class Message extends Base { /** * Reference data sent in a message that contains ids identifying the referenced message. * This can be present in the following types of message: - * Crossposted messages (`MessageFlags.Crossposted`) - * {@link MessageType.ChannelPinnedMessage} - * {@link MessageType.ChannelFollowAdd} - * {@link MessageType.Reply} - * {@link MessageType.ThreadStarterMessage} + * - Crossposted messages ({@link MessageFlags.Crossposted}) + * - {@link MessageType.ChannelPinnedMessage} + * - {@link MessageType.ChannelFollowAdd} + * - {@link MessageType.Reply} + * - {@link MessageType.ThreadStarterMessage} * * @see {@link https://discord.com/developers/docs/resources/message#message-object-message-types} * @typedef {Object} MessageReference @@ -626,7 +626,7 @@ class Message extends Base { /** * Creates a reaction collector. * - * @param {ReactionCollectorOptions} [options] Options to send to the collector + * @param {ReactionCollectorOptions} [options={}] Options to send to the collector * @returns {ReactionCollector} * @example * // Create a reaction collector @@ -650,7 +650,7 @@ class Message extends Base { * Similar to createReactionCollector but in promise form. * Resolves with a collection of reactions that pass the specified filter. * - * @param {AwaitReactionsOptions} [options] Optional options to pass to the internal collector + * @param {AwaitReactionsOptions} [options={}] Optional options to pass to the internal collector * @returns {Promise>} * @example * // Create a reaction collector @@ -680,7 +680,7 @@ class Message extends Base { /** * Creates a message component interaction collector. * - * @param {MessageComponentCollectorOptions} [options] Options to send to the collector + * @param {MessageComponentCollectorOptions} [options={}] Options to send to the collector * @returns {InteractionCollector} * @example * // Create a message component interaction collector @@ -712,7 +712,7 @@ class Message extends Base { * Collects a single component interaction that passes the filter. * The Promise will reject if the time expires. * - * @param {AwaitMessageComponentOptions} [options] Options to pass to the internal collector + * @param {AwaitMessageComponentOptions} [options={}] Options to pass to the internal collector * @returns {Promise} * @example * // Collect a message component interaction @@ -1061,7 +1061,7 @@ class Message extends Base { /** * Fetch this message. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=true] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { @@ -1083,7 +1083,7 @@ class Message extends Base { /** * Suppresses or unsuppresses embeds on a message. * - * @param {boolean} [suppress] If the embeds should be suppressed or not + * @param {boolean} [suppress=true] If the embeds should be suppressed or not * @returns {Promise} */ async suppressEmbeds(suppress = true) { diff --git a/packages/discord.js/src/structures/MessageComponentInteraction.js b/packages/discord.js/src/structures/MessageComponentInteraction.js index 23b41b316441..b3f54eae2fb2 100644 --- a/packages/discord.js/src/structures/MessageComponentInteraction.js +++ b/packages/discord.js/src/structures/MessageComponentInteraction.js @@ -76,12 +76,12 @@ class MessageComponentInteraction extends BaseInteraction { /** * Components that can be placed in an action row for messages. - * ButtonComponent - * StringSelectMenuComponent - * UserSelectMenuComponent - * RoleSelectMenuComponent - * MentionableSelectMenuComponent - * ChannelSelectMenuComponent + * - ButtonComponent + * - StringSelectMenuComponent + * - UserSelectMenuComponent + * - RoleSelectMenuComponent + * - MentionableSelectMenuComponent + * - ChannelSelectMenuComponent * * @typedef {ButtonComponent|StringSelectMenuComponent|UserSelectMenuComponent| * RoleSelectMenuComponent|MentionableSelectMenuComponent|ChannelSelectMenuComponent} MessageActionRowComponent diff --git a/packages/discord.js/src/structures/MessagePayload.js b/packages/discord.js/src/structures/MessagePayload.js index 86b8628f8c95..154075d5ea01 100644 --- a/packages/discord.js/src/structures/MessagePayload.js +++ b/packages/discord.js/src/structures/MessagePayload.js @@ -292,7 +292,7 @@ class MessagePayload { * * @param {MessageTarget} target Target to send to * @param {string|MessagePayloadOption} options Options or content to use - * @param {MessagePayloadOption} [extra] Extra options to add onto specified options + * @param {MessagePayloadOption} [extra={}] Extra options to add onto specified options * @returns {MessagePayload} */ static create(target, options, extra = {}) { diff --git a/packages/discord.js/src/structures/PartialGroupDMChannel.js b/packages/discord.js/src/structures/PartialGroupDMChannel.js index ab3c1cbd070e..7b21a2f5183a 100644 --- a/packages/discord.js/src/structures/PartialGroupDMChannel.js +++ b/packages/discord.js/src/structures/PartialGroupDMChannel.js @@ -90,7 +90,7 @@ class PartialGroupDMChannel extends BaseChannel { /** * The URL to this channel's icon. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ iconURL(options = {}) { diff --git a/packages/discord.js/src/structures/PermissionOverwrites.js b/packages/discord.js/src/structures/PermissionOverwrites.js index 969027649840..7c62c3bde827 100644 --- a/packages/discord.js/src/structures/PermissionOverwrites.js +++ b/packages/discord.js/src/structures/PermissionOverwrites.js @@ -160,8 +160,8 @@ class PermissionOverwrites extends Base { /** * Data that can be resolved into {@link APIOverwrite}. This can be: - * PermissionOverwrites - * OverwriteData + * - PermissionOverwrites + * - OverwriteData * * @typedef {PermissionOverwrites|OverwriteData} OverwriteResolvable */ diff --git a/packages/discord.js/src/structures/PollAnswer.js b/packages/discord.js/src/structures/PollAnswer.js index 5e208d073c0e..1e9633e44f27 100644 --- a/packages/discord.js/src/structures/PollAnswer.js +++ b/packages/discord.js/src/structures/PollAnswer.js @@ -105,7 +105,7 @@ class PollAnswer extends Base { /** * Fetches the users that voted for this answer. * - * @param {BaseFetchPollAnswerVotersOptions} [options] The options for fetching voters + * @param {BaseFetchPollAnswerVotersOptions} [options={}] The options for fetching voters * @returns {Promise>} * @deprecated Use {@link PollAnswerVoterManager#fetch} instead */ diff --git a/packages/discord.js/src/structures/Presence.js b/packages/discord.js/src/structures/Presence.js index f3de71ab5a1f..e6f32807c995 100644 --- a/packages/discord.js/src/structures/Presence.js +++ b/packages/discord.js/src/structures/Presence.js @@ -16,19 +16,19 @@ const { Emoji } = require('./Emoji.js'); /** * The status of this presence: - * **`online`** - user is online - * **`idle`** - user is AFK - * **`offline`** - user is offline or invisible - * **`dnd`** - user is in Do Not Disturb + * - __`online`__ - user is online + * - __`idle`__ - user is AFK + * - __`offline`__ - user is offline or invisible + * - __`dnd`__ - user is in Do Not Disturb * * @typedef {string} PresenceStatus */ /** * The status of this presence: - * **`online`** - user is online - * **`idle`** - user is AFK - * **`dnd`** - user is in Do Not Disturb + * - __`online`__ - user is online + * - __`idle`__ - user is AFK + * - __`dnd`__ - user is in Do Not Disturb * * @typedef {string} ClientPresenceStatus */ @@ -374,7 +374,7 @@ class RichPresenceAssets { /** * Gets the URL of the small image asset * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ smallImageURL(options = {}) { @@ -395,7 +395,7 @@ class RichPresenceAssets { /** * Gets the URL of the large image asset * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ largeImageURL(options = {}) { diff --git a/packages/discord.js/src/structures/ReactionCollector.js b/packages/discord.js/src/structures/ReactionCollector.js index b2ce65190f67..e4c40eb2d910 100644 --- a/packages/discord.js/src/structures/ReactionCollector.js +++ b/packages/discord.js/src/structures/ReactionCollector.js @@ -25,7 +25,7 @@ const { Collector } = require('./interfaces/Collector.js'); class ReactionCollector extends Collector { /** * @param {Message} message The message upon which to collect reactions - * @param {ReactionCollectorOptions} [options] The options to apply to this collector + * @param {ReactionCollectorOptions} [options={}] The options to apply to this collector */ constructor(message, options = {}) { super(message.client, options); diff --git a/packages/discord.js/src/structures/Role.js b/packages/discord.js/src/structures/Role.js index d2a5d7a63b98..0abbf50271f6 100644 --- a/packages/discord.js/src/structures/Role.js +++ b/packages/discord.js/src/structures/Role.js @@ -288,7 +288,7 @@ class Role extends Base { * taking into account permission overwrites. * * @param {GuildChannel|Snowflake} channel The guild channel to use as context - * @param {boolean} [checkAdmin] Whether having the {@link PermissionFlagsBits.Administrator} permission + * @param {boolean} [checkAdmin=true] Whether having the {@link PermissionFlagsBits.Administrator} permission * will return all permissions * @returns {Readonly} */ @@ -333,7 +333,7 @@ class Role extends Base { /** * Sets whether or not the role should be hoisted. * - * @param {boolean} [hoist] Whether or not to hoist the role + * @param {boolean} [hoist=true] Whether or not to hoist the role * @param {string} [reason] Reason for setting whether or not the role should be hoisted * @returns {Promise} * @example @@ -370,7 +370,7 @@ class Role extends Base { /** * Sets whether this role is mentionable. * - * @param {boolean} [mentionable] Whether this role should be mentionable + * @param {boolean} [mentionable=true] Whether this role should be mentionable * @param {string} [reason] Reason for setting whether or not this role should be mentionable * @returns {Promise} * @example @@ -455,7 +455,7 @@ class Role extends Base { /** * A link to the role's icon * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ iconURL(options = {}) { diff --git a/packages/discord.js/src/structures/StickerPack.js b/packages/discord.js/src/structures/StickerPack.js index b9ec2d1c4250..21b86a7a0375 100644 --- a/packages/discord.js/src/structures/StickerPack.js +++ b/packages/discord.js/src/structures/StickerPack.js @@ -96,7 +96,7 @@ class StickerPack extends Base { /** * The URL to this sticker pack's banner. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ bannerURL(options = {}) { diff --git a/packages/discord.js/src/structures/Team.js b/packages/discord.js/src/structures/Team.js index 00fcac29f308..380c514fc2a9 100644 --- a/packages/discord.js/src/structures/Team.js +++ b/packages/discord.js/src/structures/Team.js @@ -101,7 +101,7 @@ class Team extends Base { /** * A link to the team's icon. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ iconURL(options = {}) { diff --git a/packages/discord.js/src/structures/ThreadChannel.js b/packages/discord.js/src/structures/ThreadChannel.js index 48d76a2c0b2b..5d576a1b5c9e 100644 --- a/packages/discord.js/src/structures/ThreadChannel.js +++ b/packages/discord.js/src/structures/ThreadChannel.js @@ -304,7 +304,7 @@ class ThreadChannel extends BaseChannel { * account. * * @param {UserResolvable|RoleResolvable} memberOrRole The member or role to obtain the overall permissions for - * @param {boolean} [checkAdmin] Whether having the {@link PermissionFlagsBits.Administrator} permission + * @param {boolean} [checkAdmin=true] Whether having the {@link PermissionFlagsBits.Administrator} permission * will return all permissions * @returns {?Readonly} */ @@ -393,7 +393,7 @@ class ThreadChannel extends BaseChannel { /** * Sets whether the thread is archived. * - * @param {boolean} [archived] Whether the thread is archived + * @param {boolean} [archived=true] Whether the thread is archived * @param {string} [reason] Reason for archiving or unarchiving * @returns {Promise} * @example @@ -429,7 +429,7 @@ class ThreadChannel extends BaseChannel { * Sets whether members without the {@link PermissionFlagsBits.ManageThreads} permission * can invite other members to this thread. * - * @param {boolean} [invitable] Whether non-moderators can invite non-moderators to this thread + * @param {boolean} [invitable=true] Whether non-moderators can invite non-moderators to this thread * @param {string} [reason] Reason for changing invite * @returns {Promise} */ @@ -446,7 +446,7 @@ class ThreadChannel extends BaseChannel { * {@link PermissionFlagsBits.SendMessages} permission. When a thread is locked, only members with the * {@link PermissionFlagsBits.ManageThreads} permission can unarchive it. * - * @param {boolean} [locked] Whether the thread is locked + * @param {boolean} [locked=true] Whether the thread is locked * @param {string} [reason] Reason for locking or unlocking the thread * @returns {Promise} * @example diff --git a/packages/discord.js/src/structures/ThreadOnlyChannel.js b/packages/discord.js/src/structures/ThreadOnlyChannel.js index c94d5e4bc0eb..81debc7141c3 100644 --- a/packages/discord.js/src/structures/ThreadOnlyChannel.js +++ b/packages/discord.js/src/structures/ThreadOnlyChannel.js @@ -199,7 +199,7 @@ class ThreadOnlyChannel extends GuildChannel { * Fetches a collection of invites to this guild channel. * Resolves with a collection mapping invites by their codes. * - * @param {boolean} [cache] Whether to cache the fetched invites + * @param {boolean} [cache=true] Whether to cache the fetched invites * @returns {Promise>} */ async fetchInvites(cache) { diff --git a/packages/discord.js/src/structures/User.js b/packages/discord.js/src/structures/User.js index 2851179e5619..e2fa4cab4fde 100644 --- a/packages/discord.js/src/structures/User.js +++ b/packages/discord.js/src/structures/User.js @@ -186,7 +186,7 @@ class User extends Base { /** * A link to the user's avatar. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ avatarURL(options = {}) { @@ -217,7 +217,7 @@ class User extends Base { * A link to the user's avatar if they have one. * Otherwise a link to their default avatar will be returned. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {string} */ displayAvatarURL(options) { @@ -239,7 +239,7 @@ class User extends Base { /** * A link to the user's banner. See {@link User#banner} for more info * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ bannerURL(options = {}) { @@ -285,7 +285,7 @@ class User extends Base { /** * Creates a DM channel between the client and the user. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=false] Whether to skip the cache check and request the API * @returns {Promise} */ async createDM(force = false) { @@ -370,7 +370,7 @@ class User extends Base { /** * Fetches this user. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=true] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { diff --git a/packages/discord.js/src/structures/VoiceState.js b/packages/discord.js/src/structures/VoiceState.js index 6661314a3ff9..06f55c090637 100644 --- a/packages/discord.js/src/structures/VoiceState.js +++ b/packages/discord.js/src/structures/VoiceState.js @@ -187,7 +187,7 @@ class VoiceState extends Base { /** * Mutes/unmutes the member of this voice state. * - * @param {boolean} [mute] Whether or not the member should be muted + * @param {boolean} [mute=true] Whether or not the member should be muted * @param {string} [reason] Reason for muting or unmuting * @returns {Promise} */ @@ -198,7 +198,7 @@ class VoiceState extends Base { /** * Deafens/undeafens the member of this voice state. * - * @param {boolean} [deaf] Whether or not the member should be deafened + * @param {boolean} [deaf=true] Whether or not the member should be deafened * @param {string} [reason] Reason for deafening or undeafening * @returns {Promise} */ @@ -277,7 +277,7 @@ class VoiceState extends Base { /** * Fetches this voice state. * - * @param {boolean} [force] Whether to skip the cache check and request the API + * @param {boolean} [force=true] Whether to skip the cache check and request the API * @returns {Promise} */ async fetch(force = true) { @@ -304,7 +304,7 @@ class VoiceState extends Base { /** * Suppress/unsuppress the user. Only applicable for stage channels. * - * @param {boolean} [suppressed] Whether or not the user should be suppressed. + * @param {boolean} [suppressed=true] Whether or not the user should be suppressed. * @example * // Making the client a speaker * guild.members.me.voice.setSuppressed(false); diff --git a/packages/discord.js/src/structures/Webhook.js b/packages/discord.js/src/structures/Webhook.js index fc179629daf2..7622e764f420 100644 --- a/packages/discord.js/src/structures/Webhook.js +++ b/packages/discord.js/src/structures/Webhook.js @@ -333,7 +333,7 @@ class Webhook { * Gets a message that was sent by this webhook. * * @param {Snowflake|'@original'} message The id of the message to fetch - * @param {WebhookFetchMessageOptions} [options] The options to provide to fetch the message. + * @param {WebhookFetchMessageOptions} [options={}] The options to provide to fetch the message. * @returns {Promise} Returns the message sent by this webhook */ async fetchMessage(message, { threadId } = {}) { @@ -459,7 +459,7 @@ class Webhook { /** * A link to the webhook's avatar. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ avatarURL(options = {}) { diff --git a/packages/discord.js/src/structures/interfaces/Application.js b/packages/discord.js/src/structures/interfaces/Application.js index f11afd0d71db..75e578d62ff7 100644 --- a/packages/discord.js/src/structures/interfaces/Application.js +++ b/packages/discord.js/src/structures/interfaces/Application.js @@ -135,7 +135,7 @@ class Application extends Base { /** * A link to the application's icon. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ iconURL(options = {}) { @@ -145,7 +145,7 @@ class Application extends Base { /** * A link to this application's cover image. * - * @param {ImageURLOptions} [options] Options for the image URL + * @param {ImageURLOptions} [options={}] Options for the image URL * @returns {?string} */ coverURL(options = {}) { diff --git a/packages/discord.js/src/structures/interfaces/Collector.js b/packages/discord.js/src/structures/interfaces/Collector.js index c314c640bd05..e110fce5ec55 100644 --- a/packages/discord.js/src/structures/interfaces/Collector.js +++ b/packages/discord.js/src/structures/interfaces/Collector.js @@ -229,7 +229,7 @@ class Collector extends AsyncEventEmitter { /** * Stops this collector and emits the `end` event. * - * @param {string} [reason] The reason this collector is ending + * @param {string} [reason='user'] The reason this collector is ending * @emits Collector#end */ stop(reason = 'user') { diff --git a/packages/discord.js/src/structures/interfaces/InteractionResponses.js b/packages/discord.js/src/structures/interfaces/InteractionResponses.js index c10606d379ab..e35d4e5ebc87 100644 --- a/packages/discord.js/src/structures/interfaces/InteractionResponses.js +++ b/packages/discord.js/src/structures/interfaces/InteractionResponses.js @@ -156,7 +156,7 @@ class InteractionResponses { * Fetches a reply to this interaction. * * @see Webhook#fetchMessage - * @param {Snowflake|'@original'} [message] The response to fetch + * @param {Snowflake|'@original'} [message='@original'] The response to fetch * @returns {Promise} * @example * // Fetch the initial reply to this interaction @@ -198,7 +198,7 @@ class InteractionResponses { * Deletes a reply to this interaction. * * @see Webhook#deleteMessage - * @param {MessageResolvable|'@original'} [message] The response to delete + * @param {MessageResolvable|'@original'} [message='@original'] The response to delete * @returns {Promise} * @example * // Delete the initial reply to this interaction @@ -290,7 +290,7 @@ class InteractionResponses { /** * Launches this application's activity, if enabled * - * @param {LaunchActivityOptions} [options] Options for launching the activity + * @param {LaunchActivityOptions} [options={}] Options for launching the activity * @returns {Promise} */ async launchActivity({ withResponse } = {}) { @@ -311,7 +311,7 @@ class InteractionResponses { * Shows a modal component * * @param {ModalBuilder|ModalComponentData|APIModalInteractionResponseCallbackData} modal The modal to show - * @param {ShowModalOptions} [options] The options for sending this interaction response + * @param {ShowModalOptions} [options={}] The options for sending this interaction response * @returns {Promise} */ async showModal(modal, options = {}) { diff --git a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js index 9883a75779d2..b7e18f26fd3e 100644 --- a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js +++ b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js @@ -194,7 +194,7 @@ class TextBasedChannel { /** * Creates a Message Collector. * - * @param {MessageCollectorOptions} [options] The options to pass to the collector + * @param {MessageCollectorOptions} [options={}] The options to pass to the collector * @returns {MessageCollector} * @example * // Create a message collector @@ -218,7 +218,7 @@ class TextBasedChannel { * Similar to createMessageCollector but in promise form. * Resolves with a collection of messages that pass the specified filter. * - * @param {AwaitMessagesOptions} [options] Optional options to pass to the internal collector + * @param {AwaitMessagesOptions} [options={}] Optional options to pass to the internal collector * @returns {Promise>} * @example * // Await !vote messages @@ -244,7 +244,7 @@ class TextBasedChannel { /** * Creates a component interaction collector. * - * @param {MessageComponentCollectorOptions} [options] Options to send to the collector + * @param {MessageComponentCollectorOptions} [options={}] Options to send to the collector * @returns {InteractionCollector} * @example * // Create a button interaction collector @@ -265,7 +265,7 @@ class TextBasedChannel { * Collects a single component interaction that passes the filter. * The Promise will reject if the time expires. * - * @param {AwaitMessageComponentOptions} [options] Options to pass to the internal collector + * @param {AwaitMessageComponentOptions} [options={}] Options to pass to the internal collector * @returns {Promise} * @example * // Collect a message component interaction @@ -291,7 +291,7 @@ class TextBasedChannel { * * @param {Collection|MessageResolvable[]|number} messages * Messages or number of messages to delete - * @param {boolean} [filterOld] Filter messages to remove those which are older than two weeks automatically + * @param {boolean} [filterOld=false] Filter messages to remove those which are older than two weeks automatically * @returns {Promise} Returns the deleted messages ids * @example * // Bulk delete messages @@ -385,7 +385,7 @@ class TextBasedChannel { /** * Sets whether this channel is flagged as NSFW. * - * @param {boolean} [nsfw] Whether the channel should be considered NSFW + * @param {boolean} [nsfw=true] Whether the channel should be considered NSFW * @param {string} [reason] Reason for changing the channel's NSFW flag * @returns {Promise} */ diff --git a/packages/discord.js/src/util/ApplicationFlagsBitField.js b/packages/discord.js/src/util/ApplicationFlagsBitField.js index 2df418b4ec7f..d0e88dcbb26e 100644 --- a/packages/discord.js/src/util/ApplicationFlagsBitField.js +++ b/packages/discord.js/src/util/ApplicationFlagsBitField.js @@ -34,10 +34,10 @@ class ApplicationFlagsBitField extends BitField { /** * Data that can be resolved to give an application flag bit field. This can be: - * A string (see {@link ApplicationFlagsBitField.Flags}) - * An application flag - * An instance of ApplicationFlagsBitField - * An Array of ApplicationFlagsResolvable + * - A string (see {@link ApplicationFlagsBitField.Flags}) + * - An application flag + * - An instance of ApplicationFlagsBitField + * - An Array of ApplicationFlagsResolvable * * @typedef {string|number|ApplicationFlagsBitField|ApplicationFlagsResolvable[]} ApplicationFlagsResolvable */ diff --git a/packages/discord.js/src/util/BitField.js b/packages/discord.js/src/util/BitField.js index a8aa2dbd1a09..98d477d06da2 100644 --- a/packages/discord.js/src/util/BitField.js +++ b/packages/discord.js/src/util/BitField.js @@ -1,3 +1,4 @@ +/* eslint-disable unicorn/prefer-number-properties */ 'use strict'; const { DiscordjsRangeError, ErrorCodes } = require('../errors/index.js'); @@ -24,7 +25,7 @@ class BitField { static DefaultBit = 0; /** - * @param {BitFieldResolvable} [bits] Bit(s) to read from + * @param {BitFieldResolvable} [bits=this.constructor.DefaultBit] Bit(s) to read from */ constructor(bits = this.constructor.DefaultBit) { /** @@ -130,7 +131,7 @@ class BitField { serialize(...hasParams) { const serialized = {}; for (const [flag, bit] of Object.entries(this.constructor.Flags)) { - if (Number.isNaN(flag)) serialized[flag] = this.has(bit, ...hasParams); + if (isNaN(flag)) serialized[flag] = this.has(bit, ...hasParams); } return serialized; @@ -156,16 +157,16 @@ class BitField { *[Symbol.iterator](...hasParams) { for (const bitName of Object.keys(this.constructor.Flags)) { - if (Number.isNaN(bitName) && this.has(bitName, ...hasParams)) yield bitName; + if (isNaN(bitName) && this.has(bitName, ...hasParams)) yield bitName; } } /** * Data that can be resolved to give a bitfield. This can be: - * A bit number (this can be a number literal or a value taken from {@link BitField.Flags}) - * A string bit number - * An instance of BitField - * An Array of BitFieldResolvable + * - A bit number (this can be a number literal or a value taken from {@link BitField.Flags}) + * - A string bit number + * - An instance of BitField + * - An Array of BitFieldResolvable * * @typedef {number|string|bigint|BitField|BitFieldResolvable[]} BitFieldResolvable */ @@ -185,7 +186,7 @@ class BitField { } if (typeof bit === 'string') { - if (!Number.isNaN(bit)) return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(bit); + if (!isNaN(bit)) return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(bit); if (this.Flags[bit] !== undefined) return this.Flags[bit]; } diff --git a/packages/discord.js/src/util/ChannelFlagsBitField.js b/packages/discord.js/src/util/ChannelFlagsBitField.js index 407abc7a1abf..4de3803750ec 100644 --- a/packages/discord.js/src/util/ChannelFlagsBitField.js +++ b/packages/discord.js/src/util/ChannelFlagsBitField.js @@ -34,10 +34,10 @@ class ChannelFlagsBitField extends BitField { /** * Data that can be resolved to give a channel flag bitfield. This can be: - * A string (see {@link ChannelFlagsBitField.Flags}) - * A channel flag - * An instance of ChannelFlagsBitField - * An Array of ChannelFlagsResolvable + * - A string (see {@link ChannelFlagsBitField.Flags}) + * - A channel flag + * - An instance of ChannelFlagsBitField + * - An Array of ChannelFlagsResolvable * * @typedef {string|number|ChannelFlagsBitField|ChannelFlagsResolvable[]} ChannelFlagsResolvable */ diff --git a/packages/discord.js/src/util/Constants.js b/packages/discord.js/src/util/Constants.js index 1469c413c2d5..06625e77dbd4 100644 --- a/packages/discord.js/src/util/Constants.js +++ b/packages/discord.js/src/util/Constants.js @@ -11,22 +11,22 @@ exports.MaxBulkDeletableMessageAge = 1_209_600_000; /** * The name of an item to be swept in Sweepers - * `autoModerationRules` - * `applicationCommands` - both global and guild commands - * `bans` - * `emojis` - * `entitlements` - * `invites` - accepts the `lifetime` property, using it will sweep based on expires timestamp - * `guildMembers` - * `messages` - accepts the `lifetime` property, using it will sweep based on edited or created timestamp - * `presences` - * `reactions` - * `stageInstances` - * `stickers` - * `threadMembers` - * `threads` - accepts the `lifetime` property, using it will sweep archived threads based on archived timestamp - * `users` - * `voiceStates` + * - `autoModerationRules` + * - `applicationCommands` - both global and guild commands + * - `bans` + * - `emojis` + * - `entitlements` + * - `invites` - accepts the `lifetime` property, using it will sweep based on expires timestamp + * - `guildMembers` + * - `messages` - accepts the `lifetime` property, using it will sweep based on edited or created timestamp + * - `presences` + * - `reactions` + * - `stageInstances` + * - `stickers` + * - `threadMembers` + * - `threads` - accepts the `lifetime` property, using it will sweep archived threads based on archived timestamp + * - `users` + * - `voiceStates` * * @typedef {string} SweeperKey */ @@ -67,24 +67,24 @@ exports.NonSystemMessageTypes = [ /** * The guild channels that are text-based. - * TextChannel - * AnnouncementChannel - * ThreadChannel - * VoiceChannel - * StageChannel + * - TextChannel + * - AnnouncementChannel + * - ThreadChannel + * - VoiceChannel + * - StageChannel * * @typedef {TextChannel|AnnouncementChannel|ThreadChannel|VoiceChannel|StageChannel} GuildTextBasedChannel */ /** * The types of guild channels that are text-based. The available types are: - * {@link ChannelType.GuildText} - * {@link ChannelType.GuildAnnouncement} - * {@link ChannelType.AnnouncementThread} - * {@link ChannelType.PublicThread} - * {@link ChannelType.PrivateThread} - * {@link ChannelType.GuildVoice} - * {@link ChannelType.GuildStageVoice} + * - {@link ChannelType.GuildText} + * - {@link ChannelType.GuildAnnouncement} + * - {@link ChannelType.AnnouncementThread} + * - {@link ChannelType.PublicThread} + * - {@link ChannelType.PrivateThread} + * - {@link ChannelType.GuildVoice} + * - {@link ChannelType.GuildStageVoice} * * @typedef {ChannelType[]} GuildTextBasedChannelTypes */ @@ -100,31 +100,31 @@ exports.GuildTextBasedChannelTypes = [ /** * The channels that are text-based. - * {@link DMChannel} - * {@link GuildTextBasedChannel} + * - {@link DMChannel} + * - {@link GuildTextBasedChannel} * * @typedef {DMChannel|GuildTextBasedChannel} TextBasedChannels */ /** * Data that resolves to give a text-based channel. This can be: - * A {@link TextBasedChannel} - * A {@link Snowflake} + * - A {@link TextBasedChannel} + * - A {@link Snowflake} * * @typedef {TextBasedChannels|Snowflake} TextBasedChannelsResolvable */ /** * The types of channels that are text-based. The available types are: - * {@link ChannelType.DM} - * {@link ChannelType.GuildText} - * {@link ChannelType.GuildAnnouncement} - * {@link ChannelType.AnnouncementThread} - * {@link ChannelType.PublicThread} - * {@link ChannelType.PrivateThread} - * {@link ChannelType.GuildVoice} - * {@link ChannelType.GuildStageVoice} - * {@link ChannelType.GroupDM} + * - {@link ChannelType.DM} + * - {@link ChannelType.GuildText} + * - {@link ChannelType.GuildAnnouncement} + * - {@link ChannelType.AnnouncementThread} + * - {@link ChannelType.PublicThread} + * - {@link ChannelType.PrivateThread} + * - {@link ChannelType.GuildVoice} + * - {@link ChannelType.GuildStageVoice} + * - {@link ChannelType.GroupDM} * * @typedef {ChannelType[]} TextBasedChannelTypes */ @@ -132,14 +132,14 @@ exports.TextBasedChannelTypes = [...exports.GuildTextBasedChannelTypes, ChannelT /** * The types of channels that are text-based and can have messages sent into. The available types are: - * {@link ChannelType.DM} - * {@link ChannelType.GuildText} - * {@link ChannelType.GuildAnnouncement} - * {@link ChannelType.AnnouncementThread} - * {@link ChannelType.PublicThread} - * {@link ChannelType.PrivateThread} - * {@link ChannelType.GuildVoice} - * {@link ChannelType.GuildStageVoice} + * - {@link ChannelType.DM} + * - {@link ChannelType.GuildText} + * - {@link ChannelType.GuildAnnouncement} + * - {@link ChannelType.AnnouncementThread} + * - {@link ChannelType.PublicThread} + * - {@link ChannelType.PrivateThread} + * - {@link ChannelType.GuildVoice} + * - {@link ChannelType.GuildStageVoice} * * @typedef {ChannelType[]} SendableChannels */ @@ -147,9 +147,9 @@ exports.SendableChannels = [...exports.GuildTextBasedChannelTypes, ChannelType.D /** * The types of channels that are threads. The available types are: - * {@link ChannelType.AnnouncementThread} - * {@link ChannelType.PublicThread} - * {@link ChannelType.PrivateThread} + * - {@link ChannelType.AnnouncementThread} + * - {@link ChannelType.PublicThread} + * - {@link ChannelType.PrivateThread} * * @typedef {ChannelType[]} ThreadChannelTypes */ @@ -157,8 +157,8 @@ exports.ThreadChannelTypes = [ChannelType.AnnouncementThread, ChannelType.Public /** * The types of channels that are voice-based. The available types are: - * {@link ChannelType.GuildVoice} - * {@link ChannelType.GuildStageVoice} + * - {@link ChannelType.GuildVoice} + * - {@link ChannelType.GuildStageVoice} * * @typedef {ChannelType[]} VoiceBasedChannelTypes */ @@ -166,11 +166,11 @@ exports.VoiceBasedChannelTypes = [ChannelType.GuildVoice, ChannelType.GuildStage /** * The types of select menus. The available types are: - * {@link ComponentType.StringSelect} - * {@link ComponentType.UserSelect} - * {@link ComponentType.RoleSelect} - * {@link ComponentType.MentionableSelect} - * {@link ComponentType.ChannelSelect} + * - {@link ComponentType.StringSelect} + * - {@link ComponentType.UserSelect} + * - {@link ComponentType.RoleSelect} + * - {@link ComponentType.MentionableSelect} + * - {@link ComponentType.ChannelSelect} * * @typedef {ComponentType[]} SelectMenuTypes */ @@ -184,12 +184,12 @@ exports.SelectMenuTypes = [ /** * The types of messages that cannot be deleted. The available types are: - * {@link MessageType.RecipientAdd} - * {@link MessageType.RecipientRemove} - * {@link MessageType.Call} - * {@link MessageType.ChannelNameChange} - * {@link MessageType.ChannelIconChange} - * {@link MessageType.ThreadStarterMessage} + * - {@link MessageType.RecipientAdd} + * - {@link MessageType.RecipientRemove} + * - {@link MessageType.Call} + * - {@link MessageType.ChannelNameChange} + * - {@link MessageType.ChannelIconChange} + * - {@link MessageType.ThreadStarterMessage} * * @typedef {MessageType[]} UndeletableMessageTypes */ @@ -204,10 +204,10 @@ exports.UndeletableMessageTypes = [ /** * A mapping between sticker formats and their respective image formats. - * {@link StickerFormatType.PNG} -> {@link ImageFormat.PNG} - * {@link StickerFormatType.APNG} -> {@link ImageFormat.PNG} - * {@link StickerFormatType.Lottie} -> {@link ImageFormat.Lottie} - * {@link StickerFormatType.GIF} -> {@link ImageFormat.GIF} + * - {@link StickerFormatType.PNG} -> {@link ImageFormat.PNG} + * - {@link StickerFormatType.APNG} -> {@link ImageFormat.PNG} + * - {@link StickerFormatType.Lottie} -> {@link ImageFormat.Lottie} + * - {@link StickerFormatType.GIF} -> {@link ImageFormat.GIF} * * @typedef {Object} StickerFormatExtensionMap * @property {"png"} 1 PNG diff --git a/packages/discord.js/src/util/DataResolver.js b/packages/discord.js/src/util/DataResolver.js index c081977ab892..1a8e19a6ee9c 100644 --- a/packages/discord.js/src/util/DataResolver.js +++ b/packages/discord.js/src/util/DataResolver.js @@ -9,16 +9,16 @@ const { Invite } = require('../structures/Invite.js'); /** * Data that can be resolved to give an invite code. This can be: - * An invite code - * An invite URL + * - An invite code + * - An invite URL * * @typedef {string} InviteResolvable */ /** * Data that can be resolved to give a template code. This can be: - * A template code - * A template URL + * - A template code + * - A template URL * * @typedef {string} GuildTemplateResolvable */ @@ -60,10 +60,10 @@ function resolveGuildTemplateCode(data) { /** * Data that can be resolved to give a Buffer. This can be: - * A Buffer - * The path to a local file - * A URL When provided a URL, discord.js will fetch the URL internally in order to create a Buffer. - * This can pose a security risk when the URL has not been sanitized + * - A Buffer + * - The path to a local file + * - A URL When provided a URL, discord.js will fetch the URL internally in order to create a Buffer. + * - This can pose a security risk when the URL has not been sanitized * * @typedef {string|Buffer} BufferResolvable */ @@ -114,8 +114,8 @@ async function resolveFile(resource) { /** * Data that resolves to give a Base64 string, typically for image uploading. This can be: - * A Buffer - * A base64 string + * - A Buffer + * - A base64 string * * @typedef {Buffer|string} Base64Resolvable */ @@ -124,7 +124,7 @@ async function resolveFile(resource) { * Resolves a Base64Resolvable to a Base 64 string. * * @param {Base64Resolvable} data The base 64 resolvable you want to resolve - * @param {string} [contentType] The content type of the data + * @param {string} [contentType='image/jpg'] The content type of the data * @returns {string} * @private */ diff --git a/packages/discord.js/src/util/GuildMemberFlagsBitField.js b/packages/discord.js/src/util/GuildMemberFlagsBitField.js index f0182d7c795c..2f1d9157c58d 100644 --- a/packages/discord.js/src/util/GuildMemberFlagsBitField.js +++ b/packages/discord.js/src/util/GuildMemberFlagsBitField.js @@ -34,10 +34,10 @@ class GuildMemberFlagsBitField extends BitField { /** * Data that can be resolved to give a guild member flag bitfield. This can be: - * A string (see {@link GuildMemberFlagsBitField.Flags}) - * A guild member flag - * An instance of GuildMemberFlagsBitField - * An Array of GuildMemberFlagsResolvable + * - A string (see {@link GuildMemberFlagsBitField.Flags}) + * - A guild member flag + * - An instance of GuildMemberFlagsBitField + * - An Array of GuildMemberFlagsResolvable * * @typedef {string|number|GuildMemberFlagsBitField|GuildMemberFlagsResolvable[]} GuildMemberFlagsResolvable */ diff --git a/packages/discord.js/src/util/IntentsBitField.js b/packages/discord.js/src/util/IntentsBitField.js index ac6f904b0da9..fefa057da77b 100644 --- a/packages/discord.js/src/util/IntentsBitField.js +++ b/packages/discord.js/src/util/IntentsBitField.js @@ -26,10 +26,10 @@ class IntentsBitField extends BitField { /** * Data that can be resolved to give a permission number. This can be: - * A string (see {@link IntentsBitField.Flags}) - * An intents flag - * An instance of {@link IntentsBitField} - * An array of IntentsResolvable + * - A string (see {@link IntentsBitField.Flags}) + * - An intents flag + * - An instance of {@link IntentsBitField} + * - An array of IntentsResolvable * * @typedef {string|number|IntentsBitField|IntentsResolvable[]} IntentsResolvable */ diff --git a/packages/discord.js/src/util/LimitedCollection.js b/packages/discord.js/src/util/LimitedCollection.js index 214d7e5c224a..ea96a8586e5e 100644 --- a/packages/discord.js/src/util/LimitedCollection.js +++ b/packages/discord.js/src/util/LimitedCollection.js @@ -17,7 +17,7 @@ const { DiscordjsTypeError, ErrorCodes } = require('../errors/index.js'); * * @extends {Collection} * @param {LimitedCollectionOptions} [options={}] Options for constructing the Collection. - * @param {Iterable} [iterable] Optional entries passed to the Map constructor. + * @param {Iterable} [iterable=null] Optional entries passed to the Map constructor. */ class LimitedCollection extends Collection { constructor(options = {}, iterable = undefined) { diff --git a/packages/discord.js/src/util/MessageFlagsBitField.js b/packages/discord.js/src/util/MessageFlagsBitField.js index b9a7a4e15127..e2b59fe23ec2 100644 --- a/packages/discord.js/src/util/MessageFlagsBitField.js +++ b/packages/discord.js/src/util/MessageFlagsBitField.js @@ -27,10 +27,10 @@ class MessageFlagsBitField extends BitField { /** * Data that can be resolved to give a message flags bit field. This can be: - * A string (see {@link MessageFlagsBitField.Flags}) - * A message flag - * An instance of {@link MessageFlagsBitField} - * An array of `MessageFlagsResolvable` + * - A string (see {@link MessageFlagsBitField.Flags}) + * - A message flag + * - An instance of {@link MessageFlagsBitField} + * - An array of `MessageFlagsResolvable` * * @typedef {string|number|MessageFlagsBitField|MessageFlagsResolvable[]} MessageFlagsResolvable */ diff --git a/packages/discord.js/src/util/Options.js b/packages/discord.js/src/util/Options.js index fda896b0d7f3..4f7e44a8e690 100644 --- a/packages/discord.js/src/util/Options.js +++ b/packages/discord.js/src/util/Options.js @@ -102,7 +102,7 @@ class Options extends null { /** * Create a cache factory using predefined settings to sweep or limit. * - * @param {Object} [settings] Settings passed to the relevant constructor. + * @param {Object} [settings={}] Settings passed to the relevant constructor. * If no setting is provided for a manager, it uses Collection. * If a number is provided for a manager, it uses that number as the max size for a LimitedCollection. * If LimitedCollectionOptions are provided for a manager, it uses those settings to form a LimitedCollection. @@ -159,7 +159,7 @@ class Options extends null { /** * The default settings passed to {@link ClientOptions.makeCache}. * The caches that this changes are: - * `MessageManager` - Limit to 200 messages + * - `MessageManager` - Limit to 200 messages * If you want to keep default behavior and add on top of it you can use this object and add on to it, e.g. * `makeCache: Options.cacheWithLimits({ ...Options.DefaultMakeCacheSettings, ReactionManager: 0 })` * @@ -174,7 +174,7 @@ class Options extends null { /** * The default settings passed to {@link ClientOptions.sweepers}. * The sweepers that this changes are: - * `threads` - Sweep archived threads every hour, removing those archived more than 4 hours ago + * - `threads` - Sweep archived threads every hour, removing those archived more than 4 hours ago * If you want to keep default behavior and add on top of it you can use this object and add on to it, e.g. * `sweepers: { ...Options.DefaultSweeperSettings, messages: { interval: 300, lifetime: 600 } }` * diff --git a/packages/discord.js/src/util/PermissionsBitField.js b/packages/discord.js/src/util/PermissionsBitField.js index 77c711feaf21..326aba3b3ed8 100644 --- a/packages/discord.js/src/util/PermissionsBitField.js +++ b/packages/discord.js/src/util/PermissionsBitField.js @@ -62,10 +62,10 @@ class PermissionsBitField extends BitField { /** * Data that can be resolved to give a permission number. This can be: - * A string (see {@link PermissionsBitField.Flags}) - * A permission number - * An instance of {@link PermissionsBitField} - * An Array of PermissionResolvable + * - A string (see {@link PermissionsBitField.Flags}) + * - A permission number + * - An instance of {@link PermissionsBitField} + * - An Array of PermissionResolvable * * @typedef {string|bigint|PermissionsBitField|PermissionResolvable[]} PermissionResolvable */ @@ -74,7 +74,7 @@ class PermissionsBitField extends BitField { * Gets all given bits that are missing from the bitfield. * * @param {BitFieldResolvable} bits Bit(s) to check for - * @param {boolean} [checkAdmin] Whether to allow the administrator permission to override + * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override * @returns {string[]} */ missing(bits, checkAdmin = true) { @@ -85,7 +85,7 @@ class PermissionsBitField extends BitField { * Checks whether the bitfield has a permission, or any of multiple permissions. * * @param {PermissionResolvable} permission Permission(s) to check for - * @param {boolean} [checkAdmin] Whether to allow the administrator permission to override + * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override * @returns {boolean} */ any(permission, checkAdmin = true) { @@ -96,7 +96,7 @@ class PermissionsBitField extends BitField { * Checks whether the bitfield has a permission, or multiple permissions. * * @param {PermissionResolvable} permission Permission(s) to check for - * @param {boolean} [checkAdmin] Whether to allow the administrator permission to override + * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override * @returns {boolean} */ has(permission, checkAdmin = true) { diff --git a/packages/discord.js/src/util/Sweepers.js b/packages/discord.js/src/util/Sweepers.js index 837e7fd4d1b1..faa954553db3 100644 --- a/packages/discord.js/src/util/Sweepers.js +++ b/packages/discord.js/src/util/Sweepers.js @@ -359,7 +359,7 @@ class Sweepers { /** * Create a sweepFilter function that uses a lifetime to determine sweepability. * - * @param {LifetimeFilterOptions} [options] The options used to generate the filter function + * @param {LifetimeFilterOptions} [options={}] The options used to generate the filter function * @returns {GlobalSweepFilter} */ static filterByLifetime({ @@ -398,7 +398,7 @@ class Sweepers { /** * Creates a sweep filter that sweeps archived threads * - * @param {number} [lifetime] How long a thread has to be archived to be valid for sweeping + * @param {number} [lifetime=14400] How long a thread has to be archived to be valid for sweeping * @returns {GlobalSweepFilter} */ static archivedThreadSweepFilter(lifetime = 14_400) { @@ -412,7 +412,7 @@ class Sweepers { /** * Creates a sweep filter that sweeps expired invites * - * @param {number} [lifetime] How long ago an invite has to have expired to be valid for sweeping + * @param {number} [lifetime=14400] How long ago an invite has to have expired to be valid for sweeping * @returns {GlobalSweepFilter} */ static expiredInviteSweepFilter(lifetime = 14_400) { @@ -425,7 +425,7 @@ class Sweepers { /** * Creates a sweep filter that sweeps outdated messages (edits taken into account) * - * @param {number} [lifetime] How long ago a message has to have been sent or edited to be valid for sweeping + * @param {number} [lifetime=3600] How long ago a message has to have been sent or edited to be valid for sweeping * @returns {GlobalSweepFilter} */ static outdatedMessageSweepFilter(lifetime = 3_600) { @@ -449,7 +449,7 @@ class Sweepers { * * @param {string} key The name of the property * @param {Function} filter Filter function passed to sweep - * @param {SweepEventOptions} [eventOptions] Options for the Client event emitted here + * @param {SweepEventOptions} [eventOptions={}] Options for the Client event emitted here * @returns {Object} Object containing the number of guilds swept and the number of items swept * @private */ diff --git a/packages/discord.js/src/util/SystemChannelFlagsBitField.js b/packages/discord.js/src/util/SystemChannelFlagsBitField.js index b855800af538..b2140ef71cf5 100644 --- a/packages/discord.js/src/util/SystemChannelFlagsBitField.js +++ b/packages/discord.js/src/util/SystemChannelFlagsBitField.js @@ -36,10 +36,10 @@ class SystemChannelFlagsBitField extends BitField { /** * Data that can be resolved to give a system channel flag bitfield. This can be: - * A string (see {@link SystemChannelFlagsBitField.Flags}) - * A system channel flag - * An instance of SystemChannelFlagsBitField - * An Array of SystemChannelFlagsResolvable + * - A string (see {@link SystemChannelFlagsBitField.Flags}) + * - A system channel flag + * - An instance of SystemChannelFlagsBitField + * - An Array of SystemChannelFlagsResolvable * * @typedef {string|number|SystemChannelFlagsBitField|SystemChannelFlagsResolvable[]} SystemChannelFlagsResolvable */ diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index c45c8b62ea25..e9bcec7348d7 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -99,9 +99,9 @@ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multi /** * Parses emoji info out of a string. The string must be one of: - * A UTF-8 emoji (no id) - * A URL-encoded UTF-8 emoji (no id) - * A Discord custom emoji (`<:name:id>` or ``) + * - A UTF-8 emoji (no id) + * - A URL-encoded UTF-8 emoji (no id) + * - A Discord custom emoji (`<:name:id>` or ``) * * @param {string} text Emoji string to parse * @returns {?PartialEmoji} @@ -241,7 +241,7 @@ function getSortableGroupTypes(type) { * @param {Array<*>} array Array to modify * @param {*} element Element to move * @param {number} newIndex Index or offset to move the element to - * @param {boolean} [offset] Move the element by an offset amount rather than to a set index + * @param {boolean} [offset=false] Move the element by an offset amount rather than to a set index * @returns {number} * @private */ @@ -260,9 +260,9 @@ function moveElementInArray(array, element, newIndex, offset = false) { * Verifies the provided data is a string, otherwise throws provided error. * * @param {string} data The string resolvable to resolve - * @param {Function} [error] The Error constructor to instantiate. Defaults to Error - * @param {string} [errorMessage] The error message to throw with. Defaults to "Expected string, got instead." - * @param {boolean} [allowEmpty] Whether an empty string should be allowed + * @param {Function} [error=Error] The Error constructor to instantiate. Defaults to Error + * @param {string} [errorMessage="Expected string, got instead."] The error message to throw with. Defaults to "Expected string, got instead." + * @param {boolean} [allowEmpty=true] Whether an empty string should be allowed * @returns {string} */ function verifyString( diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index 41a151cb6924..5dc2c8af09a5 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -1,3 +1,4 @@ +import type { Buffer } from 'node:buffer'; import type { ChildProcess } from 'node:child_process'; import type { Stream } from 'node:stream'; import type { MessagePort, Worker } from 'node:worker_threads'; From 04a22678a67072012b8f868a9e1eb0041516561a Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 19:27:28 +0200 Subject: [PATCH 11/38] fix: forgot Client --- packages/discord.js/src/client/Client.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/discord.js/src/client/Client.js b/packages/discord.js/src/client/Client.js index d2ee731bd59d..aa359658660c 100644 --- a/packages/discord.js/src/client/Client.js +++ b/packages/discord.js/src/client/Client.js @@ -262,7 +262,7 @@ class Client extends BaseClient { /** * Logs the client in, establishing a WebSocket connection to Discord. * - * @param {string} [token] Token of the account to log in with + * @param {string} [token=this.token] Token of the account to log in with * @returns {Promise} Token of the account used * @example * client.login('my token'); @@ -558,7 +558,7 @@ class Client extends BaseClient { /** * Obtains the list of available sticker packs. * - * @param {StickerPackFetchOptions} [options] Options for fetching sticker packs + * @param {StickerPackFetchOptions} [options={}] Options for fetching sticker packs * @returns {Promise|StickerPack>} * A collection of sticker packs, or a single sticker pack if a packId was provided * @example @@ -633,7 +633,7 @@ class Client extends BaseClient { /** * Generates a link that can be used to invite the bot to a guild. * - * @param {InviteGenerationOptions} [options] Options for the invite + * @param {InviteGenerationOptions} [options={}] Options for the invite * @returns {string} * @example * const link = client.generateInvite({ @@ -737,7 +737,7 @@ class Client extends BaseClient { /** * Validates the client options. * - * @param {ClientOptions} [options] Options to validate + * @param {ClientOptions} [options=this.options] Options to validate * @private */ _validateOptions(options = this.options) { From a58aeda45ef636f9d631b8cff8c22c888535c81a Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 20:05:16 +0200 Subject: [PATCH 12/38] Apply suggestions from code review Co-authored-by: Almeida --- packages/discord.js/src/client/Client.js | 2 +- packages/discord.js/src/sharding/Shard.js | 4 +--- packages/discord.js/src/sharding/ShardClientUtil.js | 3 +-- packages/discord.js/src/structures/Message.js | 8 +------- .../discord.js/src/structures/PermissionOverwrites.js | 2 +- packages/discord.js/src/structures/Webhook.js | 2 +- 6 files changed, 6 insertions(+), 15 deletions(-) diff --git a/packages/discord.js/src/client/Client.js b/packages/discord.js/src/client/Client.js index aa359658660c..8fef4ee1a932 100644 --- a/packages/discord.js/src/client/Client.js +++ b/packages/discord.js/src/client/Client.js @@ -269,7 +269,7 @@ class Client extends BaseClient { */ async login(token = this.token) { if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid); - this.token = token.replace(/^(?:bot|bearer)\s*/i, ''); + this.token = token.replace(/^bot\s*/i, ''); this.rest.setToken(this.token); diff --git a/packages/discord.js/src/sharding/Shard.js b/packages/discord.js/src/sharding/Shard.js index d1d6fc1d1b8c..b39afebf75c1 100644 --- a/packages/discord.js/src/sharding/Shard.js +++ b/packages/discord.js/src/sharding/Shard.js @@ -1,6 +1,4 @@ -/* eslint-disable promise/prefer-await-to-then */ -/* eslint-disable promise/prefer-await-to-callbacks */ -/* eslint-disable @typescript-eslint/no-use-before-define */ +/* eslint-disable promise/prefer-await-to-then, promise/prefer-await-to-callbacks, @typescript-eslint/no-use-before-define */ 'use strict'; const path = require('node:path'); diff --git a/packages/discord.js/src/sharding/ShardClientUtil.js b/packages/discord.js/src/sharding/ShardClientUtil.js index 716410664e8f..e88c64cd05b5 100644 --- a/packages/discord.js/src/sharding/ShardClientUtil.js +++ b/packages/discord.js/src/sharding/ShardClientUtil.js @@ -1,5 +1,4 @@ -/* eslint-disable promise/prefer-await-to-callbacks */ -/* eslint-disable promise/prefer-await-to-then */ +/* eslint-disable promise/prefer-await-to-callbacks, promise/prefer-await-to-then */ 'use strict'; const process = require('node:process'); diff --git a/packages/discord.js/src/structures/Message.js b/packages/discord.js/src/structures/Message.js index dc9212c3aea8..0f2ae1948e10 100644 --- a/packages/discord.js/src/structures/Message.js +++ b/packages/discord.js/src/structures/Message.js @@ -249,13 +249,7 @@ class Message extends Base { /** * Resolved data from auto-populated select menus. * - * @typedef {Object} CommandInteractionResolvedData - * @property {Collection} attachments attachments - * @property {Collection} channels channels - * @property {Collection} members members - * @property {Collection} messages messages - * @property {Collection} roles roles - * @property {Collection} users users + * @type {?CommandInteractionResolvedData} */ this.resolved = transformResolved( { client: this.client, guild: this.guild, channel: this.channel }, diff --git a/packages/discord.js/src/structures/PermissionOverwrites.js b/packages/discord.js/src/structures/PermissionOverwrites.js index 7c62c3bde827..7d925d00e293 100644 --- a/packages/discord.js/src/structures/PermissionOverwrites.js +++ b/packages/discord.js/src/structures/PermissionOverwrites.js @@ -112,7 +112,7 @@ class PermissionOverwrites extends Base { * } * ``` * - * @typedef {Object} PermissionOverwriteOptions + * @typedef {Object} PermissionOverwriteOptions */ /** diff --git a/packages/discord.js/src/structures/Webhook.js b/packages/discord.js/src/structures/Webhook.js index 7622e764f420..925ff5a9da21 100644 --- a/packages/discord.js/src/structures/Webhook.js +++ b/packages/discord.js/src/structures/Webhook.js @@ -250,7 +250,7 @@ class Webhook { if (!this.client.channels) return data; return ( - this.client.channels.cache.get(d.channel_id)?.messages._add(data, false) ?? new (getMessage())(this.client, data) + this.client.channels.cache.get(data.channel_id)?.messages._add(data, false) ?? new (getMessage())(this.client, data) ); } From 6e4971877412f2ce1d3882373fd99182ffbac28b Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 21:52:07 +0200 Subject: [PATCH 13/38] chore: more lint fixes --- eslint.config.js | 1 + packages/discord.js/src/client/Client.js | 2 +- .../src/client/voice/ClientVoiceManager.js | 2 +- .../websocket/handlers/THREAD_LIST_SYNC.js | 4 ++- .../discord.js/src/managers/DataManager.js | 6 ++-- .../src/managers/GuildChannelManager.js | 2 +- .../discord.js/src/managers/GuildManager.js | 35 +++++++++---------- .../src/managers/GuildMemberManager.js | 21 +++++------ .../src/sharding/ShardingManager.js | 3 +- .../src/structures/BaseGuildTextChannel.js | 2 +- .../src/structures/GuildAuditLogsEntry.js | 2 +- .../discord.js/src/structures/GuildChannel.js | 2 +- .../src/structures/GuildTemplate.js | 9 +++-- packages/discord.js/src/structures/Message.js | 4 +-- .../src/structures/ModalSubmitInteraction.js | 20 ----------- .../src/structures/PermissionOverwrites.js | 6 ++-- .../discord.js/src/structures/Presence.js | 10 ++++-- packages/discord.js/src/structures/Role.js | 2 +- .../src/structures/SoundboardSound.js | 2 +- .../src/structures/ThreadOnlyChannel.js | 2 +- .../discord.js/src/structures/VoiceState.js | 2 +- packages/discord.js/src/structures/Webhook.js | 3 +- .../src/structures/interfaces/Collector.js | 14 ++++---- .../src/util/ActivityFlagsBitField.js | 14 ++++---- packages/discord.js/src/util/Constants.js | 8 ++--- packages/discord.js/src/util/Partials.js | 14 ++++---- 26 files changed, 88 insertions(+), 104 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index aca2a321a2cc..17a315690568 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -159,6 +159,7 @@ export default tseslint.config( '@typescript-eslint/no-require-imports': 0, 'jsdoc/no-undefined-types': 0, 'jsdoc/no-defaults': 0, + 'no-eq-null': 0, '@typescript-eslint/explicit-member-accessibility': 0, '@typescript-eslint/class-literal-property-style': 0, strict: ['error', 'global'], diff --git a/packages/discord.js/src/client/Client.js b/packages/discord.js/src/client/Client.js index 8fef4ee1a932..fb328fe29a10 100644 --- a/packages/discord.js/src/client/Client.js +++ b/packages/discord.js/src/client/Client.js @@ -229,7 +229,7 @@ class Client extends BaseClient { /** * An array of queued events before this Client became ready * - * @type {object[]} + * @type {Object[]} * @private * @name Client#incomingPacketQueue */ diff --git a/packages/discord.js/src/client/voice/ClientVoiceManager.js b/packages/discord.js/src/client/voice/ClientVoiceManager.js index c92a633da5d3..a5ca81249396 100644 --- a/packages/discord.js/src/client/voice/ClientVoiceManager.js +++ b/packages/discord.js/src/client/voice/ClientVoiceManager.js @@ -19,7 +19,7 @@ class ClientVoiceManager { /** * Maps guild ids to voice adapters created for use with `@discordjs/voice`. * - * @type {Map} + * @type {Map} */ this.adapters = new Map(); diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js index edb37781cfbf..b17c4628d948 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js @@ -42,7 +42,9 @@ module.exports = (client, { d: data }) => { }; function removeStaleThreads(client, channel) { - for (const thread of channel.threads?.cache ?? []) { + if (!channel.threads) return; + + for (const thread of channel.threads.cache) { if (!thread.archived) { client.channels._remove(thread.id); } diff --git a/packages/discord.js/src/managers/DataManager.js b/packages/discord.js/src/managers/DataManager.js index 944806a442fd..2321d67da8dd 100644 --- a/packages/discord.js/src/managers/DataManager.js +++ b/packages/discord.js/src/managers/DataManager.js @@ -37,8 +37,8 @@ class DataManager extends BaseManager { /** * Resolves a data entry to a data Object. * - * @param {string | object} idOrInstance The id or instance of something in this Manager - * @returns {?object} An instance from this Manager + * @param {string | Object} idOrInstance The id or instance of something in this Manager + * @returns {?Object} An instance from this Manager */ resolve(idOrInstance) { if (idOrInstance instanceof this.holds) return idOrInstance; @@ -49,7 +49,7 @@ class DataManager extends BaseManager { /** * Resolves a data entry to an instance id. * - * @param {string | object} idOrInstance The id or instance of something in this Manager + * @param {string | Object} idOrInstance The id or instance of something in this Manager * @returns {?Snowflake} */ resolveId(idOrInstance) { diff --git a/packages/discord.js/src/managers/GuildChannelManager.js b/packages/discord.js/src/managers/GuildChannelManager.js index df5dae6accad..d73a5d7b95d2 100644 --- a/packages/discord.js/src/managers/GuildChannelManager.js +++ b/packages/discord.js/src/managers/GuildChannelManager.js @@ -510,7 +510,7 @@ class GuildChannelManager extends CachedManager { /** * Obtains all active thread channels in the guild. * - * @param {boolean} [cache] Whether to cache the fetched data + * @param {boolean} [cache=true] Whether to cache the fetched data * @returns {Promise} * @example * // Fetch all threads from the guild diff --git a/packages/discord.js/src/managers/GuildManager.js b/packages/discord.js/src/managers/GuildManager.js index 35b1114e9326..511213542a37 100644 --- a/packages/discord.js/src/managers/GuildManager.js +++ b/packages/discord.js/src/managers/GuildManager.js @@ -235,15 +235,6 @@ class GuildManager extends CachedManager { return ( this.client.guilds.cache.get(data.id) ?? new Promise(resolve => { - const handleGuild = guild => { - if (guild.id === data.id) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - clearTimeout(timeout); - this.client.decrementMaxListeners(); - resolve(guild); - } - }; - this.client.incrementMaxListeners(); this.client.once(Events.GuildCreate, handleGuild); @@ -252,6 +243,14 @@ class GuildManager extends CachedManager { this.client.decrementMaxListeners(); resolve(this.client.guilds._add(data)); }, 10_000).unref(); + + function handleGuild(guild) { + if (guild.id === data.id) { + clearTimeout(timeout); + this.client.decrementMaxListeners(); + resolve(guild); + } + } }) ); } @@ -337,8 +336,13 @@ class GuildManager extends CachedManager { const fetchedSoundboardSounds = new Collection(); - const handler = (soundboardSounds, guild) => { - // eslint-disable-next-line @typescript-eslint/no-use-before-define + const timeout = setTimeout(() => { + this.client.removeListener(Events.SoundboardSounds, handler); + this.client.decrementMaxListeners(); + reject(new DiscordjsError(ErrorCodes.GuildSoundboardSoundsTimeout)); + }, time).unref(); + + function handler(soundboardSounds, guild) { timeout.refresh(); if (!remainingGuildIds.has(guild.id)) return; @@ -348,20 +352,13 @@ class GuildManager extends CachedManager { remainingGuildIds.delete(guild.id); if (remainingGuildIds.size === 0) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(timeout); this.client.removeListener(Events.SoundboardSounds, handler); this.client.decrementMaxListeners(); resolve(fetchedSoundboardSounds); } - }; - - const timeout = setTimeout(() => { - this.client.removeListener(Events.SoundboardSounds, handler); - this.client.decrementMaxListeners(); - reject(new DiscordjsError(ErrorCodes.GuildSoundboardSoundsTimeout)); - }, time).unref(); + } this.client.incrementMaxListeners(); this.client.on(Events.SoundboardSounds, handler); diff --git a/packages/discord.js/src/managers/GuildMemberManager.js b/packages/discord.js/src/managers/GuildMemberManager.js index 294fe159fbd1..c4d3cf2508e8 100644 --- a/packages/discord.js/src/managers/GuildMemberManager.js +++ b/packages/discord.js/src/managers/GuildMemberManager.js @@ -259,9 +259,16 @@ class GuildMemberManager extends CachedManager { }); const fetchedMembers = new Collection(); let index = 0; - const handler = (members, _, chunk) => { + + const timeout = setTimeout(() => { + this.client.removeListener(Events.GuildMembersChunk, handler); + this.client.decrementMaxListeners(); + reject(new DiscordjsError(ErrorCodes.GuildMembersTimeout)); + }, time).unref(); + + function handler(members, _, chunk) { if (chunk.nonce !== nonce) return; - // eslint-disable-next-line @typescript-eslint/no-use-before-define + timeout.refresh(); index++; for (const member of members.values()) { @@ -269,19 +276,13 @@ class GuildMemberManager extends CachedManager { } if (members.size < 1_000 || (limit && fetchedMembers.size >= limit) || index === chunk.count) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(timeout); this.client.removeListener(Events.GuildMembersChunk, handler); this.client.decrementMaxListeners(); resolve(users && !Array.isArray(users) && fetchedMembers.size ? fetchedMembers.first() : fetchedMembers); } - }; + } - const timeout = setTimeout(() => { - this.client.removeListener(Events.GuildMembersChunk, handler); - this.client.decrementMaxListeners(); - reject(new DiscordjsError(ErrorCodes.GuildMembersTimeout)); - }, time).unref(); this.client.incrementMaxListeners(); this.client.on(Events.GuildMembersChunk, handler); }); @@ -385,7 +386,7 @@ class GuildMemberManager extends CachedManager { if (options.communicationDisabledUntil !== undefined) { options.communication_disabled_until = - // eslint-disable-next-line eqeqeq, no-eq-null + // eslint-disable-next-line eqeqeq options.communicationDisabledUntil == null ? options.communicationDisabledUntil : new Date(options.communicationDisabledUntil).toISOString(); diff --git a/packages/discord.js/src/sharding/ShardingManager.js b/packages/discord.js/src/sharding/ShardingManager.js index 2ad4039fc24b..148bb42c464c 100644 --- a/packages/discord.js/src/sharding/ShardingManager.js +++ b/packages/discord.js/src/sharding/ShardingManager.js @@ -5,6 +5,7 @@ const path = require('node:path'); const process = require('node:process'); const { setTimeout: sleep } = require('node:timers/promises'); const { Collection } = require('@discordjs/collection'); +const { range } = require('@discordjs/util'); const { AsyncEventEmitter } = require('@vladfrangu/async_event_emitter'); const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors/index.js'); const { fetchRecommendedShardCount } = require('../util/Util.js'); @@ -234,7 +235,7 @@ class ShardingManager extends AsyncEventEmitter { // Make sure this many shards haven't already been spawned if (this.shards.size >= shardAmount) throw new DiscordjsError(ErrorCodes.ShardingAlreadySpawned, this.shards.size); if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== shardAmount) { - this.shardList = [...Array.from({ length: shardAmount }).keys()]; + this.shardList = [...range(shardAmount)]; } if (this.totalShards === 'auto' || this.totalShards !== shardAmount) { diff --git a/packages/discord.js/src/structures/BaseGuildTextChannel.js b/packages/discord.js/src/structures/BaseGuildTextChannel.js index b8ca6b51cc56..30f470f23917 100644 --- a/packages/discord.js/src/structures/BaseGuildTextChannel.js +++ b/packages/discord.js/src/structures/BaseGuildTextChannel.js @@ -167,7 +167,7 @@ class BaseGuildTextChannel extends GuildChannel { /** * Creates an invite to this guild channel. * - * @param {InviteCreateOptions} [options] The options for creating the invite + * @param {InviteCreateOptions} [options={}] The options for creating the invite * @returns {Promise} * @example * // Create an invite to a channel diff --git a/packages/discord.js/src/structures/GuildAuditLogsEntry.js b/packages/discord.js/src/structures/GuildAuditLogsEntry.js index 2b561cc80973..ff1e8095a711 100644 --- a/packages/discord.js/src/structures/GuildAuditLogsEntry.js +++ b/packages/discord.js/src/structures/GuildAuditLogsEntry.js @@ -201,7 +201,7 @@ class GuildAuditLogsEntry { /** * Any extra data from the entry * - * @type {?(object | Role | GuildMember)} + * @type {?(Object | Role | GuildMember)} */ this.extra = null; switch (data.action_type) { diff --git a/packages/discord.js/src/structures/GuildChannel.js b/packages/discord.js/src/structures/GuildChannel.js index 0ad9135d5277..3694eb1e7a75 100644 --- a/packages/discord.js/src/structures/GuildChannel.js +++ b/packages/discord.js/src/structures/GuildChannel.js @@ -342,7 +342,7 @@ class GuildChannel extends BaseChannel { * Sets the parent of this channel. * * @param {?CategoryChannelResolvable} channel The category channel to set as the parent - * @param {SetParentOptions} [options] The options for setting the parent + * @param {SetParentOptions} [options={}] The options for setting the parent * @returns {Promise} * @example * // Add a parent to a channel diff --git a/packages/discord.js/src/structures/GuildTemplate.js b/packages/discord.js/src/structures/GuildTemplate.js index c3e13fe07035..33cf7cf4fcfe 100644 --- a/packages/discord.js/src/structures/GuildTemplate.js +++ b/packages/discord.js/src/structures/GuildTemplate.js @@ -147,20 +147,19 @@ class GuildTemplate extends Base { if (client.guilds.cache.has(data.id)) return client.guilds.cache.get(data.id); return new Promise(resolve => { - const resolveGuild = guild => { - // eslint-disable-next-line @typescript-eslint/no-use-before-define + function resolveGuild(guild) { client.off(Events.GuildCreate, handleGuild); client.decrementMaxListeners(); resolve(guild); - }; + } - const handleGuild = guild => { + function handleGuild(guild) { if (guild.id === data.id) { // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(timeout); resolveGuild(guild); } - }; + } client.incrementMaxListeners(); client.on(Events.GuildCreate, handleGuild); diff --git a/packages/discord.js/src/structures/Message.js b/packages/discord.js/src/structures/Message.js index 0f2ae1948e10..f2d7d3ea24e7 100644 --- a/packages/discord.js/src/structures/Message.js +++ b/packages/discord.js/src/structures/Message.js @@ -613,7 +613,7 @@ class Message extends Base { * @readonly */ get cleanContent() { - // eslint-disable-next-line eqeqeq, no-eq-null + // eslint-disable-next-line eqeqeq return this.content != null && this.channel ? cleanContent(this.content, this.channel) : null; } @@ -829,7 +829,7 @@ class Message extends Base { if (!messageId) throw new DiscordjsError(ErrorCodes.MessageReferenceMissing); const channel = this.client.channels.resolve(channelId); if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); - return await channel.messages.fetch(messageId); + return channel.messages.fetch(messageId); } /** diff --git a/packages/discord.js/src/structures/ModalSubmitInteraction.js b/packages/discord.js/src/structures/ModalSubmitInteraction.js index 8c6f27ed17ac..4986fc2093c7 100644 --- a/packages/discord.js/src/structures/ModalSubmitInteraction.js +++ b/packages/discord.js/src/structures/ModalSubmitInteraction.js @@ -118,26 +118,6 @@ class ModalSubmitInteraction extends BaseInteraction { isFromMessage() { return Boolean(this.message); } - - // These are here only for documentation purposes - they are implemented by InteractionResponses - - deferReply() {} - - reply() {} - - fetchReply() {} - - editReply() {} - - deleteReply() {} - - followUp() {} - - deferUpdate() {} - - update() {} - - launchActivity() {} } InteractionResponses.applyToClass(ModalSubmitInteraction, 'showModal'); diff --git a/packages/discord.js/src/structures/PermissionOverwrites.js b/packages/discord.js/src/structures/PermissionOverwrites.js index 7d925d00e293..ea7d96d826da 100644 --- a/packages/discord.js/src/structures/PermissionOverwrites.js +++ b/packages/discord.js/src/structures/PermissionOverwrites.js @@ -106,9 +106,9 @@ class PermissionOverwrites extends Base { * An object mapping permission flags to `true` (enabled), `null` (unset) or `false` (disabled). * ```js * { - * 'SendMessages': true, - * 'EmbedLinks': null, - * 'AttachFiles': false, + * 'SendMessages': true, + * 'EmbedLinks': null, + * 'AttachFiles': false, * } * ``` * diff --git a/packages/discord.js/src/structures/Presence.js b/packages/discord.js/src/structures/Presence.js index e6f32807c995..49e3305ac209 100644 --- a/packages/discord.js/src/structures/Presence.js +++ b/packages/discord.js/src/structures/Presence.js @@ -104,13 +104,17 @@ class Presence extends Base { if ('client_status' in data) { /** - * The devices this presence is on - * - * @type {?object} + * @typedef {Object} ClientPresenceStatusData * @property {?ClientPresenceStatus} web The current presence in the web application * @property {?ClientPresenceStatus} mobile The current presence in the mobile application * @property {?ClientPresenceStatus} desktop The current presence in the desktop application */ + + /** + * The devices this presence is on + * + * @type {?ClientPresenceStatusData} + */ this.clientStatus = data.client_status; } else { this.clientStatus ??= null; diff --git a/packages/discord.js/src/structures/Role.js b/packages/discord.js/src/structures/Role.js index 0abbf50271f6..982de0f0dc7e 100644 --- a/packages/discord.js/src/structures/Role.js +++ b/packages/discord.js/src/structures/Role.js @@ -129,7 +129,7 @@ class Role extends Base { /** * The tags this role has * - * @type {?object} + * @type {?Object} * @property {Snowflake} [botId] The id of the bot this role belongs to * @property {Snowflake|string} [integrationId] The id of the integration this role belongs to * @property {true} [premiumSubscriberRole] Whether this is the guild's premium subscription role diff --git a/packages/discord.js/src/structures/SoundboardSound.js b/packages/discord.js/src/structures/SoundboardSound.js index 20037218d287..4192d83cb77d 100644 --- a/packages/discord.js/src/structures/SoundboardSound.js +++ b/packages/discord.js/src/structures/SoundboardSound.js @@ -62,7 +62,7 @@ class SoundboardSound extends Base { /** * The raw emoji data of this soundboard sound * - * @type {?object} + * @type {?Object} * @private */ this._emoji = { diff --git a/packages/discord.js/src/structures/ThreadOnlyChannel.js b/packages/discord.js/src/structures/ThreadOnlyChannel.js index 81debc7141c3..cc69e4db4f2d 100644 --- a/packages/discord.js/src/structures/ThreadOnlyChannel.js +++ b/packages/discord.js/src/structures/ThreadOnlyChannel.js @@ -183,7 +183,7 @@ class ThreadOnlyChannel extends GuildChannel { /** * Creates an invite to this guild channel. * - * @param {InviteCreateOptions} [options] The options for creating the invite + * @param {InviteCreateOptions} [options={}] The options for creating the invite * @returns {Promise} * @example * // Create an invite to a channel diff --git a/packages/discord.js/src/structures/VoiceState.js b/packages/discord.js/src/structures/VoiceState.js index 06f55c090637..d5bba5204c8d 100644 --- a/packages/discord.js/src/structures/VoiceState.js +++ b/packages/discord.js/src/structures/VoiceState.js @@ -288,7 +288,7 @@ class VoiceState extends Base { * Toggles the request to speak in the channel. * Only applicable for stage channels and for the client's own voice state. * - * @param {boolean} [requestToSpeak] Whether or not the client is requesting to become a speaker. + * @param {boolean} [requestToSpeak=true] Whether or not the client is requesting to become a speaker. * @example * // Making the client request to speak in a stage channel (raise its hand) * guild.members.me.voice.setRequestToSpeak(true); diff --git a/packages/discord.js/src/structures/Webhook.js b/packages/discord.js/src/structures/Webhook.js index 925ff5a9da21..3c9e4188922b 100644 --- a/packages/discord.js/src/structures/Webhook.js +++ b/packages/discord.js/src/structures/Webhook.js @@ -250,7 +250,8 @@ class Webhook { if (!this.client.channels) return data; return ( - this.client.channels.cache.get(data.channel_id)?.messages._add(data, false) ?? new (getMessage())(this.client, data) + this.client.channels.cache.get(data.channel_id)?.messages._add(data, false) ?? + new (getMessage())(this.client, data) ); } diff --git a/packages/discord.js/src/structures/interfaces/Collector.js b/packages/discord.js/src/structures/interfaces/Collector.js index e110fce5ec55..7fabd5e8e022 100644 --- a/packages/discord.js/src/structures/interfaces/Collector.js +++ b/packages/discord.js/src/structures/interfaces/Collector.js @@ -204,22 +204,20 @@ class Collector extends AsyncEventEmitter { return; } - const cleanup = () => { - // eslint-disable-next-line @typescript-eslint/no-use-before-define + function cleanup() { this.removeListener('collect', onCollect); - // eslint-disable-next-line @typescript-eslint/no-use-before-define this.removeListener('end', onEnd); - }; + } - const onCollect = item => { + function onCollect(item) { cleanup(); resolve(item); - }; + } - const onEnd = () => { + function onEnd() { cleanup(); reject(this.collected); - }; + } this.on('collect', onCollect); this.on('end', onEnd); diff --git a/packages/discord.js/src/util/ActivityFlagsBitField.js b/packages/discord.js/src/util/ActivityFlagsBitField.js index 8e886a47fac4..415bf7d8b623 100644 --- a/packages/discord.js/src/util/ActivityFlagsBitField.js +++ b/packages/discord.js/src/util/ActivityFlagsBitField.js @@ -16,13 +16,13 @@ class ActivityFlagsBitField extends BitField { * @memberof ActivityFlagsBitField */ static Flags = ActivityFlags; -} -/** - * @name ActivityFlagsBitField - * @constructor - * @memberof ActivityFlagsBitField - * @param {BitFieldResolvable} [bits=0] Bit(s) to read from - */ + /** + * @method (constructor) + * @constructs + * @memberof ActivityFlagsBitField + * @param {BitFieldResolvable} [bits=0] Bit(s) to read from + */ +} exports.ActivityFlagsBitField = ActivityFlagsBitField; diff --git a/packages/discord.js/src/util/Constants.js b/packages/discord.js/src/util/Constants.js index 06625e77dbd4..e9d856decb2c 100644 --- a/packages/discord.js/src/util/Constants.js +++ b/packages/discord.js/src/util/Constants.js @@ -51,10 +51,10 @@ exports.SweeperKeys = [ /** * The types of messages that are not `System`. The available types are: - * {@link MessageType.Default} - * {@link MessageType.Reply} - * {@link MessageType.ChatInputCommand} - * {@link MessageType.ContextMenuCommand} + * - {@link MessageType.Default} + * - {@link MessageType.Reply} + * - {@link MessageType.ChatInputCommand} + * - {@link MessageType.ContextMenuCommand} * * @typedef {MessageType[]} NonSystemMessageTypes */ diff --git a/packages/discord.js/src/util/Partials.js b/packages/discord.js/src/util/Partials.js index abbfc7f1e3f1..d6feb81a210a 100644 --- a/packages/discord.js/src/util/Partials.js +++ b/packages/discord.js/src/util/Partials.js @@ -8,13 +8,13 @@ const { createEnum } = require('./Enums.js'); * import { Client, Partials } from 'discord.js'; * * const client = new Client({ - * intents: [ - * // Intents... - * ], - * partials: [ - * Partials.User, // We want to receive uncached users! - * Partials.Message // We want to receive uncached messages! - * ] + * intents: [ + * // Intents... + * ], + * partials: [ + * Partials.User, // We want to receive uncached users! + * Partials.Message // We want to receive uncached messages! + * ] * }); * ``` * From 6945b0e5709b5b6346fd7b1607230f8b625e0560 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sat, 3 May 2025 22:03:08 +0200 Subject: [PATCH 14/38] fix: remove useless Boolean() --- packages/discord.js/src/structures/Invite.js | 5 +++-- packages/discord.js/src/structures/MessagePayload.js | 2 +- packages/discord.js/src/util/Options.js | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/discord.js/src/structures/Invite.js b/packages/discord.js/src/structures/Invite.js index 2da88ca0b5b3..594d920c2f3e 100644 --- a/packages/discord.js/src/structures/Invite.js +++ b/packages/discord.js/src/structures/Invite.js @@ -251,10 +251,11 @@ class Invite extends Base { const guild = this.guild; if (!guild || !this.client.guilds.cache.has(guild.id)) return false; if (!guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); - return Boolean( + + return ( // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) || - guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild), + guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild) ); } diff --git a/packages/discord.js/src/structures/MessagePayload.js b/packages/discord.js/src/structures/MessagePayload.js index 154075d5ea01..ce01948235e7 100644 --- a/packages/discord.js/src/structures/MessagePayload.js +++ b/packages/discord.js/src/structures/MessagePayload.js @@ -158,7 +158,7 @@ class MessagePayload { let flags; if ( - // eslint-disable-next-line eqeqeq, no-eq-null + // eslint-disable-next-line eqeqeq this.options.flags != null ) { flags = new MessageFlagsBitField(this.options.flags).bitfield; diff --git a/packages/discord.js/src/util/Options.js b/packages/discord.js/src/util/Options.js index 4f7e44a8e690..deeec8ea78dc 100644 --- a/packages/discord.js/src/util/Options.js +++ b/packages/discord.js/src/util/Options.js @@ -123,7 +123,7 @@ class Options extends null { return (managerType, _, manager) => { const setting = settings[manager.name] ?? settings[managerType.name]; - /* eslint-disable-next-line eqeqeq, no-eq-null */ + /* eslint-disable-next-line eqeqeq */ if (setting == null) { return new Collection(); } @@ -136,7 +136,7 @@ class Options extends null { return new LimitedCollection({ maxSize: setting }); } - /* eslint-disable-next-line eqeqeq, no-eq-null */ + /* eslint-disable-next-line eqeqeq */ const noLimit = setting.maxSize == null || setting.maxSize === Infinity; if (noLimit) { return new Collection(); From 7d5d3b09f3a71972cdb2cbfc67c77c49f898ba9f Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 11:14:42 +0200 Subject: [PATCH 15/38] fix: get docs back --- .../src/structures/ModalSubmitInteraction.js | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/discord.js/src/structures/ModalSubmitInteraction.js b/packages/discord.js/src/structures/ModalSubmitInteraction.js index 4986fc2093c7..8c6f27ed17ac 100644 --- a/packages/discord.js/src/structures/ModalSubmitInteraction.js +++ b/packages/discord.js/src/structures/ModalSubmitInteraction.js @@ -118,6 +118,26 @@ class ModalSubmitInteraction extends BaseInteraction { isFromMessage() { return Boolean(this.message); } + + // These are here only for documentation purposes - they are implemented by InteractionResponses + + deferReply() {} + + reply() {} + + fetchReply() {} + + editReply() {} + + deleteReply() {} + + followUp() {} + + deferUpdate() {} + + update() {} + + launchActivity() {} } InteractionResponses.applyToClass(ModalSubmitInteraction, 'showModal'); From c8687cdd45089e6d06f8656609bf0a7d9dfa08c0 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 11:17:32 +0200 Subject: [PATCH 16/38] fix: snowflake docs --- packages/discord.js/src/client/Client.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/discord.js/src/client/Client.js b/packages/discord.js/src/client/Client.js index fb328fe29a10..a05e8549605e 100644 --- a/packages/discord.js/src/client/Client.js +++ b/packages/discord.js/src/client/Client.js @@ -818,8 +818,8 @@ exports.Client = Client; * If we have a snowflake '266241948824764416' we can represent it as binary: * ``` * 64 22 17 12 0 - * 000000111011000111100001101001000101000000 00001 00000 000000000000 - * number of milliseconds since Discord epoch worker pid increment + * 000000111011000111100001101001000101000000 00001 00000 000000000000 + * number of milliseconds since Discord epoch worker pid increment * ``` * * @typedef {string} Snowflake From 0eaeb728793976c8e3d685dbb7cfef9eadd56484 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 13:49:51 +0200 Subject: [PATCH 17/38] refactor: don't use typescript lint rules --- eslint.config.js | 6 ++++++ packages/discord.js/src/client/BaseClient.js | 1 - packages/discord.js/src/client/Client.js | 4 ++-- packages/discord.js/src/client/WebhookClient.js | 7 ++++--- .../src/client/actions/InteractionCreate.js | 1 - .../ApplicationCommandPermissionsManager.js | 8 ++++---- .../src/managers/GuildChannelManager.js | 6 +++--- packages/discord.js/src/managers/GuildManager.js | 6 +++--- .../discord.js/src/managers/GuildMemberManager.js | 2 +- .../src/managers/GuildScheduledEventManager.js | 4 ++-- packages/discord.js/src/managers/RoleManager.js | 4 ++-- packages/discord.js/src/sharding/Shard.js | 6 +++++- .../discord.js/src/sharding/ShardClientUtil.js | 4 ++++ .../src/structures/BaseGuildTextChannel.js | 1 + .../src/structures/BaseGuildVoiceChannel.js | 1 + packages/discord.js/src/structures/DMChannel.js | 1 + packages/discord.js/src/structures/Guild.js | 1 - .../src/structures/GuildAuditLogsEntry.js | 1 - .../discord.js/src/structures/GuildTemplate.js | 11 +++++------ .../src/structures/InteractionCollector.js | 1 - .../src/structures/InteractionWebhook.js | 1 + packages/discord.js/src/structures/Invite.js | 1 - .../discord.js/src/structures/MessageCollector.js | 1 - .../discord.js/src/structures/MessageReaction.js | 6 +++--- .../src/structures/PartialGroupDMChannel.js | 1 + packages/discord.js/src/structures/Presence.js | 2 +- .../src/structures/ReactionCollector.js | 2 +- .../discord.js/src/structures/ThreadChannel.js | 1 + packages/discord.js/src/structures/VoiceState.js | 1 - .../src/structures/interfaces/Collector.js | 2 ++ .../src/structures/interfaces/TextBasedChannel.js | 2 +- .../discord.js/src/util/ActivityFlagsBitField.js | 15 ++++++++------- .../src/util/ApplicationFlagsBitField.js | 3 ++- .../src/util/AttachmentFlagsBitField.js | 3 ++- .../discord.js/src/util/ChannelFlagsBitField.js | 3 ++- packages/discord.js/src/util/Channels.js | 2 ++ packages/discord.js/src/util/Components.js | 2 +- .../src/util/GuildMemberFlagsBitField.js | 3 ++- packages/discord.js/src/util/IntentsBitField.js | 3 ++- .../discord.js/src/util/MessageFlagsBitField.js | 3 ++- packages/discord.js/src/util/RoleFlagsBitField.js | 3 ++- packages/discord.js/src/util/SKUFlagsBitField.js | 3 ++- packages/discord.js/src/util/Sweepers.js | 5 ++++- .../src/util/SystemChannelFlagsBitField.js | 3 ++- .../src/util/ThreadMemberFlagsBitField.js | 3 ++- packages/discord.js/src/util/UserFlagsBitField.js | 3 ++- packages/discord.js/src/util/Util.js | 11 ++++------- packages/discord.js/tsconfig.eslint.json | 6 ------ 48 files changed, 96 insertions(+), 74 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 17a315690568..9d20761cfc72 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -21,6 +21,7 @@ const nodeRuleset = merge(...node, { files: [`**/*${commonFiles}`] }); const typeScriptRuleset = merge(...typescript, { files: [`**/*${commonFiles}`], + ignores: [`packages/discord.js/**/*.{js,mjs,cjs}`], languageOptions: { parserOptions: { warnOnUnsupportedTypeScriptVersion: false, @@ -148,6 +149,11 @@ export default tseslint.config( }, settings: { jsdoc: { + tagNamePreference: { + augments: 'extends', + fires: 'emits', + function: 'method', + }, preferredTypes: { object: 'Object', null: 'void', diff --git a/packages/discord.js/src/client/BaseClient.js b/packages/discord.js/src/client/BaseClient.js index 16e431bc445d..ba8fb214e2d7 100644 --- a/packages/discord.js/src/client/BaseClient.js +++ b/packages/discord.js/src/client/BaseClient.js @@ -119,7 +119,6 @@ class BaseClient extends AsyncEventEmitter { } async [Symbol.asyncDispose]() { - // eslint-disable-next-line @typescript-eslint/await-thenable, @typescript-eslint/no-confusing-void-expression await this.destroy(); } } diff --git a/packages/discord.js/src/client/Client.js b/packages/discord.js/src/client/Client.js index a05e8549605e..4f5d00542714 100644 --- a/packages/discord.js/src/client/Client.js +++ b/packages/discord.js/src/client/Client.js @@ -572,8 +572,8 @@ class Client extends BaseClient { */ async fetchStickerPacks({ packId } = {}) { if (packId) { - const data = await this.rest.get(Routes.stickerPack(packId)); - return new StickerPack(this, data); + const innerData = await this.rest.get(Routes.stickerPack(packId)); + return new StickerPack(this, innerData); } const data = await this.rest.get(Routes.stickerPacks()); diff --git a/packages/discord.js/src/client/WebhookClient.js b/packages/discord.js/src/client/WebhookClient.js index dacc170513ff..17b0e0972f13 100644 --- a/packages/discord.js/src/client/WebhookClient.js +++ b/packages/discord.js/src/client/WebhookClient.js @@ -72,13 +72,14 @@ class WebhookClient extends BaseClient { // These are here only for documentation purposes - they are implemented by Webhook + /* eslint-disable jsdoc/check-param-names, getter-return */ /** * Sends a message with this webhook. * * @param {string|MessagePayload|WebhookMessageCreateOptions} options The content for the reply * @returns {Promise} */ - async send(options) {} + async send() {} /** * Gets a message that was sent by this webhook. @@ -87,7 +88,7 @@ class WebhookClient extends BaseClient { * @param {WebhookFetchMessageOptions} [options] The options to provide to fetch the message. * @returns {Promise} Returns the message sent by this webhook */ - async fetchMessage(message, options) {} + async fetchMessage() {} /** * Edits a message that was sent by this webhook. @@ -96,7 +97,7 @@ class WebhookClient extends BaseClient { * @param {string|MessagePayload|WebhookMessageEditOptions} options The options to provide * @returns {Promise} Returns the message edited by this webhook */ - async editMessage(message, options) {} + async editMessage() {} sendSlackMessage() {} diff --git a/packages/discord.js/src/client/actions/InteractionCreate.js b/packages/discord.js/src/client/actions/InteractionCreate.js index a33cde44cb78..2e263425fca2 100644 --- a/packages/discord.js/src/client/actions/InteractionCreate.js +++ b/packages/discord.js/src/client/actions/InteractionCreate.js @@ -1,4 +1,3 @@ -/* eslint-disable sonarjs/no-nested-switch */ 'use strict'; const { InteractionType, ComponentType, ApplicationCommandType } = require('discord-api-types/v10'); diff --git a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js index 517efdf93fa8..c80dfa248447 100644 --- a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js @@ -107,8 +107,8 @@ class ApplicationCommandPermissionsManager extends BaseManager { async fetch({ guild, command } = {}) { const { guildId, commandId } = this._validateOptions(guild, command); if (commandId) { - const data = await this.client.rest.get(this.permissionsPath(guildId, commandId)); - return data.permissions; + const innerData = await this.client.rest.get(this.permissionsPath(guildId, commandId)); + return innerData.permissions; } const data = await this.client.rest.get(this.permissionsPath(guildId)); @@ -353,9 +353,9 @@ class ApplicationCommandPermissionsManager extends BaseManager { return !resolvedUserIds.includes(perm.id); case ApplicationCommandPermissionType.Channel: return !resolvedChannelIds.includes(perm.id); + default: + return true; } - - return true; }); return this.set({ guild: options.guildId, command: commandId, permissions, token }); diff --git a/packages/discord.js/src/managers/GuildChannelManager.js b/packages/discord.js/src/managers/GuildChannelManager.js index d73a5d7b95d2..628f0603b7ad 100644 --- a/packages/discord.js/src/managers/GuildChannelManager.js +++ b/packages/discord.js/src/managers/GuildChannelManager.js @@ -424,10 +424,10 @@ class GuildChannelManager extends CachedManager { } if (id) { - const data = await this.client.rest.get(Routes.channel(id)); + const innerData = await this.client.rest.get(Routes.channel(id)); // Since this is the guild manager, throw if on a different guild - if (this.guild.id !== data.guild_id) throw new DiscordjsError(ErrorCodes.GuildChannelUnowned); - return this.client.channels._add(data, this.guild, { cache }); + if (this.guild.id !== innerData.guild_id) throw new DiscordjsError(ErrorCodes.GuildChannelUnowned); + return this.client.channels._add(innerData, this.guild, { cache }); } const data = await this.client.rest.get(Routes.guildChannels(this.guild.id)); diff --git a/packages/discord.js/src/managers/GuildManager.js b/packages/discord.js/src/managers/GuildManager.js index 511213542a37..7b0af679b718 100644 --- a/packages/discord.js/src/managers/GuildManager.js +++ b/packages/discord.js/src/managers/GuildManager.js @@ -287,11 +287,11 @@ class GuildManager extends CachedManager { if (existing) return existing; } - const data = await this.client.rest.get(Routes.guild(id), { + const innerData = await this.client.rest.get(Routes.guild(id), { query: makeURLSearchParams({ with_counts: options.withCounts ?? true }), }); - data.shardId = ShardClientUtil.shardIdForGuildId(id, await this.client.ws.fetchShardCount()); - return this._add(data, options.cache); + innerData.shardId = ShardClientUtil.shardIdForGuildId(id, await this.client.ws.fetchShardCount()); + return this._add(innerData, options.cache); } const data = await this.client.rest.get(Routes.userGuilds(), { query: makeURLSearchParams(options) }); diff --git a/packages/discord.js/src/managers/GuildMemberManager.js b/packages/discord.js/src/managers/GuildMemberManager.js index c4d3cf2508e8..ad766fff42ed 100644 --- a/packages/discord.js/src/managers/GuildMemberManager.js +++ b/packages/discord.js/src/managers/GuildMemberManager.js @@ -409,7 +409,7 @@ class GuildMemberManager extends CachedManager { const clone = this.cache.get(id)?._clone(); clone?._patch(data); - return clone ?? this._add(d, false); + return clone ?? this._add(data, false); } /** diff --git a/packages/discord.js/src/managers/GuildScheduledEventManager.js b/packages/discord.js/src/managers/GuildScheduledEventManager.js index e0423e5b47b0..fb5b3db49897 100644 --- a/packages/discord.js/src/managers/GuildScheduledEventManager.js +++ b/packages/discord.js/src/managers/GuildScheduledEventManager.js @@ -170,10 +170,10 @@ class GuildScheduledEventManager extends CachedManager { if (existing) return existing; } - const data = await this.client.rest.get(Routes.guildScheduledEvent(this.guild.id, id), { + const innerData = await this.client.rest.get(Routes.guildScheduledEvent(this.guild.id, id), { query: makeURLSearchParams({ with_user_count: options.withUserCount ?? true }), }); - return this._add(data, options.cache); + return this._add(innerData, options.cache); } const data = await this.client.rest.get(Routes.guildScheduledEvents(this.guild.id), { diff --git a/packages/discord.js/src/managers/RoleManager.js b/packages/discord.js/src/managers/RoleManager.js index 15a02a020997..d2293e947e75 100644 --- a/packages/discord.js/src/managers/RoleManager.js +++ b/packages/discord.js/src/managers/RoleManager.js @@ -66,9 +66,9 @@ class RoleManager extends CachedManager { */ async fetch(id, { cache = true, force = false } = {}) { if (!id) { - const data = await this.client.rest.get(Routes.guildRoles(this.guild.id)); + const innerData = await this.client.rest.get(Routes.guildRoles(this.guild.id)); const roles = new Collection(); - for (const role of data) roles.set(role.id, this._add(role, cache)); + for (const role of innerData) roles.set(role.id, this._add(role, cache)); return roles; } diff --git a/packages/discord.js/src/sharding/Shard.js b/packages/discord.js/src/sharding/Shard.js index b39afebf75c1..b3f595fad2d8 100644 --- a/packages/discord.js/src/sharding/Shard.js +++ b/packages/discord.js/src/sharding/Shard.js @@ -1,4 +1,4 @@ -/* eslint-disable promise/prefer-await-to-then, promise/prefer-await-to-callbacks, @typescript-eslint/no-use-before-define */ +/* eslint-disable promise/prefer-await-to-callbacks, promise/prefer-await-to-then, no-use-before-define */ 'use strict'; const path = require('node:path'); @@ -32,6 +32,8 @@ class Shard extends AsyncEventEmitter { case 'worker': Worker = require('node:worker_threads').Worker; break; + default: + break; } /** @@ -163,6 +165,8 @@ class Shard extends AsyncEventEmitter { .on('message', this._handleMessage.bind(this)) .on('exit', this._exitListener); break; + default: + break; } this._evals.clear(); diff --git a/packages/discord.js/src/sharding/ShardClientUtil.js b/packages/discord.js/src/sharding/ShardClientUtil.js index e88c64cd05b5..799519b9818a 100644 --- a/packages/discord.js/src/sharding/ShardClientUtil.js +++ b/packages/discord.js/src/sharding/ShardClientUtil.js @@ -61,6 +61,8 @@ class ShardClientUtil { this.parentPort.postMessage({ _resume: true }); }); break; + default: + break; } } @@ -84,6 +86,8 @@ class ShardClientUtil { this.parentPort.postMessage(message); resolve(); break; + default: + break; } }); } diff --git a/packages/discord.js/src/structures/BaseGuildTextChannel.js b/packages/discord.js/src/structures/BaseGuildTextChannel.js index 30f470f23917..ae7eb073e5ab 100644 --- a/packages/discord.js/src/structures/BaseGuildTextChannel.js +++ b/packages/discord.js/src/structures/BaseGuildTextChannel.js @@ -192,6 +192,7 @@ class BaseGuildTextChannel extends GuildChannel { // These are here only for documentation purposes - they are implemented by TextBasedChannel + /* eslint-disable getter-return */ get lastMessage() {} get lastPinAt() {} diff --git a/packages/discord.js/src/structures/BaseGuildVoiceChannel.js b/packages/discord.js/src/structures/BaseGuildVoiceChannel.js index b17a90fa3590..50a221315447 100644 --- a/packages/discord.js/src/structures/BaseGuildVoiceChannel.js +++ b/packages/discord.js/src/structures/BaseGuildVoiceChannel.js @@ -234,6 +234,7 @@ class BaseGuildVoiceChannel extends GuildChannel { // These are here only for documentation purposes - they are implemented by TextBasedChannel + // eslint-disable-next-line getter-return get lastMessage() {} send() {} diff --git a/packages/discord.js/src/structures/DMChannel.js b/packages/discord.js/src/structures/DMChannel.js index 0bb1935999dc..c7e7db9864d3 100644 --- a/packages/discord.js/src/structures/DMChannel.js +++ b/packages/discord.js/src/structures/DMChannel.js @@ -112,6 +112,7 @@ class DMChannel extends BaseChannel { // These are here only for documentation purposes - they are implemented by TextBasedChannel + /* eslint-disable getter-return */ get lastMessage() {} get lastPinAt() {} diff --git a/packages/discord.js/src/structures/Guild.js b/packages/discord.js/src/structures/Guild.js index 2eb33a6f413b..06ef2da3a09d 100644 --- a/packages/discord.js/src/structures/Guild.js +++ b/packages/discord.js/src/structures/Guild.js @@ -644,7 +644,6 @@ class Guild extends AnonymousGuild { return 384_000; } - // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check switch (this.premiumTier) { case GuildPremiumTier.Tier1: return 128_000; diff --git a/packages/discord.js/src/structures/GuildAuditLogsEntry.js b/packages/discord.js/src/structures/GuildAuditLogsEntry.js index ff1e8095a711..2359ed91dff3 100644 --- a/packages/discord.js/src/structures/GuildAuditLogsEntry.js +++ b/packages/discord.js/src/structures/GuildAuditLogsEntry.js @@ -238,7 +238,6 @@ class GuildAuditLogsEntry { case AuditLogEvent.ChannelOverwriteCreate: case AuditLogEvent.ChannelOverwriteUpdate: case AuditLogEvent.ChannelOverwriteDelete: - // eslint-disable-next-line sonarjs/no-nested-switch switch (data.options.type) { case AuditLogOptionsType.Role: this.extra = guild.roles.cache.get(data.options.id) ?? { diff --git a/packages/discord.js/src/structures/GuildTemplate.js b/packages/discord.js/src/structures/GuildTemplate.js index 33cf7cf4fcfe..3dceea76f452 100644 --- a/packages/discord.js/src/structures/GuildTemplate.js +++ b/packages/discord.js/src/structures/GuildTemplate.js @@ -153,18 +153,17 @@ class GuildTemplate extends Base { resolve(guild); } + client.incrementMaxListeners(); + client.on(Events.GuildCreate, handleGuild); + + const timeout = setTimeout(() => resolveGuild(client.guilds._add(data)), 10_000).unref(); + function handleGuild(guild) { if (guild.id === data.id) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(timeout); resolveGuild(guild); } } - - client.incrementMaxListeners(); - client.on(Events.GuildCreate, handleGuild); - - const timeout = setTimeout(() => resolveGuild(client.guilds._add(data)), 10_000).unref(); }); } diff --git a/packages/discord.js/src/structures/InteractionCollector.js b/packages/discord.js/src/structures/InteractionCollector.js index d0e925c52115..9443310bb060 100644 --- a/packages/discord.js/src/structures/InteractionCollector.js +++ b/packages/discord.js/src/structures/InteractionCollector.js @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/unbound-method */ 'use strict'; const { Collection } = require('@discordjs/collection'); diff --git a/packages/discord.js/src/structures/InteractionWebhook.js b/packages/discord.js/src/structures/InteractionWebhook.js index d633d3a9d9f3..78837e38919c 100644 --- a/packages/discord.js/src/structures/InteractionWebhook.js +++ b/packages/discord.js/src/structures/InteractionWebhook.js @@ -58,6 +58,7 @@ class InteractionWebhook { deleteMessage() {} + // eslint-disable-next-line getter-return get url() {} } diff --git a/packages/discord.js/src/structures/Invite.js b/packages/discord.js/src/structures/Invite.js index 594d920c2f3e..c5b50ddee272 100644 --- a/packages/discord.js/src/structures/Invite.js +++ b/packages/discord.js/src/structures/Invite.js @@ -253,7 +253,6 @@ class Invite extends Base { if (!guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); return ( - // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) || guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild) ); diff --git a/packages/discord.js/src/structures/MessageCollector.js b/packages/discord.js/src/structures/MessageCollector.js index 998e7bb87e66..257472828b7e 100644 --- a/packages/discord.js/src/structures/MessageCollector.js +++ b/packages/discord.js/src/structures/MessageCollector.js @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/unbound-method */ 'use strict'; const { Events } = require('../util/Events.js'); diff --git a/packages/discord.js/src/structures/MessageReaction.js b/packages/discord.js/src/structures/MessageReaction.js index 0328decd0fbc..145ebdf428cb 100644 --- a/packages/discord.js/src/structures/MessageReaction.js +++ b/packages/discord.js/src/structures/MessageReaction.js @@ -135,9 +135,9 @@ class MessageReaction { if (this._emoji.id) { const applicationEmojis = this.message.client.application.emojis.cache; if (applicationEmojis.has(this._emoji.id)) { - const emoji = applicationEmojis.get(this._emoji.id); - this._emoji = emoji; - return emoji; + const innerEmoji = applicationEmojis.get(this._emoji.id); + this._emoji = innerEmoji; + return innerEmoji; } } diff --git a/packages/discord.js/src/structures/PartialGroupDMChannel.js b/packages/discord.js/src/structures/PartialGroupDMChannel.js index 7b21a2f5183a..e5b087f59925 100644 --- a/packages/discord.js/src/structures/PartialGroupDMChannel.js +++ b/packages/discord.js/src/structures/PartialGroupDMChannel.js @@ -121,6 +121,7 @@ class PartialGroupDMChannel extends BaseChannel { // These are here only for documentation purposes - they are implemented by TextBasedChannel + /* eslint-disable getter-return */ get lastMessage() {} get lastPinAt() {} diff --git a/packages/discord.js/src/structures/Presence.js b/packages/discord.js/src/structures/Presence.js index 49e3305ac209..ab38d1359a7c 100644 --- a/packages/discord.js/src/structures/Presence.js +++ b/packages/discord.js/src/structures/Presence.js @@ -1,4 +1,4 @@ -/* eslint-disable @typescript-eslint/no-use-before-define */ +/* eslint-disable no-use-before-define */ 'use strict'; const { ActivityFlagsBitField } = require('../util/ActivityFlagsBitField.js'); diff --git a/packages/discord.js/src/structures/ReactionCollector.js b/packages/discord.js/src/structures/ReactionCollector.js index e4c40eb2d910..180cb35de9a2 100644 --- a/packages/discord.js/src/structures/ReactionCollector.js +++ b/packages/discord.js/src/structures/ReactionCollector.js @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/unbound-method */ 'use strict'; const { Collection } = require('@discordjs/collection'); @@ -115,6 +114,7 @@ class ReactionCollector extends Collector { * @returns {?(Snowflake|string)} * @private */ + // eslint-disable-next-line no-unused-vars collect(reaction, user) { /** * Emitted whenever a reaction is collected. diff --git a/packages/discord.js/src/structures/ThreadChannel.js b/packages/discord.js/src/structures/ThreadChannel.js index 5d576a1b5c9e..589555a68ea8 100644 --- a/packages/discord.js/src/structures/ThreadChannel.js +++ b/packages/discord.js/src/structures/ThreadChannel.js @@ -636,6 +636,7 @@ class ThreadChannel extends BaseChannel { // These are here only for documentation purposes - they are implemented by TextBasedChannel + /* eslint-disable getter-return */ get lastMessage() {} get lastPinAt() {} diff --git a/packages/discord.js/src/structures/VoiceState.js b/packages/discord.js/src/structures/VoiceState.js index d5bba5204c8d..9842397f2566 100644 --- a/packages/discord.js/src/structures/VoiceState.js +++ b/packages/discord.js/src/structures/VoiceState.js @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */ 'use strict'; const { ChannelType, Routes } = require('discord-api-types/v10'); diff --git a/packages/discord.js/src/structures/interfaces/Collector.js b/packages/discord.js/src/structures/interfaces/Collector.js index 7fabd5e8e022..da941eaae771 100644 --- a/packages/discord.js/src/structures/interfaces/Collector.js +++ b/packages/discord.js/src/structures/interfaces/Collector.js @@ -347,6 +347,7 @@ class Collector extends AsyncEventEmitter { * @returns {?(*|Promise)} Data to insert into collection, if any * @abstract */ + // eslint-disable-next-line no-unused-vars collect(...args) {} /** @@ -358,6 +359,7 @@ class Collector extends AsyncEventEmitter { * @returns {?*} Key to remove from the collection, if any * @abstract */ + // eslint-disable-next-line no-unused-vars dispose(...args) {} } diff --git a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js index b7e18f26fd3e..39c256b9687f 100644 --- a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js +++ b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js @@ -21,7 +21,7 @@ class TextBasedChannel { * * @type {GuildMessageManager} */ - // eslint-disable-next-line @typescript-eslint/no-use-before-define + // eslint-disable-next-line no-use-before-define this.messages = new GuildMessageManager(this); /** diff --git a/packages/discord.js/src/util/ActivityFlagsBitField.js b/packages/discord.js/src/util/ActivityFlagsBitField.js index 415bf7d8b623..7033d3c7e0e9 100644 --- a/packages/discord.js/src/util/ActivityFlagsBitField.js +++ b/packages/discord.js/src/util/ActivityFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { ActivityFlags } = require('discord-api-types/v10'); @@ -16,13 +17,13 @@ class ActivityFlagsBitField extends BitField { * @memberof ActivityFlagsBitField */ static Flags = ActivityFlags; - - /** - * @method (constructor) - * @constructs - * @memberof ActivityFlagsBitField - * @param {BitFieldResolvable} [bits=0] Bit(s) to read from - */ } +/** + * @name ActivityFlagsBitField + * @kind constructor + * @memberof ActivityFlagsBitField + * @param {BitFieldResolvable} [bits=0] Bit(s) to read from + */ + exports.ActivityFlagsBitField = ActivityFlagsBitField; diff --git a/packages/discord.js/src/util/ApplicationFlagsBitField.js b/packages/discord.js/src/util/ApplicationFlagsBitField.js index d0e88dcbb26e..6ffa9996d2bd 100644 --- a/packages/discord.js/src/util/ApplicationFlagsBitField.js +++ b/packages/discord.js/src/util/ApplicationFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { ApplicationFlags } = require('discord-api-types/v10'); @@ -20,7 +21,7 @@ class ApplicationFlagsBitField extends BitField { /** * @name ApplicationFlagsBitField - * @constructor + * @kind constructor * @memberof ApplicationFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/AttachmentFlagsBitField.js b/packages/discord.js/src/util/AttachmentFlagsBitField.js index 8afcefaebbbf..8f3df8c5b0ed 100644 --- a/packages/discord.js/src/util/AttachmentFlagsBitField.js +++ b/packages/discord.js/src/util/AttachmentFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { AttachmentFlags } = require('discord-api-types/v10'); @@ -20,7 +21,7 @@ class AttachmentFlagsBitField extends BitField { /** * @name AttachmentFlagsBitField - * @constructor + * @kind constructor * @memberof AttachmentFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/ChannelFlagsBitField.js b/packages/discord.js/src/util/ChannelFlagsBitField.js index 4de3803750ec..98b972c1773c 100644 --- a/packages/discord.js/src/util/ChannelFlagsBitField.js +++ b/packages/discord.js/src/util/ChannelFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { ChannelFlags } = require('discord-api-types/v10'); @@ -20,7 +21,7 @@ class ChannelFlagsBitField extends BitField { /** * @name ChannelFlagsBitField - * @constructor + * @kind constructor * @memberof ChannelFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/Channels.js b/packages/discord.js/src/util/Channels.js index 7d28302eadaa..ebd99bf57231 100644 --- a/packages/discord.js/src/util/Channels.js +++ b/packages/discord.js/src/util/Channels.js @@ -87,6 +87,8 @@ function createChannel(client, data, guild, { allowUnknownGuild } = {}) { case ChannelType.GuildMedia: channel = new (getMediaChannel())(resolvedGuild, data, client); break; + default: + break; } if (channel && !allowUnknownGuild) resolvedGuild.channels?.cache.set(channel.id, channel); diff --git a/packages/discord.js/src/util/Components.js b/packages/discord.js/src/util/Components.js index 5b57261f00ea..302a833f449e 100644 --- a/packages/discord.js/src/util/Components.js +++ b/packages/discord.js/src/util/Components.js @@ -1,4 +1,4 @@ -/* eslint-disable @typescript-eslint/no-use-before-define */ +/* eslint-disable no-use-before-define */ 'use strict'; // eslint-disable-next-line import-x/order diff --git a/packages/discord.js/src/util/GuildMemberFlagsBitField.js b/packages/discord.js/src/util/GuildMemberFlagsBitField.js index 2f1d9157c58d..247d343e4b85 100644 --- a/packages/discord.js/src/util/GuildMemberFlagsBitField.js +++ b/packages/discord.js/src/util/GuildMemberFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { GuildMemberFlags } = require('discord-api-types/v10'); @@ -20,7 +21,7 @@ class GuildMemberFlagsBitField extends BitField { /** * @name GuildMemberFlagsBitField - * @constructor + * @kind constructor * @memberof GuildMemberFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/IntentsBitField.js b/packages/discord.js/src/util/IntentsBitField.js index fefa057da77b..67632e43d644 100644 --- a/packages/discord.js/src/util/IntentsBitField.js +++ b/packages/discord.js/src/util/IntentsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { GatewayIntentBits } = require('discord-api-types/v10'); const { BitField } = require('./BitField.js'); @@ -19,7 +20,7 @@ class IntentsBitField extends BitField { /** * @name IntentsBitField - * @constructor + * @kind constructor * @memberof IntentsBitField * @param {IntentsResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/MessageFlagsBitField.js b/packages/discord.js/src/util/MessageFlagsBitField.js index e2b59fe23ec2..c0a42ac113b4 100644 --- a/packages/discord.js/src/util/MessageFlagsBitField.js +++ b/packages/discord.js/src/util/MessageFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { MessageFlags } = require('discord-api-types/v10'); @@ -20,7 +21,7 @@ class MessageFlagsBitField extends BitField { /** * @name MessageFlagsBitField - * @constructor + * @kind constructor * @memberof MessageFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/RoleFlagsBitField.js b/packages/discord.js/src/util/RoleFlagsBitField.js index e0d4c117c482..36f744c5617e 100644 --- a/packages/discord.js/src/util/RoleFlagsBitField.js +++ b/packages/discord.js/src/util/RoleFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { RoleFlags } = require('discord-api-types/v10'); @@ -20,7 +21,7 @@ class RoleFlagsBitField extends BitField { /** * @name RoleFlagsBitField - * @constructor + * @kind constructor * @memberof RoleFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/SKUFlagsBitField.js b/packages/discord.js/src/util/SKUFlagsBitField.js index fa46485f4cac..96e58a527a0f 100644 --- a/packages/discord.js/src/util/SKUFlagsBitField.js +++ b/packages/discord.js/src/util/SKUFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { SKUFlags } = require('discord-api-types/v10'); @@ -20,7 +21,7 @@ class SKUFlagsBitField extends BitField { /** * @name SKUFlagsBitField - * @constructor + * @kind constructor * @memberof SKUFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/Sweepers.js b/packages/discord.js/src/util/Sweepers.js index faa954553db3..2451fe809d74 100644 --- a/packages/discord.js/src/util/Sweepers.js +++ b/packages/discord.js/src/util/Sweepers.js @@ -57,6 +57,9 @@ class Sweepers { break; case 'threads': clonedOptions.filter = this.constructor.archivedThreadSweepFilter(clonedOptions.lifetime); + break; + default: + break; } } @@ -431,7 +434,7 @@ class Sweepers { static outdatedMessageSweepFilter(lifetime = 3_600) { return this.filterByLifetime({ lifetime, - getComparisonTimestamp: message => message.editedTimestamp ?? mesage.createdTimestamp, + getComparisonTimestamp: message => message.editedTimestamp ?? message.createdTimestamp, }); } diff --git a/packages/discord.js/src/util/SystemChannelFlagsBitField.js b/packages/discord.js/src/util/SystemChannelFlagsBitField.js index b2140ef71cf5..d100611ef889 100644 --- a/packages/discord.js/src/util/SystemChannelFlagsBitField.js +++ b/packages/discord.js/src/util/SystemChannelFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { GuildSystemChannelFlags } = require('discord-api-types/v10'); @@ -22,7 +23,7 @@ class SystemChannelFlagsBitField extends BitField { /** * @name SystemChannelFlagsBitField - * @constructor + * @kind constructor * @memberof SystemChannelFlagsBitField * @param {SystemChannelFlagsResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/ThreadMemberFlagsBitField.js b/packages/discord.js/src/util/ThreadMemberFlagsBitField.js index 1b38c504d24a..cc1c528a03d0 100644 --- a/packages/discord.js/src/util/ThreadMemberFlagsBitField.js +++ b/packages/discord.js/src/util/ThreadMemberFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { BitField } = require('./BitField.js'); @@ -19,7 +20,7 @@ class ThreadMemberFlagsBitField extends BitField { /** * @name ThreadMemberFlagsBitField - * @constructor + * @kind constructor * @memberof ThreadMemberFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/UserFlagsBitField.js b/packages/discord.js/src/util/UserFlagsBitField.js index ce6c61d3f483..55e53605cf81 100644 --- a/packages/discord.js/src/util/UserFlagsBitField.js +++ b/packages/discord.js/src/util/UserFlagsBitField.js @@ -1,3 +1,4 @@ +/* eslint-disable jsdoc/check-values */ 'use strict'; const { UserFlags } = require('discord-api-types/v10'); @@ -20,7 +21,7 @@ class UserFlagsBitField extends BitField { /** * @name UserFlagsBitField - * @constructor + * @kind constructor * @memberof UserFlagsBitField * @param {BitFieldResolvable} [bits=0] Bit(s) to read from */ diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index e9bcec7348d7..12c4d9719c08 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -1,6 +1,5 @@ 'use strict'; -// eslint-disable-next-line @typescript-eslint/unbound-method const { parse } = require('node:path'); const { Collection } = require('@discordjs/collection'); const { ChannelType, RouteBases, Routes } = require('discord-api-types/v10'); @@ -80,7 +79,6 @@ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multi }); if (!response.ok) { if (response.status === 401) throw new DiscordjsError(ErrorCodes.TokenInvalid); - // eslint-disable-next-line @typescript-eslint/only-throw-error throw response; } @@ -218,7 +216,6 @@ const CategorySortableGroupTypes = [ChannelType.GuildCategory]; * @private */ function getSortableGroupTypes(type) { - // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check switch (type) { case ChannelType.GuildText: case ChannelType.GuildAnnouncement: @@ -355,7 +352,7 @@ function resolveColor(color) { * @returns {Collection} */ function discordSort(collection) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define + // eslint-disable-next-line no-use-before-define const isGuildChannel = collection.first() instanceof GuildChannel; return collection.toSorted( isGuildChannel @@ -380,7 +377,7 @@ function discordSort(collection) { async function setPosition(item, position, relative, sorted, client, route, reason) { let updatedItems = [...sorted.values()]; moveElementInArray(updatedItems, item, position, relative); - updatedItems = updatedItems.map((item, index) => ({ id: item.id, position: index })); + updatedItems = updatedItems.map((innerItem, index) => ({ id: innerItem.id, position: index })); await client.rest.patch(route, { body: updatedItems, reason }); return updatedItems; } @@ -538,7 +535,7 @@ function transformResolved( if (attachments) { result.attachments = new Collection(); for (const attachment of Object.values(attachments)) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define + // eslint-disable-next-line no-use-before-define const patched = new Attachment(attachment); result.attachments.set(attachment.id, patched); } @@ -555,7 +552,7 @@ function transformResolved( */ function resolveSKUId(resolvable) { if (typeof resolvable === 'string') return resolvable; - // eslint-disable-next-line @typescript-eslint/no-use-before-define + // eslint-disable-next-line no-use-before-define if (resolvable instanceof SKU) return resolvable.id; return null; } diff --git a/packages/discord.js/tsconfig.eslint.json b/packages/discord.js/tsconfig.eslint.json index 71f4be685f0c..c829c5f64180 100644 --- a/packages/discord.js/tsconfig.eslint.json +++ b/packages/discord.js/tsconfig.eslint.json @@ -6,13 +6,7 @@ }, "include": [ "*.ts", - "*.js", - "*.cjs", - "*.mjs", "src/**/*.ts", - "src/**/*.js", - "src/**/*.cjs", - "src/**/*.mjs", "typings/**/*.d.ts", "typings/**/*.test-d.ts", "bin", From 9e7644ff81525713c7a279ddfb02837573374c88 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 13:52:30 +0200 Subject: [PATCH 18/38] fix: code review --- packages/discord.js/src/structures/GuildAuditLogsEntry.js | 4 ++-- packages/discord.js/src/util/DataResolver.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/discord.js/src/structures/GuildAuditLogsEntry.js b/packages/discord.js/src/structures/GuildAuditLogsEntry.js index 2359ed91dff3..56a70aa23a36 100644 --- a/packages/discord.js/src/structures/GuildAuditLogsEntry.js +++ b/packages/discord.js/src/structures/GuildAuditLogsEntry.js @@ -55,12 +55,12 @@ const Targets = { * - An object with an id key if target was deleted or fake entity * - An object where the keys represent either the new value or the old value * - * @typedef {?(object|Guild|BaseChannel|User|Role|Invite|Webhook|GuildEmoji|Integration|StageInstance|Sticker| + * @typedef {?(Object|Guild|BaseChannel|User|Role|Invite|Webhook|GuildEmoji|Integration|StageInstance|Sticker| * GuildScheduledEvent|ApplicationCommand|AutoModerationRule|GuildOnboardingPrompt|SoundboardSound)} AuditLogEntryTarget */ /** - * The action type of an entry, e.g. `Create`. Here are the available types: + * The action type of an entry. Here are the available types: * - Create * - Delete * - Update diff --git a/packages/discord.js/src/util/DataResolver.js b/packages/discord.js/src/util/DataResolver.js index 1a8e19a6ee9c..411aba65e43a 100644 --- a/packages/discord.js/src/util/DataResolver.js +++ b/packages/discord.js/src/util/DataResolver.js @@ -63,7 +63,7 @@ function resolveGuildTemplateCode(data) { * - A Buffer * - The path to a local file * - A URL When provided a URL, discord.js will fetch the URL internally in order to create a Buffer. - * - This can pose a security risk when the URL has not been sanitized + * This can pose a security risk when the URL has not been sanitized * * @typedef {string|Buffer} BufferResolvable */ From 4bf9089ba90985e1cfde840fc3d158345bae5e4e Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 15:12:58 +0200 Subject: [PATCH 19/38] fix: tidy up disabled rules --- eslint.config.js | 7 +- .../src/structures/MessagePayload.js | 14 +- .../src/util/PermissionsBitField.js | 1 + packages/discord.js/src/util/Util.js | 27 +- packages/discord.js/tsconfig.eslint.json | 2 + packages/discord.js/typings/index.test-d.ts | 679 +++++++++--------- 6 files changed, 380 insertions(+), 350 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 9d20761cfc72..09291864a357 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -161,15 +161,10 @@ export default tseslint.config( }, }, rules: { - '@typescript-eslint/no-var-requires': 0, - '@typescript-eslint/no-require-imports': 0, 'jsdoc/no-undefined-types': 0, 'jsdoc/no-defaults': 0, 'no-eq-null': 0, - '@typescript-eslint/explicit-member-accessibility': 0, - '@typescript-eslint/class-literal-property-style': 0, strict: ['error', 'global'], - 'unicorn/consistent-function-scoping': 0, 'no-restricted-syntax': [ 'error', @@ -199,7 +194,7 @@ export default tseslint.config( }, }, { - files: [`packages/discord.js/typings/*{d.ts,test-d.ts}`], + files: [`packages/discord.js/typings/*{d.ts,test-d.ts,d.mts,test-d.mts}`], rules: { '@typescript-eslint/no-unsafe-declaration-merging': 0, '@typescript-eslint/no-empty-object-type': 0, diff --git a/packages/discord.js/src/structures/MessagePayload.js b/packages/discord.js/src/structures/MessagePayload.js index ce01948235e7..173f43b2f446 100644 --- a/packages/discord.js/src/structures/MessagePayload.js +++ b/packages/discord.js/src/structures/MessagePayload.js @@ -6,7 +6,7 @@ const { DiscordSnowflake } = require('@sapphire/snowflake'); const { DiscordjsError, DiscordjsRangeError, ErrorCodes } = require('../errors/index.js'); const { resolveFile } = require('../util/DataResolver.js'); const { MessageFlagsBitField } = require('../util/MessageFlagsBitField.js'); -const { basename, verifyString, resolvePartialEmoji } = require('../util/Util.js'); +const { findName, verifyString, resolvePartialEmoji } = require('../util/Util.js'); /** * Represents a message to be sent to the API. @@ -261,18 +261,6 @@ class MessagePayload { let attachment; let name; - const findName = thing => { - if (typeof thing === 'string') { - return basename(thing); - } - - if (thing.path) { - return basename(thing.path); - } - - return 'file.jpg'; - }; - const ownAttachment = typeof fileLike === 'string' || fileLike instanceof Buffer || typeof fileLike.pipe === 'function'; if (ownAttachment) { diff --git a/packages/discord.js/src/util/PermissionsBitField.js b/packages/discord.js/src/util/PermissionsBitField.js index 326aba3b3ed8..c368cd2c6462 100644 --- a/packages/discord.js/src/util/PermissionsBitField.js +++ b/packages/discord.js/src/util/PermissionsBitField.js @@ -27,6 +27,7 @@ class PermissionsBitField extends BitField { * @memberof PermissionsBitField */ + // eslint-disable-next-line unicorn/consistent-function-scoping static All = Object.values(PermissionFlagsBits).reduce((all, perm) => all | perm, 0n); /** diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index 12c4d9719c08..a6f535a5ea4a 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -395,6 +395,24 @@ function basename(path, ext) { return ext && res.ext.startsWith(ext) ? res.name : res.base.split('?')[0]; } +/** + * Find the filename to use for attachments. + * + * @param {BufferResolvable|Stream} thing The thing to attach as attachment + * @returns {string} filename to use + */ +function findName(thing) { + if (typeof thing === 'string') { + return basename(thing); + } + + if (thing.path) { + return basename(thing.path); + } + + return 'file.jpg'; +} + /** * The content to have all mentions replaced by the equivalent text. * @@ -463,13 +481,7 @@ function parseWebhookURL(url) { url, ); - if (!matches?.groups) return null; - - const { id, token } = matches.groups; - return { - id, - token, - }; + return matches && { id: matches.groups.id, token: matches.groups.token }; } /** @@ -571,6 +583,7 @@ exports.resolveColor = resolveColor; exports.discordSort = discordSort; exports.setPosition = setPosition; exports.basename = basename; +exports.findName = findName; exports.cleanContent = cleanContent; exports.cleanCodeBlockContent = cleanCodeBlockContent; exports.parseWebhookURL = parseWebhookURL; diff --git a/packages/discord.js/tsconfig.eslint.json b/packages/discord.js/tsconfig.eslint.json index c829c5f64180..0f886fbc99bf 100644 --- a/packages/discord.js/tsconfig.eslint.json +++ b/packages/discord.js/tsconfig.eslint.json @@ -8,7 +8,9 @@ "*.ts", "src/**/*.ts", "typings/**/*.d.ts", + "typings/**/*.d.mts", "typings/**/*.test-d.ts", + "typings/**/*.test-d.mts", "bin", "scripts", "__tests__", diff --git a/packages/discord.js/typings/index.test-d.ts b/packages/discord.js/typings/index.test-d.ts index 60e9cd60175d..3e5003d3bcf3 100644 --- a/packages/discord.js/typings/index.test-d.ts +++ b/packages/discord.js/typings/index.test-d.ts @@ -1,7 +1,4 @@ -/* eslint-disable @typescript-eslint/unbound-method */ -/* eslint-disable @typescript-eslint/ban-ts-comment */ -/* eslint-disable no-param-reassign */ -/* eslint-disable id-length */ +/* eslint-disable no-lone-blocks, @typescript-eslint/unbound-method, @typescript-eslint/ban-ts-comment, no-param-reassign, id-length */ import type { ChildProcess } from 'node:child_process'; import type { Worker } from 'node:worker_threads'; import type { ContextMenuCommandBuilder, ChatInputCommandBuilder } from '@discordjs/builders'; @@ -412,14 +409,16 @@ client.on('messageCreate', async message => { const { client, channel } = message; // https://github.com/discordjs/discord.js/issues/8545 - // These should not throw any errors when comparing messages from any source. - channel.messages.cache.filter(Boolean); - (await channel.messages.fetch()).filter(({ author }) => author.id === message.author.id); + { + // These should not throw any errors when comparing messages from any source. + channel.messages.cache.filter(Boolean); + (await channel.messages.fetch()).filter(({ author }) => author.id === message.author.id); - if (channel.isDMBased()) { - expectType(channel.messages.channel.messages); - } else { - expectType(channel.messages.channel.messages); + if (channel.isDMBased()) { + expectType(channel.messages.channel.messages); + } else { + expectType(channel.messages.channel.messages); + } } if (!message.inGuild() && message.partial) { @@ -1521,39 +1520,40 @@ declare const applicationCommandData: ApplicationCommandData; declare const applicationCommandOptionData: ApplicationCommandOptionData; declare const applicationCommandResolvable: ApplicationCommandResolvable; declare const applicationCommandManager: ApplicationCommandManager; +{ + type ApplicationCommandScope = ApplicationCommand<{ guild: GuildResolvable }>; -type ApplicationCommandScope = ApplicationCommand<{ guild: GuildResolvable }>; - -expectType>(applicationCommandManager.create(applicationCommandData)); -expectAssignable>(applicationCommandManager.create(applicationCommandData, '0')); -expectType>( - applicationCommandManager.edit(applicationCommandResolvable, applicationCommandData), -); -expectType>( - applicationCommandManager.edit(applicationCommandResolvable, applicationCommandData, '0'), -); -expectType>>( - applicationCommandManager.set([applicationCommandData]), -); -expectType>>( - applicationCommandManager.set([applicationCommandData] as const, '0'), -); + expectType>(applicationCommandManager.create(applicationCommandData)); + expectAssignable>(applicationCommandManager.create(applicationCommandData, '0')); + expectType>( + applicationCommandManager.edit(applicationCommandResolvable, applicationCommandData), + ); + expectType>( + applicationCommandManager.edit(applicationCommandResolvable, applicationCommandData, '0'), + ); + expectType>>( + applicationCommandManager.set([applicationCommandData]), + ); + expectType>>( + applicationCommandManager.set([applicationCommandData] as const, '0'), + ); -// Test inference of choice values. -if ('choices' in applicationCommandOptionData) { - if (applicationCommandOptionData.type === ApplicationCommandOptionType.String) { - expectType(applicationCommandOptionData.choices[0]!.value); - expectNotType(applicationCommandOptionData.choices[0]!.value); - } + // Test inference of choice values. + if ('choices' in applicationCommandOptionData) { + if (applicationCommandOptionData.type === ApplicationCommandOptionType.String) { + expectType(applicationCommandOptionData.choices[0]!.value); + expectNotType(applicationCommandOptionData.choices[0]!.value); + } - if (applicationCommandOptionData.type === ApplicationCommandOptionType.Integer) { - expectType(applicationCommandOptionData.choices[0]!.value); - expectNotType(applicationCommandOptionData.choices[0]!.value); - } + if (applicationCommandOptionData.type === ApplicationCommandOptionType.Integer) { + expectType(applicationCommandOptionData.choices[0]!.value); + expectNotType(applicationCommandOptionData.choices[0]!.value); + } - if (applicationCommandOptionData.type === ApplicationCommandOptionType.Number) { - expectType(applicationCommandOptionData.choices[0]!.value); - expectNotType(applicationCommandOptionData.choices[0]!.value); + if (applicationCommandOptionData.type === ApplicationCommandOptionType.Number) { + expectType(applicationCommandOptionData.choices[0]!.value); + expectNotType(applicationCommandOptionData.choices[0]!.value); + } } } @@ -1563,56 +1563,62 @@ declare const applicationCommandPermissionsManager: ApplicationCommandPermission Guild | null, Snowflake >; - -await applicationCommandPermissionsManager.add({ permissions: [], token: '' }); -await applicationCommandPermissionsManager.add({ permissions: [] as const, token: '' }); -await applicationCommandPermissionsManager.set({ permissions: [], token: '' }); -await applicationCommandPermissionsManager.set({ permissions: [] as const, token: '' }); -await applicationCommandPermissionsManager.remove({ channels: [], roles: [], users: [], token: '' }); - -await applicationCommandPermissionsManager.remove({ - channels: [] as const, - roles: [] as const, - users: [] as const, - token: '', -}); +{ + await applicationCommandPermissionsManager.add({ permissions: [], token: '' }); + await applicationCommandPermissionsManager.add({ permissions: [] as const, token: '' }); + await applicationCommandPermissionsManager.set({ permissions: [], token: '' }); + await applicationCommandPermissionsManager.set({ permissions: [] as const, token: '' }); + await applicationCommandPermissionsManager.remove({ channels: [], roles: [], users: [], token: '' }); + + await applicationCommandPermissionsManager.remove({ + channels: [] as const, + roles: [] as const, + users: [] as const, + token: '', + }); +} declare const chatInputApplicationCommandData: ChatInputApplicationCommandData; - -chatInputApplicationCommandData.options = []; -chatInputApplicationCommandData.options = [] as const; +{ + chatInputApplicationCommandData.options = []; + chatInputApplicationCommandData.options = [] as const; +} declare const applicationCommandChannelOptionData: ApplicationCommandChannelOptionData; declare const applicationCommandChannelOption: ApplicationCommandChannelOption; - -applicationCommandChannelOptionData.channelTypes = [] as const; -applicationCommandChannelOptionData.channel_types = [] as const; -applicationCommandChannelOption.channelTypes = [] as const; +{ + applicationCommandChannelOptionData.channelTypes = [] as const; + applicationCommandChannelOptionData.channel_types = [] as const; + applicationCommandChannelOption.channelTypes = [] as const; +} declare const applicationNonChoiceOptionData: ApplicationCommandOptionData & { type: CommandOptionNonChoiceResolvableType; }; +{ + // Options aren't allowed on this command type. -// Options aren't allowed on this command type. - -// @ts-expect-error -applicationNonChoiceOptionData.choices = []; + // @ts-expect-error + applicationNonChoiceOptionData.choices = []; +} declare const applicationCommandChoicesData: ApplicationCommandChoicesData; declare const applicationCommandChoicesOption: ApplicationCommandChoicesOption; - -applicationCommandChoicesData.choices = []; -applicationCommandChoicesData.choices = [] as const; -applicationCommandChoicesOption.choices = []; -applicationCommandChoicesOption.choices = [] as const; +{ + applicationCommandChoicesData.choices = []; + applicationCommandChoicesData.choices = [] as const; + applicationCommandChoicesOption.choices = []; + applicationCommandChoicesOption.choices = [] as const; +} declare const applicationCommandSubCommandData: ApplicationCommandSubCommandData; declare const applicationCommandSubCommand: ApplicationCommandSubCommand; - -applicationCommandSubCommandData.options = []; -applicationCommandSubCommandData.options = [] as const; -applicationCommandSubCommand.options = []; -applicationCommandSubCommand.options = [] as const; +{ + applicationCommandSubCommandData.options = []; + applicationCommandSubCommandData.options = [] as const; + applicationCommandSubCommand.options = []; + applicationCommandSubCommand.options = [] as const; +} declare const applicationSubGroupCommandData: ApplicationCommandSubGroupData; declare const applicationCommandSubGroup: ApplicationCommandSubGroup; @@ -1624,23 +1630,24 @@ applicationCommandSubGroup.options = []; applicationCommandSubGroup.options = [] as const; declare const autoModerationRuleManager: AutoModerationRuleManager; - -expectType>(autoModerationRuleManager.fetch('1234567890')); -expectType>(autoModerationRuleManager.fetch({ autoModerationRule: '1234567890' })); -expectType>( - autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', cache: false }), -); -expectType>( - autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', force: true }), -); -expectType>( - autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', cache: false, force: true }), -); -expectType>>(autoModerationRuleManager.fetch()); -expectType>>(autoModerationRuleManager.fetch({})); -expectType>>(autoModerationRuleManager.fetch({ cache: false })); -// @ts-expect-error The `force` option cannot be used alongside fetching all auto moderation rules. -await autoModerationRuleManager.fetch({ force: false }); +{ + expectType>(autoModerationRuleManager.fetch('1234567890')); + expectType>(autoModerationRuleManager.fetch({ autoModerationRule: '1234567890' })); + expectType>( + autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', cache: false }), + ); + expectType>( + autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', force: true }), + ); + expectType>( + autoModerationRuleManager.fetch({ autoModerationRule: '1234567890', cache: false, force: true }), + ); + expectType>>(autoModerationRuleManager.fetch()); + expectType>>(autoModerationRuleManager.fetch({})); + expectType>>(autoModerationRuleManager.fetch({ cache: false })); + // @ts-expect-error The `force` option cannot be used alongside fetching all auto moderation rules. + await autoModerationRuleManager.fetch({ force: false }); +} declare const guildApplicationCommandManager: GuildApplicationCommandManager; expectType>(guildApplicationCommandManager.fetch('0')); @@ -1648,49 +1655,53 @@ expectType>(guildApplicationCommandManager.fetch({ i expectType>>(guildApplicationCommandManager.fetch()); declare const categoryChannelChildManager: CategoryChannelChildManager; - -expectType>(categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildVoice })); -expectType>(categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildText })); -expectType>( - categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildAnnouncement }), -); -expectType>( - categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildStageVoice }), -); -expectType>(categoryChannelChildManager.create({ name: 'name' })); -expectType>(categoryChannelChildManager.create({ name: 'name' })); +{ + expectType>(categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildVoice })); + expectType>(categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildText })); + expectType>( + categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildAnnouncement }), + ); + expectType>( + categoryChannelChildManager.create({ name: 'name', type: ChannelType.GuildStageVoice }), + ); + expectType>(categoryChannelChildManager.create({ name: 'name' })); + expectType>(categoryChannelChildManager.create({ name: 'name' })); +} declare const guildChannelManager: GuildChannelManager; +{ + expectType>(guildChannelManager.create({ name: 'name' })); + expectType>(guildChannelManager.create({ name: 'name' })); + expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildVoice })); + expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildCategory })); + expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildText })); + expectType>( + guildChannelManager.create({ name: 'name', type: ChannelType.GuildAnnouncement }), + ); + expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildStageVoice })); + expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildForum })); + expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildMedia })); -expectType>(guildChannelManager.create({ name: 'name' })); -expectType>(guildChannelManager.create({ name: 'name' })); -expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildVoice })); -expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildCategory })); -expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildText })); -expectType>( - guildChannelManager.create({ name: 'name', type: ChannelType.GuildAnnouncement }), -); -expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildStageVoice })); -expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildForum })); -expectType>(guildChannelManager.create({ name: 'name', type: ChannelType.GuildMedia })); - -expectType>>(guildChannelManager.fetch()); -expectType>>(guildChannelManager.fetch(undefined, {})); -expectType>(guildChannelManager.fetch('0')); - -const channel = guildChannelManager.cache.first()!; - -if (channel.isTextBased()) { - const { messages } = channel; - const message = await messages.fetch('123'); - expectType(messages); - expectType>>(messages.crosspost('1234567890')); - expectType>>(messages.edit('1234567890', 'text')); - expectType>>(messages.fetch('1234567890')); - expectType>>>(messages.fetchPinned()); - expectType(message.guild); - expectType(message.guildId); - expectType(message.channel.messages.channel); + expectType>>(guildChannelManager.fetch()); + expectType>>( + guildChannelManager.fetch(undefined, {}), + ); + expectType>(guildChannelManager.fetch('0')); + + const channel = guildChannelManager.cache.first()!; + + if (channel.isTextBased()) { + const { messages } = channel; + const message = await messages.fetch('123'); + expectType(messages); + expectType>>(messages.crosspost('1234567890')); + expectType>>(messages.edit('1234567890', 'text')); + expectType>>(messages.fetch('1234567890')); + expectType>>>(messages.fetchPinned()); + expectType(message.guild); + expectType(message.guildId); + expectType(message.channel.messages.channel); + } } { @@ -1717,15 +1728,16 @@ if (channel.isTextBased()) { } declare const threadManager: ThreadManager; - -expectType>(threadManager.fetch('12345678901234567')); -expectType>(threadManager.fetch('12345678901234567', { cache: true, force: false })); -expectType>(threadManager.fetch()); -expectType>(threadManager.fetch({})); -expectType>(threadManager.fetch({ archived: { limit: 4 } })); - -// @ts-expect-error The force option has no effect here. -await threadManager.fetch({ archived: {} }, { force: true }); +{ + expectType>(threadManager.fetch('12345678901234567')); + expectType>(threadManager.fetch('12345678901234567', { cache: true, force: false })); + expectType>(threadManager.fetch()); + expectType>(threadManager.fetch({})); + expectType>(threadManager.fetch({ archived: { limit: 4 } })); + + // @ts-expect-error The force option has no effect here. + await threadManager.fetch({ archived: {} }, { force: true }); +} declare const guildForumThreadManager: GuildForumThreadManager; expectType(guildForumThreadManager.channel); @@ -1736,45 +1748,48 @@ declare const guildTextThreadManager: GuildTextThreadManager< expectType(guildTextThreadManager.channel); declare const guildMemberManager: GuildMemberManager; +{ + expectType>(guildMemberManager.fetch('12345678901234567')); + expectType>(guildMemberManager.fetch({ user: '12345678901234567' })); + expectType>(guildMemberManager.fetch({ user: '12345678901234567', cache: true, force: false })); + expectType>(guildMemberManager.fetch({ user: '12345678901234567', cache: true, force: false })); + expectType>>(guildMemberManager.fetch()); + expectType>>(guildMemberManager.fetch({})); + expectType>>(guildMemberManager.fetch({ user: ['12345678901234567'] })); + expectType>>(guildMemberManager.fetch({ withPresences: false })); + expectType>(guildMemberManager.fetch({ user: '12345678901234567', withPresences: true })); + + expectType>>( + guildMemberManager.fetch({ query: 'test', user: ['12345678901234567'], nonce: 'test' }), + ); -expectType>(guildMemberManager.fetch('12345678901234567')); -expectType>(guildMemberManager.fetch({ user: '12345678901234567' })); -expectType>(guildMemberManager.fetch({ user: '12345678901234567', cache: true, force: false })); -expectType>(guildMemberManager.fetch({ user: '12345678901234567', cache: true, force: false })); -expectType>>(guildMemberManager.fetch()); -expectType>>(guildMemberManager.fetch({})); -expectType>>(guildMemberManager.fetch({ user: ['12345678901234567'] })); -expectType>>(guildMemberManager.fetch({ withPresences: false })); -expectType>(guildMemberManager.fetch({ user: '12345678901234567', withPresences: true })); - -expectType>>( - guildMemberManager.fetch({ query: 'test', user: ['12345678901234567'], nonce: 'test' }), -); - -// @ts-expect-error The cache & force options have no effect here. -await guildMemberManager.fetch({ cache: true, force: false }); -// @ts-expect-error The force option has no effect here. -await guildMemberManager.fetch({ user: ['12345678901234567'], cache: true, force: false }); + // @ts-expect-error The cache & force options have no effect here. + await guildMemberManager.fetch({ cache: true, force: false }); + // @ts-expect-error The force option has no effect here. + await guildMemberManager.fetch({ user: ['12345678901234567'], cache: true, force: false }); +} declare const messageManager: MessageManager; - -expectType>(messageManager.fetch('1234567890')); -expectType>(messageManager.fetch({ message: '1234567890' })); -expectType>(messageManager.fetch({ message: '1234567890', cache: true, force: false })); -expectType>>(messageManager.fetch()); -expectType>>(messageManager.fetch({})); -expectType>>( - messageManager.fetch({ limit: 100, before: '1234567890', cache: false }), -); -// @ts-expect-error -await messageManager.fetch({ cache: true, force: false }); -// @ts-expect-error -await messageManager.fetch({ message: '1234567890', after: '1234567890', cache: true, force: false }); +{ + expectType>(messageManager.fetch('1234567890')); + expectType>(messageManager.fetch({ message: '1234567890' })); + expectType>(messageManager.fetch({ message: '1234567890', cache: true, force: false })); + expectType>>(messageManager.fetch()); + expectType>>(messageManager.fetch({})); + expectType>>( + messageManager.fetch({ limit: 100, before: '1234567890', cache: false }), + ); + // @ts-expect-error + await messageManager.fetch({ cache: true, force: false }); + // @ts-expect-error + await messageManager.fetch({ message: '1234567890', after: '1234567890', cache: true, force: false }); +} declare const pollAnswerVoterManager: PollAnswerVoterManager; - -expectType>>(pollAnswerVoterManager.fetch()); -expectType(pollAnswerVoterManager.answer); +{ + expectType>>(pollAnswerVoterManager.fetch()); + expectType(pollAnswerVoterManager.answer); +} declare const roleManager: RoleManager; expectType>>(roleManager.fetch()); @@ -1792,39 +1807,43 @@ expectType>>(applicationEmojiMan expectType>(applicationEmojiManager.fetch('0')); declare const guildBanManager: GuildBanManager; - -expectType>(guildBanManager.fetch('1234567890')); -expectType>(guildBanManager.fetch({ user: '1234567890' })); -expectType>(guildBanManager.fetch({ user: '1234567890', cache: true, force: false })); -expectType>>(guildBanManager.fetch()); -expectType>>(guildBanManager.fetch({})); -expectType>>(guildBanManager.fetch({ limit: 100, before: '1234567890' })); -// @ts-expect-error -await guildBanManager.fetch({ cache: true, force: false }); -// @ts-expect-error -await guildBanManager.fetch({ user: '1234567890', after: '1234567890', cache: true, force: false }); +{ + expectType>(guildBanManager.fetch('1234567890')); + expectType>(guildBanManager.fetch({ user: '1234567890' })); + expectType>(guildBanManager.fetch({ user: '1234567890', cache: true, force: false })); + expectType>>(guildBanManager.fetch()); + expectType>>(guildBanManager.fetch({})); + expectType>>(guildBanManager.fetch({ limit: 100, before: '1234567890' })); + // @ts-expect-error + await guildBanManager.fetch({ cache: true, force: false }); + // @ts-expect-error + await guildBanManager.fetch({ user: '1234567890', after: '1234567890', cache: true, force: false }); +} declare const threadMemberWithGuildMember: ThreadMember; declare const threadMemberManager: ThreadMemberManager; +{ + expectType>(threadMemberManager.fetch('12345678')); + expectType>(threadMemberManager.fetch({ member: '12345678', cache: false })); + expectType>(threadMemberManager.fetch({ member: '12345678', force: true })); + expectType>>(threadMemberManager.fetch({ member: threadMemberWithGuildMember })); + expectType>>(threadMemberManager.fetch({ member: '12345678901234567', withMember: true })); + expectType>>(threadMemberManager.fetch()); + expectType>>(threadMemberManager.fetch({})); + + expectType>>>( + threadMemberManager.fetch({ cache: true, limit: 50, withMember: true, after: '12345678901234567' }), + ); -expectType>(threadMemberManager.fetch('12345678')); -expectType>(threadMemberManager.fetch({ member: '12345678', cache: false })); -expectType>(threadMemberManager.fetch({ member: '12345678', force: true })); -expectType>>(threadMemberManager.fetch({ member: threadMemberWithGuildMember })); -expectType>>(threadMemberManager.fetch({ member: '12345678901234567', withMember: true })); -expectType>>(threadMemberManager.fetch()); -expectType>>(threadMemberManager.fetch({})); - -expectType>>>( - threadMemberManager.fetch({ cache: true, limit: 50, withMember: true, after: '12345678901234567' }), -); - -expectType>>(threadMemberManager.fetch({ cache: true, withMember: false })); + expectType>>( + threadMemberManager.fetch({ cache: true, withMember: false }), + ); -// @ts-expect-error The `force` option cannot be used alongside fetching all thread members. -await threadMemberManager.fetch({ cache: true, force: false }); -// @ts-expect-error `withMember` needs to be `true` to receive paginated results. -await threadMemberManager.fetch({ withMember: false, limit: 5, after: '12345678901234567' }); + // @ts-expect-error The `force` option cannot be used alongside fetching all thread members. + await threadMemberManager.fetch({ cache: true, force: false }); + // @ts-expect-error `withMember` needs to be `true` to receive paginated results. + await threadMemberManager.fetch({ withMember: false, limit: 5, after: '12345678901234567' }); +} declare const typing: Typing; expectType(typing.user); @@ -2684,59 +2703,61 @@ expectType(partialUser.tag); expectType(partialUser.discriminator); declare const emoji: Emoji; - -expectType(resolvePartialEmoji('12345678901234567')); -expectType(resolvePartialEmoji(emoji)); +{ + expectType(resolvePartialEmoji('12345678901234567')); + expectType(resolvePartialEmoji(emoji)); +} declare const application: ClientApplication; declare const entitlement: Entitlement; declare const sku: SKU; +{ + expectType>(await application.fetchSKUs()); + expectType>(await application.entitlements.fetch()); -expectType>(await application.fetchSKUs()); -expectType>(await application.entitlements.fetch()); + await application.entitlements.fetch({ + guild, + skus: ['12345678901234567', sku], + user, + excludeEnded: true, + limit: 10, + }); -await application.entitlements.fetch({ - guild, - skus: ['12345678901234567', sku], - user, - excludeEnded: true, - limit: 10, -}); + await application.entitlements.createTest({ sku: '12345678901234567', user }); + await application.entitlements.createTest({ sku, guild }); -await application.entitlements.createTest({ sku: '12345678901234567', user }); -await application.entitlements.createTest({ sku, guild }); + await application.entitlements.deleteTest(entitlement); -await application.entitlements.deleteTest(entitlement); + await application.entitlements.consume(snowflake); -await application.entitlements.consume(snowflake); + expectType(entitlement.isActive()); -expectType(entitlement.isActive()); + if (entitlement.isUserSubscription()) { + expectType(entitlement.userId); + expectType(await entitlement.fetchUser()); + expectType(entitlement.guildId); + expectType(entitlement.guild); -if (entitlement.isUserSubscription()) { - expectType(entitlement.userId); - expectType(await entitlement.fetchUser()); - expectType(entitlement.guildId); - expectType(entitlement.guild); + await application.entitlements.deleteTest(entitlement); + } else if (entitlement.isGuildSubscription()) { + expectType(entitlement.guildId); + expectType(entitlement.guild); - await application.entitlements.deleteTest(entitlement); -} else if (entitlement.isGuildSubscription()) { - expectType(entitlement.guildId); - expectType(entitlement.guild); + await application.entitlements.deleteTest(entitlement); + } - await application.entitlements.deleteTest(entitlement); -} + if (entitlement.isTest()) { + expectType(entitlement.startsTimestamp); + expectType(entitlement.endsTimestamp); + expectType(entitlement.startsAt); + expectType(entitlement.endsAt); + } -if (entitlement.isTest()) { - expectType(entitlement.startsTimestamp); - expectType(entitlement.endsTimestamp); - expectType(entitlement.startsAt); - expectType(entitlement.endsAt); + client.on(Events.InteractionCreate, async interaction => { + expectType>(interaction.entitlements); + }); } -client.on(Events.InteractionCreate, async interaction => { - expectType>(interaction.entitlements); -}); - await client.channels.createMessage('123', { poll: { question: { @@ -2749,22 +2770,24 @@ await client.channels.createMessage('123', { }); declare const partialPoll: PartialPoll; - -if (partialPoll.partial) { - expectType(partialPoll.question.text); - expectType(partialPoll.message); - expectType(partialPoll.allowMultiselect); - expectType(partialPoll.layoutType); - expectType(partialPoll.expiresTimestamp); - expectType>(partialPoll.answers); +{ + if (partialPoll.partial) { + expectType(partialPoll.question.text); + expectType(partialPoll.message); + expectType(partialPoll.allowMultiselect); + expectType(partialPoll.layoutType); + expectType(partialPoll.expiresTimestamp); + expectType>(partialPoll.answers); + } } declare const partialPollAnswer: PartialPollAnswer; - -if (partialPollAnswer.partial) { - expectType(partialPollAnswer.poll); - expectType(partialPollAnswer.emoji); - expectType(partialPollAnswer.text); +{ + if (partialPollAnswer.partial) { + expectType(partialPollAnswer.poll); + expectType(partialPollAnswer.emoji); + expectType(partialPollAnswer.text); + } } declare const poll: Poll; @@ -2819,80 +2842,88 @@ client.on('interactionCreate', async interaction => { declare const guildScheduledEventManager: GuildScheduledEventManager; await guildScheduledEventManager.edit(snowflake, { recurrenceRule: null }); -expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, - interval: 1, - byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], - byMonthDay: [4], - // Invalid property - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], -}); - -expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, - interval: 1, - byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], - byMonthDay: [4], - // Invalid property - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], -}); - -expectAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, - interval: 1, - byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], - byMonthDay: [4], -}); - -expectAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Monthly, - interval: 1, - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], -}); +{ + expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, + interval: 1, + byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], + byMonthDay: [4], + // Invalid property + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + }); + + expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, + interval: 1, + byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], + byMonthDay: [4], + // Invalid property + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], + }); + + expectAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Yearly, + interval: 1, + byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], + byMonthDay: [4], + }); +} -expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Monthly, - interval: 1, - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], - // Invalid property - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], -}); +{ + expectAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Monthly, + interval: 1, + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], + }); -expectAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Weekly, - interval: 1, - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], -}); + expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Monthly, + interval: 1, + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], + // Invalid property + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + }); +} -expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Weekly, - interval: 1, - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - // Invalid property - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], -}); +{ + expectAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Weekly, + interval: 1, + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + }); -expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Daily, - interval: 1, - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - // Invalid property - byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], -}); + expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Weekly, + interval: 1, + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + // Invalid property + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], + }); +} -expectNotAssignable({ - startAt: new Date(), - frequency: GuildScheduledEventRecurrenceRuleFrequency.Daily, - interval: 1, - byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], - // Invalid property - byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], -}); +{ + expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Daily, + interval: 1, + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + // Invalid property + byNWeekday: [{ n: 1, day: GuildScheduledEventRecurrenceRuleWeekday.Monday }], + }); + + expectNotAssignable({ + startAt: new Date(), + frequency: GuildScheduledEventRecurrenceRuleFrequency.Daily, + interval: 1, + byWeekday: [GuildScheduledEventRecurrenceRuleWeekday.Monday], + // Invalid property + byMonth: [GuildScheduledEventRecurrenceRuleMonth.May], + }); +} From 5da6f14f16adffacf5904aafc2d2cbe6304d794c Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 15:24:14 +0200 Subject: [PATCH 20/38] chore: code review --- packages/discord.js/src/structures/GuildAuditLogsEntry.js | 2 +- packages/discord.js/src/structures/Message.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/discord.js/src/structures/GuildAuditLogsEntry.js b/packages/discord.js/src/structures/GuildAuditLogsEntry.js index 56a70aa23a36..697b7c67f310 100644 --- a/packages/discord.js/src/structures/GuildAuditLogsEntry.js +++ b/packages/discord.js/src/structures/GuildAuditLogsEntry.js @@ -201,7 +201,7 @@ class GuildAuditLogsEntry { /** * Any extra data from the entry * - * @type {?(Object | Role | GuildMember)} + * @type {?(Object|Role|GuildMember)} */ this.extra = null; switch (data.action_type) { diff --git a/packages/discord.js/src/structures/Message.js b/packages/discord.js/src/structures/Message.js index f2d7d3ea24e7..99a4dfd17b94 100644 --- a/packages/discord.js/src/structures/Message.js +++ b/packages/discord.js/src/structures/Message.js @@ -383,7 +383,7 @@ class Message extends Base { /** * Reference data sent in a message that contains ids identifying the referenced message. * This can be present in the following types of message: - * - Crossposted messages ({@link MessageFlags.Crossposted}) + * - {@link MessageFlags.Crossposted} * - {@link MessageType.ChannelPinnedMessage} * - {@link MessageType.ChannelFollowAdd} * - {@link MessageType.Reply} From e80a44018461802445339c67e9312598ed79e40c Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 15:50:46 +0200 Subject: [PATCH 21/38] chore: code review --- eslint.config.js | 2 + packages/discord.js/typings/index.d.ts | 760 +------------------------ 2 files changed, 22 insertions(+), 740 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 09291864a357..d47483e2d9ff 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -199,6 +199,8 @@ export default tseslint.config( '@typescript-eslint/no-unsafe-declaration-merging': 0, '@typescript-eslint/no-empty-object-type': 0, '@typescript-eslint/no-use-before-define': 0, + '@typescript-eslint/consistent-type-imports': 0, + '@stylistic/ts/lines-between-class-members': 0, 'no-restricted-syntax': [ 2, { diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index 5dc2c8af09a5..e836fadd57da 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -1,17 +1,14 @@ -import type { Buffer } from 'node:buffer'; -import type { ChildProcess } from 'node:child_process'; -import type { Stream } from 'node:stream'; -import type { MessagePort, Worker } from 'node:worker_threads'; -import type { - ApplicationCommandOptionAllowedChannelTypes, - MessageActionRowComponentBuilder, -} from '@discordjs/builders'; -import type { Collection, ReadonlyCollection } from '@discordjs/collection'; -import type { BaseImageURLOptions, ImageURLOptions, RawFile, REST, RESTOptions } from '@discordjs/rest'; -import type { Awaitable, JSONEncodable } from '@discordjs/util'; -import type { WebSocketManager, WebSocketManagerOptions } from '@discordjs/ws'; +import { Buffer } from 'node:buffer'; +import { ChildProcess } from 'node:child_process'; +import { Stream } from 'node:stream'; +import { MessagePort, Worker } from 'node:worker_threads'; +import { ApplicationCommandOptionAllowedChannelTypes, MessageActionRowComponentBuilder } from '@discordjs/builders'; +import { Collection, ReadonlyCollection } from '@discordjs/collection'; +import { BaseImageURLOptions, ImageURLOptions, RawFile, REST, RESTOptions } from '@discordjs/rest'; +import { Awaitable, JSONEncodable } from '@discordjs/util'; +import { WebSocketManager, WebSocketManagerOptions } from '@discordjs/ws'; import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter'; -import type { +import { APIActionRowComponent, APIApplicationCommandInteractionData, APIApplicationCommandOption, @@ -48,6 +45,7 @@ import type { MessageType, OAuth2Scopes, RESTPostAPIApplicationCommandsJSONBody, + Snowflake, StageInstancePrivacyLevel, StickerFormatType, StickerType, @@ -168,9 +166,8 @@ import type { RESTAPIPoll, EntryPointCommandHandlerType, APISoundboardSound, - Snowflake, } from 'discord-api-types/v10'; -import type { +import { RawActivityData, RawAnonymousGuildData, RawApplicationCommandData, @@ -232,40 +229,26 @@ import type { export class Activity { private constructor(presence: Presence, data?: RawActivityData); public readonly presence: Presence; - public applicationId: Snowflake | null; - public assets: RichPresenceAssets | null; - public buttons: string[]; - public get createdAt(): Date; public createdTimestamp: number; - public details: string | null; - public emoji: Emoji | null; - public flags: Readonly; - public name: string; - public party: { id: string | null; size: [number, number]; } | null; - public state: string | null; - public syncId: string | null; - public timestamps: { end: Date | null; start: Date | null; } | null; - public type: ActivityType; - public url: string | null; public equals(activity: Activity): boolean; public toString(): string; @@ -322,17 +305,11 @@ export class ActivityFlagsBitField extends BitField { export abstract class AnonymousGuild extends BaseGuild { protected constructor(client: Client, data: RawAnonymousGuildData, immediatePatch?: boolean); public banner: string | null; - public description: string | null; - public nsfwLevel: GuildNSFWLevel; - public premiumSubscriptionCount: number | null; - public splash: string | null; - public vanityURLCode: string | null; - public verificationLevel: GuildVerificationLevel; public bannerURL(options?: ImageURLOptions): string | null; public splashURL(options?: ImageURLOptions): string | null; @@ -341,28 +318,18 @@ export abstract class AnonymousGuild extends BaseGuild { export class AutoModerationActionExecution { private constructor(data: GatewayAutoModerationActionExecutionDispatchData, guild: Guild); public guild: Guild; - public action: AutoModerationAction; - public ruleId: Snowflake; - public ruleTriggerType: AutoModerationRuleTriggerType; - public get user(): User | null; public userId: Snowflake; - public get channel(): ForumChannel | GuildTextBasedChannel | MediaChannel | null; public channelId: Snowflake | null; - public get member(): GuildMember | null; public messageId: Snowflake | null; - public alertSystemMessageId: Snowflake | null; - public content: string; - public matchedKeyword: string | null; - public matchedContent: string | null; public get autoModerationRule(): AutoModerationRule | null; } @@ -370,25 +337,15 @@ export class AutoModerationActionExecution { export class AutoModerationRule extends Base { private constructor(client: Client, data: APIAutoModerationRule, guild: Guild); public id: Snowflake; - public guild: Guild; - public name: string; - public creatorId: Snowflake; - public eventType: AutoModerationRuleEventType; - public triggerType: AutoModerationRuleTriggerType; - public triggerMetadata: AutoModerationTriggerMetadata; - public actions: AutoModerationAction[]; - public enabled: boolean; - public exemptRoles: Collection; - public exemptChannels: Collection; public edit(options: AutoModerationRuleEditOptions): Promise; public delete(reason?: string): Promise; @@ -423,21 +380,13 @@ export abstract class Application extends Base { public get createdAt(): Date; public get createdTimestamp(): number; public description: string | null; - public icon: string | null; - public id: Snowflake; - public name: string | null; - public termsOfServiceURL: string | null; - public privacyPolicyURL: string | null; - public rpcOrigins: string[]; - public cover: string | null; - public verifyKey: string | null; public coverURL(options?: ImageURLOptions): string | null; public iconURL(options?: ImageURLOptions): string | null; @@ -448,49 +397,31 @@ export abstract class Application extends Base { export class ApplicationCommand extends Base { private constructor(client: Client, data: RawApplicationCommandData, guild?: Guild, guildId?: Snowflake); public applicationId: Snowflake; - public contexts: InteractionContextType[] | null; - public get createdAt(): Date; public get createdTimestamp(): number; public defaultMemberPermissions: Readonly | null; - public description: string; - public descriptionLocalizations: LocalizationMap | null; - public descriptionLocalized: string | null; - public guild: Guild | null; - public guildId: Snowflake | null; - public get manager(): ApplicationCommandManager; public id: Snowflake; - public integrationTypes: ApplicationIntegrationType[] | null; - public handler: EntryPointCommandHandlerType | null; - public name: string; - public nameLocalizations: LocalizationMap | null; - public nameLocalized: string | null; - public options: (ApplicationCommandOption & { descriptionLocalized?: string; nameLocalized?: string })[]; - public permissions: ApplicationCommandPermissionsManager< PermissionsFetchType, PermissionsFetchType, Guild | null, Snowflake >; - public type: ApplicationCommandType; - public version: Snowflake; - public nsfw: boolean; public delete(): Promise>; public edit(data: Partial): Promise>; @@ -531,15 +462,10 @@ export class ApplicationCommand extends Base { export class ApplicationRoleConnectionMetadata { private constructor(data: APIApplicationRoleConnectionMetadata); public name: string; - public nameLocalizations: LocalizationMap | null; - public description: string; - public descriptionLocalizations: LocalizationMap | null; - public key: string; - public type: ApplicationRoleConnectionMetadataType; } @@ -567,7 +493,6 @@ export class BaseClient extends AsyncEventEmitter imp private incrementMaxListeners(): void; public options: ClientOptions | WebhookClientOptions; - public rest: REST; public destroy(): void; public toJSON(...props: Record[]): unknown; @@ -586,24 +511,15 @@ export type BooleanCache = Cached extends 'cached' ? t export abstract class CommandInteraction extends BaseInteraction { public type: InteractionType.ApplicationCommand; - public get command(): ApplicationCommand | ApplicationCommand<{ guild: GuildResolvable }> | null; public channelId: Snowflake; - public commandId: Snowflake; - public commandName: string; - public commandType: ApplicationCommandType; - public commandGuildId: Snowflake | null; - public deferred: boolean; - public ephemeral: boolean | null; - public replied: boolean; - public webhook: InteractionWebhook; public inGuild(): this is CommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is CommandInteraction<'cached'>; @@ -670,11 +586,8 @@ export abstract class BaseGuild extends Base { public get createdAt(): Date; public get createdTimestamp(): number; public features: `${GuildFeature}`[]; - public icon: string | null; - public id: Snowflake; - public name: string; public get nameAcronym(): string; public get partnered(): boolean; @@ -689,15 +602,11 @@ export class BaseGuildEmoji extends Emoji { public imageURL(options?: ImageURLOptions): string; public get url(): string; public available: boolean | null; - public get createdAt(): Date; public get createdTimestamp(): number; public guild: Guild | GuildPreview; - public id: Snowflake; - public managed: boolean | null; - public requiresColons: boolean | null; } @@ -705,15 +614,10 @@ export interface BaseGuildTextChannel extends TextBasedChannelFields {} export class BaseGuildTextChannel extends GuildChannel { protected constructor(guild: Guild, data?: RawGuildChannelData, client?: Client, immediatePatch?: boolean); public defaultAutoArchiveDuration?: ThreadAutoArchiveDuration; - public defaultThreadRateLimitPerUser: number | null; - public rateLimitPerUser: number | null; - public nsfw: boolean; - public threads: GuildTextThreadManager; - public topic: string | null; public createInvite(options?: InviteCreateOptions): Promise; public fetchInvites(cache?: boolean): Promise>; @@ -730,18 +634,13 @@ export interface BaseGuildVoiceChannel extends Omit export class BaseGuildVoiceChannel extends GuildChannel { public constructor(guild: Guild, data?: RawGuildChannelData); public bitrate: number; - public get full(): boolean; public get joinable(): boolean; public get members(): Collection; public nsfw: boolean; - public rateLimitPerUser: number | null; - public rtcRegion: string | null; - public userLimit: number; - public videoQualityMode: VideoQualityMode | null; public createInvite(options?: InviteCreateOptions): Promise; public fetchInvites(cache?: boolean): Promise>; @@ -756,7 +655,6 @@ export type EnumLike = Record; export class BitField { public constructor(bits?: BitFieldResolvable); public bitfield: Type; - public add(...bits: BitFieldResolvable[]): BitField; public any(bit: BitFieldResolvable): boolean; public equals(bit: BitFieldResolvable): boolean; @@ -910,7 +808,6 @@ export type CategoryChannelChildTypes = export class CategoryChannel extends GuildChannel { public get children(): CategoryChannelChildManager; public type: ChannelType.GuildCategory; - public get parent(): null; public parentId: null; } @@ -931,9 +828,7 @@ export abstract class BaseChannel extends Base { public get createdAt(): Date | null; public get createdTimestamp(): number | null; public id: Snowflake; - public flags: Readonly | null; - public get partial(): false; public type: ChannelType; public get url(): string; @@ -957,17 +852,11 @@ export type If = Value ex export class Client extends BaseClient { public constructor(options: ClientOptions); private readonly actions: unknown; - private readonly expectedGuilds: Set; - private readonly packetQueue: unknown[]; - private readonly presence: ClientPresence; - private readonly pings: Collection; - private readonly readyTimeout: NodeJS.Timeout | null; - private _broadcast(packet: GatewaySendPayload): void; private _eval(script: string): unknown; private _handlePacket(packet?: GatewayDispatchPayload, shardId?: number): boolean; @@ -979,34 +868,21 @@ export class Client extends BaseClient; - public channels: ChannelManager; - public guilds: GuildManager; - public lastPingTimestamps: ReadonlyCollection; - public options: Omit & { intents: IntentsBitField }; - public get ping(): number | null; public get readyAt(): If; public readyTimestamp: If; - public sweepers: Sweepers; - public shard: ShardClientUtil | null; - public status: Status; - public token: If; - public get uptime(): If; public user: If; - public users: UserManager; - public voice: ClientVoiceManager; - public ws: WebSocketManager; public destroy(): Promise; @@ -1034,47 +910,27 @@ export interface StickerPackFetchOptions { export class ClientApplication extends Application { private constructor(client: Client, data: RawClientApplicationData); public botPublic: boolean | null; - public botRequireCodeGrant: boolean | null; - public bot: User | null; - public commands: ApplicationCommandManager; - public emojis: ApplicationEmojiManager; - public entitlements: EntitlementManager; - public subscriptions: SubscriptionManager; - public guildId: Snowflake | null; - public get guild(): Guild | null; public flags: Readonly; - public approximateGuildCount: number | null; - public approximateUserInstallCount: number | null; - public tags: string[]; - public installParams: ClientApplicationInstallParams | null; - public integrationTypesConfig: IntegrationTypesConfiguration | null; - public customInstallURL: string | null; - public owner: Team | User | null; - public get partial(): boolean; public interactionsEndpointURL: string | null; - public eventWebhooksURL: string | null; - public eventWebhooksStatus: ApplicationWebhookEventStatus | null; - public eventWebhooksTypes: ApplicationWebhookEventType[] | null; - public roleConnectionsVerificationURL: string | null; public edit(options: ClientApplicationEditOptions): Promise; public fetch(): Promise; @@ -1094,7 +950,6 @@ export class ClientPresence extends Presence { export class ClientUser extends User { public mfaEnabled: boolean; - public get presence(): ClientPresence; public verified: boolean; public edit(options: ClientUserEditOptions): Promise; @@ -1121,7 +976,6 @@ export class Options extends null { export class ClientVoiceManager { private constructor(client: Client); public readonly client: Client; - public adapters: Map; } @@ -1142,23 +996,16 @@ export abstract class Collector< > extends AsyncEventEmitter { protected constructor(client: Client, options?: CollectorOptions<[Value, ...Extras]>); private readonly _timeout: NodeJS.Timeout | null; - private readonly _idletimeout: NodeJS.Timeout | null; - private readonly _endReason: string | null; public readonly client: Client; - public collected: Collection; - public lastCollectedTimestamp: number | null; - public get lastCollectedAt(): Date | null; public ended: boolean; - public get endReason(): string | null; public filter: CollectorFilter<[Value, ...Extras]>; - public get next(): Promise; public options: CollectorOptions<[Value, ...Extras]>; public checkEnd(): boolean; @@ -1176,7 +1023,6 @@ export abstract class Collector< export class ChatInputCommandInteraction extends CommandInteraction { public commandType: ApplicationCommandType.ChatInput; - public options: Omit, 'getFocused' | 'getMessage'>; public inGuild(): this is ChatInputCommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is ChatInputCommandInteraction<'cached'>; @@ -1186,20 +1032,13 @@ export class ChatInputCommandInteraction e export class AutocompleteInteraction extends BaseInteraction { public type: InteractionType.ApplicationCommandAutocomplete; - public get command(): ApplicationCommand | ApplicationCommand<{ guild: GuildResolvable }> | null; public channelId: Snowflake; - public commandId: Snowflake; - public commandName: string; - public commandType: ApplicationCommandType.ChatInput; - public commandGuildId: Snowflake | null; - public responded: boolean; - public options: Omit< CommandInteractionOptionResolver, 'getAttachment' | 'getChannel' | 'getMember' | 'getMentionable' | 'getMessage' | 'getRole' | 'getUser' @@ -1217,15 +1056,10 @@ export class CommandInteractionOptionResolver[]; - public readonly resolved: Readonly> | null; - private readonly _group: string | null; - private readonly _hoistedOptions: CommandInteractionOption[]; - private readonly _subcommand: string | null; private _getTypedOption( name: string, @@ -1332,9 +1166,7 @@ export class ContextMenuCommandInteraction | 'getSubcommandGroup' | 'getUser' >; - public commandType: ApplicationCommandType.Message | ApplicationCommandType.User; - public targetId: Snowflake; public inGuild(): this is ContextMenuCommandInteraction<'cached' | 'raw'>; public inCachedGuild(): this is ContextMenuCommandInteraction<'cached'>; @@ -1359,9 +1191,7 @@ export interface DMChannel export class DMChannel extends BaseChannel { private constructor(client: Client, data?: RawDMChannelData); public flags: Readonly; - public recipientId: Snowflake; - public get recipient(): User | null; public type: ChannelType.DM; public fetch(force?: boolean): Promise; @@ -1371,11 +1201,9 @@ export class DMChannel extends BaseChannel { export class Emoji extends Base { protected constructor(client: Client, emoji: RawEmojiData); public animated: boolean | null; - public get createdAt(): Date | null; public get createdTimestamp(): number | null; public id: Snowflake | null; - public name: string | null; public get identifier(): string; public imageURL(options?: ImageURLOptions): string | null; @@ -1397,13 +1225,9 @@ export class ApplicationEmoji extends Emoji { private constructor(client: Client, data: RawApplicationEmojiData, application: ClientApplication); public application: ClientApplication; - public author: User | null; - public id: Snowflake; - public managed: boolean | null; - public requiresColons: boolean | null; public delete(): Promise; public edit(options: ApplicationEmojiEditOptions): Promise; @@ -1426,23 +1250,14 @@ export class ApplicationEmojiManager extends CachedManager, data: APIEntitlement); public id: Snowflake; - public skuId: Snowflake; - public userId: Snowflake; - public guildId: Snowflake | null; - public applicationId: Snowflake; - public type: EntitlementType; - public consumed: boolean; - public deleted: boolean; - public startsTimestamp: number | null; - public endsTimestamp: number | null; public get guild(): Guild | null; public get startsAt(): Date | null; @@ -1467,97 +1282,54 @@ export class Guild extends AnonymousGuild { public get afkChannel(): VoiceChannel | null; public afkChannelId: Snowflake | null; - public afkTimeout: number; - public applicationId: Snowflake | null; - public maxVideoChannelUsers: number | null; - public approximateMemberCount: number | null; - public approximatePresenceCount: number | null; - public autoModerationRules: AutoModerationRuleManager; - public available: boolean; - public bans: GuildBanManager; - public channels: GuildChannelManager; - public commands: GuildApplicationCommandManager; - public defaultMessageNotifications: GuildDefaultMessageNotifications; - public discoverySplash: string | null; - public emojis: GuildEmojiManager; - public explicitContentFilter: GuildExplicitContentFilter; - public invites: GuildInviteManager; - public get joinedAt(): Date; public joinedTimestamp: number; - public large: boolean; - public maximumMembers: number | null; - public maximumPresences: number | null; - public maxStageVideoChannelUsers: number | null; - public memberCount: number; - public members: GuildMemberManager; - public mfaLevel: GuildMFALevel; - public ownerId: Snowflake; - public preferredLocale: Locale; - public premiumProgressBarEnabled: boolean; - public premiumTier: GuildPremiumTier; - public presences: PresenceManager; - public get publicUpdatesChannel(): TextChannel | null; public publicUpdatesChannelId: Snowflake | null; - public roles: RoleManager; - public get rulesChannel(): TextChannel | null; public rulesChannelId: Snowflake | null; - public get safetyAlertsChannel(): TextChannel | null; public safetyAlertsChannelId: Snowflake | null; - public scheduledEvents: GuildScheduledEventManager; - public shardId: number; - public soundboardSounds: GuildSoundboardSoundManager; - public stageInstances: StageInstanceManager; - public stickers: GuildStickerManager; - public incidentsData: IncidentActions | null; - public get systemChannel(): TextChannel | null; public systemChannelFlags: Readonly; - public systemChannelId: Snowflake | null; - public vanityURLUses: number | null; - public get voiceAdapterCreator(): InternalDiscordGatewayAdapterCreator; public voiceStates: VoiceStateManager; - public get widgetChannel(): | AnnouncementChannel | ForumChannel @@ -1566,7 +1338,6 @@ export class Guild extends AnonymousGuild { | VoiceBasedChannel | null; public widgetChannelId: Snowflake | null; - public widgetEnabled: boolean | null; public get maximumBitrate(): number; public createTemplate(name: string, description?: string): Promise; @@ -1628,15 +1399,10 @@ export class Guild extends AnonymousGuild { export class GuildAuditLogs { private constructor(guild: Guild, data: RawGuildAuditLogData); private readonly applicationCommands: Collection; - private readonly webhooks: Collection>; - private readonly integrations: Collection; - private readonly guildScheduledEvents: Collection; - private readonly autoModerationRules: Collection; - public entries: Collection>; public toJSON(): unknown; } @@ -1652,31 +1418,20 @@ export class GuildAuditLogsEntry< > { private constructor(guild: Guild, data: RawGuildAuditLogEntryData, logs?: GuildAuditLogs); public static Targets: GuildAuditLogsTargets; - public action: TAction; - public actionType: TActionType; - public changes: AuditLogChange[]; - public get createdAt(): Date; public get createdTimestamp(): number; public executorId: Snowflake | null; - public executor: PartialUser | User | null; - public extra: TAction extends keyof GuildAuditLogsEntryExtraField ? GuildAuditLogsEntryExtraField[TAction] : null; - public id: Snowflake; - public reason: string | null; - public targetId: Snowflake | null; - public target: TTargetType extends keyof GuildAuditLogsEntryTargetField ? GuildAuditLogsEntryTargetField[TTargetType] : { [x: string]: unknown; id: Snowflake | undefined } | null; - public targetType: TTargetType; public static actionType(action: AuditLogEvent): GuildAuditLogsActionType; public static targetType(target: AuditLogEvent): GuildAuditLogsTargetType; @@ -1693,9 +1448,7 @@ export class GuildAuditLogsEntry< export class GuildBan extends Base { private constructor(client: Client, data: RawGuildBanData, guild: Guild); public guild: Guild; - public user: User; - public get partial(): boolean; public reason?: string | null; public fetch(force?: boolean): Promise; @@ -1709,24 +1462,17 @@ export abstract class GuildChannel extends BaseChannel { public get createdTimestamp(): number; public get deletable(): boolean; public flags: Readonly; - public guild: Guild; - public guildId: Snowflake; - public get manageable(): boolean; public get members(): Collection; public name: string; - public get parent(): CategoryChannel | null; public parentId: Snowflake | null; - public permissionOverwrites: PermissionOverwriteManager; - public get permissionsLocked(): boolean | null; public get position(): number; public rawPosition: number; - public type: GuildChannelTypes; public get viewable(): boolean; public clone(options?: GuildChannelCloneOptions): Promise; @@ -1752,7 +1498,6 @@ export class GuildEmoji extends BaseGuildEmoji { public get deletable(): boolean; public guild: Guild; - public author: User | null; public get roles(): GuildEmojiRoleManager; public delete(reason?: string): Promise; @@ -1775,39 +1520,29 @@ export interface GuildMember extends PartialTextBasedChannelFields {} export class GuildMember extends Base { private constructor(client: Client, data: RawGuildMemberData, guild: Guild); private readonly _roles: Snowflake[]; - public avatar: string | null; - public banner: string | null; - public get bannable(): boolean; public get dmChannel(): DMChannel | null; public get displayColor(): number; public get displayHexColor(): HexColorString; public get displayName(): string; public guild: Guild; - public get id(): Snowflake; public pending: boolean; - public get communicationDisabledUntil(): Date | null; public communicationDisabledUntilTimestamp: number | null; - public flags: Readonly; - public get joinedAt(): Date | null; public joinedTimestamp: number | null; - public get kickable(): boolean; public get manageable(): boolean; public get moderatable(): boolean; public nickname: string | null; - public get partial(): false; public get permissions(): Readonly; public get premiumSince(): Date | null; public premiumSinceTimestamp: number | null; - public get presence(): Presence | null; public get roles(): GuildMemberRoleManager; public user: User; @@ -1840,33 +1575,22 @@ export class GuildOnboarding extends Base { private constructor(client: Client, data: RESTGetAPIGuildOnboardingResult); public get guild(): Guild; public guildId: Snowflake; - public prompts: Collection; - public defaultChannels: Collection; - public enabled: boolean; - public mode: GuildOnboardingMode; } export class GuildOnboardingPrompt extends Base { private constructor(client: Client, data: APIGuildOnboardingPrompt, guildId: Snowflake); public id: Snowflake; - public get guild(): Guild; public guildId: Snowflake; - public options: Collection; - public title: string; - public singleSelect: boolean; - public required: boolean; - public inOnboarding: boolean; - public type: GuildOnboardingPromptType; } @@ -1875,44 +1599,29 @@ export class GuildOnboardingPromptOption extends Base { private readonly _emoji: APIPartialEmoji; public id: Snowflake; - public get emoji(): Emoji | GuildEmoji | null; public get guild(): Guild; public guildId: Snowflake; - public channels: Collection; - public roles: Collection; - public title: string; - public description: string | null; } export class GuildPreview extends Base { private constructor(client: Client, data: RawGuildPreviewData); public approximateMemberCount: number; - public approximatePresenceCount: number; - public get createdAt(): Date; public get createdTimestamp(): number; public description: string | null; - public discoverySplash: string | null; - public emojis: Collection; - public stickers: Collection; - public features: `${GuildFeature}`[]; - public icon: string | null; - public id: Snowflake; - public name: string; - public splash: string | null; public discoverySplashURL(options?: ImageURLOptions): string | null; public iconURL(options?: ImageURLOptions): string | null; @@ -1925,37 +1634,21 @@ export class GuildPreview extends Base { export class GuildScheduledEvent extends Base { private constructor(client: Client, data: RawGuildScheduledEventData); public id: Snowflake; - public guildId: Snowflake; - public channelId: Snowflake | null; - public creatorId: Snowflake | null; - public name: string; - public description: string | null; - public scheduledStartTimestamp: number | null; - public scheduledEndTimestamp: number | null; - public privacyLevel: GuildScheduledEventPrivacyLevel; - public status: Status; - public entityType: GuildScheduledEventEntityType; - public entityId: Snowflake | null; - public entityMetadata: GuildScheduledEventEntityMetadata | null; - public userCount: number | null; - public creator: User | null; - public recurrenceRule: GuildScheduledEventRecurrenceRule | null; - public get createdTimestamp(): number; public get createdAt(): Date; public get scheduledStartAt(): Date | null; @@ -2017,31 +1710,20 @@ export interface GuildScheduledEventRecurrenceRuleNWeekday { export class GuildTemplate extends Base { private constructor(client: Client, data: RawGuildTemplateData); public createdTimestamp: number; - public updatedTimestamp: number; - public get url(): string; public code: string; - public name: string; - public description: string | null; - public usageCount: number; - public creator: User; - public creatorId: Snowflake; - public get createdAt(): Date; public get updatedAt(): Date; public get guild(): Guild | null; public guildId: Snowflake; - public serializedGuild: APITemplateSerializedSourceGuild; - public unSynced: boolean | null; - public createGuild(name: string, icon?: Base64Resolvable | BufferResolvable): Promise; public delete(): Promise; public edit(options?: GuildTemplateEditOptions): Promise; @@ -2052,46 +1734,29 @@ export class GuildTemplate extends Base { export class GuildPreviewEmoji extends BaseGuildEmoji { private constructor(client: Client, data: RawGuildEmojiData, guild: GuildPreview); public guild: GuildPreview; - public roles: Snowflake[]; } export class Integration extends Base { private constructor(client: Client, data: RawIntegrationData, guild: Guild); public account: IntegrationAccount; - public application: IntegrationApplication | null; - public enabled: boolean | null; - public expireBehavior: IntegrationExpireBehavior | null; - public expireGracePeriod: number | null; - public guild: Guild; - public id: Snowflake | string; - public name: string; - public role: Role | null; - public enableEmoticons: boolean | null; - public get roles(): Collection; public scopes: OAuth2Scopes[]; - public get syncedAt(): Date | null; public syncedTimestamp: number | null; - public syncing: boolean | null; - public type: IntegrationType; - public user: User | null; - public subscriberCount: number | null; - public revoked: boolean | null; public delete(reason?: string): Promise; } @@ -2099,15 +1764,10 @@ export class Integration extends Base { export class IntegrationApplication extends Application { private constructor(client: Client, data: RawIntegrationApplicationData); public bot: User | null; - public termsOfServiceURL: string | null; - public privacyPolicyURL: string | null; - public rpcOrigins: string[]; - public cover: string | null; - public verifyKey: string | null; } @@ -2152,12 +1812,9 @@ export type RepliableInteraction = Exclude export class BaseInteraction extends Base { // This a technique used to brand different cached types. Or else we'll get `never` errors on typeguard checks. private readonly _cacheType: Cached; - protected constructor(client: Client, data: RawInteractionData); public applicationId: Snowflake; - public authorizingIntegrationOwners: APIAuthorizingIntegrationOwnersMap; - public get channel(): CacheTypeReducer< Cached, GuildTextBasedChannel | null, @@ -2166,36 +1823,22 @@ export class BaseInteraction extends Base TextBasedChannel | null >; public channelId: Snowflake | null; - public context: InteractionContextType | null; - public get createdAt(): Date; public get createdTimestamp(): number; public get guild(): CacheTypeReducer; public guildId: CacheTypeReducer; - public id: Snowflake; - public member: CacheTypeReducer; - public readonly token: string; - public type: InteractionType; - public user: User; - public version: number; - public appPermissions: Readonly; - public memberPermissions: CacheTypeReducer>; - public locale: Locale; - public guildLocale: CacheTypeReducer; - public entitlements: Collection; - public attachmentSizeLimit: number; public inGuild(): this is BaseInteraction<'cached' | 'raw'>; public inCachedGuild(): this is BaseInteraction<'cached'>; @@ -2222,37 +1865,27 @@ export class BaseInteraction extends Base export class InteractionCallback { private constructor(client: Client, data: RESTAPIInteractionCallbackObject); public activityInstanceId: string | null; - public readonly client: Client; - public get createdAt(): Date; public get createdTimestamp(): number; public id: Snowflake; - public responseMessageEphemeral: boolean | null; - public responseMessageId: Snowflake | null; - public responseMessageLoading: boolean | null; - public type: InteractionType; } export class InteractionCallbackResponse { private constructor(client: Client, data: RESTPostAPIInteractionCallbackWithResponseResult); public readonly client: Client; - public interaction: InteractionCallback; - public resource: InteractionCallbackResource | null; } export class InteractionCallbackResource { private constructor(client: Client, data: RESTAPIInteractionCallbackResourceObject); public activityInstance: RESTAPIInteractionCallbackActivityInstanceResource | null; - public message: Message | null; - public type: InteractionResponseType; } @@ -2263,19 +1896,12 @@ export class InteractionCollector exte private _handleGuildDeletion(guild: Guild): void; public channelId: Snowflake | null; - public componentType: ComponentType | null; - public guildId: Snowflake | null; - public interactionType: InteractionType | null; - public messageId: Snowflake | null; - public options: InteractionCollectorOptions; - public total: number; - public users: Collection; public collect(interaction: Interaction): Snowflake; @@ -2287,7 +1913,6 @@ export interface InteractionWebhook extends PartialWebhookFields {} export class InteractionWebhook { public constructor(client: Client, id: Snowflake, token: string); public readonly client: Client; - public token: string; public send(options: InteractionReplyOptions | MessagePayload | string): Promise; public editMessage( @@ -2300,48 +1925,31 @@ export class InteractionWebhook { export class Invite extends Base { private constructor(client: Client, data: RawInviteData); public channel: NonThreadGuildBasedChannel | PartialGroupDMChannel | null; - public channelId: Snowflake | null; - public code: string; - public get deletable(): boolean; public get createdAt(): Date | null; public createdTimestamp: number | null; - public get expiresAt(): Date | null; public get expiresTimestamp(): number | null; public guild: Guild | InviteGuild | null; - public get inviter(): User | null; public inviterId: Snowflake | null; - public maxAge: number | null; - public maxUses: number | null; - public memberCount: number; - public presenceCount: number; - public targetApplication: IntegrationApplication | null; - public targetUser: User | null; - public targetType: InviteTargetType | null; - public temporary: boolean | null; - public type: InviteType; - public get url(): string; public uses: number | null; - public delete(reason?: string): Promise; public toJSON(): unknown; public toString(): string; public static InvitesPattern: RegExp; - public guildScheduledEvent: GuildScheduledEvent | null; } @@ -2353,7 +1961,6 @@ export class InviteGuild extends AnonymousGuild { export class LimitedCollection extends Collection { public constructor(options?: LimitedCollectionOptions, iterable?: Iterable); public maxSize: number; - public keepOverLimit: ((value: Value, key: Key, collection: this) => boolean) | null; } @@ -2422,80 +2029,50 @@ export class Message extends Base { private _patch(data: RawMessageData | RawPartialMessageData): void; public activity: MessageActivity | null; - public applicationId: Snowflake | null; - public attachments: Collection; - public author: User; - public get bulkDeletable(): boolean; public get channel(): If; public channelId: Snowflake; - public get cleanContent(): string; public components: ActionRow[]; - public content: string; - public get createdAt(): Date; public createdTimestamp: number; - public get crosspostable(): boolean; public get deletable(): boolean; public get editable(): boolean; public get editedAt(): Date | null; public editedTimestamp: number | null; - public embeds: Embed[]; - public groupActivityApplication: ClientApplication | null; - public guildId: If; - public get guild(): If; public get hasThread(): boolean; public id: Snowflake; - public interactionMetadata: MessageInteractionMetadata | null; - public get member(): GuildMember | null; public mentions: MessageMentions; - public nonce: number | string | null; - public get partial(): false; public get pinnable(): boolean; public pinned: boolean; - public reactions: ReactionManager; - public stickers: Collection; - public position: number | null; - public roleSubscriptionData: RoleSubscriptionData | null; - public resolved: CommandInteractionResolvedData | null; - public system: boolean; - public get thread(): AnyThreadChannel | null; public tts: boolean; - public poll: Poll | null; - public call: MessageCall | null; - public type: MessageType; - public get url(): string; public webhookId: Snowflake | null; - public flags: Readonly; - public reference: MessageReference | null; - public messageSnapshots: Collection; public awaitMessageComponent( options?: AwaitMessageCollectorOptionsParams, @@ -2535,9 +2112,7 @@ export class Message extends Base { export class AttachmentBuilder { public constructor(attachment: BufferResolvable | Stream, data?: AttachmentData); public attachment: BufferResolvable | Stream; - public description: string | null; - public name: string | null; public get spoiler(): boolean; public setDescription(description: string): this; @@ -2551,34 +2126,20 @@ export class AttachmentBuilder { export class Attachment { private constructor(data: APIAttachment); private readonly attachment: BufferResolvable | Stream; - public contentType: string | null; - public description: string | null; - public duration: number | null; - public ephemeral: boolean; - public flags: AttachmentFlagsBitField; - public height: number | null; - public id: Snowflake; - public name: string; - public proxyURL: string; - public size: number; - public get spoiler(): boolean; public title: string | null; - public url: string; - public waveform: string | null; - public width: number | null; public toJSON(): unknown; } @@ -2596,9 +2157,7 @@ export class MessageCollector extends Collector extends BaseInteraction { protected constructor(client: Client, data: RawMessageComponentInteractionData); public type: InteractionType.MessageComponent; - public get component(): CacheTypeReducer< Cached, MessageActionRowComponent, @@ -2617,19 +2175,12 @@ export class MessageComponentInteraction e APIComponentInMessageActionRow | MessageActionRowComponent >; public componentType: MessageComponentType; - public customId: string; - public channelId: Snowflake; - public deferred: boolean; - public ephemeral: boolean | null; - public message: Message>; - public replied: boolean; - public webhook: InteractionWebhook; public inGuild(): this is MessageComponentInteraction<'cached' | 'raw'>; public inCachedGuild(): this is MessageComponentInteraction<'cached'>; @@ -2705,7 +2256,6 @@ export class MessageContextMenuCommandInteraction< Cached extends CacheType = CacheType, > extends ContextMenuCommandInteraction { public commandType: ApplicationCommandType.Message; - public options: Omit< CommandInteractionOptionResolver, | 'getAttachment' @@ -2743,42 +2293,28 @@ export class MessageMentions { repliedUser?: APIUser | User, ); private readonly _channels: Collection | null; - private readonly _content: string; - private readonly _members: Collection | null; - private readonly _parsedUsers: Collection | null; public get channels(): Collection; public readonly client: Client; - public everyone: boolean; - public readonly guild: If; - public has(data: ChannelResolvable | RoleResolvable | UserResolvable, options?: MessageMentionsHasOptions): boolean; public get members(): If>; public get parsedUsers(): Collection; public repliedUser: User | null; - public roles: Collection; - public users: Collection; - public crosspostedChannels: Collection; public toJSON(): unknown; private static readonly GlobalChannelsPattern: RegExp; - private static readonly GlobalUsersPattern: RegExp; - public static ChannelsPattern: typeof FormattingPatterns.Channel; - public static EveryonePattern: RegExp; - public static RolesPattern: typeof FormattingPatterns.Role; - public static UsersPattern: typeof FormattingPatterns.User; } @@ -2793,15 +2329,12 @@ export type MessagePayloadOption = export class MessagePayload { public constructor(target: MessageTarget, options: MessagePayloadOption); public body: RawMessagePayloadData | null; - public get isUser(): boolean; public get isWebhook(): boolean; public get isMessage(): boolean; public get isMessageManager(): boolean; public files: RawFile[] | null; - public options: MessagePayloadOption; - public target: MessageTarget; public static create( @@ -2823,20 +2356,13 @@ export class MessageReaction { private readonly _emoji: ApplicationEmoji | GuildEmoji | ReactionEmoji; public burstColors: string[] | null; - public readonly client: Client; - public count: number; - public countDetails: ReactionCountDetailsData; - public get emoji(): ApplicationEmoji | GuildEmoji | ReactionEmoji; public me: boolean; - public meBurst: boolean; - public message: Message | PartialMessage; - public get partial(): false; public users: ReactionUserManager; public react(): Promise; @@ -2878,7 +2404,6 @@ export interface ActionRowModalData { export class ModalSubmitFields { private constructor(components: readonly (readonly ModalActionRowComponent[])[]); public components: ActionRowModalData[]; - public fields: Collection; public getField(customId: string, type: Type): TextInputModalData & { type: Type }; public getField(customId: string, type?: ComponentType): TextInputModalData; @@ -2904,21 +2429,13 @@ export interface ModalMessageModalSubmitInteraction extends BaseInteraction { private constructor(client: Client, data: APIModalSubmitInteraction); public type: InteractionType.ModalSubmit; - public readonly customId: string; - public readonly components: ActionRowModalData[]; - public readonly fields: ModalSubmitFields; - public deferred: boolean; - public ephemeral: boolean | null; - public message: Message> | null; - public replied: boolean; - public readonly webhook: InteractionWebhook; public reply( options: InteractionReplyOptions & { withResponse: true }, @@ -2962,7 +2479,6 @@ export class ModalSubmitInteraction extend export class AnnouncementChannel extends BaseGuildTextChannel { public threads: GuildTextThreadManager; - public type: ChannelType.GuildAnnouncement; public addFollower(channel: TextChannelResolvable, reason?: string): Promise; } @@ -2972,7 +2488,6 @@ export type AnnouncementChannelResolvable = AnnouncementChannel | Snowflake; export class OAuth2Guild extends BaseGuild { private constructor(client: Client, data: RawOAuth2GuildData); public owner: boolean; - public permissions: Readonly; } @@ -2992,15 +2507,10 @@ export interface PartialGroupDMChannel export class PartialGroupDMChannel extends BaseChannel { private constructor(client: Client, data: RawPartialGroupDMChannelData); public type: ChannelType.GroupDM; - public flags: null; - public name: string | null; - public icon: string | null; - public recipients: PartialRecipient[]; - public ownerId: Snowflake | null; public iconURL(options?: ImageURLOptions): string | null; public fetchOwner(options?: BaseFetchOptions): Promise; @@ -3044,23 +2554,14 @@ export interface ThreadOnlyChannel > {} export abstract class ThreadOnlyChannel extends GuildChannel { public type: ChannelType.GuildForum | ChannelType.GuildMedia; - public threads: GuildForumThreadManager; - public availableTags: GuildForumTag[]; - public defaultReactionEmoji: DefaultReactionEmoji | null; - public defaultThreadRateLimitPerUser: number | null; - public rateLimitPerUser: number | null; - public defaultAutoArchiveDuration: ThreadAutoArchiveDuration | null; - public nsfw: boolean; - public topic: string | null; - public defaultSortOrder: SortOrderType | null; public setAvailableTags(tags: readonly GuildForumTagData[], reason?: string): Promise; public setDefaultReactionEmoji(emojiId: DefaultReactionEmoji | null, reason?: string): Promise; @@ -3077,7 +2578,6 @@ export abstract class ThreadOnlyChannel extends GuildChannel { export class ForumChannel extends ThreadOnlyChannel { public type: ChannelType.GuildForum; - public defaultForumLayout: ForumLayoutType; public setDefaultForumLayout(defaultForumLayout: ForumLayoutType, reason?: string): Promise; } @@ -3089,13 +2589,9 @@ export class MediaChannel extends ThreadOnlyChannel { export class PermissionOverwrites extends Base { private constructor(client: Client, data: RawPermissionOverwriteData, channel: NonThreadGuildBasedChannel); public allow: Readonly; - public readonly channel: NonThreadGuildBasedChannel; - public deny: Readonly; - public id: Snowflake; - public type: OverwriteType; public edit(options: PermissionOverwriteOptions, reason?: string): Promise; public delete(reason?: string): Promise; @@ -3117,11 +2613,8 @@ export class PermissionsBitField extends BitField { public toArray(): PermissionsString[]; public static All: bigint; - public static Default: bigint; - public static StageModerator: bigint; - public static Flags: typeof PermissionFlagsBits; public static resolve(permission?: PermissionResolvable): bigint; } @@ -3129,14 +2622,10 @@ export class PermissionsBitField extends BitField { export class Presence extends Base { protected constructor(client: Client, data?: RawPresenceData); public activities: Activity[]; - public clientStatus: ClientPresenceStatusData | null; - public guild: Guild | null; - public get member(): GuildMember | null; public status: PresenceStatus; - public get user(): User | null; public userId: Snowflake; public equals(presence: Presence): boolean; @@ -3155,24 +2644,15 @@ export class PollAnswerVoterManager extends CachedManager, data: APIPoll, message: Message, channel: TextBasedChannel); public readonly channel: TextBasedChannel; - public channelId: Snowflake; - public readonly message: Message; - public messageId: Snowflake; - public question: PollQuestionMedia; - public answers: Collection; - public expiresTimestamp: number | null; - public get expiresAt(): Date | null; public allowMultiselect: boolean; - public layoutType: PollLayoutType; - public resultsFinalized: boolean; public get partial(): false; public fetch(): Promise; @@ -3187,15 +2667,10 @@ export interface BaseFetchPollAnswerVotersOptions { export class PollAnswer extends Base { private constructor(client: Client, data: APIPollAnswer & { count?: number }, poll: Poll); private readonly _emoji: APIPartialEmoji | null; - public readonly poll: PartialPoll | Poll; - public id: number; - public text: string | null; - public voteCount: number; - public voters: PollAnswerVoterManager; public get emoji(): Emoji | GuildEmoji | null; public get partial(): false; @@ -3221,11 +2696,8 @@ export class ReactionCollector extends Collector< private _handleMessageDeletion(message: Message): void; public message: Message; - public options: ReactionCollectorOptions; - public total: number; - public users: Collection; public static key(reaction: MessageReaction): Snowflake | string; @@ -3244,13 +2716,9 @@ export class ReactionEmoji extends Emoji { export class RichPresenceAssets { private constructor(activity: Activity, assets: RawRichPresenceAssets); public readonly activity: Activity; - public largeImage: Snowflake | null; - public largeText: string | null; - public smallImage: Snowflake | null; - public smallText: string | null; public largeImageURL(options?: ImageURLOptions): string | null; public smallImageURL(options?: ImageURLOptions): string | null; @@ -3259,36 +2727,24 @@ export class RichPresenceAssets { export class Role extends Base { private constructor(client: Client, data: RawRoleData, guild: Guild); public color: number; - public get createdAt(): Date; public get createdTimestamp(): number; public get editable(): boolean; public flags: RoleFlagsBitField; - public guild: Guild; - public get hexColor(): HexColorString; public hoist: boolean; - public id: Snowflake; - public managed: boolean; - public get members(): Collection; public mentionable: boolean; - public name: string; - public permissions: Readonly; - public get position(): number; public rawPosition: number; - public tags: RoleTagData | null; - public comparePositionTo(role: RoleResolvable): number; public icon: string | null; - public unicodeEmoji: string | null; public delete(reason?: string): Promise; public edit(options: RoleEditOptions): Promise; @@ -3329,7 +2785,6 @@ export class StringSelectMenuInteraction< APIStringSelectComponent | StringSelectMenuComponent >; public componentType: ComponentType.StringSelect; - public values: string[]; public inGuild(): this is StringSelectMenuInteraction<'cached' | 'raw'>; public inCachedGuild(): this is StringSelectMenuInteraction<'cached'>; @@ -3348,11 +2803,8 @@ export class UserSelectMenuInteraction< APIUserSelectComponent | UserSelectMenuComponent >; public componentType: ComponentType.UserSelect; - public values: Snowflake[]; - public users: Collection; - public members: Collection< Snowflake, CacheTypeReducer @@ -3374,9 +2826,7 @@ export class RoleSelectMenuInteraction< APIRoleSelectComponent | RoleSelectMenuComponent >; public componentType: ComponentType.RoleSelect; - public values: Snowflake[]; - public roles: Collection>; public inGuild(): this is RoleSelectMenuInteraction<'cached' | 'raw'>; public inCachedGuild(): this is RoleSelectMenuInteraction<'cached'>; @@ -3395,16 +2845,12 @@ export class MentionableSelectMenuInteraction< APIMentionableSelectComponent | MentionableSelectMenuComponent >; public componentType: ComponentType.MentionableSelect; - public values: Snowflake[]; - public users: Collection; - public members: Collection< Snowflake, CacheTypeReducer >; - public roles: Collection>; public inGuild(): this is MentionableSelectMenuInteraction<'cached' | 'raw'>; public inCachedGuild(): this is MentionableSelectMenuInteraction<'cached'>; @@ -3423,9 +2869,7 @@ export class ChannelSelectMenuInteraction< APIChannelSelectComponent | ChannelSelectMenuComponent >; public componentType: ComponentType.ChannelSelect; - public values: Snowflake[]; - public channels: Collection< Snowflake, CacheTypeReducer @@ -3458,9 +2902,7 @@ export interface ShardEventTypes { export class Shard extends AsyncEventEmitter { private constructor(manager: ShardingManager, id: number); private readonly _evals: Map>; - private readonly _exitListener: (...args: any[]) => void; - private readonly _fetches: Map>; private _handleExit(respawn?: boolean, timeout?: number): void; private _handleMessage(message: unknown): void; @@ -3468,21 +2910,13 @@ export class Shard extends AsyncEventEmitter { private decrementMaxListeners(emitter: ChildProcess | Worker): void; public args: string[]; - public execArgv: string[]; - public env: unknown; - public id: number; - public manager: ShardingManager; - public process: ChildProcess | null; - public ready: boolean; - public silent: boolean; - public worker: Worker | null; public eval(script: string): Promise; public eval(fn: (client: Client) => Result): Promise; @@ -3505,9 +2939,7 @@ export class ShardClientUtil { private decrementMaxListeners(emitter: ChildProcess | Worker): void; public client: Client; - public mode: ShardingManagerMode; - public parentPort: MessagePort | null; public broadcastEval(fn: (client: Client) => Awaitable): Promise[]>; public broadcastEval( @@ -3541,19 +2973,12 @@ export class ShardingManager extends AsyncEventEmitter; public file: string; - public respawn: boolean; - public silent: boolean; - public shardArgs: string[]; - public shards: Collection; - public token: string | null; - public totalShards: number | 'auto'; - public shardList: number[] | 'auto'; public broadcast(message: unknown): Promise; public broadcastEval(fn: (client: Client) => Awaitable): Promise[]>; @@ -3590,15 +3015,10 @@ export { export class SKU extends Base { private constructor(client: Client, data: APISKU); public id: Snowflake; - public type: SKUType; - public applicationId: Snowflake; - public name: string; - public slug: string; - public flags: Readonly; } @@ -3612,23 +3032,14 @@ export class SKUFlagsBitField extends BitField { export class Subscription extends Base { private constructor(client: Client, data: APISubscription); public id: Snowflake; - public userId: Snowflake; - public skuIds: Snowflake[]; - public entitlementIds: Snowflake[]; - public renewalSkuIds: Snowflake[] | null; - public currentPeriodStartTimestamp: number; - public currentPeriodEndTimestamp: number; - public status: SubscriptionStatus; - public canceledTimestamp: number | null; - public country: string | null; public get canceledAt(): Date | null; public get currentPeriodStartAt(): Date; @@ -3638,7 +3049,6 @@ export class Subscription extends Base { export class StageChannel extends BaseGuildVoiceChannel { public get stageInstance(): StageInstance | null; public topic: string | null; - public type: ChannelType.GuildStageVoice; public createStageInstance(options: StageInstanceCreateOptions): Promise; public setTopic(topic: string): Promise; @@ -3646,11 +3056,8 @@ export class StageChannel extends BaseGuildVoiceChannel { export class DirectoryChannel extends BaseChannel { public flags: Readonly; - public guild: InviteGuild; - public guildId: Snowflake; - public name: string; public toString(): ChannelMention; } @@ -3658,15 +3065,10 @@ export class DirectoryChannel extends BaseChannel { export class StageInstance extends Base { private constructor(client: Client, data: RawStageInstanceData, channel: StageChannel); public id: Snowflake; - public guildId: Snowflake; - public channelId: Snowflake; - public topic: string; - public privacyLevel: StageInstancePrivacyLevel; - public guildScheduledEventId?: Snowflake; public get channel(): StageChannel | null; public get guild(): Guild | null; @@ -3683,27 +3085,17 @@ export class Sticker extends Base { public get createdTimestamp(): number; public get createdAt(): Date; public available: boolean | null; - public description: string | null; - public format: StickerFormatType; - public get guild(): Guild | null; public guildId: Snowflake | null; - public id: Snowflake; - public name: string; - public packId: Snowflake | null; - public get partial(): boolean; public sortValue: number | null; - public tags: string | null; - public type: StickerType | null; - public user: User | null; public get url(): string; public fetch(): Promise; @@ -3719,18 +3111,12 @@ export class StickerPack extends Base { public get createdTimestamp(): number; public get createdAt(): Date; public bannerId: Snowflake | null; - public get coverSticker(): Sticker | null; public coverStickerId: Snowflake | null; - public description: string; - public id: Snowflake; - public name: string; - public skuId: Snowflake; - public stickers: Collection; public bannerURL(options?: ImageURLOptions): string | null; } @@ -3738,9 +3124,7 @@ export class StickerPack extends Base { export class Sweepers { public constructor(client: Client, options: SweeperOptions); public readonly client: Client; - public intervals: Record; - public options: SweeperOptions; public sweepApplicationCommands( @@ -3820,13 +3204,9 @@ export class SystemChannelFlagsBitField extends BitField, data: RawTeamData); public id: Snowflake; - public name: string; - public icon: string | null; - public ownerId: Snowflake | null; - public members: Collection; public get owner(): TeamMember | null; public get createdAt(): Date; @@ -3840,12 +3220,9 @@ export class Team extends Base { export class TeamMember extends Base { private constructor(team: Team, data: RawTeamMemberData); public team: Team; - public get id(): Snowflake; public membershipState: TeamMemberMembershipState; - public user: User; - public role: TeamMemberRole; public toString(): UserMention; @@ -3853,9 +3230,7 @@ export class TeamMember extends Base { export class TextChannel extends BaseGuildTextChannel { public rateLimitPerUser: number; - public threads: GuildTextThreadManager; - public type: ChannelType.GuildText; } @@ -3878,52 +3253,34 @@ export interface ThreadChannel export class ThreadChannel extends BaseChannel { private constructor(guild: Guild, data?: RawThreadChannelData, client?: Client); public archived: boolean | null; - public get archivedAt(): Date | null; public archiveTimestamp: number | null; - public get createdAt(): Date | null; private readonly _createdTimestamp: number | null; - public get createdTimestamp(): number | null; public autoArchiveDuration: ThreadAutoArchiveDuration | null; - public get editable(): boolean; public flags: Readonly; - public guild: Guild; - public guildId: Snowflake; - public get guildMembers(): Collection; public invitable: boolean | null; - public get joinable(): boolean; public get joined(): boolean; public locked: boolean | null; - public get manageable(): boolean; public get viewable(): boolean; public get sendable(): boolean; public memberCount: number | null; - public messageCount: number | null; - public appliedTags: Snowflake[]; - public totalMessageSent: number | null; - public members: ThreadMemberManager; - public name: string; - public ownerId: Snowflake; - public get parent(): If | null; public parentId: Snowflake | null; - public rateLimitPerUser: number | null; - public type: ThreadChannelType; public get unarchivable(): boolean; public delete(reason?: string): Promise; @@ -3952,15 +3309,11 @@ export class ThreadChannel extends BaseCha export class ThreadMember extends Base { private constructor(thread: ThreadChannel, data: RawThreadMemberData, extra?: unknown); public flags: ThreadMemberFlagsBitField; - private readonly member: If; - public get guildMember(): HasMemberData extends true ? GuildMember : GuildMember | null; public id: Snowflake; - public get joinedAt(): Date | null; public joinedTimestamp: number | null; - public get manageable(): boolean; public thread: AnyThreadChannel; public get user(): User | null; @@ -3978,9 +3331,7 @@ export class ThreadMemberFlagsBitField extends BitField export class Typing extends Base { private constructor(channel: TextBasedChannel, user: PartialUser, data?: RawTypingData); public channel: TextBasedChannel; - public user: PartialUser | User; - public startedTimestamp: number; public get startedAt(): Date; public get guild(): Guild | null; @@ -4002,32 +3353,22 @@ export class User extends Base { private _equals(user: APIUser): boolean; public accentColor: number | null | undefined; - public avatar: string | null; - public avatarDecorationData: AvatarDecorationData | null; - public banner: string | null | undefined; - public bot: boolean; - public get createdAt(): Date; public get createdTimestamp(): number; public discriminator: string; - public get displayName(): string; public get defaultAvatarURL(): string; public get dmChannel(): DMChannel | null; public flags: Readonly | null; - public globalName: string | null; - public get hexAccentColor(): HexColorString | null | undefined; public id: Snowflake; - public get partial(): false; public system: boolean; - public get tag(): string; public username: string; public avatarURL(options?: ImageURLOptions): string | null; @@ -4045,7 +3386,6 @@ export class UserContextMenuCommandInteraction< Cached extends CacheType = CacheType, > extends ContextMenuCommandInteraction { public commandType: ApplicationCommandType.User; - public options: Omit< CommandInteractionOptionResolver, | 'getAttachment' @@ -4099,7 +3439,8 @@ export function makePlainError(err: Error): MakeErrorOptions; * @internal */ export function moveElementInArray( - array: readonly unknown[], + // eslint-disable-next-line no-restricted-syntax + array: unknown[], element: unknown, newIndex: number, offset?: boolean, @@ -4171,19 +3512,12 @@ export class VoiceChannel extends BaseGuildVoiceChannel { export class VoiceChannelEffect { private constructor(data: GatewayVoiceChannelEffectSendDispatchData, guild: Guild); public guild: Guild; - public channelId: Snowflake; - public userId: Snowflake; - public emoji: Emoji | null; - public animationType: VoiceChannelEffectSendAnimationType | null; - public animationId: number | null; - public soundId: Snowflake | number | null; - public soundVolume: number | null; public get channel(): VoiceChannel | null; public get soundboardSound(): GuildSoundboardSound | null; @@ -4192,13 +3526,9 @@ export class VoiceChannelEffect { export class VoiceRegion { private constructor(data: RawVoiceRegionData); public custom: boolean; - public deprecated: boolean; - public id: string; - public name: string; - public optimal: boolean; public toJSON(): unknown; } @@ -4207,30 +3537,19 @@ export class VoiceState extends Base { private constructor(guild: Guild, data: RawVoiceStateData); public get channel(): VoiceBasedChannel | null; public channelId: Snowflake | null; - public get deaf(): boolean | null; public guild: Guild; - public id: Snowflake; - public get member(): GuildMember | null; public get mute(): boolean | null; public selfDeaf: boolean | null; - public selfMute: boolean | null; - public serverDeaf: boolean | null; - public serverMute: boolean | null; - public sessionId: string | null; - public streaming: boolean | null; - public selfVideo: boolean | null; - public suppress: boolean | null; - public requestToSpeakTimestamp: number | null; public setDeaf(deaf?: boolean, reason?: string): Promise; @@ -4247,30 +3566,20 @@ export interface Webhook extends Webhook export class Webhook { private constructor(client: Client, data?: RawWebhookData); public avatar: string | null; - public avatarURL(options?: ImageURLOptions): string | null; public channelId: Snowflake; - public readonly client: Client; - public guildId: Snowflake; - public name: string; - public owner: Type extends WebhookType.Incoming ? APIUser | User | null : APIUser | User; - public sourceGuild: Type extends WebhookType.ChannelFollower ? APIPartialGuild | Guild : null; - public sourceChannel: Type extends WebhookType.ChannelFollower ? AnnouncementChannel | APIPartialChannel : null; - public token: Type extends WebhookType.Incoming ? string : Type extends WebhookType.ChannelFollower ? null : string | null; - public type: Type; - public applicationId: Type extends WebhookType.Application ? Snowflake : null; public get channel(): | AnnouncementChannel @@ -4299,9 +3608,7 @@ export interface WebhookClient extends WebhookFields, BaseClient<{}> {} export class WebhookClient extends BaseClient<{}> { public constructor(data: WebhookClientData, options?: WebhookClientOptions); public readonly client: this; - public options: WebhookClientOptions; - public token: string; public editMessage( message: MessageResolvable, @@ -4317,44 +3624,27 @@ export class Widget extends Base { public fetch(): Promise; public imageURL(style?: GuildWidgetStyle): string; public id: Snowflake; - public name: string; - public instantInvite?: string; - public channels: Collection; - public members: Collection; - public presenceCount: number; } export class WidgetMember extends Base { private constructor(client: Client, data: RawWidgetMemberData); public id: string; - public username: string; - public discriminator: string; - public avatar: string | null; - public status: PresenceStatus; - public deaf: boolean | null; - public mute: boolean | null; - public selfDeaf: boolean | null; - public selfMute: boolean | null; - public suppress: boolean | null; - public channelId: Snowflake | null; - public avatarURL: string; - public activity: WidgetActivity | null; } @@ -4363,17 +3653,11 @@ export type SoundboardSoundResolvable = Snowflake | SoundboardSound | string; export class SoundboardSound extends Base { private constructor(client: Client, data: APISoundboardSound); public name: string; - public soundId: Snowflake | string; - public volume: number; - private readonly _emoji: Omit | null; - public guildId: Snowflake | null; - public available: boolean; - public user: User | null; public get createdAt(): Date; public get createdTimestamp(): number; @@ -4391,11 +3675,8 @@ export type GuildSoundboardSound = SoundboardSound & { get guild(): Guild; guild export class WelcomeChannel extends Base { private constructor(guild: Guild, data: RawWelcomeChannelData); private readonly _emoji: Omit; - public channelId: Snowflake; - public guild: Guild | InviteGuild; - public description: string; public get channel(): AnnouncementChannel | ForumChannel | MediaChannel | TextChannel | null; public get emoji(): Emoji | GuildEmoji; @@ -4405,9 +3686,7 @@ export class WelcomeScreen extends Base { private constructor(guild: Guild, data: RawWelcomeScreenData); public get enabled(): boolean; public guild: Guild | InviteGuild; - public description: string | null; - public welcomeChannels: Collection; } @@ -4477,6 +3756,7 @@ export enum DiscordjsErrorCodes { FetchBanResolveId = 'FetchBanResolveId', FetchGroupDMChannel = 'FetchGroupDMChannel', + FetchOwnerId = 'FetchOwnerId', FileNotFound = 'FileNotFound', @@ -4559,13 +3839,16 @@ export enum DiscordjsErrorCodes { TokenInvalid = 'TokenInvalid', TokenMissing = 'TokenMissing', + UserNoDMChannel = 'UserNoDMChannel', VoiceNotStageChannel = 'VoiceNotStageChannel', VoiceStateInvalidType = 'VoiceStateInvalidType', VoiceStateNotOwn = 'VoiceStateNotOwn', + WebhookApplication = 'WebhookApplication', + WebhookMessage = 'WebhookMessage', WebhookTokenUnavailable = 'WebhookTokenUnavailable', @@ -4675,9 +3958,7 @@ export class ApplicationCommandPermissionsManager< private readonly manager: ApplicationCommand | ApplicationCommandManager | GuildApplicationCommandManager; public commandId: CommandIdType; - public guild: GuildType; - public guildId: Snowflake | null; public add( options: EditApplicationCommandPermissionsMixin & FetchSingleOptions, @@ -4893,7 +4174,6 @@ export class GuildEmojiManager extends CachedManager { private constructor(emoji: GuildEmoji); public emoji: GuildEmoji; - public guild: Guild; public add( roleOrRoles: ReadonlyCollection | RoleResolvable | readonly RoleResolvable[], @@ -5058,7 +4338,6 @@ export class GuildMemberRoleManager extends DataManager { - answers: ReadonlyCollection; + // eslint-disable-next-line no-restricted-syntax + answers: Collection; message: PartialMessage; question: { text: null }; } From 0f1a7633d110fbe3d078ecc00d4121b1dcb408e7 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 16:13:34 +0200 Subject: [PATCH 22/38] chore: code review --- packages/discord.js/src/errors/ErrorCodes.js | 41 +++++++++++++++++++- packages/discord.js/src/errors/Messages.js | 2 +- packages/discord.js/src/sharding/Shard.js | 2 +- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/packages/discord.js/src/errors/ErrorCodes.js b/packages/discord.js/src/errors/ErrorCodes.js index 2e61da8c6188..1ac26a94611b 100644 --- a/packages/discord.js/src/errors/ErrorCodes.js +++ b/packages/discord.js/src/errors/ErrorCodes.js @@ -1,4 +1,4 @@ -/* eslint-disable jsdoc/require-property-description */ +/* eslint-disable jsdoc/tag-lines, jsdoc/require-property-description */ 'use strict'; /** @@ -7,10 +7,13 @@ * @property {'ClientInvalidProvidedShards'} ClientInvalidProvidedShards * @property {'ClientMissingIntents'} ClientMissingIntents * @property {'ClientNotReady'} ClientNotReady + * * @property {'TokenInvalid'} TokenInvalid * @property {'TokenMissing'} TokenMissing * @property {'ApplicationCommandPermissionsTokenMissing'} ApplicationCommandPermissionsTokenMissing + * * @property {'BitFieldInvalid'} BitFieldInvalid + * * @property {'ShardingNoShards'} ShardingNoShards * @property {'ShardingInProcess'} ShardingInProcess * @property {'ShardingInvalidEvalBroadcast'} ShardingInvalidEvalBroadcast @@ -23,23 +26,35 @@ * @property {'ShardingReadyDied'} ShardingReadyDied * @property {'ShardingNoChildExists'} ShardingNoChildExists * @property {'ShardingShardMiscalculation'} ShardingShardMiscalculation + * * @property {'ColorRange'} ColorRange * @property {'ColorConvert'} ColorConvert + * * @property {'InviteOptionsMissingChannel'} InviteOptionsMissingChannel + * * @property {'InteractionCollectorError'} InteractionCollectorError + * * @property {'FileNotFound'} FileNotFound + * * @property {'UserNoDMChannel'} UserNoDMChannel + * * @property {'VoiceNotStageChannel'} VoiceNotStageChannel + * * @property {'VoiceStateNotOwn'} VoiceStateNotOwn * @property {'VoiceStateInvalidType'} VoiceStateInvalidType + * * @property {'ReqResourceType'} ReqResourceType + * * @property {'MessageBulkDeleteType'} MessageBulkDeleteType * @property {'MessageContentType'} MessageContentType * @property {'MessageNonceRequired'} MessageNonceRequired * @property {'MessageNonceType'} MessageNonceType + * * @property {'BanResolveId'} BanResolveId * @property {'FetchBanResolveId'} FetchBanResolveId + * * @property {'PruneDaysType'} PruneDaysType + * * @property {'GuildChannelResolve'} GuildChannelResolve * @property {'GuildVoiceChannelResolve'} GuildVoiceChannelResolve * @property {'GuildChannelOrphan'} GuildChannelOrphan @@ -52,32 +67,45 @@ * @property {'StageChannelResolve'} StageChannelResolve * @property {'GuildScheduledEventResolve'} GuildScheduledEventResolve * @property {'FetchOwnerId'} FetchOwnerId + * * @property {'InvalidType'} InvalidType * @property {'InvalidElement'} InvalidElement + * * @property {'MessageThreadParent'} MessageThreadParent * @property {'MessageExistingThread'} MessageExistingThread * @property {'ThreadInvitableType'} ThreadInvitableType * @property {'NotAThreadOfParent'} NotAThreadOfParent + * * @property {'WebhookMessage'} WebhookMessage * @property {'WebhookTokenUnavailable'} WebhookTokenUnavailable * @property {'WebhookURLInvalid'} WebhookURLInvalid * @property {'WebhookApplication'} WebhookApplication + * * @property {'MessageReferenceMissing'} MessageReferenceMissing + * * @property {'EmojiType'} EmojiType * @property {'EmojiManaged'} EmojiManaged * @property {'MissingManageGuildExpressionsPermission'} MissingManageGuildExpressionsPermission + * * @property {'NotGuildSoundboardSound'} NotGuildSoundboardSound * @property {'NotGuildSticker'} NotGuildSticker + * * @property {'ReactionResolveUser'} ReactionResolveUser + * * @property {'InviteResolveCode'} InviteResolveCode * @property {'InviteNotFound'} InviteNotFound + * * @property {'DeleteGroupDMChannel'} DeleteGroupDMChannel * @property {'FetchGroupDMChannel'} FetchGroupDMChannel + * * @property {'MemberFetchNonceLength'} MemberFetchNonceLength + * * @property {'GlobalCommandPermissions'} GlobalCommandPermissions * @property {'GuildUncachedEntityResolve'} GuildUncachedEntityResolve + * * @property {'InteractionAlreadyReplied'} InteractionAlreadyReplied * @property {'InteractionNotReplied'} InteractionNotReplied + * * @property {'CommandInteractionOptionNotFound'} CommandInteractionOptionNotFound * @property {'CommandInteractionOptionType'} CommandInteractionOptionType * @property {'CommandInteractionOptionEmpty'} CommandInteractionOptionEmpty @@ -85,16 +113,25 @@ * @property {'CommandInteractionOptionNoSubcommandGroup'} CommandInteractionOptionNoSubcommandGroup * @property {'CommandInteractionOptionInvalidChannelType'} CommandInteractionOptionInvalidChannelType * @property {'AutocompleteInteractionOptionNoFocusedOption'} AutocompleteInteractionOptionNoFocusedOption + * * @property {'ModalSubmitInteractionFieldNotFound'} ModalSubmitInteractionFieldNotFound * @property {'ModalSubmitInteractionFieldType'} ModalSubmitInteractionFieldType + * * @property {'InvalidMissingScopes'} InvalidMissingScopes * @property {'InvalidScopesWithPermissions'} InvalidScopesWithPermissions + * * @property {'NotImplemented'} NotImplemented + * * @property {'GuildForumMessageRequired'} GuildForumMessageRequired + * * @property {'SweepFilterReturn'} SweepFilterReturn + * * @property {'EntitlementCreateInvalidOwner'} EntitlementCreateInvalidOwner + * * @property {'BulkBanUsersOptionEmpty'} BulkBanUsersOptionEmpty + * * @property {'PollAlreadyExpired'} PollAlreadyExpired + * * @property {'PermissionOverwritesTypeMandatory'} PermissionOverwritesTypeMandatory * @property {'PermissionOverwritesTypeMismatch'} PermissionOverwritesTypeMismatch */ @@ -177,6 +214,7 @@ const keys = [ 'WebhookTokenUnavailable', 'WebhookURLInvalid', 'WebhookApplication', + 'MessageReferenceMissing', 'EmojiType', @@ -189,7 +227,6 @@ const keys = [ 'ReactionResolveUser', 'InviteResolveCode', - 'InviteNotFound', 'DeleteGroupDMChannel', diff --git a/packages/discord.js/src/errors/Messages.js b/packages/discord.js/src/errors/Messages.js index 7c40bcd0f145..1b00d3a4fdd4 100644 --- a/packages/discord.js/src/errors/Messages.js +++ b/packages/discord.js/src/errors/Messages.js @@ -85,6 +85,7 @@ const Messages = { [ErrorCodes.WebhookTokenUnavailable]: 'This action requires a webhook token, but none is available.', [ErrorCodes.WebhookURLInvalid]: 'The provided webhook URL is not valid.', [ErrorCodes.WebhookApplication]: 'This message webhook belongs to an application and cannot be fetched.', + [ErrorCodes.MessageReferenceMissing]: 'The message does not reference another message', [ErrorCodes.EmojiType]: 'Emoji must be a string or GuildEmoji/ReactionEmoji', @@ -99,7 +100,6 @@ const Messages = { [ErrorCodes.ReactionResolveUser]: "Couldn't resolve the user id to remove from the reaction.", [ErrorCodes.InviteResolveCode]: 'Could not resolve the code to fetch the invite.', - [ErrorCodes.InviteNotFound]: 'Could not find the requested invite.', [ErrorCodes.DeleteGroupDMChannel]: "Bots don't have access to Group DM Channels and cannot delete them", diff --git a/packages/discord.js/src/sharding/Shard.js b/packages/discord.js/src/sharding/Shard.js index b3f595fad2d8..3b1a6a03d57d 100644 --- a/packages/discord.js/src/sharding/Shard.js +++ b/packages/discord.js/src/sharding/Shard.js @@ -33,7 +33,7 @@ class Shard extends AsyncEventEmitter { Worker = require('node:worker_threads').Worker; break; default: - break; + throw new Error(`Invalid sharding mode in Shard ${id}`); } /** From ee2462402a3427a3ae65a01ed92c391109dd45b7 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 16:31:03 +0200 Subject: [PATCH 23/38] fix: consistent spacing in typings --- packages/discord.js/typings/index.d.ts | 36 -------------------------- 1 file changed, 36 deletions(-) diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index e836fadd57da..045eab4c3583 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -3732,13 +3732,10 @@ export enum DiscordjsErrorCodes { AutocompleteInteractionOptionNoFocusedOption = 'AutocompleteInteractionOptionNoFocusedOption', BanResolveId = 'BanResolveId', BitFieldInvalid = 'BitFieldInvalid', - BulkBanUsersOptionEmpty = 'BulkBanUsersOptionEmpty', ChannelNotCached = 'ChannelNotCached', ClientInvalidOption = 'ClientInvalidOption', - ClientInvalidProvidedShards = 'ClientInvalidProvidedShards', - ClientMissingIntents = 'ClientMissingIntents', ClientNotReady = 'ClientNotReady', ColorConvert = 'ColorConvert', @@ -3751,35 +3748,23 @@ export enum DiscordjsErrorCodes { DeleteGroupDMChannel = 'DeleteGroupDMChannel', EmojiManaged = 'EmojiManaged', EmojiType = 'EmojiType', - EntitlementCreateInvalidOwner = 'EntitlementCreateInvalidOwner', FetchBanResolveId = 'FetchBanResolveId', - FetchGroupDMChannel = 'FetchGroupDMChannel', - FetchOwnerId = 'FetchOwnerId', - FileNotFound = 'FileNotFound', - GlobalCommandPermissions = 'GlobalCommandPermissions', - GuildChannelOrphan = 'GuildChannelOrphan', - GuildChannelResolve = 'GuildChannelResolve', GuildChannelUnowned = 'GuildChannelUnowned', - GuildForumMessageRequired = 'GuildForumMessageRequired', - GuildMembersTimeout = 'GuildMembersTimeout', GuildOwned = 'GuildOwned', GuildScheduledEventResolve = 'GuildScheduledEventResolve', GuildSoundboardSoundsTimeout = 'GuildSoundboardSoundsTimeout', - GuildUncachedEntityResolve = 'GuildUncachedEntityResolve', GuildUncachedMe = 'GuildUncachedMe', - GuildVoiceChannelResolve = 'GuildVoiceChannelResolve', - InteractionAlreadyReplied = 'InteractionAlreadyReplied', InteractionCollectorError = 'InteractionCollectorError', InteractionNotReplied = 'InteractionNotReplied', @@ -3792,67 +3777,46 @@ export enum DiscordjsErrorCodes { InviteResolveCode = 'InviteResolveCode', MemberFetchNonceLength = 'MemberFetchNonceLength', MessageBulkDeleteType = 'MessageBulkDeleteType', - MessageContentType = 'MessageContentType', MessageExistingThread = 'MessageExistingThread', - MessageNonceRequired = 'MessageNonceRequired', MessageNonceType = 'MessageNonceType', MessageReferenceMissing = 'MessageReferenceMissing', - MessageThreadParent = 'MessageThreadParent', MissingManageGuildExpressionsPermission = 'MissingManageGuildExpressionsPermission', ModalSubmitInteractionFieldNotFound = 'ModalSubmitInteractionFieldNotFound', ModalSubmitInteractionFieldType = 'ModalSubmitInteractionFieldType', NotGuildSoundboardSound = 'NotGuildSoundboardSound', - NotGuildSticker = 'NotGuildSticker', NotImplemented = 'NotImplemented', PollAlreadyExpired = 'PollAlreadyExpired', - PruneDaysType = 'PruneDaysType', ReactionResolveUser = 'ReactionResolveUser', - ReqResourceType = 'ReqResourceType', - ShardingAlreadySpawned = 'ShardingAlreadySpawned', - ShardingInProcess = 'ShardingInProcess', - ShardingInvalidEvalBroadcast = 'ShardingInvalidEvalBroadcast', ShardingNoChildExists = 'ShardingNoChildExists', - ShardingNoShards = 'ShardingNoShards', - ShardingProcessExists = 'ShardingProcessExists', ShardingReadyDied = 'ShardingReadyDied', - ShardingReadyDisconnected = 'ShardingReadyDisconnected', ShardingReadyTimeout = 'ShardingReadyTimeout', - ShardingShardMiscalculation = 'ShardingShardMiscalculation', ShardingShardNotFound = 'ShardingShardNotFound', ShardingWorkerExists = 'ShardingWorkerExists', StageChannelResolve = 'StageChannelResolve', SweepFilterReturn = 'SweepFilterReturn', ThreadInvitableType = 'ThreadInvitableType', - TokenInvalid = 'TokenInvalid', TokenMissing = 'TokenMissing', - UserNoDMChannel = 'UserNoDMChannel', VoiceNotStageChannel = 'VoiceNotStageChannel', - VoiceStateInvalidType = 'VoiceStateInvalidType', - VoiceStateNotOwn = 'VoiceStateNotOwn', - WebhookApplication = 'WebhookApplication', - WebhookMessage = 'WebhookMessage', - WebhookTokenUnavailable = 'WebhookTokenUnavailable', - WebhookURLInvalid = 'WebhookURLInvalid', } From 23c5e7b26619814a73889629a8d1238f1fc2a479 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 16:57:44 +0200 Subject: [PATCH 24/38] fix: tests --- packages/discord.js/typings/index.test-d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/discord.js/typings/index.test-d.ts b/packages/discord.js/typings/index.test-d.ts index 3e5003d3bcf3..8466b8212cdb 100644 --- a/packages/discord.js/typings/index.test-d.ts +++ b/packages/discord.js/typings/index.test-d.ts @@ -2777,7 +2777,7 @@ declare const partialPoll: PartialPoll; expectType(partialPoll.allowMultiselect); expectType(partialPoll.layoutType); expectType(partialPoll.expiresTimestamp); - expectType>(partialPoll.answers); + expectType>(partialPoll.answers); } } From 5b56c4fc562419d017b53dcce07a151149235880 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 17:16:05 +0200 Subject: [PATCH 25/38] fix: unsort ErrorCodes --- packages/discord.js/typings/index.d.ts | 180 +++++++++++++++---------- 1 file changed, 109 insertions(+), 71 deletions(-) diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index 045eab4c3583..8da8fd42058e 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -3727,98 +3727,136 @@ export const version: string; // #endregion // #region Errors +/* eslint-disable typescript-sort-keys/string-enum */ export enum DiscordjsErrorCodes { - ApplicationCommandPermissionsTokenMissing = 'ApplicationCommandPermissionsTokenMissing', - AutocompleteInteractionOptionNoFocusedOption = 'AutocompleteInteractionOptionNoFocusedOption', - BanResolveId = 'BanResolveId', - BitFieldInvalid = 'BitFieldInvalid', - BulkBanUsersOptionEmpty = 'BulkBanUsersOptionEmpty', - ChannelNotCached = 'ChannelNotCached', ClientInvalidOption = 'ClientInvalidOption', ClientInvalidProvidedShards = 'ClientInvalidProvidedShards', ClientMissingIntents = 'ClientMissingIntents', ClientNotReady = 'ClientNotReady', - ColorConvert = 'ColorConvert', + + TokenInvalid = 'TokenInvalid', + TokenMissing = 'TokenMissing', + ApplicationCommandPermissionsTokenMissing = 'ApplicationCommandPermissionsTokenMissing', + + BitFieldInvalid = 'BitFieldInvalid', + + ShardingNoShards = 'ShardingNoShards', + ShardingInProcess = 'ShardingInProcess', + ShardingInvalidEvalBroadcast = 'ShardingInvalidEvalBroadcast', + ShardingShardNotFound = 'ShardingShardNotFound', + ShardingAlreadySpawned = 'ShardingAlreadySpawned', + ShardingProcessExists = 'ShardingProcessExists', + ShardingWorkerExists = 'ShardingWorkerExists', + ShardingReadyTimeout = 'ShardingReadyTimeout', + ShardingReadyDisconnected = 'ShardingReadyDisconnected', + ShardingReadyDied = 'ShardingReadyDied', + ShardingNoChildExists = 'ShardingNoChildExists', + ShardingShardMiscalculation = 'ShardingShardMiscalculation', + ColorRange = 'ColorRange', - CommandInteractionOptionEmpty = 'CommandInteractionOptionEmpty', - CommandInteractionOptionNoSubcommand = 'CommandInteractionOptionNoSubcommand', - CommandInteractionOptionNoSubcommandGroup = 'CommandInteractionOptionNoSubcommandGroup', - CommandInteractionOptionNotFound = 'CommandInteractionOptionNotFound', - CommandInteractionOptionType = 'CommandInteractionOptionType', - DeleteGroupDMChannel = 'DeleteGroupDMChannel', - EmojiManaged = 'EmojiManaged', - EmojiType = 'EmojiType', - EntitlementCreateInvalidOwner = 'EntitlementCreateInvalidOwner', - FetchBanResolveId = 'FetchBanResolveId', - FetchGroupDMChannel = 'FetchGroupDMChannel', - FetchOwnerId = 'FetchOwnerId', + ColorConvert = 'ColorConvert', + + InviteOptionsMissingChannel = 'InviteOptionsMissingChannel', + + InteractionCollectorError = 'InteractionCollectorError', + FileNotFound = 'FileNotFound', - GlobalCommandPermissions = 'GlobalCommandPermissions', - GuildChannelOrphan = 'GuildChannelOrphan', + + UserNoDMChannel = 'UserNoDMChannel', + + VoiceNotStageChannel = 'VoiceNotStageChannel', + + VoiceStateNotOwn = 'VoiceStateNotOwn', + VoiceStateInvalidType = 'VoiceStateInvalidType', + + ReqResourceType = 'ReqResourceType', + + MessageBulkDeleteType = 'MessageBulkDeleteType', + MessageContentType = 'MessageContentType', + MessageNonceRequired = 'MessageNonceRequired', + MessageNonceType = 'MessageNonceType', + + BanResolveId = 'BanResolveId', + FetchBanResolveId = 'FetchBanResolveId', + + PruneDaysType = 'PruneDaysType', + GuildChannelResolve = 'GuildChannelResolve', + GuildVoiceChannelResolve = 'GuildVoiceChannelResolve', + GuildChannelOrphan = 'GuildChannelOrphan', GuildChannelUnowned = 'GuildChannelUnowned', - GuildForumMessageRequired = 'GuildForumMessageRequired', - GuildMembersTimeout = 'GuildMembersTimeout', GuildOwned = 'GuildOwned', - GuildScheduledEventResolve = 'GuildScheduledEventResolve', + GuildMembersTimeout = 'GuildMembersTimeout', GuildSoundboardSoundsTimeout = 'GuildSoundboardSoundsTimeout', - GuildUncachedEntityResolve = 'GuildUncachedEntityResolve', GuildUncachedMe = 'GuildUncachedMe', - GuildVoiceChannelResolve = 'GuildVoiceChannelResolve', - InteractionAlreadyReplied = 'InteractionAlreadyReplied', - InteractionCollectorError = 'InteractionCollectorError', - InteractionNotReplied = 'InteractionNotReplied', - InvalidElement = 'InvalidElement', - InvalidMissingScopes = 'InvalidMissingScopes', - InvalidScopesWithPermissions = 'InvalidScopesWithPermissions', + ChannelNotCached = 'ChannelNotCached', + StageChannelResolve = 'StageChannelResolve', + GuildScheduledEventResolve = 'GuildScheduledEventResolve', + FetchOwnerId = 'FetchOwnerId', + InvalidType = 'InvalidType', - InviteNotFound = 'InviteNotFound', - InviteOptionsMissingChannel = 'InviteOptionsMissingChannel', - InviteResolveCode = 'InviteResolveCode', - MemberFetchNonceLength = 'MemberFetchNonceLength', - MessageBulkDeleteType = 'MessageBulkDeleteType', - MessageContentType = 'MessageContentType', + InvalidElement = 'InvalidElement', + + MessageThreadParent = 'MessageThreadParent', MessageExistingThread = 'MessageExistingThread', - MessageNonceRequired = 'MessageNonceRequired', - MessageNonceType = 'MessageNonceType', + ThreadInvitableType = 'ThreadInvitableType', + + WebhookMessage = 'WebhookMessage', + WebhookTokenUnavailable = 'WebhookTokenUnavailable', + WebhookURLInvalid = 'WebhookURLInvalid', + WebhookApplication = 'WebhookApplication', + MessageReferenceMissing = 'MessageReferenceMissing', - MessageThreadParent = 'MessageThreadParent', + + EmojiType = 'EmojiType', + EmojiManaged = 'EmojiManaged', MissingManageGuildExpressionsPermission = 'MissingManageGuildExpressionsPermission', - ModalSubmitInteractionFieldNotFound = 'ModalSubmitInteractionFieldNotFound', - ModalSubmitInteractionFieldType = 'ModalSubmitInteractionFieldType', + NotGuildSoundboardSound = 'NotGuildSoundboardSound', NotGuildSticker = 'NotGuildSticker', - NotImplemented = 'NotImplemented', - PollAlreadyExpired = 'PollAlreadyExpired', - PruneDaysType = 'PruneDaysType', + ReactionResolveUser = 'ReactionResolveUser', - ReqResourceType = 'ReqResourceType', - ShardingAlreadySpawned = 'ShardingAlreadySpawned', - ShardingInProcess = 'ShardingInProcess', - ShardingInvalidEvalBroadcast = 'ShardingInvalidEvalBroadcast', - ShardingNoChildExists = 'ShardingNoChildExists', - ShardingNoShards = 'ShardingNoShards', - ShardingProcessExists = 'ShardingProcessExists', - ShardingReadyDied = 'ShardingReadyDied', - ShardingReadyDisconnected = 'ShardingReadyDisconnected', - ShardingReadyTimeout = 'ShardingReadyTimeout', - ShardingShardMiscalculation = 'ShardingShardMiscalculation', - ShardingShardNotFound = 'ShardingShardNotFound', - ShardingWorkerExists = 'ShardingWorkerExists', - StageChannelResolve = 'StageChannelResolve', + + InviteResolveCode = 'InviteResolveCode', + InviteNotFound = 'InviteNotFound', + + DeleteGroupDMChannel = 'DeleteGroupDMChannel', + FetchGroupDMChannel = 'FetchGroupDMChannel', + + MemberFetchNonceLength = 'MemberFetchNonceLength', + + GlobalCommandPermissions = 'GlobalCommandPermissions', + GuildUncachedEntityResolve = 'GuildUncachedEntityResolve', + + InteractionAlreadyReplied = 'InteractionAlreadyReplied', + InteractionNotReplied = 'InteractionNotReplied', + + CommandInteractionOptionNotFound = 'CommandInteractionOptionNotFound', + CommandInteractionOptionType = 'CommandInteractionOptionType', + CommandInteractionOptionEmpty = 'CommandInteractionOptionEmpty', + CommandInteractionOptionNoSubcommand = 'CommandInteractionOptionNoSubcommand', + CommandInteractionOptionNoSubcommandGroup = 'CommandInteractionOptionNoSubcommandGroup', + AutocompleteInteractionOptionNoFocusedOption = 'AutocompleteInteractionOptionNoFocusedOption', + + ModalSubmitInteractionFieldNotFound = 'ModalSubmitInteractionFieldNotFound', + ModalSubmitInteractionFieldType = 'ModalSubmitInteractionFieldType', + + InvalidMissingScopes = 'InvalidMissingScopes', + InvalidScopesWithPermissions = 'InvalidScopesWithPermissions', + + NotImplemented = 'NotImplemented', + SweepFilterReturn = 'SweepFilterReturn', - ThreadInvitableType = 'ThreadInvitableType', - TokenInvalid = 'TokenInvalid', - TokenMissing = 'TokenMissing', - UserNoDMChannel = 'UserNoDMChannel', - VoiceNotStageChannel = 'VoiceNotStageChannel', - VoiceStateInvalidType = 'VoiceStateInvalidType', - VoiceStateNotOwn = 'VoiceStateNotOwn', - WebhookApplication = 'WebhookApplication', - WebhookMessage = 'WebhookMessage', - WebhookTokenUnavailable = 'WebhookTokenUnavailable', - WebhookURLInvalid = 'WebhookURLInvalid', + + GuildForumMessageRequired = 'GuildForumMessageRequired', + + EntitlementCreateInvalidOwner = 'EntitlementCreateInvalidOwner', + + BulkBanUsersOptionEmpty = 'BulkBanUsersOptionEmpty', + + PollAlreadyExpired = 'PollAlreadyExpired', } +/* eslint-enable typescript-sort-keys/string-enum */ export class DiscordjsError extends Error { private constructor(code: DiscordjsErrorCodes, ...args: unknown[]); From 5d3a393e6f5387dbd5d2527c0a5f41f57b5ac230 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 4 May 2025 18:01:39 +0200 Subject: [PATCH 26/38] chore: get comments back --- packages/discord.js/typings/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index 8da8fd42058e..101febeb9738 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -7030,6 +7030,8 @@ export type Serialized = Value extends bigint | symbol | (() => any) // #region Voice /** + * Use `DiscordGatewayAdapterLibraryMethods` from `@discordjs/voice` instead. + * * @internal */ export interface InternalDiscordGatewayAdapterLibraryMethods { @@ -7039,6 +7041,8 @@ export interface InternalDiscordGatewayAdapterLibraryMethods { } /** + * Use `DiscordGatewayAdapterImplementerMethods` from `@discordjs/voice` instead. + * * @internal */ export interface InternalDiscordGatewayAdapterImplementerMethods { @@ -7047,6 +7051,8 @@ export interface InternalDiscordGatewayAdapterImplementerMethods { } /** + * Use `DiscordGatewayAdapterCreator` from `@discordjs/voice` instead. + * * @internal */ export type InternalDiscordGatewayAdapterCreator = ( From 2b552e6dc0aa047fce0382f9ff93279c6a3c7eba Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Fri, 9 May 2025 19:39:46 +0200 Subject: [PATCH 27/38] Update packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com> --- .../src/client/websocket/handlers/THREAD_LIST_SYNC.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js index b17c4628d948..d92a86aa6d51 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js @@ -44,7 +44,7 @@ module.exports = (client, { d: data }) => { function removeStaleThreads(client, channel) { if (!channel.threads) return; - for (const thread of channel.threads.cache) { + for (const thread of channel.threads.cache.values()) { if (!thread.archived) { client.channels._remove(thread.id); } From 6c4cfc5a18682ea062611c87034a2ee8b20d8487 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Mon, 12 May 2025 23:34:55 +0200 Subject: [PATCH 28/38] fix: remove unused parameter --- packages/discord.js/src/structures/ReactionCollector.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/discord.js/src/structures/ReactionCollector.js b/packages/discord.js/src/structures/ReactionCollector.js index 180cb35de9a2..13c484e97af6 100644 --- a/packages/discord.js/src/structures/ReactionCollector.js +++ b/packages/discord.js/src/structures/ReactionCollector.js @@ -110,12 +110,10 @@ class ReactionCollector extends Collector { * Handles an incoming reaction for possible collection. * * @param {MessageReaction} reaction The reaction to possibly collect - * @param {User} user The user that added the reaction * @returns {?(Snowflake|string)} * @private */ - // eslint-disable-next-line no-unused-vars - collect(reaction, user) { + collect(reaction) { /** * Emitted whenever a reaction is collected. * From 1a0ab7f3d7d446b1a6f112c18a284d0611142f13 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Tue, 13 May 2025 10:55:54 +0200 Subject: [PATCH 29/38] fix: merge messed up types --- packages/discord.js/typings/index.d.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index 679528058b49..7956a13141d2 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -6534,17 +6534,21 @@ export interface BaseMessageOptions { allowedMentions?: MessageMentionOptions; components?: readonly ( | ActionRowData - | APIActionRowComponent - | JSONEncodable> - )[]; - components?: readonly ( - | ActionRowData - | APIActionRowComponent + | APIMessageTopLevelComponent | JSONEncodable> + | JSONEncodable + | TopLevelComponentData )[]; content?: string; embeds?: readonly (APIEmbed | JSONEncodable)[]; - files?: readonly (Attachment | AttachmentBuilder | AttachmentPayload)[]; + files?: readonly ( + | Attachment + | AttachmentBuilder + | AttachmentPayload + | BufferResolvable + | JSONEncodable + | Stream + )[]; } export interface BaseMessageOptionsWithPoll extends BaseMessageOptions { From 03231778c1871b5adc56b56fc4f1dd4678013063 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Tue, 13 May 2025 11:43:30 +0200 Subject: [PATCH 30/38] fix: more type mess from merge --- packages/discord.js/typings/index.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/discord.js/typings/index.d.ts b/packages/discord.js/typings/index.d.ts index 7956a13141d2..e03354ac641c 100644 --- a/packages/discord.js/typings/index.d.ts +++ b/packages/discord.js/typings/index.d.ts @@ -3649,10 +3649,11 @@ export function createChannel( ): Channel; export type ComponentData = - | ActionRowData - | ActionRowData + | ComponentInContainerData + | ContainerComponentData | MessageActionRowComponentData - | ModalActionRowComponentData; + | ModalActionRowComponentData + | ThumbnailComponentData; export interface SendSoundboardSoundOptions { guildId?: Snowflake; From d63c91bf4c34e598a127fd7dafcfb9ece46a0742 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 25 May 2025 15:12:06 +0200 Subject: [PATCH 31/38] fix: generate script for ActionsManager --- eslint.config.js | 2 +- packages/discord.js/package.json | 4 ++-- packages/discord.js/scripts/esmDts.mjs | 6 ++---- packages/discord.js/scripts/generateRequires.mjs | 5 +++-- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index d47483e2d9ff..d3eef24fa092 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -138,7 +138,7 @@ export default tseslint.config( }, }, { - files: [`packages/discord.js/**/*{js,mjs,cjs}`], + files: [`packages/discord.js/**/*.{js,cjs}`], languageOptions: { sourceType: 'commonjs', parserOptions: { diff --git a/packages/discord.js/package.json b/packages/discord.js/package.json index 967d2ecf8313..bbd7eb16f30b 100644 --- a/packages/discord.js/package.json +++ b/packages/discord.js/package.json @@ -6,8 +6,8 @@ "scripts": { "test": "pnpm run docs:test && pnpm run test:typescript", "test:typescript": "tsc --noEmit && tsd", - "lint": "prettier --check . && cross-env TIMING=1 eslint --format=pretty src typings", - "format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src typings", + "lint": "prettier --check . && cross-env TIMING=1 eslint --format=pretty scripts src typings", + "format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty scripts src typings", "fmt": "pnpm run format", "docs": "docgen -i \"./src/*.js\" \"./src/**/*.js\" -c ./docs/index.json -r ../../ -o ./docs/docs.json && pnpm run docs:new", "docs:test": "docgen -i \"./src/*.js\" \"./src/**/*.js\" -c ./docs/index.json -r ../../", diff --git a/packages/discord.js/scripts/esmDts.mjs b/packages/discord.js/scripts/esmDts.mjs index 8fc490561b33..add422096021 100644 --- a/packages/discord.js/scripts/esmDts.mjs +++ b/packages/discord.js/scripts/esmDts.mjs @@ -1,4 +1,5 @@ import { readFile, writeFile } from 'node:fs/promises'; +import { URL } from 'node:url'; const rawTypesDTS = new URL('../typings/rawDataTypes.d.ts', import.meta.url); const rawIndexDTS = new URL('../typings/index.d.ts', import.meta.url); @@ -12,14 +13,11 @@ const [rawTypesString, rawIndexString] = await Promise.all([ ]); /** - * * @param {string} source * @param {[from: string, to: string][]} imports */ function updateImports(source, imports) { - return imports.reduce((code, [from, to]) => { - return code.replaceAll(from, to); - }, source); + return imports.reduce((code, [from, to]) => code.replaceAll(from, to), source); } /** @type {[string, string][]} */ diff --git a/packages/discord.js/scripts/generateRequires.mjs b/packages/discord.js/scripts/generateRequires.mjs index 898f62acbeee..2a2e8f078caf 100644 --- a/packages/discord.js/scripts/generateRequires.mjs +++ b/packages/discord.js/scripts/generateRequires.mjs @@ -1,4 +1,5 @@ import { readdir, writeFile } from 'node:fs/promises'; +import { URL } from 'node:url'; async function writeWebsocketHandlerImports() { const lines = ["'use strict';\n", 'const PacketHandlers = Object.fromEntries([']; @@ -25,8 +26,8 @@ async function writeClientActionImports() { ' // These symbols represent fully built data that we inject at times when calling actions manually.', ' // Action#getUser, for example, will return the injected data (which is assumed to be a built structure)', ' // instead of trying to make it from provided data', - " injectedUser = Symbol('djs.actions.injectedUser');", - " injectedChannel = Symbol('djs.actions.injectedChannel');", + " injectedUser = Symbol('djs.actions.injectedUser');\n", + " injectedChannel = Symbol('djs.actions.injectedChannel');\n", " injectedMessage = Symbol('djs.actions.injectedMessage');\n", ' constructor(client) {', ' this.client = client;\n', From da5520ebbdd1076230b169287c4429b69f6837c5 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 25 May 2025 17:09:48 +0200 Subject: [PATCH 32/38] fix: code review --- .../discord.js/src/managers/GuildManager.js | 35 ++++++++++-------- .../src/managers/GuildMemberManager.js | 18 ++++----- packages/discord.js/src/structures/Message.js | 37 +++++++------------ .../src/structures/interfaces/Collector.js | 14 ++++--- 4 files changed, 49 insertions(+), 55 deletions(-) diff --git a/packages/discord.js/src/managers/GuildManager.js b/packages/discord.js/src/managers/GuildManager.js index 7b0af679b718..3f56ffa0a975 100644 --- a/packages/discord.js/src/managers/GuildManager.js +++ b/packages/discord.js/src/managers/GuildManager.js @@ -235,6 +235,15 @@ class GuildManager extends CachedManager { return ( this.client.guilds.cache.get(data.id) ?? new Promise(resolve => { + const handleGuild = guild => { + if (guild.id === data.id) { + // eslint-disable-next-line no-use-before-define + clearTimeout(timeout); + this.client.decrementMaxListeners(); + resolve(guild); + } + }; + this.client.incrementMaxListeners(); this.client.once(Events.GuildCreate, handleGuild); @@ -243,14 +252,6 @@ class GuildManager extends CachedManager { this.client.decrementMaxListeners(); resolve(this.client.guilds._add(data)); }, 10_000).unref(); - - function handleGuild(guild) { - if (guild.id === data.id) { - clearTimeout(timeout); - this.client.decrementMaxListeners(); - resolve(guild); - } - } }) ); } @@ -336,13 +337,8 @@ class GuildManager extends CachedManager { const fetchedSoundboardSounds = new Collection(); - const timeout = setTimeout(() => { - this.client.removeListener(Events.SoundboardSounds, handler); - this.client.decrementMaxListeners(); - reject(new DiscordjsError(ErrorCodes.GuildSoundboardSoundsTimeout)); - }, time).unref(); - - function handler(soundboardSounds, guild) { + const handler = (soundboardSounds, guild) => { + // eslint-disable-next-line no-use-before-define timeout.refresh(); if (!remainingGuildIds.has(guild.id)) return; @@ -352,13 +348,20 @@ class GuildManager extends CachedManager { remainingGuildIds.delete(guild.id); if (remainingGuildIds.size === 0) { + // eslint-disable-next-line no-use-before-define clearTimeout(timeout); this.client.removeListener(Events.SoundboardSounds, handler); this.client.decrementMaxListeners(); resolve(fetchedSoundboardSounds); } - } + }; + + const timeout = setTimeout(() => { + this.client.removeListener(Events.SoundboardSounds, handler); + this.client.decrementMaxListeners(); + reject(new DiscordjsError(ErrorCodes.GuildSoundboardSoundsTimeout)); + }, time).unref(); this.client.incrementMaxListeners(); this.client.on(Events.SoundboardSounds, handler); diff --git a/packages/discord.js/src/managers/GuildMemberManager.js b/packages/discord.js/src/managers/GuildMemberManager.js index ad766fff42ed..6e1ee21bd121 100644 --- a/packages/discord.js/src/managers/GuildMemberManager.js +++ b/packages/discord.js/src/managers/GuildMemberManager.js @@ -259,16 +259,10 @@ class GuildMemberManager extends CachedManager { }); const fetchedMembers = new Collection(); let index = 0; - - const timeout = setTimeout(() => { - this.client.removeListener(Events.GuildMembersChunk, handler); - this.client.decrementMaxListeners(); - reject(new DiscordjsError(ErrorCodes.GuildMembersTimeout)); - }, time).unref(); - - function handler(members, _, chunk) { + const handler = (members, _, chunk) => { if (chunk.nonce !== nonce) return; + // eslint-disable-next-line no-use-before-define timeout.refresh(); index++; for (const member of members.values()) { @@ -276,13 +270,19 @@ class GuildMemberManager extends CachedManager { } if (members.size < 1_000 || (limit && fetchedMembers.size >= limit) || index === chunk.count) { + // eslint-disable-next-line no-use-before-define clearTimeout(timeout); this.client.removeListener(Events.GuildMembersChunk, handler); this.client.decrementMaxListeners(); resolve(users && !Array.isArray(users) && fetchedMembers.size ? fetchedMembers.first() : fetchedMembers); } - } + }; + const timeout = setTimeout(() => { + this.client.removeListener(Events.GuildMembersChunk, handler); + this.client.decrementMaxListeners(); + reject(new DiscordjsError(ErrorCodes.GuildMembersTimeout)); + }, time).unref(); this.client.incrementMaxListeners(); this.client.on(Events.GuildMembersChunk, handler); }); diff --git a/packages/discord.js/src/structures/Message.js b/packages/discord.js/src/structures/Message.js index de33964bd703..c3b85e888aa7 100644 --- a/packages/discord.js/src/structures/Message.js +++ b/packages/discord.js/src/structures/Message.js @@ -287,30 +287,19 @@ class Message extends Base { this.reactions ??= new ReactionManager(this); } - if (this.mentions) { - /** - * All valid mentions that the message contains - * - * @type {MessageMentions} - */ - this.mentions = new MessageMentions( - this, - data.mentions ?? this.mentions.users, - data.mention_roles ?? this.mentions.roles, - data.mention_everyone ?? this.mentions.everyone, - data.mention_channels ?? this.mentions.crosspostedChannels, - data.referenced_message?.author ?? this.mentions.repliedUser, - ); - } else { - this.mentions = new MessageMentions( - this, - data.mentions, - data.mention_roles, - data.mention_everyone, - data.mention_channels, - data.referenced_message?.author, - ); - } + /** + * All valid mentions that the message contains + * + * @type {MessageMentions} + */ + this.mentions = new MessageMentions( + this, + data.mentions ?? this.mentions?.users, + data.mention_roles ?? this.mentions?.roles, + data.mention_everyone ?? this.mentions?.everyone, + data.mention_channels ?? this.mentions?.crosspostedChannels, + data.referenced_message?.author ?? this.mentions?.repliedUser, + ); if ('webhook_id' in data) { /** diff --git a/packages/discord.js/src/structures/interfaces/Collector.js b/packages/discord.js/src/structures/interfaces/Collector.js index da941eaae771..a5fde7db484b 100644 --- a/packages/discord.js/src/structures/interfaces/Collector.js +++ b/packages/discord.js/src/structures/interfaces/Collector.js @@ -204,20 +204,22 @@ class Collector extends AsyncEventEmitter { return; } - function cleanup() { + const cleanup = () => { + // eslint-disable-next-line no-use-before-define this.removeListener('collect', onCollect); + // eslint-disable-next-line no-use-before-define this.removeListener('end', onEnd); - } + }; - function onCollect(item) { + const onCollect = item => { cleanup(); resolve(item); - } + }; - function onEnd() { + const onEnd = () => { cleanup(); reject(this.collected); - } + }; this.on('collect', onCollect); this.on('end', onEnd); From 3789ab03f63f9425a00174db31976a4bced13d57 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 25 May 2025 21:56:26 +0200 Subject: [PATCH 33/38] Update packages/discord.js/src/structures/MessageMentions.js Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com> --- packages/discord.js/src/structures/MessageMentions.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/discord.js/src/structures/MessageMentions.js b/packages/discord.js/src/structures/MessageMentions.js index c1c32516ff95..fdb2e0c778b7 100644 --- a/packages/discord.js/src/structures/MessageMentions.js +++ b/packages/discord.js/src/structures/MessageMentions.js @@ -217,7 +217,7 @@ class MessageMentions { if (this._members) return this._members; if (!this.guild) return null; this._members = new Collection(); - for (const user of this.users) { + for (const user of this.users.values()) { const member = this.guild.members.resolve(user); if (member) this._members.set(member.user.id, member); } From 0f32ab1891a8fad312fc0ddfd8a0185a18e148bb Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Sun, 25 May 2025 21:57:06 +0200 Subject: [PATCH 34/38] Update packages/discord.js/src/structures/Presence.js Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com> --- packages/discord.js/src/structures/Presence.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/discord.js/src/structures/Presence.js b/packages/discord.js/src/structures/Presence.js index ab38d1359a7c..f40cfd976be8 100644 --- a/packages/discord.js/src/structures/Presence.js +++ b/packages/discord.js/src/structures/Presence.js @@ -16,10 +16,10 @@ const { Emoji } = require('./Emoji.js'); /** * The status of this presence: - * - __`online`__ - user is online - * - __`idle`__ - user is AFK - * - __`offline`__ - user is offline or invisible - * - __`dnd`__ - user is in Do Not Disturb + * - `online` - user is online + * - `idle` - user is AFK + * - `offline` - user is offline or invisible + * - `dnd` - user is in Do Not Disturb * * @typedef {string} PresenceStatus */ From a460ad4cd1e533e186e95d3bc9d156236d5a406a Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Mon, 26 May 2025 07:33:09 +0200 Subject: [PATCH 35/38] fix: replace is faster, unicorn is wrong --- packages/discord.js/src/structures/BaseGuild.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/discord.js/src/structures/BaseGuild.js b/packages/discord.js/src/structures/BaseGuild.js index b7c6124e27d2..fed2bb964877 100644 --- a/packages/discord.js/src/structures/BaseGuild.js +++ b/packages/discord.js/src/structures/BaseGuild.js @@ -71,10 +71,12 @@ class BaseGuild extends Base { * @readonly */ get nameAcronym() { + /* eslint-disable unicorn/prefer-string-replace-all */ return this.name - .replaceAll("'s ", ' ') - .replaceAll(/\w+/g, word => word[0]) - .replaceAll(/\s/g, ''); + .replace(/'s /g, ' ') + .replace(/\w+/g, word => word[0]) + .replace(/\s/g, ''); + /* eslint-enable unicorn/prefer-string-replace-all */ } /** From 437660df0832aa625b01cbb25e664a2338dcda40 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Mon, 26 May 2025 08:25:41 +0200 Subject: [PATCH 36/38] fix: consistency --- packages/discord.js/src/structures/Presence.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/discord.js/src/structures/Presence.js b/packages/discord.js/src/structures/Presence.js index f40cfd976be8..de5ca9f979bf 100644 --- a/packages/discord.js/src/structures/Presence.js +++ b/packages/discord.js/src/structures/Presence.js @@ -26,9 +26,9 @@ const { Emoji } = require('./Emoji.js'); /** * The status of this presence: - * - __`online`__ - user is online - * - __`idle`__ - user is AFK - * - __`dnd`__ - user is in Do Not Disturb + * - `online` - user is online + * - `idle` - user is AFK + * - `dnd` - user is in Do Not Disturb * * @typedef {string} ClientPresenceStatus */ From 7950a897bf85af4b4da5d070f1ce4acae5733fac Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Mon, 26 May 2025 21:53:15 +0200 Subject: [PATCH 37/38] fix: delete obsolete file --- packages/discord.js/tslint.json | 30 ------------------------------ 1 file changed, 30 deletions(-) delete mode 100644 packages/discord.js/tslint.json diff --git a/packages/discord.js/tslint.json b/packages/discord.js/tslint.json deleted file mode 100644 index c24dcd13231f..000000000000 --- a/packages/discord.js/tslint.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tslint.json", - "extends": ["dtslint/dtslint.json"], - "rules": { - "prefer-readonly": false, - "await-promise": false, - "no-for-in-array": false, - "no-null-undefined-union": false, - "no-promise-as-boolean": false, - "no-void-expression": false, - "strict-string-expressions": false, - "strict-comparisons": false, - "use-default-type-parameter": false, - "no-boolean-literal-compare": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "expect": false, - "no-import-default-of-export-equals": false, - "no-relative-import-in-test": false, - "no-unnecessary-generics": false, - "strict-export-declare-modifiers": false, - "no-single-declare-module": false, - "member-access": true, - "no-unnecessary-class": false, - "array-type": [true, "array"], - "one-line": false, - "no-any-union": false, - "void-return": false - } -} From 42c57619655a652a0a72211decea3feb9bc7bba6 Mon Sep 17 00:00:00 2001 From: Qjuh <76154676+Qjuh@users.noreply.github.com> Date: Mon, 26 May 2025 23:19:47 +0200 Subject: [PATCH 38/38] fix: minor nit in test file --- packages/discord.js/typings/index.test-d.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/discord.js/typings/index.test-d.ts b/packages/discord.js/typings/index.test-d.ts index a98c5698b618..0dea9ece153e 100644 --- a/packages/discord.js/typings/index.test-d.ts +++ b/packages/discord.js/typings/index.test-d.ts @@ -79,10 +79,10 @@ import type { ChannelMention, ChannelSelectMenuComponent, ChannelSelectMenuInteraction, - ClientApplication, - ClientUser, ChatInputApplicationCommandData, ChatInputCommandInteraction, + ClientApplication, + ClientUser, CollectedMessageInteraction, Collector, CommandInteraction, @@ -1681,12 +1681,13 @@ declare const applicationCommandSubCommand: ApplicationCommandSubCommand; declare const applicationSubGroupCommandData: ApplicationCommandSubGroupData; declare const applicationCommandSubGroup: ApplicationCommandSubGroup; - -expectType(applicationSubGroupCommandData.type); -applicationSubGroupCommandData.options = []; -applicationSubGroupCommandData.options = [] as const; -applicationCommandSubGroup.options = []; -applicationCommandSubGroup.options = [] as const; +{ + expectType(applicationSubGroupCommandData.type); + applicationSubGroupCommandData.options = []; + applicationSubGroupCommandData.options = [] as const; + applicationCommandSubGroup.options = []; + applicationCommandSubGroup.options = [] as const; +} declare const autoModerationRuleManager: AutoModerationRuleManager; {