refactor discord types into separate npm package (#3520)

Co-authored-by: V <vendicated@riseup.net>
Co-authored-by: sadan <117494111+sadan4@users.noreply.github.com>
Co-authored-by: ezzud <contact@ezzud.fr>
This commit is contained in:
V 2025-07-10 00:38:39 +02:00 committed by GitHub
parent c55833d95f
commit dc9064326b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
149 changed files with 1561 additions and 751 deletions

View file

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View file

@ -0,0 +1,42 @@
# Discord Types
This package provides TypeScript types for the Webpack modules of Discord's web app.
While it was primarily created for Vencord, other client mods could also benefit from this, so it is published as a standalone package!
## Installation
```bash
npm install -D @vencord/discord-types
yarn add -D @vencord/discord-types
pnpm add -D @vencord/discord-types
```
## Example Usage
```ts
import type { UserStore } from "@vencord/discord-types";
const userStore: UserStore = findStore("UserStore"); // findStore is up to you to implement, this library only provides types and no runtime code
```
## Enums
This library also exports some const enums that you can use from Typescript code:
```ts
import { ApplicationCommandType } from "@vencord/discord-types/enums";
console.log(ApplicationCommandType.CHAT_INPUT); // 1
```
### License
This package is licensed under the [LGPL-3.0](./LICENSE) (or later) license.
A very short summary of the license is that you can use this package as a library in both open source and closed source projects,
similar to an MIT-licensed project.
However, if you modify the code of this package, you must release source code of your modified version under the same license.
### Credit
This package was inspired by Swishilicous' [discord-types](https://www.npmjs.com/package/discord-types) package.

View file

@ -0,0 +1,27 @@
export const enum ApplicationCommandOptionType {
SUB_COMMAND = 1,
SUB_COMMAND_GROUP = 2,
STRING = 3,
INTEGER = 4,
BOOLEAN = 5,
USER = 6,
CHANNEL = 7,
ROLE = 8,
MENTIONABLE = 9,
NUMBER = 10,
ATTACHMENT = 11,
}
export const enum ApplicationCommandInputType {
BUILT_IN = 0,
BUILT_IN_TEXT = 1,
BUILT_IN_INTEGRATION = 2,
BOT = 3,
PLACEHOLDER = 4,
}
export const enum ApplicationCommandType {
CHAT_INPUT = 1,
USER = 2,
MESSAGE = 3,
}

View file

@ -0,0 +1 @@
export * from "./commands";

View file

@ -0,0 +1,19 @@
{
"name": "@vencord/discord-types",
"author": "Vencord Contributors",
"description": "Typescript definitions for the webpack modules of the Discord Web app",
"version": "1.0.0",
"license": "LGPL-3.0-or-later",
"types": "src/index.d.ts",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/Vendicated/Vencord.git",
"directory": "packages/discord-types"
},
"dependencies": {
"@types/react": "^19.0.10",
"moment": "^2.22.2",
"type-fest": "^4.41.0"
}
}

21
packages/discord-types/src/classes.d.ts vendored Normal file
View file

@ -0,0 +1,21 @@
export interface ImageModalClasses {
image: string,
modal: string,
}
export interface ButtonWrapperClasses {
hoverScale: string;
buttonWrapper: string;
button: string;
iconMask: string;
buttonContent: string;
icon: string;
pulseIcon: string;
pulseButton: string;
notificationDot: string;
sparkleContainer: string;
sparkleStar: string;
sparklePlus: string;
sparkle: string;
active: string;
}

View file

@ -0,0 +1,83 @@
import { DiscordRecord } from "./Record";
export class Channel extends DiscordRecord {
constructor(channel: object);
application_id: number | undefined;
bitrate: number;
defaultAutoArchiveDuration: number | undefined;
flags: number;
guild_id: string;
icon: string;
id: string;
lastMessageId: string;
lastPinTimestamp: string | undefined;
member: unknown;
memberCount: number | undefined;
memberIdsPreview: string[] | undefined;
memberListId: unknown;
messageCount: number | undefined;
name: string;
nicks: Record<string, unknown>;
nsfw: boolean;
originChannelId: unknown;
ownerId: string;
parent_id: string;
permissionOverwrites: {
[role: string]: {
id: string;
type: number;
deny: bigint;
allow: bigint;
};
};
position: number;
rateLimitPerUser: number;
rawRecipients: {
id: string;
avatar: string;
username: string;
public_flags: number;
discriminator: string;
}[];
recipients: string[];
rtcRegion: string;
threadMetadata: {
locked: boolean;
archived: boolean;
invitable: boolean;
createTimestamp: string | undefined;
autoArchiveDuration: number;
archiveTimestamp: string | undefined;
};
topic: string;
type: number;
userLimit: number;
videoQualityMode: undefined;
get accessPermissions(): bigint;
get lastActiveTimestamp(): number;
computeLurkerPermissionsAllowList(): unknown;
getApplicationId(): unknown;
getGuildId(): string;
getRecipientId(): unknown;
hasFlag(flag: number): boolean;
isActiveThread(): boolean;
isArchivedThread(): boolean;
isCategory(): boolean;
isDM(): boolean;
isDirectory(): boolean;
isForumChannel(): boolean;
isGroupDM(): boolean;
isGuildStageVoice(): boolean;
isGuildVoice(): boolean;
isListenModeCapable(): boolean;
isManaged(): boolean;
isMultiUserDM(): boolean;
isNSFW(): boolean;
isOwner(): boolean;
isPrivate(): boolean;
isSystemDM(): boolean;
isThread(): boolean;
isVocal(): boolean;
}

View file

@ -0,0 +1,64 @@
import { Role } from './Role';
import { DiscordRecord } from './Record';
// copy(Object.keys(findByProps("CREATOR_MONETIZABLE")).map(JSON.stringify).join("|"))
export type GuildFeatures =
"INVITE_SPLASH" | "VIP_REGIONS" | "VANITY_URL" | "MORE_EMOJI" | "MORE_STICKERS" | "MORE_SOUNDBOARD" | "VERIFIED" | "COMMERCE" | "DISCOVERABLE" | "COMMUNITY" | "FEATURABLE" | "NEWS" | "HUB" | "PARTNERED" | "ANIMATED_ICON" | "BANNER" | "ENABLED_DISCOVERABLE_BEFORE" | "WELCOME_SCREEN_ENABLED" | "MEMBER_VERIFICATION_GATE_ENABLED" | "PREVIEW_ENABLED" | "ROLE_SUBSCRIPTIONS_ENABLED" | "ROLE_SUBSCRIPTIONS_AVAILABLE_FOR_PURCHASE" | "CREATOR_MONETIZABLE" | "CREATOR_MONETIZABLE_PROVISIONAL" | "CREATOR_MONETIZABLE_WHITEGLOVE" | "CREATOR_MONETIZABLE_DISABLED" | "CREATOR_MONETIZABLE_RESTRICTED" | "CREATOR_STORE_PAGE" | "CREATOR_MONETIZABLE_PENDING_NEW_OWNER_ONBOARDING" | "PRODUCTS_AVAILABLE_FOR_PURCHASE" | "GUILD_WEB_PAGE_VANITY_URL" | "THREADS_ENABLED" | "THREADS_ENABLED_TESTING" | "NEW_THREAD_PERMISSIONS" | "ROLE_ICONS" | "TEXT_IN_STAGE_ENABLED" | "TEXT_IN_VOICE_ENABLED" | "HAS_DIRECTORY_ENTRY" | "ANIMATED_BANNER" | "LINKED_TO_HUB" | "EXPOSED_TO_ACTIVITIES_WTP_EXPERIMENT" | "GUILD_HOME_DEPRECATION_OVERRIDE" | "GUILD_HOME_TEST" | "GUILD_HOME_OVERRIDE" | "GUILD_ONBOARDING" | "GUILD_ONBOARDING_EVER_ENABLED" | "GUILD_ONBOARDING_HAS_PROMPTS" | "GUILD_SERVER_GUIDE" | "INTERNAL_EMPLOYEE_ONLY" | "AUTO_MODERATION" | "INVITES_DISABLED" | "BURST_REACTIONS" | "SOUNDBOARD" | "SHARD" | "ACTIVITY_FEED_ENABLED_BY_USER" | "ACTIVITY_FEED_DISABLED_BY_USER" | "SUMMARIES_ENABLED_GA" | "LEADERBOARD_ENABLED" | "SUMMARIES_ENABLED_BY_USER" | "SUMMARIES_OPT_OUT_EXPERIENCE" | "CHANNEL_ICON_EMOJIS_GENERATED" | "NON_COMMUNITY_RAID_ALERTS" | "RAID_ALERTS_DISABLED" | "AUTOMOD_TRIGGER_USER_PROFILE" | "ENABLED_MODERATION_EXPERIENCE_FOR_NON_COMMUNITY" | "GUILD_PRODUCTS_ALLOW_ARCHIVED_FILE" | "CLAN" | "MEMBER_VERIFICATION_MANUAL_APPROVAL" | "FORWARDING_DISABLED" | "MEMBER_VERIFICATION_ROLLOUT_TEST" | "AUDIO_BITRATE_128_KBPS" | "AUDIO_BITRATE_256_KBPS" | "AUDIO_BITRATE_384_KBPS" | "VIDEO_BITRATE_ENHANCED" | "MAX_FILE_SIZE_50_MB" | "MAX_FILE_SIZE_100_MB" | "GUILD_TAGS" | "ENHANCED_ROLE_COLORS" | "PREMIUM_TIER_3_OVERRIDE" | "REPORT_TO_MOD_PILOT" | "TIERLESS_BOOSTING_SYSTEM_MESSAGE";
export type GuildPremiumFeatures =
"ANIMATED_ICON" | "STAGE_CHANNEL_VIEWERS_150" | "ROLE_ICONS" | "GUILD_TAGS" | "BANNER" | "MAX_FILE_SIZE_50_MB" | "VIDEO_QUALITY_720_60FPS" | "STAGE_CHANNEL_VIEWERS_50" | "VIDEO_QUALITY_1080_60FPS" | "MAX_FILE_SIZE_100_MB" | "VANITY_URL" | "VIDEO_BITRATE_ENHANCED" | "STAGE_CHANNEL_VIEWERS_300" | "AUDIO_BITRATE_128_KBPS" | "ANIMATED_BANNER" | "TIERLESS_BOOSTING" | "ENHANCED_ROLE_COLORS" | "INVITE_SPLASH" | "AUDIO_BITRATE_256_KBPS" | "AUDIO_BITRATE_384_KBPS";
export class Guild extends DiscordRecord {
constructor(guild: object);
afkChannelId: string | undefined;
afkTimeout: number;
applicationCommandCounts: {
0: number;
1: number;
2: number;
};
application_id: unknown;
banner: string | undefined;
defaultMessageNotifications: number;
description: string | undefined;
discoverySplash: string | undefined;
explicitContentFilter: number;
features: Set<GuildFeatures>;
homeHeader: string | undefined;
hubType: unknown;
icon: string | undefined;
id: string;
joinedAt: Date;
latestOnboardingQuestionId: string | undefined;
maxMembers: number;
maxStageVideoChannelUsers: number;
maxVideoChannelUsers: number;
mfaLevel: number;
moderatorReporting: unknown;
name: string;
nsfwLevel: number;
ownerConfiguredContentLevel: number;
ownerId: string;
preferredLocale: string;
premiumFeatures: {
additionalEmojiSlots: number;
additionalSoundSlots: number;
additionalStickerSlots: number;
features: Array<GuildPremiumFeatures>;
};
premiumProgressBarEnabled: boolean;
premiumSubscriberCount: number;
premiumTier: number;
profile: {
badge: string | undefined;
tag: string | undefined;
} | undefined;
publicUpdatesChannelId: string | undefined;
roles: Record<string, Role>;
rulesChannelId: string | undefined;
safetyAlertsChannelId: string | undefined;
splash: string | undefined;
systemChannelFlags: number;
systemChannelId: string | undefined;
vanityURLCode: string | undefined;
verificationLevel: number;
}

View file

@ -0,0 +1,26 @@
export interface GuildMember {
avatar: string | undefined;
avatarDecoration: string | undefined;
banner: string | undefined;
bio: string;
colorRoleId: string | undefined;
colorString: string;
colorStrings: {
primaryColor: string | undefined;
secondaryColor: string | undefined;
tertiaryColor: string | undefined;
};
communicationDisabledUntil: string | undefined;
flags: number;
fullProfileLoadedTimestamp: number;
guildId: string;
highestRoleId: string;
hoistRoleId: string;
iconRoleId: string;
isPending: boolean | undefined;
joinedAt: string | undefined;
nick: string | undefined;
premiumSince: string | undefined;
roles: string[];
userId: string;
}

View file

@ -0,0 +1,12 @@
type Updater = (value: any) => any;
/**
* Common Record class extended by various Discord data structures, like User, Channel, Guild, etc.
*/
export class DiscordRecord {
toJS(): Record<string, any>;
set(key: string, value: any): this;
merge(data: Record<string, any>): this;
update(key: string, defaultValueOrUpdater: Updater | any, updater?: Updater): this;
}

View file

@ -0,0 +1,33 @@
export interface Role {
color: number;
colorString: string | undefined;
colorStrings: {
primaryColor: string | undefined;
secondaryColor: string | undefined;
tertiaryColor: string | undefined;
};
colors: {
primary_color: number | undefined;
secondary_color: number | undefined;
tertiary_color: number | undefined;
};
flags: number;
hoist: boolean;
icon: string | undefined;
id: string;
managed: boolean;
mentionable: boolean;
name: string;
originalPosition: number;
permissions: bigint;
position: number;
/**
* probably incomplete
*/
tags: {
bot_id: string;
integration_id: string;
premium_subscriber: unknown;
} | undefined;
unicodeEmoji: string | undefined;
}

View file

@ -0,0 +1,66 @@
// TODO: a lot of optional params can also be null, not just undef
import { DiscordRecord } from "./Record";
export class User extends DiscordRecord {
constructor(user: object);
accentColor: number;
avatar: string;
banner: string;
bio: string;
bot: boolean;
desktop: boolean;
discriminator: string;
email: string | undefined;
flags: number;
globalName: string | undefined;
guildMemberAvatars: Record<string, string>;
id: string;
mfaEnabled: boolean;
mobile: boolean;
nsfwAllowed: boolean | undefined;
phone: string | undefined;
premiumType: number | undefined;
premiumUsageFlags: number;
publicFlags: number;
purchasedFlags: number;
system: boolean;
username: string;
verified: boolean;
themeColors?: [number, number];
get createdAt(): Date;
get hasPremiumPerks(): boolean;
get tag(): string;
get usernameNormalized(): string;
addGuildAvatarHash(guildId: string, avatarHash: string): User;
getAvatarSource(guildId: string, canAnimate?: boolean): { uri: string; };
getAvatarURL(guildId?: string | null, t?: unknown, canAnimate?: boolean): string;
hasAvatarForGuild(guildId: string): boolean;
hasDisabledPremium(): boolean;
hasFlag(flag: number): boolean;
hasFreePremium(): boolean;
hasHadSKU(e: unknown): boolean;
hasPremiumUsageFlag(flag: number): boolean;
hasPurchasedFlag(flag: number): boolean;
hasUrgentMessages(): boolean;
isClaimed(): boolean;
isLocalBot(): boolean;
isNonUserBot(): boolean;
isPhoneVerified(): boolean;
isStaff(): boolean;
isSystemUser(): boolean;
isVerifiedBot(): boolean;
removeGuildAvatarHash(guildId: string): User;
toString(): string;
}
export interface UserJSON {
avatar: string;
avatarDecoration: unknown | undefined;
discriminator: string;
id: string;
publicFlags: number;
username: string;
}

View file

@ -0,0 +1,7 @@
export * from "./Channel";
export * from "./Guild";
export * from "./GuildMember";
export * from "./messages";
export * from "./Role";
export * from "./User";
export * from "./Record";

View file

@ -0,0 +1,61 @@
import { Channel } from "../Channel";
import { Guild } from "../Guild";
import { Promisable } from "type-fest";
import { ApplicationCommandInputType, ApplicationCommandOptionType, ApplicationCommandType } from "../../../enums";
export interface CommandContext {
channel: Channel;
guild?: Guild;
}
export interface CommandOption {
name: string;
displayName?: string;
type: ApplicationCommandOptionType;
description: string;
displayDescription?: string;
required?: boolean;
options?: CommandOption[];
choices?: Array<ChoicesOption>;
}
export interface ChoicesOption {
label: string;
value: string;
name: string;
displayName?: string;
}
export interface CommandReturnValue {
content: string;
// TODO: implement
// cancel?: boolean;
}
export interface CommandArgument {
type: ApplicationCommandOptionType;
name: string;
value: string;
focused: undefined;
options: CommandArgument[];
}
export interface Command {
id?: string;
applicationId?: string;
type?: ApplicationCommandType;
inputType?: ApplicationCommandInputType;
plugin?: string;
name: string;
untranslatedName?: string;
displayName?: string;
description: string;
untranslatedDescription?: string;
displayDescription?: string;
options?: CommandOption[];
predicate?(ctx: CommandContext): boolean;
execute(args: CommandArgument[], ctx: CommandContext): Promisable<void | CommandReturnValue>;
}

View file

@ -0,0 +1,70 @@
export interface Embed {
author?: {
name: string;
url: string;
iconURL: string | undefined;
iconProxyURL: string | undefined;
};
color: string;
fields: [];
id: string;
image?: {
height: number;
width: number;
url: string;
proxyURL: string;
};
provider?: {
name: string;
url: string | undefined;
};
rawDescription: string;
rawTitle: string;
referenceId: unknown;
timestamp: string;
thumbnail?: {
height: number;
proxyURL: string | undefined;
url: string;
width: number;
};
type: string;
url: string | undefined;
video?: {
height: number;
width: number;
url: string;
proxyURL: string | undefined;
};
}
export interface EmbedJSON {
author?: {
name: string;
url: string;
icon_url: string;
proxy_icon_url: string;
};
title: string;
color: string;
description: string;
type: string;
url: string | undefined;
provider?: {
name: string;
url: string;
};
timestamp: string;
thumbnail?: {
height: number;
width: number;
url: string;
proxy_url: string | undefined;
};
video?: {
height: number;
width: number;
url: string;
proxy_url: string | undefined;
};
}

View file

@ -0,0 +1,42 @@
export type Emoji = CustomEmoji | UnicodeEmoji;
export interface CustomEmoji {
type: 1;
allNamesString: string;
animated: boolean;
available: boolean;
guildId: string;
id: string;
managed: boolean;
name: string;
originalName?: string;
require_colons: boolean;
roles: string[];
}
export interface UnicodeEmoji {
type: 0;
diversityChildren: Record<any, any>;
emojiObject: {
names: string[];
surrogates: string;
unicodeVersion: number;
};
index: number;
surrogates: string;
uniqueName: string;
useSpriteSheet: boolean;
get allNamesString(): string;
get animated(): boolean;
get defaultDiversityChild(): any;
get hasDiversity(): boolean | undefined;
get hasDiversityParent(): boolean | undefined;
get hasMultiDiversity(): boolean | undefined;
get hasMultiDiversityParent(): boolean | undefined;
get managed(): boolean;
get name(): string;
get names(): string[];
get optionallyDiverseSequence(): string | undefined;
get unicodeVersion(): number;
get url(): string;
}

View file

@ -0,0 +1,191 @@
import { CommandOption } from './Commands';
import { User, UserJSON } from '../User';
import { Embed, EmbedJSON } from './Embed';
import { DiscordRecord } from "../Record";
/**
* TODO: looks like discord has moved over to Date instead of Moment;
*/
export class Message extends DiscordRecord {
constructor(message: object);
activity: unknown;
application: unknown;
applicationId: string | unknown;
attachments: MessageAttachment[];
author: User;
blocked: boolean;
bot: boolean;
call: {
duration: moment.Duration;
endedTimestamp: moment.Moment;
participants: string[];
};
channel_id: string;
/**
* NOTE: not fully typed
*/
codedLinks: {
code?: string;
type: string;
}[];
colorString: unknown;
components: unknown[];
content: string;
customRenderedContent: unknown;
editedTimestamp: Date;
embeds: Embed[];
flags: number;
giftCodes: string[];
id: string;
interaction: {
id: string;
name: string;
type: number;
user: User;
}[] | undefined;
interactionData: {
application_command: {
application_id: string;
default_member_permissions: unknown;
default_permission: boolean;
description: string;
dm_permission: unknown;
id: string;
name: string;
options: CommandOption[];
permissions: unknown[];
type: number;
version: string;
};
attachments: MessageAttachment[];
guild_id: string | undefined;
id: string;
name: string;
options: {
focused: unknown;
name: string;
type: number;
value: string;
}[];
type: number;
version: string;
}[];
interactionError: unknown[];
isSearchHit: boolean;
loggingName: unknown;
mentionChannels: string[];
mentionEveryone: boolean;
mentionRoles: string[];
mentioned: boolean;
mentions: string[];
messageReference: {
guild_id?: string;
channel_id: string;
message_id: string;
} | undefined;
nick: unknown; // probably a string
nonce: string | undefined;
pinned: boolean;
reactions: MessageReaction[];
state: string;
stickerItems: {
format_type: number;
id: string;
name: string;
}[];
stickers: unknown[];
timestamp: moment.Moment;
tts: boolean;
type: number;
webhookId: string | undefined;
/**
* Doesn't actually update the original message; it just returns a new message instance with the added reaction.
*/
addReaction(emoji: ReactionEmoji, fromCurrentUser: boolean): Message;
/**
* Searches each reaction and if the provided string has an index above -1 it'll return the reaction object.
*/
getReaction(name: string): MessageReaction;
/**
* Doesn't actually update the original message; it just returns the message instance without the reaction searched with the provided emoji object.
*/
removeReactionsForEmoji(emoji: ReactionEmoji): Message;
/**
* Doesn't actually update the original message; it just returns the message instance without the reaction.
*/
removeReaction(emoji: ReactionEmoji, fromCurrentUser: boolean): Message;
getChannelId(): string;
hasFlag(flag: number): boolean;
isCommandType(): boolean;
isEdited(): boolean;
isSystemDM(): boolean;
}
/** A smaller Message object found in FluxDispatcher and elsewhere. */
export interface MessageJSON {
attachments: MessageAttachment[];
author: UserJSON;
channel_id: string;
components: unknown[];
content: string;
edited_timestamp: string;
embeds: EmbedJSON[];
flags: number;
guild_id: string | undefined;
id: string;
loggingName: unknown;
member: {
avatar: string | undefined;
communication_disabled_until: string | undefined;
deaf: boolean;
hoisted_role: string | undefined;
is_pending: boolean;
joined_at: string;
mute: boolean;
nick: string | boolean;
pending: boolean;
premium_since: string | undefined;
roles: string[];
} | undefined;
mention_everyone: boolean;
mention_roles: string[];
mentions: UserJSON[];
message_reference: {
guild_id?: string;
channel_id: string;
message_id: string;
} | undefined;
nonce: string | undefined;
pinned: boolean;
referenced_message: MessageJSON | undefined;
state: string;
timestamp: string;
tts: boolean;
type: number;
}
export interface MessageAttachment {
filename: string;
id: string;
proxy_url: string;
size: number;
spoiler: boolean;
url: string;
content_type?: string;
width?: number;
height?: number;
}
export interface ReactionEmoji {
id: string | undefined;
name: string;
animated: boolean;
}
export interface MessageReaction {
count: number;
emoji: ReactionEmoji;
me: boolean;
}

View file

@ -0,0 +1,4 @@
export * from "./Commands";
export * from "./Message";
export * from "./Embed";
export * from "./Emoji";

View file

@ -0,0 +1,527 @@
import type { ComponentClass, ComponentPropsWithRef, ComponentType, CSSProperties, FunctionComponent, HtmlHTMLAttributes, HTMLProps, JSX, KeyboardEvent, MouseEvent, PointerEvent, PropsWithChildren, ReactNode, Ref, RefObject } from "react";
// copy(find(m => Array.isArray(m) && m.includes("heading-sm/normal")).map(JSON.stringify).join("|"))
export type TextVariant = "heading-sm/normal" | "heading-sm/medium" | "heading-sm/semibold" | "heading-sm/bold" | "heading-sm/extrabold" | "heading-md/normal" | "heading-md/medium" | "heading-md/semibold" | "heading-md/bold" | "heading-md/extrabold" | "heading-lg/normal" | "heading-lg/medium" | "heading-lg/semibold" | "heading-lg/bold" | "heading-lg/extrabold" | "heading-xl/normal" | "heading-xl/medium" | "heading-xl/semibold" | "heading-xl/bold" | "heading-xl/extrabold" | "heading-xxl/normal" | "heading-xxl/medium" | "heading-xxl/semibold" | "heading-xxl/bold" | "heading-xxl/extrabold" | "eyebrow" | "heading-deprecated-12/normal" | "heading-deprecated-12/medium" | "heading-deprecated-12/semibold" | "heading-deprecated-12/bold" | "heading-deprecated-12/extrabold" | "redesign/heading-18/bold" | "text-xxs/normal" | "text-xxs/medium" | "text-xxs/semibold" | "text-xxs/bold" | "text-xs/normal" | "text-xs/medium" | "text-xs/semibold" | "text-xs/bold" | "text-sm/normal" | "text-sm/medium" | "text-sm/semibold" | "text-sm/bold" | "text-md/normal" | "text-md/medium" | "text-md/semibold" | "text-md/bold" | "text-lg/normal" | "text-lg/medium" | "text-lg/semibold" | "text-lg/bold" | "redesign/message-preview/normal" | "redesign/message-preview/medium" | "redesign/message-preview/semibold" | "redesign/message-preview/bold" | "redesign/channel-title/normal" | "redesign/channel-title/medium" | "redesign/channel-title/semibold" | "redesign/channel-title/bold" | "display-sm" | "display-md" | "display-lg" | "code";
export type FormTextTypes = Record<"DEFAULT" | "INPUT_PLACEHOLDER" | "DESCRIPTION" | "LABEL_BOLD" | "LABEL_SELECTED" | "LABEL_DESCRIPTOR" | "ERROR" | "SUCCESS", string>;
export type HeadingTag = `h${1 | 2 | 3 | 4 | 5 | 6}`;
export type Margins = Record<"marginTop16" | "marginTop8" | "marginBottom8" | "marginTop20" | "marginBottom20", string>;
export type TextProps = PropsWithChildren<HtmlHTMLAttributes<HTMLDivElement> & {
variant?: TextVariant;
tag?: "div" | "span" | "p" | "strong" | HeadingTag;
selectable?: boolean;
lineClamp?: number;
}>;
export type Text = ComponentType<TextProps>;
export type Heading = ComponentType<TextProps>;
export type FormTitle = ComponentType<HTMLProps<HTMLTitleElement> & PropsWithChildren<{
/** default is h5 */
tag?: HeadingTag;
faded?: boolean;
disabled?: boolean;
required?: boolean;
error?: ReactNode;
}>>;
export type FormSection = ComponentType<PropsWithChildren<{
/** default is h5 */
tag?: HeadingTag;
className?: string;
titleClassName?: string;
titleId?: string;
title?: ReactNode;
disabled?: boolean;
htmlFor?: unknown;
}>>;
export type FormDivider = ComponentType<{
className?: string;
style?: CSSProperties;
}>;
export type FormText = ComponentType<PropsWithChildren<{
disabled?: boolean;
selectable?: boolean;
/** defaults to FormText.Types.DEFAULT */
type?: string;
}> & TextProps> & { Types: FormTextTypes; };
export type Tooltip = ComponentType<{
text: ReactNode | ComponentType;
children: FunctionComponent<{
onClick(): void;
onMouseEnter(): void;
onMouseLeave(): void;
onContextMenu(): void;
onFocus(): void;
onBlur(): void;
"aria-label"?: string;
}>;
"aria-label"?: string;
allowOverflow?: boolean;
forceOpen?: boolean;
hide?: boolean;
hideOnClick?: boolean;
shouldShow?: boolean;
spacing?: number;
/** Tooltip.Colors.BLACK */
color?: string;
/** TooltipPositions.TOP */
position?: PopoutPosition;
tooltipClassName?: string;
tooltipContentClassName?: string;
}> & {
Colors: Record<"BLACK" | "BRAND" | "CUSTOM" | "GREEN" | "GREY" | "PRIMARY" | "RED" | "YELLOW", string>;
};
export type TooltipPositions = Record<"BOTTOM" | "CENTER" | "LEFT" | "RIGHT" | "TOP" | "WINDOW_CENTER", string>;
export type TooltipContainer = ComponentType<PropsWithChildren<{
text: ReactNode;
element?: "div" | "span";
"aria-label"?: string | false;
delay?: number;
/** Tooltip.Colors.BLACK */
color?: string;
/** TooltipPositions.TOP */
position?: PopoutPosition;
spacing?: number;
className?: string;
tooltipClassName?: string | null;
tooltipContentClassName?: string | null;
allowOverflow?: boolean;
forceOpen?: boolean;
hideOnClick?: boolean;
disableTooltipPointerEvents?: boolean;
}>>;
export type Card = ComponentType<PropsWithChildren<HTMLProps<HTMLDivElement> & {
editable?: boolean;
outline?: boolean;
/** Card.Types.PRIMARY */
type?: string;
}>> & {
Types: Record<"BRAND" | "CUSTOM" | "DANGER" | "PRIMARY" | "SUCCESS" | "WARNING", string>;
};
export type ComboboxPopout = ComponentType<PropsWithChildren<{
value: Set<any>;
placeholder: string;
children(query: string): ReactNode[];
onChange(value: any): void;
itemToString?: (item: any) => string;
onClose?(): void;
className?: string;
listClassName?: string;
autoFocus?: boolean;
multiSelect?: boolean;
maxVisibleItems?: number;
showScrollbar?: boolean;
}>>;
export interface ButtonProps extends PropsWithChildren<Omit<HTMLProps<HTMLButtonElement>, "size">> {
/** Button.Looks.FILLED */
look?: string;
/** Button.Colors.BRAND */
color?: string;
/** Button.Sizes.MEDIUM */
size?: string;
/** Button.BorderColors.BLACK */
borderColor?: string;
wrapperClassName?: string;
className?: string;
innerClassName?: string;
buttonRef?: Ref<HTMLButtonElement>;
focusProps?: any;
submitting?: boolean;
submittingStartedLabel?: string;
submittingFinishedLabel?: string;
}
export type Button = ComponentType<ButtonProps> & {
BorderColors: Record<"BLACK" | "BRAND" | "BRAND_NEW" | "GREEN" | "LINK" | "PRIMARY" | "RED" | "TRANSPARENT" | "WHITE" | "YELLOW", string>;
Colors: Record<"BRAND" | "RED" | "GREEN" | "YELLOW" | "PRIMARY" | "LINK" | "WHITE" | "BLACK" | "TRANSPARENT" | "BRAND_NEW" | "CUSTOM", string>;
Hovers: Record<"DEFAULT" | "BRAND" | "RED" | "GREEN" | "YELLOW" | "PRIMARY" | "LINK" | "WHITE" | "BLACK" | "TRANSPARENT", string>;
Looks: Record<"FILLED" | "INVERTED" | "OUTLINED" | "LINK" | "BLANK", string>;
Sizes: Record<"NONE" | "TINY" | "SMALL" | "MEDIUM" | "LARGE" | "XLARGE" | "MIN" | "MAX" | "ICON", string>;
Link: any;
};
export type Switch = ComponentType<PropsWithChildren<{
value: boolean;
onChange(value: boolean): void;
disabled?: boolean;
hideBorder?: boolean;
className?: string;
style?: CSSProperties;
note?: ReactNode;
tooltipNote?: ReactNode;
}>>;
export type CheckboxAligns = {
CENTER: "center";
TOP: "top";
};
export type CheckboxTypes = {
DEFAULT: "default";
INVERTED: "inverted";
GHOST: "ghost";
ROW: "row";
};
export type Checkbox = ComponentType<PropsWithChildren<{
value: boolean;
onChange(event: PointerEvent, value: boolean): void;
align?: "center" | "top";
disabled?: boolean;
displayOnly?: boolean;
readOnly?: boolean;
reverse?: boolean;
shape?: string;
size?: number;
type?: "default" | "inverted" | "ghost" | "row";
}>> & {
Shapes: Record<"BOX" | "ROUND" | "SMALL_BOX", string>;
Aligns: CheckboxAligns;
Types: CheckboxTypes;
};
export type Timestamp = ComponentType<PropsWithChildren<{
timestamp: Date;
isEdited?: boolean;
className?: string;
id?: string;
cozyAlt?: boolean;
compact?: boolean;
isInline?: boolean;
isVisibleOnlyOnHover?: boolean;
}>>;
export type TextInput = ComponentType<PropsWithChildren<{
name?: string;
onChange?(value: string, name?: string): void;
placeholder?: string;
editable?: boolean;
/** defaults to 999. Pass null to disable this default */
maxLength?: number | null;
error?: string;
inputClassName?: string;
inputPrefix?: string;
inputRef?: Ref<HTMLInputElement>;
prefixElement?: ReactNode;
focusProps?: any;
/** TextInput.Sizes.DEFAULT */
size?: string;
} & Omit<HTMLProps<HTMLInputElement>, "onChange" | "maxLength">>> & {
Sizes: Record<"DEFAULT" | "MINI", string>;
};
export type TextArea = ComponentType<Omit<HTMLProps<HTMLTextAreaElement>, "onChange"> & {
onChange(v: string): void;
}>;
interface SelectOption {
disabled?: boolean;
value: any;
label: string;
key?: React.Key;
default?: boolean;
}
export type Select = ComponentType<PropsWithChildren<{
placeholder?: string;
options: ReadonlyArray<SelectOption>; // TODO
/**
* - 0 ~ Filled
* - 1 ~ Custom
*/
look?: 0 | 1;
className?: string;
popoutClassName?: string;
popoutPosition?: PopoutPosition;
optionClassName?: string;
autoFocus?: boolean;
isDisabled?: boolean;
clearable?: boolean;
closeOnSelect?: boolean;
hideIcon?: boolean;
select(value: any): void;
isSelected(value: any): boolean;
serialize(value: any): string;
clear?(): void;
maxVisibleItems?: number;
popoutWidth?: number;
onClose?(): void;
onOpen?(): void;
renderOptionLabel?(option: SelectOption): ReactNode;
/** discord stupid this gets all options instead of one yeah */
renderOptionValue?(option: SelectOption[]): ReactNode;
"aria-label"?: boolean;
"aria-labelledby"?: boolean;
}>>;
export type SearchableSelect = ComponentType<PropsWithChildren<{
placeholder?: string;
options: ReadonlyArray<SelectOption>; // TODO
value?: SelectOption;
/**
* - 0 ~ Filled
* - 1 ~ Custom
*/
look?: 0 | 1;
className?: string;
popoutClassName?: string;
wrapperClassName?: string;
popoutPosition?: PopoutPosition;
optionClassName?: string;
autoFocus?: boolean;
isDisabled?: boolean;
clearable?: boolean;
closeOnSelect?: boolean;
clearOnSelect?: boolean;
multi?: boolean;
onChange(value: any): void;
onSearchChange?(value: string): void;
onClose?(): void;
onOpen?(): void;
onBlur?(): void;
renderOptionPrefix?(option: SelectOption): ReactNode;
renderOptionSuffix?(option: SelectOption): ReactNode;
filter?(option: SelectOption[], query: string): SelectOption[];
centerCaret?: boolean;
debounceTime?: number;
maxVisibleItems?: number;
popoutWidth?: number;
"aria-labelledby"?: boolean;
}>>;
export type Slider = ComponentClass<PropsWithChildren<{
initialValue: number;
defaultValue?: number;
keyboardStep?: number;
maxValue?: number;
minValue?: number;
markers?: number[];
stickToMarkers?: boolean;
/** 0 above, 1 below */
markerPosition?: 0 | 1;
orientation?: "horizontal" | "vertical";
getAriaValueText?(currentValue: number): string;
renderMarker?(marker: number): ReactNode;
onMarkerRender?(marker: number): ReactNode;
onValueRender?(value: number): ReactNode;
onValueChange?(value: number): void;
asValueChanges?(value: number): void;
className?: string;
disabled?: boolean;
handleSize?: number;
mini?: boolean;
hideBubble?: boolean;
fillStyles?: CSSProperties;
barStyles?: CSSProperties;
grabberStyles?: CSSProperties;
grabberClassName?: string;
barClassName?: string;
"aria-hidden"?: boolean;
"aria-label"?: string;
"aria-labelledby"?: string;
"aria-describedby"?: string;
}>>;
// TODO - type maybe idk probably not that useful other than the constants
export type Flex = ComponentType<PropsWithChildren<any>> & {
Align: Record<"START" | "END" | "CENTER" | "STRETCH" | "BASELINE", string>;
Direction: Record<"VERTICAL" | "HORIZONTAL" | "HORIZONTAL_REVERSE", string>;
Justify: Record<"START" | "END" | "CENTER" | "BETWEEN" | "AROUND", string>;
Wrap: Record<"NO_WRAP" | "WRAP" | "WRAP_REVERSE", string>;
};
declare enum PopoutAnimation {
NONE = "1",
TRANSLATE = "2",
SCALE = "3",
FADE = "4"
}
type PopoutPosition = "top" | "bottom" | "left" | "right" | "center" | "window_center";
export type Popout = ComponentType<{
children(
thing: {
"aria-controls": string;
"aria-expanded": boolean;
onClick(event: MouseEvent<HTMLElement>): void;
onKeyDown(event: KeyboardEvent<HTMLElement>): void;
onMouseDown(event: MouseEvent<HTMLElement>): void;
},
data: {
isShown: boolean;
position: PopoutPosition;
}
): ReactNode;
shouldShow?: boolean;
targetElementRef: RefObject<any>;
renderPopout(args: {
closePopout(): void;
isPositioned: boolean;
nudge: number;
position: PopoutPosition;
setPopoutRef(ref: any): void;
updatePosition(): void;
}): ReactNode;
onRequestOpen?(): void;
onRequestClose?(): void;
/** "center" and others */
align?: "left" | "right" | "center";
/** Popout.Animation */
animation?: PopoutAnimation;
autoInvert?: boolean;
nudgeAlignIntoViewport?: boolean;
/** "bottom" and others */
position?: PopoutPosition;
positionKey?: string;
spacing?: number;
}> & {
Animation: typeof PopoutAnimation;
};
export type Dialog = ComponentType<JSX.IntrinsicElements["div"]>;
type Resolve = (data: { theme: "light" | "dark", saturation: number; }) => {
hex(): string;
hsl(): string;
int(): number;
spring(): string;
};
export type useToken = (color: {
css: string;
resolve: Resolve;
}) => ReturnType<Resolve>;
export type Paginator = ComponentType<{
currentPage: number;
maxVisiblePages: number;
pageSize: number;
totalCount: number;
onPageChange?(page: number): void;
hideMaxPage?: boolean;
}>;
export type MaskedLink = ComponentType<PropsWithChildren<{
href: string;
rel?: string;
target?: string;
title?: string,
className?: string;
tabIndex?: number;
onClick?(): void;
trusted?: boolean;
messageId?: string;
channelId?: string;
}>>;
export type ScrollerThin = ComponentType<PropsWithChildren<{
className?: string;
style?: CSSProperties;
dir?: "ltr";
orientation?: "horizontal" | "vertical" | "auto";
paddingFix?: boolean;
fade?: boolean;
onClose?(): void;
onScroll?(): void;
}>>;
export type Clickable = <T extends "a" | "div" | "span" | "li" = "div">(props: PropsWithChildren<ComponentPropsWithRef<T>> & {
tag?: T;
}) => ReactNode;
export type Avatar = ComponentType<PropsWithChildren<{
className?: string;
src?: string;
size?: "SIZE_16" | "SIZE_20" | "SIZE_24" | "SIZE_32" | "SIZE_40" | "SIZE_48" | "SIZE_56" | "SIZE_80" | "SIZE_120";
statusColor?: string;
statusTooltip?: string;
statusBackdropColor?: string;
isMobile?: boolean;
isTyping?: boolean;
isSpeaking?: boolean;
typingIndicatorRef?: unknown;
"aria-hidden"?: boolean;
"aria-label"?: string;
}>>;
type FocusLock = ComponentType<PropsWithChildren<{
containerRef: Ref<HTMLElement>;
}>>;
export type Icon = ComponentType<JSX.IntrinsicElements["svg"] & {
size?: string;
colorClass?: string;
} & Record<string, any>>;
export type ColorPicker = ComponentType<{
color: number | null;
showEyeDropper?: boolean;
suggestedColors?: string[];
label?: ReactNode;
onChange(value: number | null): void;
}>;

30
packages/discord-types/src/flux.d.ts vendored Normal file
View file

@ -0,0 +1,30 @@
import { FluxStore } from "./stores/FluxStore";
export class FluxEmitter {
constructor();
changeSentinel: number;
changedStores: Set<FluxStore>;
isBatchEmitting: boolean;
isDispatching: boolean;
isPaused: boolean;
pauseTimer: NodeJS.Timeout | null;
reactChangedStores: Set<FluxStore>;
batched(batch: (...args: any[]) => void): void;
destroy(): void;
emit(): void;
emitNonReactOnce(): void;
emitReactOnce(): void;
getChangeSentinel(): number;
getIsPaused(): boolean;
injectBatchEmitChanges(batch: (...args: any[]) => void): void;
markChanged(store: FluxStore): void;
pause(): void;
resume(): void;
}
export interface Flux {
Store: typeof FluxStore;
Emitter: FluxEmitter;
}

File diff suppressed because one or more lines are too long

9
packages/discord-types/src/index.d.ts vendored Normal file
View file

@ -0,0 +1,9 @@
export * from "./common";
export * from "./classes";
export * from "./components";
export * from "./flux";
export * from "./fluxEvents";
export * from "./menu";
export * from "./stores";
export * from "./utils";
export * as Webpack from "../webpack";

78
packages/discord-types/src/menu.d.ts vendored Normal file
View file

@ -0,0 +1,78 @@
import type { ComponentType, CSSProperties, MouseEvent, PropsWithChildren, ReactNode, UIEvent } from "react";
type RC<C> = ComponentType<PropsWithChildren<C & Record<string, any>>>;
export interface Menu {
Menu: RC<{
navId: string;
onClose(): void;
className?: string;
style?: CSSProperties;
hideScroller?: boolean;
onSelect?(): void;
}>;
MenuSeparator: ComponentType;
MenuGroup: RC<{
label?: string;
}>;
MenuItem: RC<{
id: string;
label: ReactNode;
action?(e: MouseEvent): void;
icon?: ComponentType<any>;
color?: string;
render?: ComponentType<any>;
onChildrenScroll?: Function;
childRowHeight?: number;
listClassName?: string;
disabled?: boolean;
}>;
MenuCheckboxItem: RC<{
id: string;
label: string;
checked: boolean;
action?(e: MouseEvent): void;
disabled?: boolean;
}>;
MenuRadioItem: RC<{
id: string;
group: string;
label: string;
checked: boolean;
action?(e: MouseEvent): void;
disabled?: boolean;
}>;
MenuControlItem: RC<{
id: string;
interactive?: boolean;
}>;
MenuSliderControl: RC<{
minValue: number,
maxValue: number,
value: number,
onChange(value: number): void,
renderValue?(value: number): string,
}>;
MenuSearchControl: RC<{
query: string;
onChange(query: string): void;
placeholder?: string;
}>;
}
export interface ContextMenuApi {
closeContextMenu(): void;
openContextMenu(
event: UIEvent,
render?: Menu["Menu"],
options?: { enableSpellCheck?: boolean; },
renderLazy?: () => Promise<Menu["Menu"]>
): void;
openContextMenuLazy(
event: UIEvent,
renderLazy?: () => Promise<Menu["Menu"]>,
options?: { enableSpellCheck?: boolean; }
): void;
}

View file

@ -0,0 +1,24 @@
import { Channel, FluxStore } from "..";
export class ChannelStore extends FluxStore {
getChannel(channelId: string): Channel;
getBasicChannel(channelId: string): Channel | undefined;
hasChannel(channelId: string): boolean;
getChannelIds(guildId?: string | null): string[];
getMutableBasicGuildChannelsForGuild(guildId: string): Record<string, Channel>;
getMutableGuildChannelsForGuild(guildId: string): Record<string, Channel>;
getAllThreadsForGuild(guildId: string): Channel[];
getAllThreadsForParent(channelId: string): Channel[];
getDMFromUserId(userId: string): string;
getDMChannelFromUserId(userId: string): Channel | undefined;
getDMUserIds(): string[];
getMutableDMsByUserIds(): Record<string, string>;
getMutablePrivateChannels(): Record<string, Channel>;
getSortedPrivateChannels(): Channel[];
getGuildChannelsVersion(guildId: string): number;
getPrivateChannelsVersion(): number;
getInitialOverlayState(): Record<string, Channel>;
}

View file

@ -0,0 +1,43 @@
import { FluxStore } from "..";
export enum DraftType {
ChannelMessage = 0,
ThreadSettings = 1,
FirstThreadMessage = 2,
ApplicationLauncherCommand = 3,
Poll = 4,
SlashCommand = 5,
ForwardContextMessage = 6
}
export interface Draft {
timestamp: number;
draft: string;
}
export interface ThreadSettingsDraft {
timestamp: number;
parentMessageId?: string;
name?: string;
isPrivate?: boolean;
parentChannelId?: string;
location?: string;
}
export type ChannelDrafts = {
[DraftType.ThreadSettings]: ThreadSettingsDraft;
} & {
[key in Exclude<DraftType, DraftType.ThreadSettings>]: Draft;
};
export type UserDrafts = Partial<Record<string, ChannelDrafts>>;
export type DraftState = Partial<Record<string, UserDrafts>>;
export class DraftStore extends FluxStore {
getState(): DraftState;
getRecentlyEditedDrafts(type: DraftType): Array<Draft & { channelId: string; }>;
getDraft(channelId: string, type: DraftType): string;
getThreadSettings(channelId: string): ThreadSettingsDraft | null | undefined;
getThreadDraftWithParentMessageId(parentMessageId: string): ThreadSettingsDraft | null | undefined;
}

View file

@ -0,0 +1,57 @@
import { Channel, CustomEmoji, Emoji, FluxStore } from "..";
export class EmojiStore extends FluxStore {
getCustomEmojiById(id?: string | null): CustomEmoji | undefined;
getUsableCustomEmojiById(id?: string | null): CustomEmoji | undefined;
getGuilds(): Record<string, {
id: string;
get emojis(): CustomEmoji[];
get rawEmojis(): CustomEmoji[];
get usableEmojis(): CustomEmoji[];
get emoticons(): any[];
getEmoji(id: string): CustomEmoji | undefined;
isUsable(emoji: CustomEmoji): boolean;
}>;
getGuildEmoji(guildId?: string | null): CustomEmoji[];
getNewlyAddedEmoji(guildId?: string | null): CustomEmoji[];
getTopEmoji(guildId?: string | null): CustomEmoji[];
getTopEmojisMetadata(guildId?: string | null): {
emojiIds: string[];
topEmojisTTL: number;
};
hasPendingUsage(): boolean;
hasUsableEmojiInAnyGuild(): boolean;
searchWithoutFetchingLatest(data: any): any;
getSearchResultsOrder(...args: any[]): any;
getState(): {
pendingUsages: { key: string, timestamp: number; }[];
};
searchWithoutFetchingLatest(data: {
channel: Channel;
query: string;
count?: number;
intention: number;
includeExternalGuilds?: boolean;
matchComparator?(name: string): boolean;
}): Record<"locked" | "unlocked", Emoji[]>;
getDisambiguatedEmojiContext(): {
backfillTopEmojis: Record<any, any>;
customEmojis: Record<string, CustomEmoji>;
emojisById: Record<string, CustomEmoji>;
emojisByName: Record<string, CustomEmoji>;
emoticonRegex: RegExp | null;
emoticonsByName: Record<string, any>;
escapedEmoticonNames: string;
favoriteNamesAndIds?: any;
favorites?: any;
frequentlyUsed?: any;
groupedCustomEmojis: Record<string, CustomEmoji[]>;
guildId?: string;
isFavoriteEmojiWithoutFetchingLatest(e: Emoji): boolean;
newlyAddedEmoji: Record<string, CustomEmoji[]>;
topEmojis?: any;
unicodeAliases: Record<string, string>;
get favoriteEmojisWithoutFetchingLatest(): Emoji[];
};
}

View file

@ -0,0 +1,44 @@
import { FluxDispatcher, FluxEvents } from "..";
type Callback = () => void;
/*
For some reason, this causes type errors when you try to destructure it:
```ts
interface FluxEvent {
type: FluxEvents;
[key: string]: any;
}
```
*/
export type FluxEvent = any;
export type ActionHandler = (event: FluxEvent) => void;
export type ActionHandlers = Partial<Record<FluxEvents, ActionHandler>>;
export class FluxStore {
constructor(dispatcher: FluxDispatcher, actionHandlers?: ActionHandlers);
getName(): string;
addChangeListener(callback: Callback): void;
/** Listener will be removed once the callback returns false. */
addConditionalChangeListener(callback: () => boolean, preemptive?: boolean): void;
addReactChangeListener(callback: Callback): void;
removeChangeListener(callback: Callback): void;
removeReactChangeListener(callback: Callback): void;
doEmitChanges(event: FluxEvent): void;
emitChange(): void;
getDispatchToken(): string;
initialize(): void;
initializeIfNeeded(): void;
/** this is a setter */
mustEmitChanges(actionHandler: ActionHandler | undefined): void;
registerActionHandlers(actionHandlers: ActionHandlers): void;
syncWith(stores: FluxStore[], callback: Callback, timeout?: number): void;
waitFor(...stores: FluxStore[]): void;
static getAll(): FluxStore[];
}

View file

@ -0,0 +1,27 @@
import { FluxStore, GuildMember } from "..";
export class GuildMemberStore extends FluxStore {
/** @returns Format: [guildId-userId: Timestamp (string)] */
getCommunicationDisabledUserMap(): Record<string, string>;
getCommunicationDisabledVersion(): number;
getMutableAllGuildsAndMembers(): Record<string, Record<string, GuildMember>>;
getMember(guildId: string, userId: string): GuildMember | null;
getTrueMember(guildId: string, userId: string): GuildMember | null;
getMemberIds(guildId: string): string[];
getMembers(guildId: string): GuildMember[];
getCachedSelfMember(guildId: string): GuildMember | null;
getSelfMember(guildId: string): GuildMember | null;
getSelfMemberJoinedAt(guildId: string): Date | null;
getNick(guildId: string, userId: string): string | null;
getNicknameGuildsMapping(userId: string): Record<string, string[]>;
getNicknames(userId: string): string[];
isMember(guildId: string, userId: string): boolean;
isMember(guildId: string, userId: string): boolean;
isGuestOrLurker(guildId: string, userId: string): boolean;
isCurrentUserGuest(guildId: string): boolean;
}

View file

@ -0,0 +1,7 @@
import { FluxStore, Role } from "..";
export class GuildRoleStore extends FluxStore {
getRole(guildId: string, roleId: string): Role;
getRoles(guildId: string): Record<string, Role>;
getAllGuildRoles(): Record<string, Record<string, Role>>;
}

View file

@ -0,0 +1,8 @@
import { Guild, FluxStore } from "..";
export class GuildStore extends FluxStore {
getGuild(guildId: string): Guild;
getGuildCount(): number;
getGuilds(): Record<string, Guild>;
getGuildIds(): string[];
}

View file

@ -0,0 +1,13 @@
import { MessageJSON, FluxStore, Message } from "..";
export class MessageStore extends FluxStore {
getMessage(channelId: string, messageId: string): Message;
/** @returns This return object is fucking huge; I'll type it later. */
getMessages(channelId: string): unknown;
getRawMessages(channelId: string): Record<string | number, MessageJSON>;
hasCurrentUserSentMessage(channelId: string): boolean;
hasPresent(channelId: string): boolean;
isLoadingMessages(channelId: string): boolean;
jumpedMessageId(channelId: string): string | undefined;
whenReady(channelId: string, callback: () => void): void;
}

View file

@ -0,0 +1,21 @@
import { FluxStore } from "..";
export class RelationshipStore extends FluxStore {
getFriendIDs(): string[];
getIgnoredIDs(): string[];
getBlockedIDs(): string[];
getPendingCount(): number;
getRelationshipCount(): number;
/** Related to friend nicknames. */
getNickname(userId: string): string;
/** @returns Enum value from constants.RelationshipTypes */
getRelationshipType(userId: string): number;
isFriend(userId: string): boolean;
isBlocked(userId: string): boolean;
isIgnored(userId: string): boolean;
getSince(userId: string): string;
getMutableRelationships(): Map<string, number>;
}

View file

@ -0,0 +1,14 @@
import { FluxStore } from "..";
export class SelectedChannelStore extends FluxStore {
getChannelId(guildId?: string | null): string;
getVoiceChannelId(): string | undefined;
getCurrentlySelectedChannelId(guildId?: string): string | undefined;
getMostRecentSelectedTextChannelId(guildId: string): string | undefined;
getLastSelectedChannelId(guildId?: string): string;
// yes this returns a string
getLastSelectedChannels(guildId?: string): string;
/** If you follow an announcement channel, this will return whichever channel you chose as destination */
getLastChannelFollowingDestination(): { guildId?: string; channelId?: string; } | undefined;
}

View file

@ -0,0 +1,14 @@
import { FluxStore } from "..";
export interface SelectedGuildState {
selectedGuildTimestampMillis: Record<string | number, number>;
selectedGuildId: string | null;
lastSelectedGuildId: string | null;
}
export class SelectedGuildStore extends FluxStore {
getGuildId(): string | null;
getLastSelectedGuildId(): string | null;
getLastSelectedTimestamp(guildId: string): number | null;
getState(): SelectedGuildState | undefined;
}

View file

@ -0,0 +1,18 @@
import { FluxStore } from "..";
export type ThemePreference = "dark" | "light" | "unknown";
export type SystemTheme = "dark" | "light";
export type Theme = "light" | "dark" | "darker" | "midnight";
export interface ThemeState {
theme: Theme;
status: 0 | 1;
preferences: Record<ThemePreference, Theme>;
}
export class ThemeStore extends FluxStore {
get theme(): Theme;
get darkSidebar(): boolean;
get systemTheme(): SystemTheme;
themePreferenceForSystemTheme(preference: ThemePreference): Theme;
getState(): ThemeState;
}

View file

@ -0,0 +1,10 @@
import { FluxStore, User } from "..";
export class UserStore extends FluxStore {
filter(filter: (user: User) => boolean, sort?: boolean): Record<string, User>;
findByTag(username: string, discriminator: string): User;
forEach(action: (user: User) => void): void;
getCurrentUser(): User;
getUser(userId: string): User;
getUsers(): Record<string, User>;
}

View file

@ -0,0 +1,7 @@
import { FluxStore } from "..";
export class WindowStore extends FluxStore {
isElementFullScreen(): boolean;
isFocused(): boolean;
windowSize(): Record<"width" | "height", number>;
}

View file

@ -0,0 +1,32 @@
// please keep in alphabetical order
export * from "./ChannelStore";
export * from "./DraftStore";
export * from "./EmojiStore";
export * from "./FluxStore";
export * from "./GuildMemberStore";
export * from "./GuildRoleStore";
export * from "./GuildStore";
export * from "./MessageStore";
export * from "./RelationshipStore";
export * from "./SelectedChannelStore";
export * from "./SelectedGuildStore";
export * from "./ThemeStore";
export * from "./UserStore";
export * from "./WindowStore";
/**
* React hook that returns stateful data for one or more stores
* You might need a custom comparator (4th argument) if your store data is an object
* @param stores The stores to listen to
* @param mapper A function that returns the data you need
* @param dependencies An array of reactive values which the hook depends on. Use this if your mapper or equality function depends on the value of another hook
* @param isEqual A custom comparator for the data returned by mapper
*
* @example const user = useStateFromStores([UserStore], () => UserStore.getCurrentUser(), null, (old, current) => old.id === current.id);
*/
export type useStateFromStores = <T>(
stores: any[],
mapper: () => T,
dependencies?: any,
isEqual?: (old: T, newer: T) => boolean
) => T;

335
packages/discord-types/src/utils.d.ts vendored Normal file
View file

@ -0,0 +1,335 @@
import { Channel, Guild, GuildMember, Message, User } from ".";
import type { ReactNode } from "react";
import { LiteralUnion } from "type-fest";
import type { FluxEvents } from "./fluxEvents";
export { FluxEvents };
export interface FluxDispatcher {
_actionHandlers: any;
_subscriptions: any;
dispatch(event: { [key: string]: unknown; type: FluxEvents; }): Promise<void>;
isDispatching(): boolean;
subscribe(event: FluxEvents, callback: (data: any) => void): void;
unsubscribe(event: FluxEvents, callback: (data: any) => void): void;
wait(callback: () => void): void;
}
export type Parser = Record<
| "parse"
| "parseTopic"
| "parseEmbedTitle"
| "parseInlineReply"
| "parseGuildVerificationFormRule"
| "parseGuildEventDescription"
| "parseAutoModerationSystemMessage"
| "parseForumPostGuidelines"
| "parseForumPostMostRecentMessage",
(content: string, inline?: boolean, state?: Record<string, any>) => ReactNode[]
> & Record<"defaultRules" | "guildEventRules", Record<string, Record<"react" | "html" | "parse" | "match" | "order", any>>>;
export interface Alerts {
show(alert: {
title: any;
body: React.ReactNode;
className?: string;
confirmColor?: string;
cancelText?: string;
confirmText?: string;
secondaryConfirmText?: string;
onCancel?(): void;
onConfirm?(): void;
onConfirmSecondary?(): void;
onCloseCallback?(): void;
}): void;
/** This is a noop, it does nothing. */
close(): void;
}
export interface SnowflakeUtils {
fromTimestamp(timestamp: number): string;
extractTimestamp(snowflake: string): number;
age(snowflake: string): number;
atPreviousMillisecond(snowflake: string): string;
compare(snowflake1?: string, snowflake2?: string): number;
}
interface RestRequestData {
url: string;
query?: Record<string, any>;
body?: Record<string, any>;
oldFormErrors?: boolean;
retries?: number;
}
export type RestAPI = Record<"del" | "get" | "patch" | "post" | "put", (data: RestRequestData) => Promise<any>>;
export type Permissions = "CREATE_INSTANT_INVITE"
| "KICK_MEMBERS"
| "BAN_MEMBERS"
| "ADMINISTRATOR"
| "MANAGE_CHANNELS"
| "MANAGE_GUILD"
| "CHANGE_NICKNAME"
| "MANAGE_NICKNAMES"
| "MANAGE_ROLES"
| "MANAGE_WEBHOOKS"
| "MANAGE_GUILD_EXPRESSIONS"
| "CREATE_GUILD_EXPRESSIONS"
| "VIEW_AUDIT_LOG"
| "VIEW_CHANNEL"
| "VIEW_GUILD_ANALYTICS"
| "VIEW_CREATOR_MONETIZATION_ANALYTICS"
| "MODERATE_MEMBERS"
| "SEND_MESSAGES"
| "SEND_TTS_MESSAGES"
| "MANAGE_MESSAGES"
| "EMBED_LINKS"
| "ATTACH_FILES"
| "READ_MESSAGE_HISTORY"
| "MENTION_EVERYONE"
| "USE_EXTERNAL_EMOJIS"
| "ADD_REACTIONS"
| "USE_APPLICATION_COMMANDS"
| "MANAGE_THREADS"
| "CREATE_PUBLIC_THREADS"
| "CREATE_PRIVATE_THREADS"
| "USE_EXTERNAL_STICKERS"
| "SEND_MESSAGES_IN_THREADS"
| "SEND_VOICE_MESSAGES"
| "CONNECT"
| "SPEAK"
| "MUTE_MEMBERS"
| "DEAFEN_MEMBERS"
| "MOVE_MEMBERS"
| "USE_VAD"
| "PRIORITY_SPEAKER"
| "STREAM"
| "USE_EMBEDDED_ACTIVITIES"
| "USE_SOUNDBOARD"
| "USE_EXTERNAL_SOUNDS"
| "REQUEST_TO_SPEAK"
| "MANAGE_EVENTS"
| "CREATE_EVENTS";
export type PermissionsBits = Record<Permissions, bigint>;
export interface MessageSnapshot {
message: Message;
}
export interface Locale {
name: string;
value: string;
localizedName: string;
}
export interface LocaleInfo {
code: string;
enabled: boolean;
name: string;
englishName: string;
postgresLang: string;
}
export interface Clipboard {
copy(text: string): void;
SUPPORTS_COPY: boolean;
}
export interface NavigationRouter {
back(): void;
forward(): void;
transitionTo(path: string, ...args: unknown[]): void;
transitionToGuild(guildId: string, ...args: unknown[]): void;
}
export interface ChannelRouter {
transitionToChannel: (channelId: string) => void;
transitionToThread: (channel: Channel) => void;
}
export interface IconUtils {
getUserAvatarURL(user: User, canAnimate?: boolean, size?: number, format?: string): string;
getDefaultAvatarURL(id: string, discriminator?: string): string;
getUserBannerURL(data: { id: string, banner: string, canAnimate?: boolean, size: number; }): string | undefined;
getAvatarDecorationURL(dara: { avatarDecoration: string, size: number; canCanimate?: boolean; }): string | undefined;
getGuildMemberAvatarURL(member: GuildMember, canAnimate?: string): string | null;
getGuildMemberAvatarURLSimple(data: { guildId: string, userId: string, avatar: string, canAnimate?: boolean; size?: number; }): string;
getGuildMemberBannerURL(data: { id: string, guildId: string, banner: string, canAnimate?: boolean, size: number; }): string | undefined;
getGuildIconURL(data: { id: string, icon?: string, size?: number, canAnimate?: boolean; }): string | undefined;
getGuildBannerURL(guild: Guild, canAnimate?: boolean): string | null;
getChannelIconURL(data: { id: string; icon?: string; applicationId?: string; size?: number; }): string | undefined;
getEmojiURL(data: { id: string, animated: boolean, size: number, forcePNG?: boolean; }): string;
hasAnimatedGuildIcon(guild: Guild): boolean;
isAnimatedIconHash(hash: string): boolean;
getGuildSplashURL: any;
getGuildDiscoverySplashURL: any;
getGuildHomeHeaderURL: any;
getResourceChannelIconURL: any;
getNewMemberActionIconURL: any;
getGuildTemplateIconURL: any;
getApplicationIconURL: any;
getGameAssetURL: any;
getVideoFilterAssetURL: any;
getGuildMemberAvatarSource: any;
getUserAvatarSource: any;
getGuildSplashSource: any;
getGuildDiscoverySplashSource: any;
makeSource: any;
getGameAssetSource: any;
getGuildIconSource: any;
getGuildTemplateIconSource: any;
getGuildBannerSource: any;
getGuildHomeHeaderSource: any;
getChannelIconSource: any;
getApplicationIconSource: any;
getAnimatableSourceWithFallback: any;
}
export interface Constants {
Endpoints: Record<string, any>;
UserFlags: Record<string, number>;
FriendsSections: Record<string, string>;
}
export type ActiveView = LiteralUnion<"emoji" | "gif" | "sticker" | "soundboard", string>;
export interface ExpressionPickerStoreState extends Record<PropertyKey, any> {
activeView: ActiveView | null;
lastActiveView: ActiveView | null;
activeViewType: any | null;
searchQuery: string;
isSearchSuggestion: boolean,
pickerId: string;
}
export interface ExpressionPickerStore {
openExpressionPicker(activeView: ActiveView, activeViewType?: any): void;
closeExpressionPicker(activeViewType?: any): void;
toggleMultiExpressionPicker(activeViewType?: any): void;
toggleExpressionPicker(activeView: ActiveView, activeViewType?: any): void;
setExpressionPickerView(activeView: ActiveView): void;
setSearchQuery(searchQuery: string, isSearchSuggestion?: boolean): void;
useExpressionPickerStore(): ExpressionPickerStoreState;
useExpressionPickerStore<T>(selector: (state: ExpressionPickerStoreState) => T): T;
}
export interface BrowserWindowFeatures {
toolbar?: boolean;
menubar?: boolean;
location?: boolean;
directories?: boolean;
width?: number;
height?: number;
defaultWidth?: number;
defaultHeight?: number;
left?: number;
top?: number;
defaultAlwaysOnTop?: boolean;
movable?: boolean;
resizable?: boolean;
frame?: boolean;
alwaysOnTop?: boolean;
hasShadow?: boolean;
transparent?: boolean;
skipTaskbar?: boolean;
titleBarStyle?: string | null;
backgroundColor?: string;
}
export interface PopoutActions {
open(key: string, render: (windowKey: string) => ReactNode, features?: BrowserWindowFeatures);
close(key: string): void;
setAlwaysOnTop(key: string, alwaysOnTop: boolean): void;
}
export type UserNameUtilsTagInclude = LiteralUnion<"auto" | "always" | "never", string>;
export interface UserNameUtilsTagOptions {
forcePomelo?: boolean;
identifiable?: UserNameUtilsTagInclude;
decoration?: UserNameUtilsTagInclude;
mode?: "full" | "username";
}
export interface UsernameUtils {
getGlobalName(user: User): string;
getFormattedName(user: User, useTagInsteadOfUsername?: boolean): string;
getName(user: User): string;
useName(user: User): string;
getUserTag(user: User, options?: UserNameUtilsTagOptions): string;
useUserTag(user: User, options?: UserNameUtilsTagOptions): string;
useDirectMessageRecipient: any;
humanizeStatus: any;
}
export class DisplayProfile {
userId: string;
banner?: string;
bio?: string;
pronouns?: string;
accentColor?: number;
themeColors?: number[];
popoutAnimationParticleType?: any;
profileEffectId?: string;
_userProfile?: any;
_guildMemberProfile?: any;
canUsePremiumProfileCustomization: boolean;
canEditThemes: boolean;
premiumGuildSince: Date | null;
premiumSince: Date | null;
premiumType?: number;
primaryColor?: number;
getBadges(): Array<{
id: string;
description: string;
icon: string;
link?: string;
}>;
getBannerURL(options: { canAnimate: boolean; size: number; }): string;
getLegacyUsername(): string | null;
hasFullProfile(): boolean;
hasPremiumCustomization(): boolean;
hasThemeColors(): boolean;
isUsingGuildMemberBanner(): boolean;
isUsingGuildMemberBio(): boolean;
isUsingGuildMemberPronouns(): boolean;
}
export interface DisplayProfileUtils {
getDisplayProfile(userId: string, guildId?: string, customStores?: any): DisplayProfile | null;
useDisplayProfile(userId: string, guildId?: string, customStores?: any): DisplayProfile | null;
}
export interface DateUtils {
isSameDay(date1: Date, date2: Date): boolean;
calendarFormat(date: Date): string;
dateFormat(date: Date, format: string): string;
diffAsUnits(start: Date, end: Date, stopAtOneSecond?: boolean): Record<"days" | "hours" | "minutes" | "seconds", number>;
}
export interface CommandOptions {
type: number;
name: string;
description: string;
required?: boolean;
choices?: {
name: string;
values: string | number;
}[];
options?: CommandOptions[];
channel_types?: number[];
min_value?: number;
max_value?: number;
autocomplete?: boolean;
}

View file

@ -0,0 +1,215 @@
/*
* @vencord/discord-types
* Copyright (c) 2024 Vendicated, Nuckyz and contributors
* SPDX-License-Identifier: LGPL-3.0-or-later
*/
export type ModuleExports = any;
export type Module = {
id: PropertyKey;
loaded: boolean;
exports: ModuleExports;
};
/** exports can be anything, however initially it is always an empty object */
export type ModuleFactory = (this: ModuleExports, module: Module, exports: ModuleExports, require: WebpackRequire) => void;
/** Keys here can be symbols too, but we can't properly type them */
export type AsyncModulePromise = Promise<ModuleExports> & {
"__webpack_queues__": (fnQueue: ((queue: any[]) => any)) => any;
"__webpack_exports__": ModuleExports;
"__webpack_error__"?: any;
};
export type AsyncModuleBody = (
handleAsyncDependencies: (deps: AsyncModulePromise[]) =>
Promise<() => ModuleExports[]> | (() => ModuleExports[]),
asyncResult: (error?: any) => void
) => Promise<void>;
export type EnsureChunkHandlers = {
/**
* Ensures the js file for this chunk is loaded, or starts to load if it's not.
* @param chunkId The chunk id
* @param promises The promises array to add the loading promise to
*/
j: (this: EnsureChunkHandlers, chunkId: PropertyKey, promises: Promise<void[]>) => void;
/**
* Ensures the css file for this chunk is loaded, or starts to load if it's not.
* @param chunkId The chunk id
* @param promises The promises array to add the loading promise to. This array will likely contain the promise of the js file too
*/
css: (this: EnsureChunkHandlers, chunkId: PropertyKey, promises: Promise<void[]>) => void;
/**
* Trigger for prefetching next chunks. This is called after ensuring a chunk is loaded and internally looks up
* a map to see if the chunk that just loaded has next chunks to prefetch.
*
* Note that this does not add an extra promise to the promises array, and instead only executes the prefetching after
* calling Promise.all on the promises array.
* @param chunkId The chunk id
* @param promises The promises array of ensuring the chunk is loaded
*/
prefetch: (this: EnsureChunkHandlers, chunkId: PropertyKey, promises: Promise<void[]>) => void;
};
export type PrefetchChunkHandlers = {
/**
* Prefetches the js file for this chunk.
* @param chunkId The chunk id
*/
j: (this: PrefetchChunkHandlers, chunkId: PropertyKey) => void;
};
export type ScriptLoadDone = (event: Event) => void;
export type OnChunksLoaded = ((this: WebpackRequire, result: any, chunkIds: PropertyKey[] | undefined | null, callback: () => any, priority: number) => any) & {
/** Check if a chunk has been loaded */
j: (this: OnChunksLoaded, chunkId: PropertyKey) => boolean;
};
export type WebpackRequire = ((moduleId: PropertyKey) => ModuleExports) & {
/** The module factories, where all modules that have been loaded are stored (pre-loaded or loaded by lazy chunks) */
m: Record<PropertyKey, ModuleFactory>;
/** The module cache, where all modules which have been WebpackRequire'd are stored */
c: Record<PropertyKey, Module>;
// /**
// * Export star. Sets properties of "fromObject" to "toObject" as getters that return the value from "fromObject", like this:
// * @example
// * const fromObject = { a: 1 };
// * Object.keys(fromObject).forEach(key => {
// * if (key !== "default" && !Object.hasOwn(toObject, key)) {
// * Object.defineProperty(toObject, key, {
// * get: () => fromObject[key],
// * enumerable: true
// * });
// * }
// * });
// * @returns fromObject
// */
// es: (this: WebpackRequire, fromObject: AnyRecord, toObject: AnyRecord) => AnyRecord;
/**
* Creates an async module. A module that which has top level await, or requires an export from an async module.
*
* The body function must be an async function. "module.exports" will become an {@link AsyncModulePromise}.
*
* The body function will be called with a function to handle requires that import from an async module, and a function to resolve this async module. An example on how to handle async dependencies:
* @example
* const factory = (module, exports, wreq) => {
* wreq.a(module, async (handleAsyncDependencies, asyncResult) => {
* try {
* const asyncRequireA = wreq(...);
*
* const asyncDependencies = handleAsyncDependencies([asyncRequire]);
* const [requireAResult] = asyncDependencies.then != null ? (await asyncDependencies)() : asyncDependencies;
*
* // Use the required module
* console.log(requireAResult);
*
* // Mark this async module as resolved
* asyncResult();
* } catch(error) {
* // Mark this async module as rejected with an error
* asyncResult(error);
* }
* }, false); // false because our module does not have an await after dealing with the async requires
* }
*/
a: (this: WebpackRequire, module: Module, body: AsyncModuleBody, hasAwaitAfterDependencies?: boolean) => void;
/** getDefaultExport function for compatibility with non-harmony modules */
n: (this: WebpackRequire, exports: any) => () => ModuleExports;
/**
* Create a fake namespace object, useful for faking an __esModule with a default export.
*
* mode & 1: Value is a module id, require it
*
* mode & 2: Merge all properties of value into the namespace
*
* mode & 4: Return value when already namespace object
*
* mode & 16: Return value when it's Promise-like
*
* mode & (8|1): Behave like require
*/
t: (this: WebpackRequire, value: any, mode: number) => any;
/**
* Define getter functions for harmony exports. For every prop in "definiton" (the module exports), set a getter in "exports" for the getter function in the "definition", like this:
* @example
* const exports = {};
* const definition = { exportName: () => someExportedValue };
* for (const key in definition) {
* if (Object.hasOwn(definition, key) && !Object.hasOwn(exports, key)) {
* Object.defineProperty(exports, key, {
* get: definition[key],
* enumerable: true
* });
* }
* }
* // exports is now { exportName: someExportedValue } (but each value is actually a getter)
*/
d: (this: WebpackRequire, exports: Record<PropertyKey, any>, definiton: Record<PropertyKey, () => ModuleExports>) => void;
/** The ensure chunk handlers, which are used to ensure the files of the chunks are loaded, or load if necessary */
f: EnsureChunkHandlers;
/**
* The ensure chunk function, it ensures a chunk is loaded, or loads if needed.
* Internally it uses the handlers in {@link WebpackRequire.f} to load/ensure the chunk is loaded.
*/
e: (this: WebpackRequire, chunkId: PropertyKey) => Promise<void[]>;
/** The prefetch chunk handlers, which are used to prefetch the files of the chunks */
F: PrefetchChunkHandlers;
/**
* The prefetch chunk function.
* Internally it uses the handlers in {@link WebpackRequire.F} to prefetch a chunk.
*/
E: (this: WebpackRequire, chunkId: PropertyKey) => void;
/** Get the filename for the css part of a chunk */
k: (this: WebpackRequire, chunkId: PropertyKey) => string;
/** Get the filename for the js part of a chunk */
u: (this: WebpackRequire, chunkId: PropertyKey) => string;
/** The global object, will likely always be the window */
g: typeof globalThis;
/** Harmony module decorator. Decorates a module as an ES Module, and prevents Node.js "module.exports" from being set */
hmd: (this: WebpackRequire, module: Module) => any;
/** Shorthand for Object.prototype.hasOwnProperty */
o: typeof Object.prototype.hasOwnProperty;
/**
* Function to load a script tag. "done" is called when the loading has finished or a timeout has occurred.
* "done" will be attached to existing scripts loading if src === url or data-webpack === `${uniqueName}:${key}`,
* so it will be called when that existing script finishes loading.
*/
l: (this: WebpackRequire, url: string, done: ScriptLoadDone, key?: string | number, chunkId?: PropertyKey) => void;
/** Defines __esModule on the exports, marking ES Modules compatibility as true */
r: (this: WebpackRequire, exports: ModuleExports) => void;
/** Node.js module decorator. Decorates a module as a Node.js module */
nmd: (this: WebpackRequire, module: Module) => any;
/**
* Register deferred code which will be executed when the passed chunks are loaded.
*
* If chunkIds is defined, it defers the execution of the callback and returns undefined.
*
* If chunkIds is undefined, and no deferred code exists or can be executed, it returns the value of the result argument.
*
* If chunkIds is undefined, and some deferred code can already be executed, it returns the result of the callback function of the last deferred code.
*
* When (priority & 1) it will wait for all other handlers with lower priority to be executed before itself is executed.
*/
O: OnChunksLoaded;
/**
* Instantiate a wasm instance with source using "wasmModuleHash", and importObject "importsObj", and then assign the exports of its instance to "exports".
* @returns The exports argument, but now assigned with the exports of the wasm instance
*/
v: (this: WebpackRequire, exports: ModuleExports, wasmModuleId: any, wasmModuleHash: string, importsObj?: WebAssembly.Imports) => Promise<any>;
/** Bundle public path, where chunk files are stored. Used by other methods which load chunks to obtain the full asset url */
p: string;
/** The runtime id of the current runtime */
j: string;
/** Document baseURI or WebWorker location.href */
b: string;
/* rspack only */
/** rspack version */
rv: (this: WebpackRequire) => string;
/** rspack unique id */
ruid: string;
};

View file

@ -21,7 +21,6 @@
"@types/node": "^22.13.4",
"@types/react": "18.3.1",
"@types/react-dom": "18.3.1",
"discord-types": "^1.3.26",
"standalone-electron-types": "^34.2.0",
"type-fest": "^4.35.0"
}