From d6f120943866a8acfc27e4d2143cd4167eb13e22 Mon Sep 17 00:00:00 2001 From: vee Date: Wed, 19 Jun 2024 03:04:15 +0200 Subject: [PATCH 01/24] fix first set of plugins (#2591) * Add back mangled webpack searching * Make window non enumerable in all cases * fix some webpack commons * oops * fix more webpack commons * fix some finds * fix more webpack commons * fix common names * fix reporter * fix Constants common * more fix * fix SettingsStores (return of old SettingsStoreAPI) * doomsday fix: MutualGroupDMs (#2585) * fix SettingsStoreAPI * fix MessageLinkEmbeds * fix checking uninitialised settings * doomsday fix: BetterSessions (#2587) * doomsday fix: ReviewDB and Summaries (#2586) Co-authored-by: vee * fix various things that use default/other names * fix settings * wbctxmenus * fix BetterSettings * wouldnt it be funny if discord reverted again once we're done * fix ViewIcons * fix showconnections * fix FriendsSince * FakeNitro: fix app icons * doomsday fix: NoPendingCount (#2590) --------- Co-authored-by: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Co-authored-by: Amia <9750071+aamiaa@users.noreply.github.com> Co-authored-by: Manti <67705577+mantikafasi@users.noreply.github.com> --- scripts/generateReport.ts | 3 +- src/api/Commands/commandHelpers.ts | 6 +- src/api/SettingsStores.ts | 69 +++++++++++++++ src/api/index.ts | 3 + src/plugins/_api/badges/index.tsx | 2 +- src/plugins/_api/settingsStores.ts | 43 ++++++++++ src/plugins/_core/settings.tsx | 6 +- src/plugins/arRPC.web/index.tsx | 6 +- src/plugins/betterGifAltText/index.ts | 2 +- src/plugins/betterRoleContext/index.tsx | 8 +- src/plugins/betterSessions/index.tsx | 17 ++-- src/plugins/betterSettings/index.tsx | 10 +-- src/plugins/customRPC/index.tsx | 11 ++- src/plugins/customidle/index.ts | 6 +- src/plugins/fakeNitro/index.tsx | 2 +- src/plugins/friendsSince/index.tsx | 8 +- src/plugins/gameActivityToggle/index.tsx | 9 +- src/plugins/ignoreActivities/index.tsx | 8 +- src/plugins/index.ts | 3 +- src/plugins/messageLinkEmbeds/index.tsx | 12 +-- src/plugins/mutualGroupDMs/index.tsx | 2 +- src/plugins/noPendingCount/index.ts | 2 +- src/plugins/pinDms/index.tsx | 4 +- .../reviewDB/components/ReviewComponent.tsx | 2 +- .../reviewDB/components/ReviewsView.tsx | 13 ++- src/plugins/roleColorEverywhere/index.tsx | 2 +- src/plugins/searchReply/index.tsx | 8 +- src/plugins/seeSummaries/index.tsx | 8 +- src/plugins/serverInfo/GuildInfoModal.tsx | 4 +- src/plugins/showConnections/index.tsx | 9 +- .../components/HiddenChannelLockScreen.tsx | 2 +- src/plugins/spotifyControls/SpotifyStore.ts | 6 +- src/plugins/spotifyControls/index.tsx | 4 +- src/plugins/viewIcons/index.tsx | 4 +- src/plugins/webContextMenus.web/index.ts | 4 +- src/plugins/xsOverlay.desktop/index.ts | 8 +- src/utils/discord.tsx | 2 + src/utils/modal.tsx | 5 +- src/webpack/common/menu.ts | 8 +- src/webpack/common/settingsStores.ts | 13 ++- src/webpack/common/stores.ts | 6 +- src/webpack/common/types/utils.d.ts | 14 ++-- src/webpack/common/utils.ts | 42 ++++++---- src/webpack/patchWebpack.ts | 50 ++++++++--- src/webpack/webpack.ts | 84 +++++++++++++++++++ 45 files changed, 393 insertions(+), 147 deletions(-) create mode 100644 src/api/SettingsStores.ts create mode 100644 src/plugins/_api/settingsStores.ts diff --git a/scripts/generateReport.ts b/scripts/generateReport.ts index b05a424ed..d8cbb44a0 100644 --- a/scripts/generateReport.ts +++ b/scripts/generateReport.ts @@ -46,7 +46,8 @@ await page.setBypassCSP(true); async function maybeGetError(handle: JSHandle): Promise { return await (handle as JSHandle)?.getProperty("message") - .then(m => m?.jsonValue()); + .then(m => m?.jsonValue()) + .catch(() => undefined); } const report = { diff --git a/src/api/Commands/commandHelpers.ts b/src/api/Commands/commandHelpers.ts index 2f7039137..4ae022c59 100644 --- a/src/api/Commands/commandHelpers.ts +++ b/src/api/Commands/commandHelpers.ts @@ -17,14 +17,14 @@ */ import { mergeDefaults } from "@utils/mergeDefaults"; -import { findByPropsLazy } from "@webpack"; +import { findByCodeLazy } from "@webpack"; import { MessageActions, SnowflakeUtils } from "@webpack/common"; import { Message } from "discord-types/general"; import type { PartialDeep } from "type-fest"; import { Argument } from "./types"; -const MessageCreator = findByPropsLazy("createBotMessage"); +const createBotMessage = findByCodeLazy('username:"Clyde"'); export function generateId() { return `-${SnowflakeUtils.fromTimestamp(Date.now())}`; @@ -37,7 +37,7 @@ export function generateId() { * @returns {Message} */ export function sendBotMessage(channelId: string, message: PartialDeep): Message { - const botMessage = MessageCreator.createBotMessage({ channelId, content: "", embeds: [] }); + const botMessage = createBotMessage({ channelId, content: "", embeds: [] }); MessageActions.receiveMessage(channelId, mergeDefaults(message, botMessage)); diff --git a/src/api/SettingsStores.ts b/src/api/SettingsStores.ts new file mode 100644 index 000000000..18139e4e6 --- /dev/null +++ b/src/api/SettingsStores.ts @@ -0,0 +1,69 @@ +/* + * Vencord, a modification for Discord's desktop app + * Copyright (c) 2023 Vendicated and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . +*/ + +import { proxyLazy } from "@utils/lazy"; +import { Logger } from "@utils/Logger"; +import { findModuleId, proxyLazyWebpack, wreq } from "@webpack"; + +import { Settings } from "./Settings"; + +interface Setting { + /** + * Get the setting value + */ + getSetting(): T; + /** + * Update the setting value + * @param value The new value + */ + updateSetting(value: T | ((old: T) => T)): Promise; + /** + * React hook for automatically updating components when the setting is updated + */ + useSetting(): T; + settingsStoreApiGroup: string; + settingsStoreApiName: string; +} + +export const SettingsStores: Array> | undefined = proxyLazyWebpack(() => { + const modId = findModuleId('"textAndImages","renderSpoilers"') as any; + if (modId == null) return new Logger("SettingsStoreAPI").error("Didn't find stores module."); + + const mod = wreq(modId); + if (mod == null) return; + + return Object.values(mod).filter((s: any) => s?.settingsStoreApiGroup) as any; +}); + +/** + * Get the store for a setting + * @param group The setting group + * @param name The name of the setting + */ +export function getSettingStore(group: string, name: string): Setting | undefined { + if (!Settings.plugins.SettingsStoreAPI.enabled) throw new Error("Cannot use SettingsStoreAPI without setting as dependency."); + + return SettingsStores?.find(s => s?.settingsStoreApiGroup === group && s?.settingsStoreApiName === name); +} + +/** + * getSettingStore but lazy + */ +export function getSettingStoreLazy(group: string, name: string) { + return proxyLazy(() => getSettingStore(group, name)); +} diff --git a/src/api/index.ts b/src/api/index.ts index 02c70008a..737e06d60 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -31,6 +31,7 @@ import * as $Notices from "./Notices"; import * as $Notifications from "./Notifications"; import * as $ServerList from "./ServerList"; import * as $Settings from "./Settings"; +import * as $SettingsStores from "./SettingsStores"; import * as $Styles from "./Styles"; /** @@ -116,3 +117,5 @@ export const ChatButtons = $ChatButtons; * An API allowing you to update and re-render messages */ export const MessageUpdater = $MessageUpdater; + +export const SettingsStores = $SettingsStores; diff --git a/src/plugins/_api/badges/index.tsx b/src/plugins/_api/badges/index.tsx index d8e391ae9..cb153c6a9 100644 --- a/src/plugins/_api/badges/index.tsx +++ b/src/plugins/_api/badges/index.tsx @@ -93,7 +93,7 @@ export default definePlugin({ { find: ".PANEL]:14", replacement: { - match: /(?<=(\i)=\(0,\i\.default\)\(\i\);)return 0===\i.length\?/, + match: /(?<=(\i)=\(0,\i\.\i\)\(\i\);)return 0===\i.length\?/, replace: "$1.unshift(...$self.getBadges(arguments[0].displayProfile));$&" } }, diff --git a/src/plugins/_api/settingsStores.ts b/src/plugins/_api/settingsStores.ts new file mode 100644 index 000000000..a888532ee --- /dev/null +++ b/src/plugins/_api/settingsStores.ts @@ -0,0 +1,43 @@ +/* + * Vencord, a modification for Discord's desktop app + * Copyright (c) 2022 Vendicated and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . +*/ + +import { Devs } from "@utils/constants"; +import definePlugin from "@utils/types"; + +export default definePlugin({ + name: "SettingsStoreAPI", + description: "Patches Discord's SettingsStores to expose their group and name", + authors: [Devs.Nuckyz], + + patches: [ + { + find: ",updateSetting:", + replacement: [ + { + match: /(?<=INFREQUENT_USER_ACTION.{0,20}),useSetting:/, + replace: ",settingsStoreApiGroup:arguments[0],settingsStoreApiName:arguments[1]$&" + }, + // some wrapper. just make it copy the group and name + { + match: /updateSetting:.{0,20}shouldSync/, + replace: "settingsStoreApiGroup:arguments[0].settingsStoreApiGroup,settingsStoreApiName:arguments[0].settingsStoreApiName,$&" + } + ] + } + ] +}); diff --git a/src/plugins/_core/settings.tsx b/src/plugins/_core/settings.tsx index e998b8643..85300862a 100644 --- a/src/plugins/_core/settings.tsx +++ b/src/plugins/_core/settings.tsx @@ -94,8 +94,8 @@ export default definePlugin({ { find: "Messages.USER_SETTINGS_ACTIONS_MENU_LABEL", replacement: { - match: /(?<=function\((\i),\i\)\{)(?=let \i=Object.values\(\i.UserSettingsSections\).*?(\i)\.default\.open\()/, - replace: "$2.default.open($1);return;" + match: /(?<=function\((\i),\i\)\{)(?=let \i=Object.values\(\i.\i\).*?(\i\.\i)\.open\()/, + replace: "$2.open($1);return;" } } ], @@ -182,7 +182,7 @@ export default definePlugin({ patchedSettings: new WeakSet(), addSettings(elements: any[], element: { header?: string; settings: string[]; }, sectionTypes: SectionTypes) { - if (this.patchedSettings.has(elements)) return; + if (this.patchedSettings.has(elements) || !this.isRightSpot(element)) return; this.patchedSettings.add(elements); diff --git a/src/plugins/arRPC.web/index.tsx b/src/plugins/arRPC.web/index.tsx index e41e8675e..df307e756 100644 --- a/src/plugins/arRPC.web/index.tsx +++ b/src/plugins/arRPC.web/index.tsx @@ -20,10 +20,10 @@ import { popNotice, showNotice } from "@api/Notices"; import { Link } from "@components/Link"; import { Devs } from "@utils/constants"; import definePlugin, { ReporterTestable } from "@utils/types"; -import { findByPropsLazy } from "@webpack"; +import { findByCodeLazy } from "@webpack"; import { ApplicationAssetUtils, FluxDispatcher, Forms, Toasts } from "@webpack/common"; -const RpcUtils = findByPropsLazy("fetchApplicationsRPC", "getRemoteIconURL"); +const fetchApplicationsRPC = findByCodeLazy("APPLICATION_RPC(", "Client ID"); async function lookupAsset(applicationId: string, key: string): Promise { return (await ApplicationAssetUtils.fetchAssetIds(applicationId, [key]))[0]; @@ -32,7 +32,7 @@ async function lookupAsset(applicationId: string, key: string): Promise const apps: any = {}; async function lookupApp(applicationId: string): Promise { const socket: any = {}; - await RpcUtils.fetchApplicationsRPC(socket, applicationId); + await fetchApplicationsRPC(socket, applicationId); return socket.application; } diff --git a/src/plugins/betterGifAltText/index.ts b/src/plugins/betterGifAltText/index.ts index f0090343e..55fa22525 100644 --- a/src/plugins/betterGifAltText/index.ts +++ b/src/plugins/betterGifAltText/index.ts @@ -36,7 +36,7 @@ export default definePlugin({ { find: ".Messages.GIF,", replacement: { - match: /alt:(\i)=(\i\.default\.Messages\.GIF)(?=,[^}]*\}=(\i))/, + match: /alt:(\i)=(\i\.\i\.Messages\.GIF)(?=,[^}]*\}=(\i))/, replace: // rename prop so we can always use default value "alt_$$:$1=$self.altify($3)||$2", diff --git a/src/plugins/betterRoleContext/index.tsx b/src/plugins/betterRoleContext/index.tsx index ecb1ed400..d69e188c0 100644 --- a/src/plugins/betterRoleContext/index.tsx +++ b/src/plugins/betterRoleContext/index.tsx @@ -5,15 +5,18 @@ */ import { definePluginSettings } from "@api/Settings"; +import { getSettingStoreLazy } from "@api/SettingsStores"; import { ImageIcon } from "@components/Icons"; import { Devs } from "@utils/constants"; import { getCurrentGuild, openImageModal } from "@utils/discord"; import definePlugin, { OptionType } from "@utils/types"; import { findByPropsLazy } from "@webpack"; -import { Clipboard, GuildStore, Menu, PermissionStore, TextAndImagesSettingsStores } from "@webpack/common"; +import { Clipboard, GuildStore, Menu, PermissionStore } from "@webpack/common"; const GuildSettingsActions = findByPropsLazy("open", "selectRole", "updateGuild"); +const DeveloperMode = getSettingStoreLazy("appearance", "developerMode")!; + function PencilIcon() { return ( `${leftPart} 48 - ((this.props.lowerBadgeHeight ?? 16) + 8) + 4 ${rightPart} (this.props.lowerBadgeHeight ?? 16) + 8,` - } } ], @@ -153,14 +144,16 @@ export default definePlugin({ } - lowerBadgeWidth={20} - lowerBadgeHeight={20} + lowerBadgeSize={{ + width: 20, + height: 20 + }} >
- +
); diff --git a/src/plugins/betterSettings/index.tsx b/src/plugins/betterSettings/index.tsx index e0267e4b0..6d8d9855a 100644 --- a/src/plugins/betterSettings/index.tsx +++ b/src/plugins/betterSettings/index.tsx @@ -83,19 +83,19 @@ export default definePlugin({ find: "this.renderArtisanalHack()", replacement: [ { // Fade in on layer - match: /(?<=\((\i),"contextType",\i\.AccessibilityPreferencesContext\);)/, + match: /(?<=\((\i),"contextType",\i\.\i\);)/, replace: "$1=$self.Layer;", predicate: () => settings.store.disableFade }, { // Lazy-load contents - match: /createPromise:\(\)=>([^:}]*?),webpackId:"\d+",name:(?!="CollectiblesShop")"[^"]+"/g, + match: /createPromise:\(\)=>([^:}]*?),webpackId:\d+,name:(?!="CollectiblesShop")"[^"]+"/g, replace: "$&,_:$1", predicate: () => settings.store.eagerLoad } ] }, { // For some reason standardSidebarView also has a small fade-in - find: "DefaultCustomContentScroller:function()", + find: 'minimal:"contentColumnMinimal"', replacement: [ { match: /\(0,\i\.useTransition\)\((\i)/, @@ -111,7 +111,7 @@ export default definePlugin({ { // Load menu TOC eagerly find: "Messages.USER_SETTINGS_WITH_BUILD_OVERRIDE.format", replacement: { - match: /(\i)\(this,"handleOpenSettingsContextMenu",.{0,100}?openContextMenuLazy.{0,100}?(await Promise\.all[^};]*?\)\)).*?,(?=\1\(this)/, + match: /(\i)\(this,"handleOpenSettingsContextMenu",.{0,100}?\i\.\i\).{0,100}?(await Promise\.all[^};]*?\)\)).*?,(?=\1\(this)/, replace: "$&(async ()=>$2)()," }, predicate: () => settings.store.eagerLoad @@ -119,7 +119,7 @@ export default definePlugin({ { // Settings cog context menu find: "Messages.USER_SETTINGS_ACTIONS_MENU_LABEL", replacement: { - match: /\(0,\i.useDefaultUserSettingsSections\)\(\)(?=\.filter\(\i=>\{let\{section:\i\}=)/, + match: /\(0,\i.\i\)\(\)(?=\.filter\(\i=>\{let\{section:\i\}=)/, replace: "$self.wrapMenu($&)" } } diff --git a/src/plugins/customRPC/index.tsx b/src/plugins/customRPC/index.tsx index ed354cba4..7e4e9a938 100644 --- a/src/plugins/customRPC/index.tsx +++ b/src/plugins/customRPC/index.tsx @@ -17,6 +17,7 @@ */ import { definePluginSettings, Settings } from "@api/Settings"; +import { getSettingStoreLazy } from "@api/SettingsStores"; import { ErrorCard } from "@components/ErrorCard"; import { Link } from "@components/Link"; import { Devs } from "@utils/constants"; @@ -26,12 +27,15 @@ import { classes } from "@utils/misc"; import { useAwaiter } from "@utils/react"; import definePlugin, { OptionType } from "@utils/types"; import { findByCodeLazy, findByPropsLazy, findComponentByCodeLazy } from "@webpack"; -import { ApplicationAssetUtils, Button, FluxDispatcher, Forms, GuildStore, React, SelectedChannelStore, SelectedGuildStore, StatusSettingsStores, UserStore } from "@webpack/common"; +import { ApplicationAssetUtils, Button, FluxDispatcher, Forms, GuildStore, React, SelectedChannelStore, SelectedGuildStore, UserStore } from "@webpack/common"; const useProfileThemeStyle = findByCodeLazy("profileThemeStyle:", "--profile-gradient-primary-color"); const ActivityComponent = findComponentByCodeLazy("onOpenGameProfile"); const ActivityClassName = findByPropsLazy("activity", "buttonColor"); +const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; + + async function getApplicationAsset(key: string): Promise { if (/https?:\/\/(cdn|media)\.discordapp\.(com|net)\/attachments\//.test(key)) return "mp:" + key.replace(/https?:\/\/(cdn|media)\.discordapp\.(com|net)\//, ""); return (await ApplicationAssetUtils.fetchAssetIds(settings.store.appID!, [key]))[0]; @@ -390,13 +394,14 @@ export default definePlugin({ name: "CustomRPC", description: "Allows you to set a custom rich presence.", authors: [Devs.captain, Devs.AutumnVN, Devs.nin0dev], + dependencies: ["SettingsStoreAPI"], start: setRpc, stop: () => setRpc(true), settings, settingsAboutComponent: () => { const activity = useAwaiter(createActivity); - const gameActivityEnabled = StatusSettingsStores.ShowCurrentGame.useSetting(); + const gameActivityEnabled = ShowCurrentGame.useSetting(); const { profileThemeStyle } = useProfileThemeStyle({}); return ( @@ -412,7 +417,7 @@ export default definePlugin({ diff --git a/src/plugins/customidle/index.ts b/src/plugins/customidle/index.ts index a59bbcb01..87caea75e 100644 --- a/src/plugins/customidle/index.ts +++ b/src/plugins/customidle/index.ts @@ -44,15 +44,15 @@ export default definePlugin({ find: 'type:"IDLE",idle:', replacement: [ { - match: /Math\.min\((\i\.AfkTimeout\.getSetting\(\)\*\i\.default\.Millis\.SECOND),\i\.IDLE_DURATION\)/, + match: /Math\.min\((\i\.\i\.getSetting\(\)\*\i\.\i\.\i\.SECOND),\i\.\i\)/, replace: "$1" // Decouple idle from afk (phone notifications will remain at user setting or 10 min maximum) }, { - match: /\i\.default\.dispatch\({type:"IDLE",idle:!1}\)/, + match: /\i\.\i\.dispatch\({type:"IDLE",idle:!1}\)/, replace: "$self.handleOnline()" }, { - match: /(setInterval\(\i,\.25\*)\i\.IDLE_DURATION/, + match: /(setInterval\(\i,\.25\*)\i\.\i/, replace: "$1$self.getIntervalDelay()" // For web installs } ] diff --git a/src/plugins/fakeNitro/index.tsx b/src/plugins/fakeNitro/index.tsx index a6c3540d7..cdf74d153 100644 --- a/src/plugins/fakeNitro/index.tsx +++ b/src/plugins/fakeNitro/index.tsx @@ -399,7 +399,7 @@ export default definePlugin({ }, // Separate patch for allowing using custom app icons { - find: ".FreemiumAppIconIds.DEFAULT&&(", + find: /\.getCurrentDesktopIcon.{0,25}\.isPremium/, replacement: { match: /\i\.\i\.isPremium\(\i\.\i\.getCurrentUser\(\)\)/, replace: "true" diff --git a/src/plugins/friendsSince/index.tsx b/src/plugins/friendsSince/index.tsx index 58014f362..6c3542780 100644 --- a/src/plugins/friendsSince/index.tsx +++ b/src/plugins/friendsSince/index.tsx @@ -26,17 +26,17 @@ export default definePlugin({ patches: [ // User popup { - find: ".AnalyticsSections.USER_PROFILE}", + find: ".USER_PROFILE}};return", replacement: { - match: /\i.default,\{userId:(\i.id).{0,30}}\)/, + match: /\i.\i,\{userId:(\i.id).{0,30}}\)/, replace: "$&,$self.friendsSince({ userId: $1 })" } }, // User DMs "User Profile" popup in the right { - find: ".UserPopoutUpsellSource.PROFILE_PANEL,", + find: ".PROFILE_PANEL,", replacement: { - match: /\i.default,\{userId:([^,]+?)}\)/, + match: /\i.\i,\{userId:([^,]+?)}\)/, replace: "$&,$self.friendsSince({ userId: $1 })" } }, diff --git a/src/plugins/gameActivityToggle/index.tsx b/src/plugins/gameActivityToggle/index.tsx index 51feb9165..4e2a390d6 100644 --- a/src/plugins/gameActivityToggle/index.tsx +++ b/src/plugins/gameActivityToggle/index.tsx @@ -17,17 +17,19 @@ */ import { definePluginSettings } from "@api/Settings"; +import { getSettingStoreLazy } from "@api/SettingsStores"; import { disableStyle, enableStyle } from "@api/Styles"; import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants"; import definePlugin, { OptionType } from "@utils/types"; import { findComponentByCodeLazy } from "@webpack"; -import { StatusSettingsStores } from "@webpack/common"; import style from "./style.css?managed"; const Button = findComponentByCodeLazy("Button.Sizes.NONE,disabled:"); +const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; + function makeIcon(showCurrentGame?: boolean) { const { oldIcon } = settings.use(["oldIcon"]); @@ -60,7 +62,7 @@ function makeIcon(showCurrentGame?: boolean) { } function GameActivityToggleButton() { - const showCurrentGame = StatusSettingsStores.ShowCurrentGame.useSetting(); + const showCurrentGame = ShowCurrentGame.useSetting(); return ( + */} - About {plugin.name} - {plugin.description} + + {plugin.description} + {!pluginMeta.userPlugin && ( +
+ + +
+ )} +
Authors
; export default plugins; + export const PluginMeta: Record; } declare module "~pluginNatives" { diff --git a/src/utils/modal.tsx b/src/utils/modal.tsx index 4203068c9..79f777088 100644 --- a/src/utils/modal.tsx +++ b/src/utils/modal.tsx @@ -38,7 +38,7 @@ const enum ModalTransitionState { export interface ModalProps { transitionState: ModalTransitionState; - onClose(): Promise; + onClose(): void; } export interface ModalOptions { diff --git a/src/webpack/common/types/utils.d.ts b/src/webpack/common/types/utils.d.ts index 1cd2bf69d..7f6249be6 100644 --- a/src/webpack/common/types/utils.d.ts +++ b/src/webpack/common/types/utils.d.ts @@ -18,6 +18,7 @@ import { Guild, GuildMember } from "discord-types/general"; import type { ReactNode } from "react"; +import { LiteralUnion } from "type-fest"; import type { FluxEvents } from "./fluxEvents"; import { i18nMessages } from "./i18nMessages"; @@ -221,3 +222,37 @@ export interface Constants { UserFlags: Record; FriendsSections: Record; } + +export interface ExpressionPickerStore { + closeExpressionPicker(activeViewType?: any): void; + openExpressionPicker(activeView: LiteralUnion<"emoji" | "gif" | "sticker", string>, activeViewType?: any): void; +} + +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; +} diff --git a/src/webpack/common/utils.ts b/src/webpack/common/utils.ts index a724769c8..a6853c84a 100644 --- a/src/webpack/common/utils.ts +++ b/src/webpack/common/utils.ts @@ -160,9 +160,15 @@ export const InviteActions = findByPropsLazy("resolveInvite"); export const IconUtils: t.IconUtils = findByPropsLazy("getGuildBannerURL", "getUserAvatarURL"); -const openExpressionPickerMatcher = canonicalizeMatch(/setState\({activeView:\i/); +const openExpressionPickerMatcher = canonicalizeMatch(/setState\({activeView:\i,activeViewType:/); // TODO: type -export const ExpressionPickerStore = mapMangledModuleLazy("expression-picker-last-active-view", { +export const ExpressionPickerStore: t.ExpressionPickerStore = mapMangledModuleLazy("expression-picker-last-active-view", { closeExpressionPicker: filters.byCode("setState({activeView:null"), openExpressionPicker: m => typeof m === "function" && openExpressionPickerMatcher.test(m.toString()), }); + +export const PopoutActions: t.PopoutActions = mapMangledModuleLazy('type:"POPOUT_WINDOW_OPEN"', { + open: filters.byCode('type:"POPOUT_WINDOW_OPEN"'), + close: filters.byCode('type:"POPOUT_WINDOW_CLOSE"'), + setAlwaysOnTop: filters.byCode('type:"POPOUT_WINDOW_SET_ALWAYS_ON_TOP"'), +}); From d07042236d5974f9018a55d032a652ad19733313 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Wed, 19 Jun 2024 16:16:48 -0300 Subject: [PATCH 12/24] Add wrapSettingsHook back; Fix FakeNitro subscription emoji bypass --- src/plugins/_core/settings.tsx | 33 +++++++++------------------------ src/plugins/fakeNitro/index.tsx | 17 +++++++---------- 2 files changed, 16 insertions(+), 34 deletions(-) diff --git a/src/plugins/_core/settings.tsx b/src/plugins/_core/settings.tsx index 50cd6f04b..3cc020836 100644 --- a/src/plugins/_core/settings.tsx +++ b/src/plugins/_core/settings.tsx @@ -56,33 +56,18 @@ export default definePlugin({ } ] }, - // Discord Stable - // FIXME: remove once change merged to stable { find: "Messages.ACTIVITY_SETTINGS", - noWarn: true, - replacement: { - get match() { - switch (Settings.plugins.Settings.settingsLocation) { - case "top": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.USER_SETTINGS/; - case "aboveNitro": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.BILLING_SETTINGS/; - case "belowNitro": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.APP_SETTINGS/; - case "belowActivity": return /(?<=\{section:(\i\.\i)\.DIVIDER},)\{section:"changelog"/; - case "bottom": return /\{section:(\i\.\i)\.CUSTOM,\s*element:.+?}/; - case "aboveActivity": - default: - return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.ACTIVITY_SETTINGS/; - } + replacement: [ + { + match: /(?<=section:(.{0,50})\.DIVIDER\}\))([,;])(?=.{0,200}(\i)\.push.{0,100}label:(\i)\.header)/, + replace: (_, sectionTypes, commaOrSemi, elements, element) => `${commaOrSemi} $self.addSettings(${elements}, ${element}, ${sectionTypes}) ${commaOrSemi}` }, - replace: "...$self.makeSettingsCategories($1),$&" - } - }, - { - find: "Messages.ACTIVITY_SETTINGS", - replacement: { - match: /(?<=section:(.{0,50})\.DIVIDER\}\))([,;])(?=.{0,200}(\i)\.push.{0,100}label:(\i)\.header)/, - replace: (_, sectionTypes, commaOrSemi, elements, element) => `${commaOrSemi} $self.addSettings(${elements}, ${element}, ${sectionTypes}) ${commaOrSemi}` - } + { + match: /({(?=.+?function (\i).{0,120}(\i)=\i\.useMemo.{0,30}return \i\.useMemo\(\(\)=>\i\(\3).+?function\(\){return )\2(?=})/, + replace: (_, rest, settingsHook) => `${rest}$self.wrapSettingsHook(${settingsHook})` + } + ] }, { find: "Messages.USER_SETTINGS_ACTIONS_MENU_LABEL", diff --git a/src/plugins/fakeNitro/index.tsx b/src/plugins/fakeNitro/index.tsx index 26e78ea26..ddcabcbdf 100644 --- a/src/plugins/fakeNitro/index.tsx +++ b/src/plugins/fakeNitro/index.tsx @@ -23,7 +23,7 @@ import { ApngBlendOp, ApngDisposeOp, importApngJs } from "@utils/dependencies"; import { getCurrentGuild } from "@utils/discord"; import { Logger } from "@utils/Logger"; import definePlugin, { OptionType } from "@utils/types"; -import { findByPropsLazy, findStoreLazy, proxyLazyWebpack } from "@webpack"; +import { findByCodeLazy, findByPropsLazy, findStoreLazy, proxyLazyWebpack } from "@webpack"; import { Alerts, ChannelStore, DraftType, EmojiStore, FluxDispatcher, Forms, IconUtils, lodash, Parser, PermissionsBits, PermissionStore, UploadHandler, UserSettingsActionCreators, UserStore } from "@webpack/common"; import type { Emoji } from "@webpack/types"; import type { Message } from "discord-types/general"; @@ -52,6 +52,7 @@ const PreloadedUserSettingsActionCreators = proxyLazyWebpack(() => UserSettingsA const AppearanceSettingsActionCreators = proxyLazyWebpack(() => searchProtoClassField("appearance", PreloadedUserSettingsActionCreators.ProtoClass)); const ClientThemeSettingsActionsCreators = proxyLazyWebpack(() => searchProtoClassField("clientThemeSettings", AppearanceSettingsActionCreators)); +const isUnusableRoleSubscriptionEmoji = findByCodeLazy(".getUserIsAdmin("); const enum EmojiIntentions { REACTION, @@ -234,16 +235,14 @@ export default definePlugin({ } ] }, - // FIXME // Allows the usage of subscription-locked emojis - /* { + { find: ".getUserIsAdmin(", replacement: { - match: /(?=.+?\.getUserIsAdmin\((?<=function (\i)\(\i,\i\){.+?))(\i):function\(\){return \1}/, - // Replace the original export with a func that always returns false and alias the original - replace: "$2:()=>()=>false,isUnusableRoleSubscriptionEmojiOriginal:function(){return $1}" + match: /(function \i\(\i,\i)\){(.{0,250}.getUserIsAdmin\(.+?return!1})/, + replace: (_, rest1, rest2) => `${rest1},fakeNitroOriginal){if(!fakeNitroOriginal)return false;${rest2}` } - }, */ + }, // Allow stickers to be sent everywhere { find: "canUseCustomStickersEverywhere:function", @@ -817,9 +816,7 @@ export default definePlugin({ if (e.type === 0) return true; if (e.available === false) return false; - // FIXME - /* const isUnusableRoleSubEmoji = isUnusableRoleSubscriptionEmojiOriginal ?? RoleSubscriptionEmojiUtils.isUnusableRoleSubscriptionEmoji; - if (isUnusableRoleSubEmoji(e, this.guildId)) return false; */ + if (isUnusableRoleSubscriptionEmoji(e, this.guildId, true)) return false; if (this.canUseEmotes) return e.guildId === this.guildId || hasExternalEmojiPerms(channelId); From a01ee40591f7a1e49b903b24a5ab2a6b278b34a2 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:49:42 -0300 Subject: [PATCH 13/24] Clean-up related additions to mangled exports --- src/api/SettingsStores.ts | 69 --------------- src/api/UserSettingDefinitions.ts | 83 +++++++++++++++++++ src/api/index.ts | 7 +- ...gsStores.ts => userSettingsDefinitions.ts} | 21 +++-- src/plugins/betterRoleContext/index.tsx | 6 +- src/plugins/customRPC/index.tsx | 7 +- src/plugins/gameActivityToggle/index.tsx | 6 +- src/plugins/ignoreActivities/index.tsx | 6 +- src/plugins/messageLinkEmbeds/index.tsx | 6 +- src/utils/discord.tsx | 2 +- src/webpack/common/index.ts | 2 +- src/webpack/common/types/index.d.ts | 1 - src/webpack/common/types/settingsStores.ts | 11 --- src/webpack/common/types/utils.d.ts | 2 +- .../{settingsStores.ts => userSettings.ts} | 0 15 files changed, 120 insertions(+), 109 deletions(-) delete mode 100644 src/api/SettingsStores.ts create mode 100644 src/api/UserSettingDefinitions.ts rename src/plugins/_api/{settingsStores.ts => userSettingsDefinitions.ts} (52%) delete mode 100644 src/webpack/common/types/settingsStores.ts rename src/webpack/common/{settingsStores.ts => userSettings.ts} (100%) diff --git a/src/api/SettingsStores.ts b/src/api/SettingsStores.ts deleted file mode 100644 index 18139e4e6..000000000 --- a/src/api/SettingsStores.ts +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Vencord, a modification for Discord's desktop app - * Copyright (c) 2023 Vendicated and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . -*/ - -import { proxyLazy } from "@utils/lazy"; -import { Logger } from "@utils/Logger"; -import { findModuleId, proxyLazyWebpack, wreq } from "@webpack"; - -import { Settings } from "./Settings"; - -interface Setting { - /** - * Get the setting value - */ - getSetting(): T; - /** - * Update the setting value - * @param value The new value - */ - updateSetting(value: T | ((old: T) => T)): Promise; - /** - * React hook for automatically updating components when the setting is updated - */ - useSetting(): T; - settingsStoreApiGroup: string; - settingsStoreApiName: string; -} - -export const SettingsStores: Array> | undefined = proxyLazyWebpack(() => { - const modId = findModuleId('"textAndImages","renderSpoilers"') as any; - if (modId == null) return new Logger("SettingsStoreAPI").error("Didn't find stores module."); - - const mod = wreq(modId); - if (mod == null) return; - - return Object.values(mod).filter((s: any) => s?.settingsStoreApiGroup) as any; -}); - -/** - * Get the store for a setting - * @param group The setting group - * @param name The name of the setting - */ -export function getSettingStore(group: string, name: string): Setting | undefined { - if (!Settings.plugins.SettingsStoreAPI.enabled) throw new Error("Cannot use SettingsStoreAPI without setting as dependency."); - - return SettingsStores?.find(s => s?.settingsStoreApiGroup === group && s?.settingsStoreApiName === name); -} - -/** - * getSettingStore but lazy - */ -export function getSettingStoreLazy(group: string, name: string) { - return proxyLazy(() => getSettingStore(group, name)); -} diff --git a/src/api/UserSettingDefinitions.ts b/src/api/UserSettingDefinitions.ts new file mode 100644 index 000000000..7a2ed5be9 --- /dev/null +++ b/src/api/UserSettingDefinitions.ts @@ -0,0 +1,83 @@ +/* + * Vencord, a modification for Discord's desktop app + * Copyright (c) 2023 Vendicated and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . +*/ + +import { proxyLazy } from "@utils/lazy"; +import { Logger } from "@utils/Logger"; +import { findModuleId, proxyLazyWebpack, wreq } from "@webpack"; + +import { Settings } from "./Settings"; + +interface UserSettingDefinition { + /** + * Get the setting value + */ + getSetting(): T; + /** + * Update the setting value + * @param value The new value + */ + updateSetting(value: T): Promise; + /** + * Update the setting value + * @param value A callback that accepts the old value as the first argument, and returns the new value + */ + updateSetting(value: (old: T) => T): Promise; + /** + * Stateful React hook for this setting value + */ + useSetting(): T; + userSettingDefinitionsAPIGroup: string; + userSettingDefinitionsAPIName: string; +} + +export const UserSettingsDefinitions: Record> | undefined = proxyLazyWebpack(() => { + const modId = findModuleId('"textAndImages","renderSpoilers"'); + if (modId == null) return new Logger("UserSettingDefinitionsAPI").error("Didn't find settings definitions module."); + + return wreq(modId as any); +}); + +/** + * Get the definition for a setting. + * + * @param group The setting group + * @param name The name of the setting + */ +export function getUserSettingDefinition(group: string, name: string): UserSettingDefinition | undefined { + if (!Settings.plugins.UserSettingDefinitionsAPI.enabled) throw new Error("Cannot use UserSettingDefinitionsAPI without setting as dependency."); + + for (const key in UserSettingsDefinitions) { + const userSettingDefinition = UserSettingsDefinitions[key]; + + if (userSettingDefinition.userSettingDefinitionsAPIGroup === group && userSettingDefinition.userSettingDefinitionsAPIName === name) { + return userSettingDefinition; + } + } +} + +/** + * {@link getUserSettingDefinition}, lazy. + * + * Get the definition for a setting. + * + * @param group The setting group + * @param name The name of the setting + */ +export function getUserSettingDefinitionLazy(group: string, name: string) { + return proxyLazy(() => getUserSettingDefinition(group, name)); +} diff --git a/src/api/index.ts b/src/api/index.ts index 737e06d60..5f8233d21 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -31,8 +31,8 @@ import * as $Notices from "./Notices"; import * as $Notifications from "./Notifications"; import * as $ServerList from "./ServerList"; import * as $Settings from "./Settings"; -import * as $SettingsStores from "./SettingsStores"; import * as $Styles from "./Styles"; +import * as $UserSettingDefinitions from "./UserSettingDefinitions"; /** * An API allowing you to listen to Message Clicks or run your own logic @@ -118,4 +118,7 @@ export const ChatButtons = $ChatButtons; */ export const MessageUpdater = $MessageUpdater; -export const SettingsStores = $SettingsStores; +/** + * An API allowing you to get the definition for an user setting + */ +export const UserSettingDefinitions = $UserSettingDefinitions; diff --git a/src/plugins/_api/settingsStores.ts b/src/plugins/_api/userSettingsDefinitions.ts similarity index 52% rename from src/plugins/_api/settingsStores.ts rename to src/plugins/_api/userSettingsDefinitions.ts index a888532ee..5577a1723 100644 --- a/src/plugins/_api/settingsStores.ts +++ b/src/plugins/_api/userSettingsDefinitions.ts @@ -20,23 +20,30 @@ import { Devs } from "@utils/constants"; import definePlugin from "@utils/types"; export default definePlugin({ - name: "SettingsStoreAPI", - description: "Patches Discord's SettingsStores to expose their group and name", + name: "UserSettingDefinitionsAPI", + description: "Patches Discord's UserSettingDefinitions to expose their group and name.", authors: [Devs.Nuckyz], patches: [ { find: ",updateSetting:", replacement: [ + // Main setting definition { - match: /(?<=INFREQUENT_USER_ACTION.{0,20}),useSetting:/, - replace: ",settingsStoreApiGroup:arguments[0],settingsStoreApiName:arguments[1]$&" + match: /(?<=INFREQUENT_USER_ACTION.{0,20},)useSetting:/, + replace: "userSettingDefinitionsAPIGroup:arguments[0],userSettingDefinitionsAPIName:arguments[1],$&" }, - // some wrapper. just make it copy the group and name + // Selective wrapper { - match: /updateSetting:.{0,20}shouldSync/, - replace: "settingsStoreApiGroup:arguments[0].settingsStoreApiGroup,settingsStoreApiName:arguments[0].settingsStoreApiName,$&" + match: /updateSetting:.{0,100}SELECTIVELY_SYNCED_USER_SETTINGS_UPDATE/, + replace: "userSettingDefinitionsAPIGroup:arguments[0].userSettingDefinitionsAPIGroup,userSettingDefinitionsAPIName:arguments[0].userSettingDefinitionsAPIName,$&" + }, + // Override wrapper + { + match: /updateSetting:.{0,60}USER_SETTINGS_OVERRIDE_CLEAR/, + replace: "userSettingDefinitionsAPIGroup:arguments[0].userSettingDefinitionsAPIGroup,userSettingDefinitionsAPIName:arguments[0].userSettingDefinitionsAPIName,$&" } + ] } ] diff --git a/src/plugins/betterRoleContext/index.tsx b/src/plugins/betterRoleContext/index.tsx index d69e188c0..77be0e2b0 100644 --- a/src/plugins/betterRoleContext/index.tsx +++ b/src/plugins/betterRoleContext/index.tsx @@ -5,7 +5,7 @@ */ import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import { ImageIcon } from "@components/Icons"; import { Devs } from "@utils/constants"; import { getCurrentGuild, openImageModal } from "@utils/discord"; @@ -15,7 +15,7 @@ import { Clipboard, GuildStore, Menu, PermissionStore } from "@webpack/common"; const GuildSettingsActions = findByPropsLazy("open", "selectRole", "updateGuild"); -const DeveloperMode = getSettingStoreLazy("appearance", "developerMode")!; +const DeveloperMode = getUserSettingDefinitionLazy("appearance", "developerMode")!; function PencilIcon() { return ( @@ -65,7 +65,7 @@ export default definePlugin({ name: "BetterRoleContext", description: "Adds options to copy role color / edit role / view role icon when right clicking roles in the user profile", authors: [Devs.Ven, Devs.goodbee], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingDefinitionsAPI"], settings, diff --git a/src/plugins/customRPC/index.tsx b/src/plugins/customRPC/index.tsx index 7e4e9a938..ed2de9b4d 100644 --- a/src/plugins/customRPC/index.tsx +++ b/src/plugins/customRPC/index.tsx @@ -17,7 +17,7 @@ */ import { definePluginSettings, Settings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import { ErrorCard } from "@components/ErrorCard"; import { Link } from "@components/Link"; import { Devs } from "@utils/constants"; @@ -33,8 +33,7 @@ const useProfileThemeStyle = findByCodeLazy("profileThemeStyle:", "--profile-gra const ActivityComponent = findComponentByCodeLazy("onOpenGameProfile"); const ActivityClassName = findByPropsLazy("activity", "buttonColor"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; - +const ShowCurrentGame = getUserSettingDefinitionLazy("status", "showCurrentGame")!; async function getApplicationAsset(key: string): Promise { if (/https?:\/\/(cdn|media)\.discordapp\.(com|net)\/attachments\//.test(key)) return "mp:" + key.replace(/https?:\/\/(cdn|media)\.discordapp\.(com|net)\//, ""); @@ -394,7 +393,7 @@ export default definePlugin({ name: "CustomRPC", description: "Allows you to set a custom rich presence.", authors: [Devs.captain, Devs.AutumnVN, Devs.nin0dev], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingDefinitionsAPI"], start: setRpc, stop: () => setRpc(true), settings, diff --git a/src/plugins/gameActivityToggle/index.tsx b/src/plugins/gameActivityToggle/index.tsx index 4e2a390d6..e7353a5d9 100644 --- a/src/plugins/gameActivityToggle/index.tsx +++ b/src/plugins/gameActivityToggle/index.tsx @@ -17,8 +17,8 @@ */ import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; import { disableStyle, enableStyle } from "@api/Styles"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants"; import definePlugin, { OptionType } from "@utils/types"; @@ -28,7 +28,7 @@ import style from "./style.css?managed"; const Button = findComponentByCodeLazy("Button.Sizes.NONE,disabled:"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; +const ShowCurrentGame = getUserSettingDefinitionLazy("status", "showCurrentGame")!; function makeIcon(showCurrentGame?: boolean) { const { oldIcon } = settings.use(["oldIcon"]); @@ -87,7 +87,7 @@ export default definePlugin({ name: "GameActivityToggle", description: "Adds a button next to the mic and deafen button to toggle game activity.", authors: [Devs.Nuckyz, Devs.RuukuLada], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingDefinitionsAPI"], settings, patches: [ diff --git a/src/plugins/ignoreActivities/index.tsx b/src/plugins/ignoreActivities/index.tsx index 6e34c79f3..431cd3e04 100644 --- a/src/plugins/ignoreActivities/index.tsx +++ b/src/plugins/ignoreActivities/index.tsx @@ -6,7 +6,7 @@ import * as DataStore from "@api/DataStore"; import { definePluginSettings, Settings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import ErrorBoundary from "@components/ErrorBoundary"; import { Flex } from "@components/Flex"; import { Devs } from "@utils/constants"; @@ -28,7 +28,7 @@ interface IgnoredActivity { const RunningGameStore = findStoreLazy("RunningGameStore"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; +const ShowCurrentGame = getUserSettingDefinitionLazy("status", "showCurrentGame")!; function ToggleIcon(activity: IgnoredActivity, tooltipText: string, path: string, fill: string) { return ( @@ -208,7 +208,7 @@ export default definePlugin({ name: "IgnoreActivities", authors: [Devs.Nuckyz], description: "Ignore activities from showing up on your status ONLY. You can configure which ones are specifically ignored from the Registered Games and Activities tabs, or use the general settings below.", - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingDefinitionsAPI"], settings, diff --git a/src/plugins/messageLinkEmbeds/index.tsx b/src/plugins/messageLinkEmbeds/index.tsx index 70681fb28..9fefc82a2 100644 --- a/src/plugins/messageLinkEmbeds/index.tsx +++ b/src/plugins/messageLinkEmbeds/index.tsx @@ -19,7 +19,7 @@ import { addAccessory, removeAccessory } from "@api/MessageAccessories"; import { updateMessage } from "@api/MessageUpdater"; import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants.js"; import { classes } from "@utils/misc"; @@ -54,7 +54,7 @@ const ChannelMessage = findComponentByCodeLazy("childrenExecutedCommand:", ".hid const SearchResultClasses = findByPropsLazy("message", "searchResult"); const EmbedClasses = findByPropsLazy("embedAuthorIcon", "embedAuthor", "embedAuthor"); -const MessageDisplayCompact = getSettingStoreLazy("textAndImages", "messageDisplayCompact")!; +const MessageDisplayCompact = getUserSettingDefinitionLazy("textAndImages", "messageDisplayCompact")!; const messageLinkRegex = /(? } - // FIXME: wtf is this? do we need to pass some proper component?? + // Don't render forward message button renderForwardComponent={() => null} shouldHideMediaOptions={false} shouldAnimate diff --git a/src/webpack/common/index.ts b/src/webpack/common/index.ts index 5da3cc68b..4193330cb 100644 --- a/src/webpack/common/index.ts +++ b/src/webpack/common/index.ts @@ -20,9 +20,9 @@ export * from "./classes"; export * from "./components"; export * from "./menu"; export * from "./react"; -export * from "./settingsStores"; export * from "./stores"; export * as ComponentTypes from "./types/components.d"; export * as MenuTypes from "./types/menu.d"; export * as UtilTypes from "./types/utils.d"; +export * from "./userSettings"; export * from "./utils"; diff --git a/src/webpack/common/types/index.d.ts b/src/webpack/common/types/index.d.ts index 01c968553..a536cdcf1 100644 --- a/src/webpack/common/types/index.d.ts +++ b/src/webpack/common/types/index.d.ts @@ -21,6 +21,5 @@ export * from "./components"; export * from "./fluxEvents"; export * from "./i18nMessages"; export * from "./menu"; -export * from "./settingsStores"; export * from "./stores"; export * from "./utils"; diff --git a/src/webpack/common/types/settingsStores.ts b/src/webpack/common/types/settingsStores.ts deleted file mode 100644 index 5453ca352..000000000 --- a/src/webpack/common/types/settingsStores.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Vencord, a Discord client mod - * Copyright (c) 2024 Vendicated and contributors - * SPDX-License-Identifier: GPL-3.0-or-later - */ - -export interface SettingsStore { - getSetting(): T; - updateSetting(value: T): void; - useSetting(): T; -} diff --git a/src/webpack/common/types/utils.d.ts b/src/webpack/common/types/utils.d.ts index 7f6249be6..ee3f69944 100644 --- a/src/webpack/common/types/utils.d.ts +++ b/src/webpack/common/types/utils.d.ts @@ -82,7 +82,7 @@ interface RestRequestData { retries?: number; } -export type RestAPI = Record<"delete" | "get" | "patch" | "post" | "put", (data: RestRequestData) => Promise>; +export type RestAPI = Record<"del" | "get" | "patch" | "post" | "put", (data: RestRequestData) => Promise>; export type Permissions = "CREATE_INSTANT_INVITE" | "KICK_MEMBERS" diff --git a/src/webpack/common/settingsStores.ts b/src/webpack/common/userSettings.ts similarity index 100% rename from src/webpack/common/settingsStores.ts rename to src/webpack/common/userSettings.ts From ceaaf9ab8a3bb87494573a8442f31cc4a2396bbf Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Thu, 20 Jun 2024 01:00:07 -0300 Subject: [PATCH 14/24] Reporter: Test mapMangledModule --- src/debug/runReporter.ts | 15 ++++++++++++--- src/webpack/webpack.ts | 4 +++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/debug/runReporter.ts b/src/debug/runReporter.ts index 6c7a2a03f..ddd5e5f18 100644 --- a/src/debug/runReporter.ts +++ b/src/debug/runReporter.ts @@ -39,9 +39,8 @@ async function runReporter() { } if (searchType === "waitForStore") method = "findStore"; + let result: any; try { - let result: any; - if (method === "proxyLazyWebpack" || method === "LazyComponentWebpack") { const [factory] = args; result = factory(); @@ -50,16 +49,26 @@ async function runReporter() { result = await Webpack.extractAndLoadChunks(code, matcher); if (result === false) result = null; + } else if (method === "mapMangledModule") { + const [code, mapper] = args; + + result = Webpack.mapMangledModule(code, mapper); + if (Object.keys(result).length !== Object.keys(mapper).length) throw new Error("Webpack Find Fail"); } else { // @ts-ignore result = Webpack[method](...args); } - if (result == null || (result.$$vencordInternal != null && result.$$vencordInternal() == null)) throw "a rock at ben shapiro"; + if (result == null || (result.$$vencordInternal != null && result.$$vencordInternal() == null)) throw new Error("Webpack Find Fail"); } catch (e) { let logMessage = searchType; if (method === "find" || method === "proxyLazyWebpack" || method === "LazyComponentWebpack") logMessage += `(${args[0].toString().slice(0, 147)}...)`; else if (method === "extractAndLoadChunks") logMessage += `([${args[0].map(arg => `"${arg}"`).join(", ")}], ${args[1].toString()})`; + else if (method === "mapMangledModule") { + const failedMappings = Object.keys(args[1]).filter(key => result?.[key] == null); + + logMessage += `("${args[0]}", {\n${failedMappings.map(mapping => `\t${mapping}: ${args[1][mapping].toString().slice(0, 147)}...`).join(",\n")}\n})`; + } else logMessage += `(${args.map(arg => `"${arg}"`).join(", ")})`; ReporterLogger.log("Webpack Find Fail:", logMessage); diff --git a/src/webpack/webpack.ts b/src/webpack/webpack.ts index b536063e8..f776ab1c3 100644 --- a/src/webpack/webpack.ts +++ b/src/webpack/webpack.ts @@ -279,7 +279,7 @@ export function findModuleFactory(...code: string[]) { return wreq.m[id]; } -export const lazyWebpackSearchHistory = [] as Array<["find" | "findByProps" | "findByCode" | "findStore" | "findComponent" | "findComponentByCode" | "findExportedComponent" | "waitFor" | "waitForComponent" | "waitForStore" | "proxyLazyWebpack" | "LazyComponentWebpack" | "extractAndLoadChunks", any[]]>; +export const lazyWebpackSearchHistory = [] as Array<["find" | "findByProps" | "findByCode" | "findStore" | "findComponent" | "findComponentByCode" | "findExportedComponent" | "waitFor" | "waitForComponent" | "waitForStore" | "proxyLazyWebpack" | "LazyComponentWebpack" | "extractAndLoadChunks" | "mapMangledModule", any[]]>; /** * This is just a wrapper around {@link proxyLazy} to make our reporter test for your webpack finds. @@ -483,6 +483,8 @@ export const mapMangledModule = traceFunction("mapMangledModule", function mapMa * }) */ export function mapMangledModuleLazy(code: string, mappers: Record): Record { + if (IS_REPORTER) lazyWebpackSearchHistory.push(["mapMangledModule", [code, mappers]]); + return proxyLazy(() => mapMangledModule(code, mappers)); } From a43d5d595a8b23e36125228d2784cd4baeec056b Mon Sep 17 00:00:00 2001 From: Vendicated Date: Thu, 20 Jun 2024 19:48:37 +0200 Subject: [PATCH 15/24] Plugin Page: add indicator for excluded plugins --- scripts/build/build.mjs | 20 ++- scripts/build/common.mjs | 59 +++++++-- scripts/generatePluginList.ts | 2 +- src/components/PluginSettings/index.tsx | 154 ++++++++++++++--------- src/modules.d.ts | 1 + src/plugins/appleMusic.desktop/index.tsx | 2 +- src/plugins/xsOverlay.desktop/index.ts | 2 +- 7 files changed, 156 insertions(+), 84 deletions(-) diff --git a/scripts/build/build.mjs b/scripts/build/build.mjs index fcf56f66c..817c2cec3 100755 --- a/scripts/build/build.mjs +++ b/scripts/build/build.mjs @@ -21,7 +21,7 @@ import esbuild from "esbuild"; import { readdir } from "fs/promises"; import { join } from "path"; -import { BUILD_TIMESTAMP, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, VERSION, watch } from "./common.mjs"; +import { BUILD_TIMESTAMP, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, resolvePluginName, VERSION, watch } from "./common.mjs"; const defines = { IS_STANDALONE, @@ -76,22 +76,20 @@ const globNativesPlugin = { for (const dir of pluginDirs) { const dirPath = join("src", dir); if (!await exists(dirPath)) continue; - const plugins = await readdir(dirPath); - for (const p of plugins) { - const nativePath = join(dirPath, p, "native.ts"); - const indexNativePath = join(dirPath, p, "native/index.ts"); + const plugins = await readdir(dirPath, { withFileTypes: true }); + for (const file of plugins) { + const fileName = file.name; + const nativePath = join(dirPath, fileName, "native.ts"); + const indexNativePath = join(dirPath, fileName, "native/index.ts"); if (!(await exists(nativePath)) && !(await exists(indexNativePath))) continue; - const nameParts = p.split("."); - const namePartsWithoutTarget = nameParts.length === 1 ? nameParts : nameParts.slice(0, -1); - // pluginName.thing.desktop -> PluginName.thing - const cleanPluginName = p[0].toUpperCase() + namePartsWithoutTarget.join(".").slice(1); + const pluginName = await resolvePluginName(dirPath, file); const mod = `p${i}`; - code += `import * as ${mod} from "./${dir}/${p}/native";\n`; - natives += `${JSON.stringify(cleanPluginName)}:${mod},\n`; + code += `import * as ${mod} from "./${dir}/${fileName}/native";\n`; + natives += `${JSON.stringify(pluginName)}:${mod},\n`; i++; } } diff --git a/scripts/build/common.mjs b/scripts/build/common.mjs index eb7ab905b..c46a559a7 100644 --- a/scripts/build/common.mjs +++ b/scripts/build/common.mjs @@ -53,6 +53,32 @@ export const banner = { `.trim() }; +const PluginDefinitionNameMatcher = /definePlugin\(\{\s*(["'])?name\1:\s*(["'`])(.+?)\2/; +/** + * @param {string} base + * @param {import("fs").Dirent} dirent + */ +export async function resolvePluginName(base, dirent) { + const fullPath = join(base, dirent.name); + const content = dirent.isFile() + ? await readFile(fullPath, "utf-8") + : await (async () => { + for (const file of ["index.ts", "index.tsx"]) { + try { + return await readFile(join(fullPath, file), "utf-8"); + } catch { + continue; + } + } + throw new Error(`Invalid plugin ${fullPath}: could not resolve entry point`); + })(); + + return PluginDefinitionNameMatcher.exec(content)?.[3] + ?? (() => { + throw new Error(`Invalid plugin ${fullPath}: must contain definePlugin call with simple string name property as first property`); + })(); +} + export async function exists(path) { return await access(path, FsConstants.F_OK) .then(() => true) @@ -88,14 +114,16 @@ export const globPlugins = kind => ({ build.onLoad({ filter, namespace: "import-plugins" }, async () => { const pluginDirs = ["plugins/_api", "plugins/_core", "plugins", "userplugins"]; let code = ""; - let plugins = "\n"; - let meta = "\n"; + let pluginsCode = "\n"; + let metaCode = "\n"; + let excludedCode = "\n"; let i = 0; for (const dir of pluginDirs) { const userPlugin = dir === "userplugins"; - if (!await exists(`./src/${dir}`)) continue; - const files = await readdir(`./src/${dir}`, { withFileTypes: true }); + const fullDir = `./src/${dir}`; + if (!await exists(fullDir)) continue; + const files = await readdir(fullDir, { withFileTypes: true }); for (const file of files) { const fileName = file.name; if (fileName.startsWith("_") || fileName.startsWith(".")) continue; @@ -104,23 +132,30 @@ export const globPlugins = kind => ({ const target = getPluginTarget(fileName); if (target && !IS_REPORTER) { - if (target === "dev" && !watch) continue; - if (target === "web" && kind === "discordDesktop") continue; - if (target === "desktop" && kind === "web") continue; - if (target === "discordDesktop" && kind !== "discordDesktop") continue; - if (target === "vencordDesktop" && kind !== "vencordDesktop") continue; + const excluded = + (target === "dev" && !IS_DEV) || + (target === "web" && kind === "discordDesktop") || + (target === "desktop" && kind === "web") || + (target === "discordDesktop" && kind !== "discordDesktop") || + (target === "vencordDesktop" && kind !== "vencordDesktop"); + + if (excluded) { + const name = await resolvePluginName(fullDir, file); + excludedCode += `${JSON.stringify(name)}:${JSON.stringify(target)},\n`; + continue; + } } const folderName = `src/${dir}/${fileName}`.replace(/^src\/plugins\//, ""); const mod = `p${i}`; code += `import ${mod} from "./${dir}/${fileName.replace(/\.tsx?$/, "")}";\n`; - plugins += `[${mod}.name]:${mod},\n`; - meta += `[${mod}.name]:${JSON.stringify({ folderName, userPlugin })},\n`; // TODO: add excluded plugins to display in the UI? + pluginsCode += `[${mod}.name]:${mod},\n`; + metaCode += `[${mod}.name]:${JSON.stringify({ folderName, userPlugin })},\n`; // TODO: add excluded plugins to display in the UI? i++; } } - code += `export default {${plugins}};export const PluginMeta={${meta}};`; + code += `export default {${pluginsCode}};export const PluginMeta={${metaCode}};export const ExcludedPlugins={${excludedCode}};`; return { contents: code, resolveDir: "./src" diff --git a/scripts/generatePluginList.ts b/scripts/generatePluginList.ts index e8aa33a46..3d7c16c01 100644 --- a/scripts/generatePluginList.ts +++ b/scripts/generatePluginList.ts @@ -39,7 +39,7 @@ interface PluginData { hasCommands: boolean; required: boolean; enabledByDefault: boolean; - target: "discordDesktop" | "vencordDesktop" | "web" | "dev"; + target: "discordDesktop" | "vencordDesktop" | "desktop" | "web" | "dev"; filePath: string; } diff --git a/src/components/PluginSettings/index.tsx b/src/components/PluginSettings/index.tsx index 978d2e85a..c659e7838 100644 --- a/src/components/PluginSettings/index.tsx +++ b/src/components/PluginSettings/index.tsx @@ -35,9 +35,9 @@ import { openModalLazy } from "@utils/modal"; import { useAwaiter } from "@utils/react"; import { Plugin } from "@utils/types"; import { findByPropsLazy } from "@webpack"; -import { Alerts, Button, Card, Forms, lodash, Parser, React, Select, Text, TextInput, Toasts, Tooltip } from "@webpack/common"; +import { Alerts, Button, Card, Forms, lodash, Parser, React, Select, Text, TextInput, Toasts, Tooltip, useMemo } from "@webpack/common"; -import Plugins from "~plugins"; +import Plugins, { ExcludedPlugins } from "~plugins"; // Avoid circular dependency const { startDependenciesRecursive, startPlugin, stopPlugin } = proxyLazy(() => require("../../plugins")); @@ -177,6 +177,37 @@ const enum SearchStatus { NEW } +function ExcludedPluginsList({ search }: { search: string; }) { + const matchingExcludedPlugins = Object.entries(ExcludedPlugins) + .filter(([name]) => name.toLowerCase().includes(search)); + + const ExcludedReasons: Record<"web" | "discordDesktop" | "vencordDesktop" | "desktop" | "dev", string> = { + desktop: "Discord Desktop app or Vesktop", + discordDesktop: "Discord Desktop app", + vencordDesktop: "Vesktop app", + web: "Vesktop app and the Web version of Discord", + dev: "Developer version of Vencord" + }; + + return ( + + {matchingExcludedPlugins.length + ? <> + Are you looking for: +
    + {matchingExcludedPlugins.map(([name, reason]) => ( +
  • + {name}: Only available on the {ExcludedReasons[reason]} +
  • + ))} +
+ + : "No plugins meet the search criteria." + } +
+ ); +} + export default function PluginSettings() { const settings = useSettings(); const changes = React.useMemo(() => new ChangeList(), []); @@ -215,26 +246,27 @@ export default function PluginSettings() { return o; }, []); - const sortedPlugins = React.useMemo(() => Object.values(Plugins) + const sortedPlugins = useMemo(() => Object.values(Plugins) .sort((a, b) => a.name.localeCompare(b.name)), []); const [searchValue, setSearchValue] = React.useState({ value: "", status: SearchStatus.ALL }); + const search = searchValue.value.toLowerCase(); const onSearch = (query: string) => setSearchValue(prev => ({ ...prev, value: query })); const onStatusChange = (status: SearchStatus) => setSearchValue(prev => ({ ...prev, status })); const pluginFilter = (plugin: typeof Plugins[keyof typeof Plugins]) => { - const enabled = settings.plugins[plugin.name]?.enabled; - if (enabled && searchValue.status === SearchStatus.DISABLED) return false; - if (!enabled && searchValue.status === SearchStatus.ENABLED) return false; - if (searchValue.status === SearchStatus.NEW && !newPlugins?.includes(plugin.name)) return false; - if (!searchValue.value.length) return true; + const { status } = searchValue; + const enabled = Vencord.Plugins.isPluginEnabled(plugin.name); + if (enabled && status === SearchStatus.DISABLED) return false; + if (!enabled && status === SearchStatus.ENABLED) return false; + if (status === SearchStatus.NEW && !newPlugins?.includes(plugin.name)) return false; + if (!search.length) return true; - const v = searchValue.value.toLowerCase(); return ( - plugin.name.toLowerCase().includes(v) || - plugin.description.toLowerCase().includes(v) || - plugin.tags?.some(t => t.toLowerCase().includes(v)) + plugin.name.toLowerCase().includes(search) || + plugin.description.toLowerCase().includes(search) || + plugin.tags?.some(t => t.toLowerCase().includes(search)) ); }; @@ -255,54 +287,48 @@ export default function PluginSettings() { return lodash.isEqual(newPlugins, sortedPluginNames) ? [] : newPlugins; })); - type P = JSX.Element | JSX.Element[]; - let plugins: P, requiredPlugins: P; - if (sortedPlugins?.length) { - plugins = []; - requiredPlugins = []; + const plugins = [] as JSX.Element[]; + const requiredPlugins = [] as JSX.Element[]; - const showApi = searchValue.value === "API"; - for (const p of sortedPlugins) { - if (p.hidden || (!p.options && p.name.endsWith("API") && !showApi)) - continue; + const showApi = searchValue.value.includes("API"); + for (const p of sortedPlugins) { + if (p.hidden || (!p.options && p.name.endsWith("API") && !showApi)) + continue; - if (!pluginFilter(p)) continue; + if (!pluginFilter(p)) continue; - const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled); + const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled); - if (isRequired) { - const tooltipText = p.required - ? "This plugin is required for Vencord to function." - : makeDependencyList(depMap[p.name]?.filter(d => settings.plugins[d].enabled)); - - requiredPlugins.push( - - {({ onMouseLeave, onMouseEnter }) => ( - changes.handleChange(name)} - disabled={true} - plugin={p} - /> - )} - - ); - } else { - plugins.push( - changes.handleChange(name)} - disabled={false} - plugin={p} - isNew={newPlugins?.includes(p.name)} - key={p.name} - /> - ); - } + if (isRequired) { + const tooltipText = p.required + ? "This plugin is required for Vencord to function." + : makeDependencyList(depMap[p.name]?.filter(d => settings.plugins[d].enabled)); + requiredPlugins.push( + + {({ onMouseLeave, onMouseEnter }) => ( + changes.handleChange(name)} + disabled={true} + plugin={p} + key={p.name} + /> + )} + + ); + } else { + plugins.push( + changes.handleChange(name)} + disabled={false} + plugin={p} + isNew={newPlugins?.includes(p.name)} + key={p.name} + /> + ); } - } else { - plugins = requiredPlugins = No plugins meet search criteria.; } return ( @@ -333,9 +359,18 @@ export default function PluginSettings() { Plugins -
- {plugins} -
+ {plugins.length || requiredPlugins.length + ? ( +
+ {plugins.length + ? plugins + : No plugins meet the search criteria. + } +
+ ) + : + } + @@ -343,7 +378,10 @@ export default function PluginSettings() { Required Plugins
- {requiredPlugins} + {requiredPlugins.length + ? requiredPlugins + : No plugins meet the search criteria. + }
); diff --git a/src/modules.d.ts b/src/modules.d.ts index 70ffcfb91..7566a5bf4 100644 --- a/src/modules.d.ts +++ b/src/modules.d.ts @@ -26,6 +26,7 @@ declare module "~plugins" { folderName: string; userPlugin: boolean; }>; + export const ExcludedPlugins: Record; } declare module "~pluginNatives" { diff --git a/src/plugins/appleMusic.desktop/index.tsx b/src/plugins/appleMusic.desktop/index.tsx index 0d81204e9..6fa989cdd 100644 --- a/src/plugins/appleMusic.desktop/index.tsx +++ b/src/plugins/appleMusic.desktop/index.tsx @@ -9,7 +9,7 @@ import { Devs } from "@utils/constants"; import definePlugin, { OptionType, PluginNative, ReporterTestable } from "@utils/types"; import { ApplicationAssetUtils, FluxDispatcher, Forms } from "@webpack/common"; -const Native = VencordNative.pluginHelpers.AppleMusic as PluginNative; +const Native = VencordNative.pluginHelpers.AppleMusicRichPresence as PluginNative; interface ActivityAssets { large_image?: string; diff --git a/src/plugins/xsOverlay.desktop/index.ts b/src/plugins/xsOverlay.desktop/index.ts index a68373a6a..b42d20210 100644 --- a/src/plugins/xsOverlay.desktop/index.ts +++ b/src/plugins/xsOverlay.desktop/index.ts @@ -136,7 +136,7 @@ const settings = definePluginSettings({ }, }); -const Native = VencordNative.pluginHelpers.XsOverlay as PluginNative; +const Native = VencordNative.pluginHelpers.XSOverlay as PluginNative; export default definePlugin({ name: "XSOverlay", From 2fc814124fa18507d61b6d8cb9a6ba6e4efa93a0 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Fri, 21 Jun 2024 02:23:04 -0300 Subject: [PATCH 16/24] add new webpack apis --- src/plugins/consoleShortcuts/index.ts | 4 +- src/plugins/decor/ui/components/index.ts | 2 +- src/plugins/devCompanion.dev/index.tsx | 2 +- src/webpack/common/components.ts | 4 +- src/webpack/common/types/utils.d.ts | 9 - src/webpack/common/utils.ts | 9 +- src/webpack/patchWebpack.ts | 70 ++- src/webpack/webpack.tsx | 515 ++++++++++++++++------- 8 files changed, 432 insertions(+), 183 deletions(-) diff --git a/src/plugins/consoleShortcuts/index.ts b/src/plugins/consoleShortcuts/index.ts index 9d7c193de..2ce4f0696 100644 --- a/src/plugins/consoleShortcuts/index.ts +++ b/src/plugins/consoleShortcuts/index.ts @@ -91,8 +91,8 @@ function makeShortcuts() { findAllByProps: (...props: string[]) => cacheFindAll(filters.byProps(...props)), findByCode: newFindWrapper(filters.byCode), findAllByCode: (code: string) => cacheFindAll(filters.byCode(code)), - findComponentByCode: newFindWrapper(filters.componentByCode), - findAllComponentsByCode: (...code: string[]) => cacheFindAll(filters.componentByCode(...code)), + findComponentByCode: newFindWrapper(filters.byComponentCode), + findAllComponentsByCode: (...code: string[]) => cacheFindAll(filters.byComponentCode(...code)), findExportedComponent: (...props: string[]) => findByProps(...props)[props[0]], findStore: newFindWrapper(filters.byStoreName), PluginsApi: { getter: () => Vencord.Plugins }, diff --git a/src/plugins/decor/ui/components/index.ts b/src/plugins/decor/ui/components/index.ts index be66fc6d4..5cb182e18 100644 --- a/src/plugins/decor/ui/components/index.ts +++ b/src/plugins/decor/ui/components/index.ts @@ -19,7 +19,7 @@ type DecorationGridItemComponent = ComponentType DecorationGridItem = v; -export const AvatarDecorationModalPreview = findComponent(filters.componentByCode(".shopPreviewBanner"), component => { +export const AvatarDecorationModalPreview = findComponent(filters.byComponentCode(".shopPreviewBanner"), component => { return React.memo(component); }); diff --git a/src/plugins/devCompanion.dev/index.tsx b/src/plugins/devCompanion.dev/index.tsx index 277960cd3..c00dd0786 100644 --- a/src/plugins/devCompanion.dev/index.tsx +++ b/src/plugins/devCompanion.dev/index.tsx @@ -216,7 +216,7 @@ function initWs(isManual = false) { results = Object.keys(search(parsedArgs[0])); break; case "ComponentByCode": - results = cacheFindAll(filters.componentByCode(...parsedArgs)); + results = cacheFindAll(filters.byComponentCode(...parsedArgs)); break; default: return reply("Unknown Find Type " + type); diff --git a/src/webpack/common/components.ts b/src/webpack/common/components.ts index 59304e275..92ff4c3b2 100644 --- a/src/webpack/common/components.ts +++ b/src/webpack/common/components.ts @@ -44,8 +44,8 @@ export let Avatar: t.Avatar = NoopComponent; export let FocusLock: t.FocusLock = NoopComponent; export let useToken: t.useToken; -export const MaskedLink = findComponent(filters.componentByCode("MASKED_LINK)")); -export const Timestamp = findComponent(filters.componentByCode(".Messages.MESSAGE_EDITED_TIMESTAMP_A11Y_LABEL.format")); +export const MaskedLink = findComponent(filters.byComponentCode("MASKED_LINK)")); +export const Timestamp = findComponent(filters.byComponentCode(".Messages.MESSAGE_EDITED_TIMESTAMP_A11Y_LABEL.format")); export const Flex = findComponent(filters.byProps("Justify", "Align", "Wrap")) as t.Flex; export const OAuth2AuthorizeModal = findExportedComponent("OAuth2AuthorizeModal"); diff --git a/src/webpack/common/types/utils.d.ts b/src/webpack/common/types/utils.d.ts index be43a54b1..16dce6d84 100644 --- a/src/webpack/common/types/utils.d.ts +++ b/src/webpack/common/types/utils.d.ts @@ -172,17 +172,8 @@ export interface Clipboard { export interface NavigationRouter { back(): void; forward(): void; - hasNavigated(): boolean; - getHistory(): { - action: string; - length: 50; - [key: string]: any; - }; transitionTo(path: string, ...args: unknown[]): void; transitionToGuild(guildId: string, ...args: unknown[]): void; - replaceWith(...args: unknown[]): void; - getLastRouteChangeSource(): any; - getLastRouteChangeSourceLocationStack(): any; } export interface IconUtils { diff --git a/src/webpack/common/utils.ts b/src/webpack/common/utils.ts index d8616122f..5958974d6 100644 --- a/src/webpack/common/utils.ts +++ b/src/webpack/common/utils.ts @@ -17,7 +17,7 @@ */ // eslint-disable-next-line path-alias/no-relative -import { _resolveDiscordLoaded, filters, find, findByCode, findByProps, waitFor } from "../webpack"; +import { _resolveDiscordLoaded, filters, find, findByCode, findByProps, mapMangledModule, waitFor } from "../webpack"; import type * as t from "./types/utils"; export const FluxDispatcher = find(filters.byProps("dispatch", "subscribe"), (m: t.FluxDispatcher) => { @@ -115,7 +115,12 @@ export const ApplicationAssetUtils = findByProps("fetch export const Clipboard = findByProps("SUPPORTS_COPY", "copy"); -export const NavigationRouter = findByProps("transitionTo", "replaceWith", "transitionToGuild"); +export const NavigationRouter: t.NavigationRouter = mapMangledModule("aTransitioning to ", { + transitionTo: filters.byCode("transitionTo -"), + transitionToGuild: filters.byCode("transitionToGuild -"), + back: filters.byCode("goBack()"), + forward: filters.byCode("goForward()"), +}); export const SettingsRouter = findByProps("open", "saveAccountChanges"); diff --git a/src/webpack/patchWebpack.ts b/src/webpack/patchWebpack.ts index a1887e8db..9797acc60 100644 --- a/src/webpack/patchWebpack.ts +++ b/src/webpack/patchWebpack.ts @@ -192,24 +192,42 @@ function patchFactories(factories: Record(r => _resolveDiscordLoaded = export let wreq: WebpackInstance; export let cache: WebpackInstance["c"]; -export type FilterFn = ((mod: any) => boolean) & { +export type FilterFn = ((module: any) => boolean) & { $$vencordProps?: string[]; + $$vencordIsFactoryFilter?: boolean; }; export const filters = { @@ -44,7 +45,7 @@ export const filters = { byCode: (...code: string[]): FilterFn => { const filter: FilterFn = m => { if (typeof m !== "function") return false; - const s = Function.prototype.toString.call(m); + const s = String(m); for (const c of code) { if (!s.includes(c)) return false; } @@ -62,7 +63,7 @@ export const filters = { return filter; }, - componentByCode: (...code: string[]): FilterFn => { + byComponentCode: (...code: string[]): FilterFn => { const byCodeFilter = filters.byCode(...code); const filter: FilterFn = m => { let inner = m; @@ -80,17 +81,39 @@ export const filters = { filter.$$vencordProps = ["componentByCode", ...code]; return filter; + }, + + byFactoryCode: (...code: string[]): FilterFn => { + const byCodeFilter = filters.byCode(...code); + + byCodeFilter.$$vencordProps = ["byFactoryCode", ...code]; + byCodeFilter.$$vencordIsFactoryFilter = true; + + return byCodeFilter; } }; -export type ModCallbackFn = ((mod: any) => void) & { +type ModuleFactory = (module: any, exports: any, require: WebpackInstance) => void; + +export type ModListenerInfo = { + id: PropertyKey; + factory: ModuleFactory; +}; + +export type ModCallbackInfo = { + id: PropertyKey; + exportKey: PropertyKey | null; + factory: ModuleFactory; +}; + +export type ModListenerFn = (module: any, info: ModListenerInfo) => void; +export type ModCallbackFn = ((module: any, info: ModCallbackInfo) => void) & { $$vencordCallbackCalled?: () => boolean; }; -export type ModCallbackFnWithId = (mod: any, id: string) => void; +export const factoryListeners = new Set<(factory: ModuleFactory) => void>(); +export const moduleListeners = new Set(); export const waitForSubscriptions = new Map(); -export const moduleListeners = new Set(); -export const factoryListeners = new Set<(factory: (module: any, exports: any, require: WebpackInstance) => void) => void>(); export const beforeInitListeners = new Set<(wreq: WebpackInstance) => void>(); export function _initWebpack(webpackRequire: WebpackInstance) { @@ -106,25 +129,25 @@ if (IS_DEV && IS_DISCORD_DESKTOP) { }, 0); } -export const webpackSearchHistory = [] as Array<["waitFor" | "find" | "findComponent" | "findExportedComponent" | "findComponentByCode" | "findByProps" | "findByCode" | "findStore" | "extractAndLoadChunks" | "webpackDependantLazy" | "webpackDependantLazyComponent", any[]]>; +export const webpackSearchHistory = [] as Array<["waitFor" | "find" | "findComponent" | "findExportedComponent" | "findComponentByCode" | "findByProps" | "findByCode" | "findStore" | "findByFactoryCode" | "mapMangledModule" | "extractAndLoadChunks" | "webpackDependantLazy" | "webpackDependantLazyComponent", any[]]>; function printFilter(filter: FilterFn) { if (filter.$$vencordProps != null) { const props = filter.$$vencordProps; - return `${props[0]}(${props.slice(1).map(arg => `"${arg}"`).join(", ")})`; + return `${props[0]}(${props.slice(1).map(arg => JSON.stringify(arg)).join(", ")})`; } return filter.toString(); } /** - * Wait for the first module that matches the provided filter to be required, - * then call the callback with the module as the first argument. + * Wait for the first export or module exports that matches the provided filter to be required, + * then call the callback with the export or module exports as the first argument. * - * If the module is already required, the callback will be called immediately. + * If the module containing the export(s) is already required, the callback will be called immediately. * - * @param filter A function that takes a module and returns a boolean - * @param callback A function that takes the found module as its first argument + * @param filter A function that takes an export or module exports and returns a boolean + * @param callback A function that takes the find result as its first argument */ export function waitFor(filter: FilterFn, callback: ModCallbackFn, { isIndirect = false }: { isIndirect?: boolean; } = {}) { if (typeof filter !== "function") @@ -147,28 +170,28 @@ export function waitFor(filter: FilterFn, callback: ModCallbackFn, { isIndirect } if (cache != null) { - const existing = cacheFind(filter); - if (existing) return callback(existing); + const { result, id, exportKey, factory } = _cacheFind(filter); + if (result != null) return callback(result, { id: id!, exportKey: exportKey as PropertyKey | null, factory: factory! }); } waitForSubscriptions.set(filter, callback); } /** - * Find the first module that matches the filter. + * Find the first export or module exports that matches the filter. * * The way this works internally is: - * Wait for the first module that matches the provided filter to be required, - * then call the callback with the module as the first argument. + * Wait for the first export or module exports that matches the provided filter to be required, + * then call the callback with the export or module exports as the first argument. * - * If the module is already required, the callback will be called immediately. + * If the module containing the export(s) is already required, the callback will be called immediately. * * The callback must return a value that will be used as the proxy inner value. * - * If no callback is specified, the default callback will assign the proxy inner value to all the module. + * If no callback is specified, the default callback will assign the proxy inner value to the plain find result * - * @param filter A function that takes a module and returns a boolean - * @param callback A function that takes the found module as its first argument and returns something to use as the proxy inner value. Useful if you want to use a value from the module, instead of all of it. Defaults to the module itself + * @param filter A function that takes an export or module exports and returns a boolean + * @param callback A function that takes the find result as its first argument and returns something to use as the proxy inner value. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself * @returns A proxy that has the callback return value as its true value, or the callback return value if the callback was called when the function was called */ export function find(filter: FilterFn, callback: (mod: any) => any = m => m, { isIndirect = false }: { isIndirect?: boolean; } = {}) { @@ -178,7 +201,7 @@ export function find(filter: FilterFn, callback: (mod: any) => an throw new Error("Invalid callback. Expected a function got " + typeof callback); const [proxy, setInnerValue] = proxyInner(`Webpack find matched no module. Filter: ${printFilter(filter)}`, "Webpack find with proxy called on a primitive value. This can happen if you try to destructure a primitive in the top level definition of the find."); - waitFor(filter, mod => setInnerValue(callback(mod)), { isIndirect: true }); + waitFor(filter, m => setInnerValue(callback(m)), { isIndirect: true }); if (IS_REPORTER && !isIndirect) { webpackSearchHistory.push(["find", [proxy, filter]]); @@ -190,9 +213,9 @@ export function find(filter: FilterFn, callback: (mod: any) => an } /** - * Find the first component that matches the filter. + * Find the first exported component that matches the filter. * - * @param filter A function that takes a module and returns a boolean + * @param filter A function that takes an export or module exports and returns a boolean * @param parse A function that takes the found component as its first argument and returns a component. Useful if you want to wrap the found component in something. Defaults to the original component * @returns The component if found, or a noop component */ @@ -277,7 +300,7 @@ export function findExportedComponent(...props: string[] } /** - * Find the first component in a default export that includes all the given code. + * Find the first component in an export that includes all the given code. * * @example findComponentByCode(".Messages.USER_SETTINGS_PROFILE_COLOR_SELECT_COLOR") * @example findComponentByCode(".Messages.USER_SETTINGS_PROFILE_COLOR_SELECT_COLOR", ".BACKGROUND_PRIMARY)", ColorPicker => React.memo(ColorPicker)) @@ -290,7 +313,7 @@ export function findComponentByCode(...code: string[] | const parse = (typeof code.at(-1) === "function" ? code.pop() : m => m) as (component: any) => LazyComponentType; const newCode = code as string[]; - const ComponentResult = findComponent(filters.componentByCode(...newCode), parse, { isIndirect: true }); + const ComponentResult = findComponent(filters.byComponentCode(...newCode), parse, { isIndirect: true }); if (IS_REPORTER) { webpackSearchHistory.push(["findComponentByCode", [ComponentResult, ...newCode]]); @@ -300,9 +323,9 @@ export function findComponentByCode(...code: string[] | } /** - * Find the first module or default export that includes all the given props. + * Find the first module exports or export that includes all the given props. * - * @param props A list of props to search the exports for + * @param props A list of props to search the module or exports for */ export function findByProps(...props: string[]) { const result = find(filters.byProps(...props), m => m, { isIndirect: true }); @@ -315,7 +338,7 @@ export function findByProps(...props: string[]) { } /** - * Find the first default export that includes all the given code. + * Find the first export that includes all the given code. * * @param code A list of code to search each export for */ @@ -345,32 +368,152 @@ export function findStore(name: string) { } /** - * Find the first already required module that matches the filter. + * Find the module exports of the first module which the factory includes all the given code. * - * @param filter A function that takes a module and returns a boolean - * @returns The found module or null + * @param code A list of code to search each factory for */ -export const cacheFind = traceFunction("cacheFind", function cacheFind(filter: FilterFn) { +export function findByFactoryCode(...code: string[]) { + const result = find(filters.byFactoryCode(...code), m => m, { isIndirect: true }); + + if (IS_REPORTER) { + webpackSearchHistory.push(["findByFactoryCode", [result, ...code]]); + } + + return result; +} + +/** + * Find the first module factory that includes all the given code. + */ +export function findModuleFactory(...code: string[]) { + const filter = filters.byFactoryCode(...code); + + const [proxy, setInnerValue] = proxyInner(`Webpack module factory find matched no module. Filter: ${printFilter(filter)}`, "Webpack find with proxy called on a primitive value. This can happen if you try to destructure a primitive in the top level definition of the find."); + waitFor(filter, (_, { factory }) => setInnerValue(factory)); + + if (proxy[SYM_PROXY_INNER_VALUE] != null) return proxy[SYM_PROXY_INNER_VALUE] as ProxyInner; + + return proxy; +} + +/** + * Find the module exports of the first module which the factory includes all the given code, + * then map them into an easily usable object via the specified mappers. + * + * @example + * const Modals = mapMangledModule("headerIdIsManaged:", { + * openModal: filters.byCode("headerIdIsManaged:"), + * closeModal: filters.byCode("key==") + * }); + * + * @param code The code or list of code to search each factory for + * @param mappers Mappers to create the non mangled exports object + * @returns Unmangled exports as specified in mappers + */ +export function mapMangledModule(code: string | string[], mappers: Record) { + const result = find>(filters.byFactoryCode(...Array.isArray(code) ? code : [code]), exports => { + const mapping = {} as Record; + + outer: + for (const newName in mappers) { + const filter = mappers[newName]; + + if (typeof exports === "object") { + for (const exportKey in exports) { + const exportValue = exports[exportKey]; + + if (exportValue != null && filter(exportValue)) { + mapping[newName] = exportValue; + continue outer; + } + } + } + + const [proxy] = proxyInner(`Webpack mapMangled mapper filter matched no module. Filter: ${printFilter(filter)}`, "Webpack find with proxy called on a primitive value. This can happen if you try to destructure a primitive in the top level definition of the find."); + // Use the proxy to throw errors because no export matched the filter + mapping[newName] = proxy; + } + + return mapping; + }, { isIndirect: true }); + + if (IS_REPORTER) { + webpackSearchHistory.push(["mapMangledModule", [result, code, mappers]]); + } + + return result; +} + +type CacheFindResult = { + /** The find result. `undefined` if nothing was found */ + result?: any; + /** The id of the module exporting where the result was found. `undefined` if nothing was found */ + id?: PropertyKey; + /** The key exporting the result. `null` if the find result was all the module exports, `undefined` if nothing was found */ + exportKey?: PropertyKey | null; + /** The factory of the module exporting the result. `undefined` if nothing was found */ + factory?: ModuleFactory; +}; + +/** + * Find the first export or module exports from an already required module that matches the filter. + * + * @param filter A function that takes an export or module exports and returns a boolean + */ +export const _cacheFind = traceFunction("cacheFind", function _cacheFind(filter: FilterFn): CacheFindResult { if (typeof filter !== "function") throw new Error("Invalid filter. Expected a function got " + typeof filter); for (const key in cache) { const mod = cache[key]; - if (!mod?.exports) continue; + if (!mod?.loaded || mod?.exports == null) continue; - if (filter(mod.exports)) { - return mod.exports; + if (filter.$$vencordIsFactoryFilter && filter(wreq.m[key])) { + return { result: exports, id: key, exportKey: null, factory: wreq.m[key] }; } - if (mod.exports.default && filter(mod.exports.default)) { - return mod.exports.default; + if (filter(mod.exports)) { + return { result: exports, id: key, exportKey: null, factory: wreq.m[key] }; + } + + if (typeof mod.exports !== "object") { + continue; + } + + if (mod.exports.default != null && filter(mod.exports.default)) { + return { result: exports.default, id: key, exportKey: "default ", factory: wreq.m[key] }; + } + + for (const exportKey in mod.exports) if (exportKey.length <= 3) { + const exportValue = mod.exports[exportKey]; + + if (exportValue != null && filter(exportValue)) { + return { result: exportValue, id: key, exportKey, factory: wreq.m[key] }; + } } } - return null; + return {}; }); +/** + * Find the first export or module exports from an already required module that matches the filter. + * + * @param filter A function that takes an export or module exports and returns a boolean + * @returns The found export or module exports, or undefined + */ +export function cacheFind(filter: FilterFn) { + const cacheFindResult = _cacheFind(filter); + return cacheFindResult.result; +} + +/** + * Find the the export or module exports from an all the required modules that match the filter. + * + * @param filter A function that takes an export or module exports and returns a boolean + * @returns An array of all the found export or module exports + */ export function cacheFindAll(filter: FilterFn) { if (typeof filter !== "function") throw new Error("Invalid filter. Expected a function got " + typeof filter); @@ -378,15 +521,32 @@ export function cacheFindAll(filter: FilterFn) { const ret = [] as any[]; for (const key in cache) { const mod = cache[key]; - if (!mod?.exports) continue; + if (!mod?.loaded || mod?.exports == null) continue; + + if (filter.$$vencordIsFactoryFilter && filter(wreq.m[key])) { + ret.push(mod.exports); + } if (filter(mod.exports)) { ret.push(mod.exports); } - if (mod.exports.default && filter(mod.exports.default)) { + if (typeof mod.exports !== "object") { + continue; + } + + if (mod.exports.default != null && filter(mod.exports.default)) { ret.push(mod.exports.default); } + + for (const exportKey in mod.exports) if (exportKey.length <= 3) { + const exportValue = mod.exports[exportKey]; + + if (exportValue != null && filter(exportValue)) { + ret.push(exportValue); + break; + } + } } return ret; @@ -395,18 +555,19 @@ export function cacheFindAll(filter: FilterFn) { /** * Same as {@link cacheFind} but in bulk. * - * @param filterFns Array of filters. Please note that this array will be modified in place, so if you still - * need it afterwards, pass a copy. + * @param filterFns Array of filters * @returns Array of results in the same order as the passed filters */ export const cacheFindBulk = traceFunction("cacheFindBulk", function cacheFindBulk(...filterFns: FilterFn[]) { - if (!Array.isArray(filterFns)) + if (!Array.isArray(filterFns)) { throw new Error("Invalid filters. Expected function[] got " + typeof filterFns); + } const { length } = filterFns; - if (length === 0) + if (length === 0) { throw new Error("Expected at least two filters."); + } if (length === 1) { if (IS_DEV) { @@ -419,27 +580,56 @@ export const cacheFindBulk = traceFunction("cacheFindBulk", function cacheFindBu let found = 0; const results = Array(length); + const filters = [...filterFns] as Array; + outer: for (const key in cache) { const mod = cache[key]; - if (!mod?.exports) continue; + if (!mod?.loaded || mod?.exports == null) continue; - for (let j = 0; j < length; j++) { - const filter = filterFns[j]; + for (let i = 0; i < length; i++) { + const filter = filters[i]; + if (filter == null) continue; + + if (filter.$$vencordIsFactoryFilter && filter(wreq.m[key])) { + results[i] = mod.exports; + filters[i] = undefined; - if (filter(mod.exports)) { - results[j] = mod.exports; - filterFns.splice(j--, 1); if (++found === length) break outer; break; } - if (mod.exports.default && filter(mod.exports.default)) { - results[j] = mod.exports.default; - filterFns.splice(j--, 1); + if (filter(mod.exports)) { + results[i] = mod.exports; + filters[i] = undefined; + if (++found === length) break outer; break; } + + if (typeof mod.exports !== "object") { + break; + } + + if (mod.exports.default != null && filter(mod.exports.default)) { + results[i] = mod.exports.default; + filters[i] = undefined; + + if (++found === length) break outer; + continue; + } + + for (const exportKey in mod.exports) if (exportKey.length <= 3) { + const exportValue = mod.exports[exportKey]; + + if (exportValue != null && filter(mod.exports[key])) { + results[i] = exportValue; + filters[i] = undefined; + + if (++found === length) break outer; + break; + } + } } } @@ -458,16 +648,17 @@ export const cacheFindBulk = traceFunction("cacheFindBulk", function cacheFindBu }); /** - * Find the id of the first module factory that includes all the given code. + * Find the id of the first already loaded module factory that includes all the given code. */ -export const findModuleId = traceFunction("findModuleId", function findModuleId(...code: string[]) { +export const cacheFindModuleId = traceFunction("cacheFindModuleId", function cacheFindModuleId(...code: string[]) { outer: for (const id in wreq.m) { - const str = wreq.m[id].toString(); + const str = String(wreq.m[id]); for (const c of code) { if (!str.includes(c)) continue outer; } + return id; } @@ -475,18 +666,17 @@ export const findModuleId = traceFunction("findModuleId", function findModuleId( if (!IS_DEV || devToolsOpen) { logger.warn(err); - return null; } else { throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found } }); /** - * Find the first module factory that includes all the given code. + * Find the first already loaded module factory that includes all the given code. */ -export function findModuleFactory(...code: string[]) { - const id = findModuleId(...code); - if (!id) return null; +export function cacheFindModuleFactory(...code: string[]) { + const id = cacheFindModuleId(...code); + if (id == null) return; return wreq.m[id]; } @@ -522,6 +712,82 @@ export function webpackDependantLazyComponent(factory: ( return LazyComponent(factory, attempts); } +export const DefaultExtractAndLoadChunksRegex = /(?:(?:Promise\.all\(\[)?(\i\.e\("?[^)]+?"?\)[^\]]*?)(?:\]\))?|Promise\.resolve\(\))\.then\(\i\.bind\(\i,"?([^)]+?)"?\)\)/; +export const ChunkIdsRegex = /\("([^"]+?)"\)/g; + +/** + * Extract and load chunks using their entry point. + * + * @param code The code or list of code the module factory containing the lazy chunk loading must include + * @param matcher A RegExp that returns the chunk ids array as the first capture group and the entry point id as the second. Defaults to a matcher that captures the first lazy chunk loading found in the module factory + * @returns A function that returns a promise that resolves with a boolean whether the chunks were loaded, on first call + */ +export function extractAndLoadChunksLazy(code: string | string[], matcher: RegExp = DefaultExtractAndLoadChunksRegex) { + const module = findModuleFactory(...Array.isArray(code) ? code : [code]); + + async function extractAndLoadChunks() { + if (module[SYM_PROXY_INNER_VALUE]) { + const err = new Error("extractAndLoadChunks: Couldn't find module factory"); + + if (!IS_DEV || devToolsOpen) { + logger.warn(err, "Code:", code, "Matcher:", matcher); + return false; + } else { + throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found + } + } + + const match = String(module).match(canonicalizeMatch(matcher)); + if (!match) { + const err = new Error("extractAndLoadChunks: Couldn't find chunk loading in module factory code"); + + if (!IS_DEV || devToolsOpen) { + logger.warn(err, "Code:", code, "Matcher:", matcher); + return false; + } else { + throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found + } + } + + const [, rawChunkIds, entryPointId] = match; + if (Number.isNaN(Number(entryPointId))) { + const err = new Error("extractAndLoadChunks: Matcher didn't return a capturing group with the chunk ids array, or the entry point id returned as the second group wasn't a number"); + + if (!IS_DEV || devToolsOpen) { + logger.warn(err, "Code:", code, "Matcher:", matcher); + return false; + } else { + throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found + } + } + + if (rawChunkIds) { + const chunkIds = Array.from(rawChunkIds.matchAll(ChunkIdsRegex)).map((m: any) => m[1]); + await Promise.all(chunkIds.map(id => wreq.e(id))); + } + + if (wreq.m[entryPointId] == null) { + const err = new Error("extractAndLoadChunks: Entry point is not loaded in the module factories, perhaps one of the chunks failed to load"); + + if (!IS_DEV || devToolsOpen) { + logger.warn(err, "Code:", code, "Matcher:", matcher); + return false; + } else { + throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found + } + } + + wreq(entryPointId as any); + return true; + } + + if (IS_REPORTER) { + webpackSearchHistory.push(["extractAndLoadChunks", [extractAndLoadChunks]]); + } + + return extractAndLoadChunks; +} + function deprecatedRedirect any>(oldMethod: string, newMethod: string, redirect: T): T { return ((...args: Parameters) => { logger.warn(`Method ${oldMethod} is deprecated. Use ${newMethod} instead. For more information read https://github.com/Vendicated/Vencord/pull/2409#issue-2277161516`); @@ -606,6 +872,25 @@ export const findComponentByCodeLazy = deprecatedRedirect("findComponentByCodeLa */ export const findExportedComponentLazy = deprecatedRedirect("findExportedComponentLazy", "findExportedComponent", findExportedComponent); +/** + * @deprecated Use {@link mapMangledModule} instead + * + * {@link mapMangledModule}, lazy. + * + * Finds a mangled module by the provided code "code" (must be unique and can be anywhere in the module) + * then maps it into an easily usable module via the specified mappers. + * + * @param code The code to look for + * @param mappers Mappers to create the non mangled exports + * @returns Unmangled exports as specified in mappers + * + * @example mapMangledModule("headerIdIsManaged:", { + * openModal: filters.byCode("headerIdIsManaged:"), + * closeModal: filters.byCode("key==") + * }) + */ +export const mapMangledModuleLazy = deprecatedRedirect("mapMangledModuleLazy", "mapMangledModule", mapMangledModule); + /** * @deprecated Use {@link cacheFindAll} instead */ @@ -622,87 +907,13 @@ export const findAll = deprecatedRedirect("findAll", "cacheFindAll", cacheFindAl */ export const findBulk = deprecatedRedirect("findBulk", "cacheFindBulk", cacheFindBulk); -export const DefaultExtractAndLoadChunksRegex = /(?:(?:Promise\.all\(\[)?(\i\.e\("[^)]+?"\)[^\]]*?)(?:\]\))?|Promise\.resolve\(\))\.then\(\i\.bind\(\i,"([^)]+?)"\)\)/; -export const ChunkIdsRegex = /\("([^"]+?)"\)/g; - /** - * Extract and load chunks using their entry point. + * @deprecated Use {@link cacheFindModuleId} instead * - * @param code An array of all the code the module factory containing the lazy chunk loading must include - * @param matcher A RegExp that returns the chunk ids array as the first capture group and the entry point id as the second. Defaults to a matcher that captures the first lazy chunk loading found in the module factory - * @returns A promise that resolves with a boolean whether the chunks were loaded + * Find the id of the first module factory that includes all the given code + * @returns string or null */ -export async function extractAndLoadChunks(code: string[], matcher: RegExp = DefaultExtractAndLoadChunksRegex) { - const module = findModuleFactory(...code); - if (!module) { - const err = new Error("extractAndLoadChunks: Couldn't find module factory"); - - if (!IS_DEV || devToolsOpen) { - logger.warn(err, "Code:", code, "Matcher:", matcher); - return false; - } else { - throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found - } - } - - const match = module.toString().match(canonicalizeMatch(matcher)); - if (!match) { - const err = new Error("extractAndLoadChunks: Couldn't find chunk loading in module factory code"); - - if (!IS_DEV || devToolsOpen) { - logger.warn(err, "Code:", code, "Matcher:", matcher); - return false; - } else { - throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found - } - } - - const [, rawChunkIds, entryPointId] = match; - if (Number.isNaN(Number(entryPointId))) { - const err = new Error("extractAndLoadChunks: Matcher didn't return a capturing group with the chunk ids array, or the entry point id returned as the second group wasn't a number"); - - if (!IS_DEV || devToolsOpen) { - logger.warn(err, "Code:", code, "Matcher:", matcher); - return false; - } else { - throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found - } - } - - if (rawChunkIds) { - const chunkIds = Array.from(rawChunkIds.matchAll(ChunkIdsRegex)).map((m: any) => m[1]); - await Promise.all(chunkIds.map(id => wreq.e(id))); - } - - if (wreq.m[entryPointId] == null) { - const err = new Error("extractAndLoadChunks: Entry point is not loaded in the module factories, perhaps one of the chunks failed to load"); - - if (!IS_DEV || devToolsOpen) { - logger.warn(err, "Code:", code, "Matcher:", matcher); - return false; - } else { - throw err; // Strict behaviour in DevBuilds to fail early and make sure the issue is found - } - } - - wreq(entryPointId); - return true; -} - -/** - * This is just a wrapper around {@link extractAndLoadChunks} to make our reporter test for your webpack finds. - * - * Extract and load chunks using their entry point. - * - * @param code An array of all the code the module factory containing the lazy chunk loading must include - * @param matcher A RegExp that returns the chunk ids array as the first capture group and the entry point id as the second. Defaults to a matcher that captures the first lazy chunk loading found in the module factory - * @returns A function that returns a promise that resolves with a boolean whether the chunks were loaded, on first call - */ -export function extractAndLoadChunksLazy(code: string[], matcher = DefaultExtractAndLoadChunksRegex) { - if (IS_REPORTER) webpackSearchHistory.push(["extractAndLoadChunks", [code, matcher]]); - - return makeLazy(() => extractAndLoadChunks(code, matcher)); -} +export const findModuleId = deprecatedRedirect("findModuleId", "cacheFindModuleId", cacheFindModuleId); /** * Search modules by keyword. This searches the factory methods, @@ -717,10 +928,10 @@ export function search(...filters: Array) { outer: for (const id in factories) { const factory = factories[id]; - const str: string = factory.toString(); + const factoryStr = String(factory); for (const filter of filters) { - if (typeof filter === "string" && !str.includes(filter)) continue outer; - if (filter instanceof RegExp && !filter.test(str)) continue outer; + if (typeof filter === "string" && !factoryStr.includes(filter)) continue outer; + if (filter instanceof RegExp && !filter.test(factoryStr)) continue outer; } results[id] = factory; } @@ -737,17 +948,17 @@ export function search(...filters: Array) { * * @param id The id of the module to extract */ -export function extract(id: string | number) { - const mod = wreq.m[id] as Function; - if (!mod) return null; +export function extract(id: PropertyKey) { + const factory = wreq.m[id] as Function; + if (!factory) return; const code = ` -// [EXTRACTED] WebpackModule${id} +// [EXTRACTED] WebpackModule${String(id)} // WARNING: This module was extracted to be more easily readable. // This module is NOT ACTUALLY USED! This means putting breakpoints will have NO EFFECT!! -0,${mod.toString()} -//# sourceURL=ExtractedWebpackModule${id} +0,${String(factory)} +//# sourceURL=ExtractedWebpackModule${String(id)} `; const extracted = (0, eval)(code); return extracted as Function; From f6dbcb77091d955e6800096a16a204d81a7db116 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Fri, 21 Jun 2024 03:05:30 -0300 Subject: [PATCH 17/24] lazy extractAndLoadChunks result --- src/webpack/webpack.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/webpack/webpack.tsx b/src/webpack/webpack.tsx index 388fe7942..36f243300 100644 --- a/src/webpack/webpack.tsx +++ b/src/webpack/webpack.tsx @@ -4,7 +4,7 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ -import { proxyLazy } from "@utils/lazy"; +import { makeLazy, proxyLazy } from "@utils/lazy"; import { LazyComponent, LazyComponentType, SYM_LAZY_COMPONENT_INNER } from "@utils/lazyReact"; import { Logger } from "@utils/Logger"; import { canonicalizeMatch } from "@utils/patches"; @@ -725,7 +725,7 @@ export const ChunkIdsRegex = /\("([^"]+?)"\)/g; export function extractAndLoadChunksLazy(code: string | string[], matcher: RegExp = DefaultExtractAndLoadChunksRegex) { const module = findModuleFactory(...Array.isArray(code) ? code : [code]); - async function extractAndLoadChunks() { + const extractAndLoadChunks = makeLazy(async () => { if (module[SYM_PROXY_INNER_VALUE] == null) { const err = new Error("extractAndLoadChunks: Couldn't find module factory"); @@ -779,7 +779,7 @@ export function extractAndLoadChunksLazy(code: string | string[], matcher: RegEx wreq(entryPointId as any); return true; - } + }); if (IS_REPORTER) { webpackSearchHistory.push(["extractAndLoadChunks", [extractAndLoadChunks]]); From e93562b95b892ed2dbdd1ad3fcea39f822d32959 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Fri, 21 Jun 2024 03:53:39 -0300 Subject: [PATCH 18/24] Test mapMangledModule with new api --- src/api/UserSettingDefinitions.ts | 2 +- .../VencordSettings/PatchHelperTab.tsx | 2 +- src/debug/loadLazyChunks.ts | 4 +- src/debug/runReporter.ts | 52 ++++++++++++++----- src/plugins/decor/ui/index.ts | 4 +- src/plugins/devCompanion.dev/index.tsx | 2 +- src/plugins/fakeProfileThemes/index.tsx | 2 +- .../pinDms/components/CreateCategoryModal.tsx | 2 +- src/webpack/webpack.tsx | 2 +- 9 files changed, 49 insertions(+), 23 deletions(-) diff --git a/src/api/UserSettingDefinitions.ts b/src/api/UserSettingDefinitions.ts index a4dd5147f..f87df9973 100644 --- a/src/api/UserSettingDefinitions.ts +++ b/src/api/UserSettingDefinitions.ts @@ -65,7 +65,7 @@ export function getUserSettingDefinition(group: string, name: string): } /** - * {@link getUserSettingDefinition}, lazy. + * Lazy version of {@link getUserSettingDefinition} * * Get the definition for a setting. * diff --git a/src/components/VencordSettings/PatchHelperTab.tsx b/src/components/VencordSettings/PatchHelperTab.tsx index e09a1dbf3..857b976e9 100644 --- a/src/components/VencordSettings/PatchHelperTab.tsx +++ b/src/components/VencordSettings/PatchHelperTab.tsx @@ -56,7 +56,7 @@ function ReplacementComponent({ module, match, replacement, setReplacementError const [compileResult, setCompileResult] = React.useState<[boolean, string]>(); const [patchedCode, matchResult, diff] = React.useMemo(() => { - const src: string = fact.toString().replaceAll("\n", ""); + const src = String(fact).replaceAll("\n", ""); try { new RegExp(match); diff --git a/src/debug/loadLazyChunks.ts b/src/debug/loadLazyChunks.ts index 64c3e0ead..abaef263d 100644 --- a/src/debug/loadLazyChunks.ts +++ b/src/debug/loadLazyChunks.ts @@ -111,14 +111,14 @@ export async function loadLazyChunks() { Webpack.factoryListeners.add(factory => { let isResolved = false; - searchAndLoadLazyChunks(factory.toString()).then(() => isResolved = true); + searchAndLoadLazyChunks(String(factory)).then(() => isResolved = true); chunksSearchPromises.push(() => isResolved); }); for (const factoryId in wreq.m) { let isResolved = false; - searchAndLoadLazyChunks(wreq.m[factoryId].toString()).then(() => isResolved = true); + searchAndLoadLazyChunks(String(wreq.m[factoryId])).then(() => isResolved = true); chunksSearchPromises.push(() => isResolved); } diff --git a/src/debug/runReporter.ts b/src/debug/runReporter.ts index 4c903bddc..e02e29a36 100644 --- a/src/debug/runReporter.ts +++ b/src/debug/runReporter.ts @@ -33,10 +33,8 @@ async function runReporter() { await Promise.all(Webpack.webpackSearchHistory.map(async ([searchType, args]) => { args = [...args]; - let result: any; + let result = null as any; try { - let result = null as any; - switch (searchType) { case "webpackDependantLazy": case "webpackDependantLazyComponent": { @@ -45,13 +43,12 @@ async function runReporter() { break; } case "extractAndLoadChunks": { - const [code, matcher] = args; - result = true; + const extractAndLoadChunks = args.shift(); - /* result = await Webpack.extractAndLoadChunks(code, matcher); + result = await extractAndLoadChunks(); if (result === false) { result = null; - } */ + } break; } @@ -65,6 +62,14 @@ async function runReporter() { if (findResult[SYM_PROXY_INNER_GET] != null) { result = findResult[SYM_PROXY_INNER_VALUE]; + + if (result != null && searchType === "mapMangledModule") { + for (const innerMap in result) { + if (result[innerMap][SYM_PROXY_INNER_GET] != null) { + throw new Error("Webpack Find Fail"); + } + } + } } if (findResult[SYM_LAZY_COMPONENT_INNER] != null) { @@ -77,7 +82,7 @@ async function runReporter() { } if (result == null) { - throw "a rock at ben shapiro"; + throw new Error("Webpack Find Fail"); } } catch (e) { let logMessage = searchType; @@ -99,23 +104,44 @@ async function runReporter() { parsedArgs === args && ["waitFor", "find", "findComponent", "webpackDependantLazy", "webpackDependantLazyComponent"].includes(searchType) ) { - let filter = parsedArgs[0].toString(); + let filter = String(parsedArgs[0]); if (filter.length > 150) { filter = filter.slice(0, 147) + "..."; } logMessage += `(${filter})`; } else if (searchType === "extractAndLoadChunks") { + const [code, matcher] = parsedArgs; + let regexStr: string; - if (parsedArgs[1] === Webpack.DefaultExtractAndLoadChunksRegex) { + if (matcher === Webpack.DefaultExtractAndLoadChunksRegex) { regexStr = "DefaultExtractAndLoadChunksRegex"; } else { - regexStr = parsedArgs[1].toString(); + regexStr = String(matcher); } - logMessage += `([${parsedArgs[0].map((arg: any) => `"${arg}"`).join(", ")}], ${regexStr})`; + logMessage += `(${JSON.stringify(code)}, ${regexStr})`; + } else if (searchType === "mapMangledModule") { + const [code, mappers] = parsedArgs; + + const parsedFailedMappers = Object.entries(mappers) + .filter(([key]) => result == null || result[key][SYM_PROXY_INNER_GET] != null) + .map(([key, filter]) => { + let parsedFilter: string; + + if (filter.$$vencordProps != null) { + const filterName = filter.$$vencordProps[0]; + parsedFilter = `${filterName}(${filter.$$vencordProps.slice(1).map((arg: any) => JSON.stringify(arg)).join(", ")})`; + } else { + parsedFilter = String(filter).slice(0, 147) + "..."; + } + + return [key, parsedFilter]; + }); + + logMessage += `(${JSON.stringify(code)}, {\n${parsedFailedMappers.map(([key, parsedFilter]) => `\t${key}: ${parsedFilter}`).join(",\n")}\n})`; } else { - logMessage += `(${filterName.length ? `${filterName}(` : ""}${parsedArgs.map(arg => `"${arg}"`).join(", ")})${filterName.length ? ")" : ""}`; + logMessage += `(${filterName.length ? `${filterName}(` : ""}${parsedArgs.map(arg => JSON.stringify(arg)).join(", ")})${filterName.length ? ")" : ""}`; } ReporterLogger.log("Webpack Find Fail:", logMessage); diff --git a/src/plugins/decor/ui/index.ts b/src/plugins/decor/ui/index.ts index 776fbff02..6890b7d37 100644 --- a/src/plugins/decor/ui/index.ts +++ b/src/plugins/decor/ui/index.ts @@ -10,5 +10,5 @@ import { extractAndLoadChunksLazy, findByProps } from "@webpack"; export const cl = classNameFactory("vc-decor-"); export const DecorationModalStyles = findByProps("modalFooterShopButton"); -export const requireAvatarDecorationModal = extractAndLoadChunksLazy([".COLLECTIBLES_SHOP_FULLSCREEN&&"]); -export const requireCreateStickerModal = extractAndLoadChunksLazy(["stickerInspected]:"]); +export const requireAvatarDecorationModal = extractAndLoadChunksLazy(".COLLECTIBLES_SHOP_FULLSCREEN&&"); +export const requireCreateStickerModal = extractAndLoadChunksLazy("stickerInspected]:"); diff --git a/src/plugins/devCompanion.dev/index.tsx b/src/plugins/devCompanion.dev/index.tsx index c00dd0786..7842655ba 100644 --- a/src/plugins/devCompanion.dev/index.tsx +++ b/src/plugins/devCompanion.dev/index.tsx @@ -160,7 +160,7 @@ function initWs(isManual = false) { return reply("Expected exactly one 'find' matches, found " + keys.length); const mod = candidates[keys[0]]; - let src = String(mod.original ?? mod).replaceAll("\n", ""); + let src = String(mod).replaceAll("\n", ""); if (src.startsWith("function(")) { src = "0," + src; diff --git a/src/plugins/fakeProfileThemes/index.tsx b/src/plugins/fakeProfileThemes/index.tsx index 093824e46..860463086 100644 --- a/src/plugins/fakeProfileThemes/index.tsx +++ b/src/plugins/fakeProfileThemes/index.tsx @@ -111,7 +111,7 @@ interface ProfileModalProps { const ColorPicker = findComponentByCode(".Messages.USER_SETTINGS_PROFILE_COLOR_SELECT_COLOR", ".BACKGROUND_PRIMARY)"); const ProfileModal = findComponentByCode('"ProfileCustomizationPreview"'); -const requireColorPicker = extractAndLoadChunksLazy(["USER_SETTINGS_PROFILE_COLOR_DEFAULT_BUTTON.format"], /createPromise:\(\)=>\i\.\i\("?(.+?)"?\).then\(\i\.bind\(\i,"?(.+?)"?\)\)/); +const requireColorPicker = extractAndLoadChunksLazy("USER_SETTINGS_PROFILE_COLOR_DEFAULT_BUTTON.format", /createPromise:\(\)=>\i\.\i\("?(.+?)"?\).then\(\i\.bind\(\i,"?(.+?)"?\)\)/); export default definePlugin({ name: "FakeProfileThemes", diff --git a/src/plugins/pinDms/components/CreateCategoryModal.tsx b/src/plugins/pinDms/components/CreateCategoryModal.tsx index be4294cb7..f9b8d0395 100644 --- a/src/plugins/pinDms/components/CreateCategoryModal.tsx +++ b/src/plugins/pinDms/components/CreateCategoryModal.tsx @@ -33,7 +33,7 @@ interface ColorPickerWithSwatchesProps { const ColorPicker = findComponentByCode(".Messages.USER_SETTINGS_PROFILE_COLOR_SELECT_COLOR", ".BACKGROUND_PRIMARY)"); const ColorPickerWithSwatches = findExportedComponent("ColorPicker", "CustomColorPicker"); -export const requireSettingsMenu = extractAndLoadChunksLazy(['name:"UserSettings"'], /createPromise:.{0,20}Promise\.all\((\[\i\.\i\("?.+?"?\).+?\])\).then\(\i\.bind\(\i,"?(.+?)"?\)\).{0,50}"UserSettings"/); +export const requireSettingsMenu = extractAndLoadChunksLazy('name:"UserSettings"', /createPromise:.{0,20}Promise\.all\((\[\i\.\i\("?.+?"?\).+?\])\).then\(\i\.bind\(\i,"?(.+?)"?\)\).{0,50}"UserSettings"/); const cl = classNameFactory("vc-pindms-modal-"); diff --git a/src/webpack/webpack.tsx b/src/webpack/webpack.tsx index 36f243300..e3f9aaccc 100644 --- a/src/webpack/webpack.tsx +++ b/src/webpack/webpack.tsx @@ -782,7 +782,7 @@ export function extractAndLoadChunksLazy(code: string | string[], matcher: RegEx }); if (IS_REPORTER) { - webpackSearchHistory.push(["extractAndLoadChunks", [extractAndLoadChunks]]); + webpackSearchHistory.push(["extractAndLoadChunks", [extractAndLoadChunks, code, matcher]]); } return extractAndLoadChunks; From cac0398276e2dcdcecd1496992cbce35415f8603 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Fri, 21 Jun 2024 03:59:38 -0300 Subject: [PATCH 19/24] ReverseImageSearch: Fix duplicate find --- src/plugins/reverseImageSearch/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/reverseImageSearch/index.tsx b/src/plugins/reverseImageSearch/index.tsx index 415dc13d8..728156b2b 100644 --- a/src/plugins/reverseImageSearch/index.tsx +++ b/src/plugins/reverseImageSearch/index.tsx @@ -108,7 +108,7 @@ export default definePlugin({ patches: [ { - find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL", + find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL,shouldHideMediaOptions", replacement: { match: /favoriteableType:\i,(?<=(\i)\.getAttribute\("data-type"\).+?)/, replace: (m, target) => `${m}reverseImageSearchType:${target}.getAttribute("data-role"),` From d4ed7474346f136ddbcbb87ff93091301dde3411 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:49:42 -0300 Subject: [PATCH 20/24] Clean-up related additions to mangled exports --- src/api/SettingsStores.ts | 69 ---------------- src/api/UserSettings.ts | 81 +++++++++++++++++++ src/api/index.ts | 7 +- .../{settingsStores.ts => userSettings.ts} | 21 +++-- src/plugins/betterRoleContext/index.tsx | 6 +- src/plugins/customRPC/index.tsx | 7 +- src/plugins/gameActivityToggle/index.tsx | 6 +- src/plugins/ignoreActivities/index.tsx | 6 +- src/plugins/messageLinkEmbeds/index.tsx | 6 +- src/utils/discord.tsx | 2 +- src/webpack/common/index.ts | 2 +- src/webpack/common/types/index.d.ts | 1 - src/webpack/common/types/settingsStores.ts | 11 --- src/webpack/common/types/utils.d.ts | 2 +- .../{settingsStores.ts => userSettings.ts} | 0 15 files changed, 118 insertions(+), 109 deletions(-) delete mode 100644 src/api/SettingsStores.ts create mode 100644 src/api/UserSettings.ts rename src/plugins/_api/{settingsStores.ts => userSettings.ts} (55%) delete mode 100644 src/webpack/common/types/settingsStores.ts rename src/webpack/common/{settingsStores.ts => userSettings.ts} (100%) diff --git a/src/api/SettingsStores.ts b/src/api/SettingsStores.ts deleted file mode 100644 index 18139e4e6..000000000 --- a/src/api/SettingsStores.ts +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Vencord, a modification for Discord's desktop app - * Copyright (c) 2023 Vendicated and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . -*/ - -import { proxyLazy } from "@utils/lazy"; -import { Logger } from "@utils/Logger"; -import { findModuleId, proxyLazyWebpack, wreq } from "@webpack"; - -import { Settings } from "./Settings"; - -interface Setting { - /** - * Get the setting value - */ - getSetting(): T; - /** - * Update the setting value - * @param value The new value - */ - updateSetting(value: T | ((old: T) => T)): Promise; - /** - * React hook for automatically updating components when the setting is updated - */ - useSetting(): T; - settingsStoreApiGroup: string; - settingsStoreApiName: string; -} - -export const SettingsStores: Array> | undefined = proxyLazyWebpack(() => { - const modId = findModuleId('"textAndImages","renderSpoilers"') as any; - if (modId == null) return new Logger("SettingsStoreAPI").error("Didn't find stores module."); - - const mod = wreq(modId); - if (mod == null) return; - - return Object.values(mod).filter((s: any) => s?.settingsStoreApiGroup) as any; -}); - -/** - * Get the store for a setting - * @param group The setting group - * @param name The name of the setting - */ -export function getSettingStore(group: string, name: string): Setting | undefined { - if (!Settings.plugins.SettingsStoreAPI.enabled) throw new Error("Cannot use SettingsStoreAPI without setting as dependency."); - - return SettingsStores?.find(s => s?.settingsStoreApiGroup === group && s?.settingsStoreApiName === name); -} - -/** - * getSettingStore but lazy - */ -export function getSettingStoreLazy(group: string, name: string) { - return proxyLazy(() => getSettingStore(group, name)); -} diff --git a/src/api/UserSettings.ts b/src/api/UserSettings.ts new file mode 100644 index 000000000..4de92a81a --- /dev/null +++ b/src/api/UserSettings.ts @@ -0,0 +1,81 @@ +/* + * Vencord, a modification for Discord's desktop app + * Copyright (c) 2023 Vendicated and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . +*/ + +import { proxyLazy } from "@utils/lazy"; +import { Logger } from "@utils/Logger"; +import { findModuleId, proxyLazyWebpack, wreq } from "@webpack"; + +interface UserSettingDefinition { + /** + * Get the setting value + */ + getSetting(): T; + /** + * Update the setting value + * @param value The new value + */ + updateSetting(value: T): Promise; + /** + * Update the setting value + * @param value A callback that accepts the old value as the first argument, and returns the new value + */ + updateSetting(value: (old: T) => T): Promise; + /** + * Stateful React hook for this setting value + */ + useSetting(): T; + userSettingsAPIGroup: string; + userSettingsAPIName: string; +} + +export const UserSettings: Record> | undefined = proxyLazyWebpack(() => { + const modId = findModuleId('"textAndImages","renderSpoilers"'); + if (modId == null) return new Logger("UserSettingsAPI ").error("Didn't find settings module."); + + return wreq(modId as any); +}); + +/** + * Get the setting with the given setting group and name. + * + * @param group The setting group + * @param name The name of the setting + */ +export function getUserSetting(group: string, name: string): UserSettingDefinition | undefined { + if (!Vencord.Plugins.isPluginEnabled("UserSettingsAPI")) throw new Error("Cannot use UserSettingsAPI without setting as dependency."); + + for (const key in UserSettings) { + const userSetting = UserSettings[key]; + + if (userSetting.userSettingsAPIGroup === group && userSetting.userSettingsAPIName === name) { + return userSetting; + } + } +} + +/** + * {@link getUserSettingDefinition}, lazy. + * + * Get the setting with the given setting group and name. + * + * @param group The setting group + * @param name The name of the setting + */ +export function getUserSettingLazy(group: string, name: string) { + return proxyLazy(() => getUserSetting(group, name)); +} diff --git a/src/api/index.ts b/src/api/index.ts index 737e06d60..d4d7b4614 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -31,8 +31,8 @@ import * as $Notices from "./Notices"; import * as $Notifications from "./Notifications"; import * as $ServerList from "./ServerList"; import * as $Settings from "./Settings"; -import * as $SettingsStores from "./SettingsStores"; import * as $Styles from "./Styles"; +import * as $UserSettings from "./UserSettings"; /** * An API allowing you to listen to Message Clicks or run your own logic @@ -118,4 +118,7 @@ export const ChatButtons = $ChatButtons; */ export const MessageUpdater = $MessageUpdater; -export const SettingsStores = $SettingsStores; +/** + * An API allowing you to get an user setting + */ +export const UserSettings = $UserSettings; diff --git a/src/plugins/_api/settingsStores.ts b/src/plugins/_api/userSettings.ts similarity index 55% rename from src/plugins/_api/settingsStores.ts rename to src/plugins/_api/userSettings.ts index a888532ee..3a00bc116 100644 --- a/src/plugins/_api/settingsStores.ts +++ b/src/plugins/_api/userSettings.ts @@ -20,23 +20,30 @@ import { Devs } from "@utils/constants"; import definePlugin from "@utils/types"; export default definePlugin({ - name: "SettingsStoreAPI", - description: "Patches Discord's SettingsStores to expose their group and name", + name: "UserSettingsAPI", + description: "Patches Discord's UserSettings to expose their group and name.", authors: [Devs.Nuckyz], patches: [ { find: ",updateSetting:", replacement: [ + // Main setting definition { - match: /(?<=INFREQUENT_USER_ACTION.{0,20}),useSetting:/, - replace: ",settingsStoreApiGroup:arguments[0],settingsStoreApiName:arguments[1]$&" + match: /(?<=INFREQUENT_USER_ACTION.{0,20},)useSetting:/, + replace: "userSettingsAPIGroup:arguments[0],userSettingsAPIName:arguments[1],$&" }, - // some wrapper. just make it copy the group and name + // Selective wrapper { - match: /updateSetting:.{0,20}shouldSync/, - replace: "settingsStoreApiGroup:arguments[0].settingsStoreApiGroup,settingsStoreApiName:arguments[0].settingsStoreApiName,$&" + match: /updateSetting:.{0,100}SELECTIVELY_SYNCED_USER_SETTINGS_UPDATE/, + replace: "userSettingsAPIGroup:arguments[0].userSettingsAPIGroup,userSettingsAPIName:arguments[0].userSettingsAPIName,$&" + }, + // Override wrapper + { + match: /updateSetting:.{0,60}USER_SETTINGS_OVERRIDE_CLEAR/, + replace: "userSettingsAPIGroup:arguments[0].userSettingsAPIGroup,userSettingsAPIName:arguments[0].userSettingsAPIName,$&" } + ] } ] diff --git a/src/plugins/betterRoleContext/index.tsx b/src/plugins/betterRoleContext/index.tsx index d69e188c0..bf4cf0f37 100644 --- a/src/plugins/betterRoleContext/index.tsx +++ b/src/plugins/betterRoleContext/index.tsx @@ -5,7 +5,7 @@ */ import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingLazy } from "@api/UserSettings"; import { ImageIcon } from "@components/Icons"; import { Devs } from "@utils/constants"; import { getCurrentGuild, openImageModal } from "@utils/discord"; @@ -15,7 +15,7 @@ import { Clipboard, GuildStore, Menu, PermissionStore } from "@webpack/common"; const GuildSettingsActions = findByPropsLazy("open", "selectRole", "updateGuild"); -const DeveloperMode = getSettingStoreLazy("appearance", "developerMode")!; +const DeveloperMode = getUserSettingLazy("appearance", "developerMode")!; function PencilIcon() { return ( @@ -65,7 +65,7 @@ export default definePlugin({ name: "BetterRoleContext", description: "Adds options to copy role color / edit role / view role icon when right clicking roles in the user profile", authors: [Devs.Ven, Devs.goodbee], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingsAPI"], settings, diff --git a/src/plugins/customRPC/index.tsx b/src/plugins/customRPC/index.tsx index 7e4e9a938..eebcd4ddb 100644 --- a/src/plugins/customRPC/index.tsx +++ b/src/plugins/customRPC/index.tsx @@ -17,7 +17,7 @@ */ import { definePluginSettings, Settings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingLazy } from "@api/UserSettings"; import { ErrorCard } from "@components/ErrorCard"; import { Link } from "@components/Link"; import { Devs } from "@utils/constants"; @@ -33,8 +33,7 @@ const useProfileThemeStyle = findByCodeLazy("profileThemeStyle:", "--profile-gra const ActivityComponent = findComponentByCodeLazy("onOpenGameProfile"); const ActivityClassName = findByPropsLazy("activity", "buttonColor"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; - +const ShowCurrentGame = getUserSettingLazy("status", "showCurrentGame")!; async function getApplicationAsset(key: string): Promise { if (/https?:\/\/(cdn|media)\.discordapp\.(com|net)\/attachments\//.test(key)) return "mp:" + key.replace(/https?:\/\/(cdn|media)\.discordapp\.(com|net)\//, ""); @@ -394,7 +393,7 @@ export default definePlugin({ name: "CustomRPC", description: "Allows you to set a custom rich presence.", authors: [Devs.captain, Devs.AutumnVN, Devs.nin0dev], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingsAPI"], start: setRpc, stop: () => setRpc(true), settings, diff --git a/src/plugins/gameActivityToggle/index.tsx b/src/plugins/gameActivityToggle/index.tsx index 4e2a390d6..7aeb470d6 100644 --- a/src/plugins/gameActivityToggle/index.tsx +++ b/src/plugins/gameActivityToggle/index.tsx @@ -17,8 +17,8 @@ */ import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; import { disableStyle, enableStyle } from "@api/Styles"; +import { getUserSettingLazy } from "@api/UserSettings"; import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants"; import definePlugin, { OptionType } from "@utils/types"; @@ -28,7 +28,7 @@ import style from "./style.css?managed"; const Button = findComponentByCodeLazy("Button.Sizes.NONE,disabled:"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; +const ShowCurrentGame = getUserSettingLazy("status", "showCurrentGame")!; function makeIcon(showCurrentGame?: boolean) { const { oldIcon } = settings.use(["oldIcon"]); @@ -87,7 +87,7 @@ export default definePlugin({ name: "GameActivityToggle", description: "Adds a button next to the mic and deafen button to toggle game activity.", authors: [Devs.Nuckyz, Devs.RuukuLada], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingsAPI"], settings, patches: [ diff --git a/src/plugins/ignoreActivities/index.tsx b/src/plugins/ignoreActivities/index.tsx index 6e34c79f3..78c1c5cf8 100644 --- a/src/plugins/ignoreActivities/index.tsx +++ b/src/plugins/ignoreActivities/index.tsx @@ -6,7 +6,7 @@ import * as DataStore from "@api/DataStore"; import { definePluginSettings, Settings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingLazy } from "@api/UserSettings"; import ErrorBoundary from "@components/ErrorBoundary"; import { Flex } from "@components/Flex"; import { Devs } from "@utils/constants"; @@ -28,7 +28,7 @@ interface IgnoredActivity { const RunningGameStore = findStoreLazy("RunningGameStore"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; +const ShowCurrentGame = getUserSettingLazy("status", "showCurrentGame")!; function ToggleIcon(activity: IgnoredActivity, tooltipText: string, path: string, fill: string) { return ( @@ -208,7 +208,7 @@ export default definePlugin({ name: "IgnoreActivities", authors: [Devs.Nuckyz], description: "Ignore activities from showing up on your status ONLY. You can configure which ones are specifically ignored from the Registered Games and Activities tabs, or use the general settings below.", - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingsAPI"], settings, diff --git a/src/plugins/messageLinkEmbeds/index.tsx b/src/plugins/messageLinkEmbeds/index.tsx index 70681fb28..cf180d0d4 100644 --- a/src/plugins/messageLinkEmbeds/index.tsx +++ b/src/plugins/messageLinkEmbeds/index.tsx @@ -19,7 +19,7 @@ import { addAccessory, removeAccessory } from "@api/MessageAccessories"; import { updateMessage } from "@api/MessageUpdater"; import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingLazy } from "@api/UserSettings"; import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants.js"; import { classes } from "@utils/misc"; @@ -54,7 +54,7 @@ const ChannelMessage = findComponentByCodeLazy("childrenExecutedCommand:", ".hid const SearchResultClasses = findByPropsLazy("message", "searchResult"); const EmbedClasses = findByPropsLazy("embedAuthorIcon", "embedAuthor", "embedAuthor"); -const MessageDisplayCompact = getSettingStoreLazy("textAndImages", "messageDisplayCompact")!; +const MessageDisplayCompact = getUserSettingLazy("textAndImages", "messageDisplayCompact")!; const messageLinkRegex = /(? } - // FIXME: wtf is this? do we need to pass some proper component?? + // Don't render forward message button renderForwardComponent={() => null} shouldHideMediaOptions={false} shouldAnimate diff --git a/src/webpack/common/index.ts b/src/webpack/common/index.ts index 5da3cc68b..4193330cb 100644 --- a/src/webpack/common/index.ts +++ b/src/webpack/common/index.ts @@ -20,9 +20,9 @@ export * from "./classes"; export * from "./components"; export * from "./menu"; export * from "./react"; -export * from "./settingsStores"; export * from "./stores"; export * as ComponentTypes from "./types/components.d"; export * as MenuTypes from "./types/menu.d"; export * as UtilTypes from "./types/utils.d"; +export * from "./userSettings"; export * from "./utils"; diff --git a/src/webpack/common/types/index.d.ts b/src/webpack/common/types/index.d.ts index 01c968553..a536cdcf1 100644 --- a/src/webpack/common/types/index.d.ts +++ b/src/webpack/common/types/index.d.ts @@ -21,6 +21,5 @@ export * from "./components"; export * from "./fluxEvents"; export * from "./i18nMessages"; export * from "./menu"; -export * from "./settingsStores"; export * from "./stores"; export * from "./utils"; diff --git a/src/webpack/common/types/settingsStores.ts b/src/webpack/common/types/settingsStores.ts deleted file mode 100644 index 5453ca352..000000000 --- a/src/webpack/common/types/settingsStores.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Vencord, a Discord client mod - * Copyright (c) 2024 Vendicated and contributors - * SPDX-License-Identifier: GPL-3.0-or-later - */ - -export interface SettingsStore { - getSetting(): T; - updateSetting(value: T): void; - useSetting(): T; -} diff --git a/src/webpack/common/types/utils.d.ts b/src/webpack/common/types/utils.d.ts index 7f6249be6..ee3f69944 100644 --- a/src/webpack/common/types/utils.d.ts +++ b/src/webpack/common/types/utils.d.ts @@ -82,7 +82,7 @@ interface RestRequestData { retries?: number; } -export type RestAPI = Record<"delete" | "get" | "patch" | "post" | "put", (data: RestRequestData) => Promise>; +export type RestAPI = Record<"del" | "get" | "patch" | "post" | "put", (data: RestRequestData) => Promise>; export type Permissions = "CREATE_INSTANT_INVITE" | "KICK_MEMBERS" diff --git a/src/webpack/common/settingsStores.ts b/src/webpack/common/userSettings.ts similarity index 100% rename from src/webpack/common/settingsStores.ts rename to src/webpack/common/userSettings.ts From db1481711bf6076267123389127b167d184ff0b0 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Thu, 20 Jun 2024 01:00:07 -0300 Subject: [PATCH 21/24] Reporter: Test mapMangledModule --- src/debug/runReporter.ts | 15 ++++++++++++--- src/webpack/webpack.ts | 4 +++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/debug/runReporter.ts b/src/debug/runReporter.ts index 6c7a2a03f..ddd5e5f18 100644 --- a/src/debug/runReporter.ts +++ b/src/debug/runReporter.ts @@ -39,9 +39,8 @@ async function runReporter() { } if (searchType === "waitForStore") method = "findStore"; + let result: any; try { - let result: any; - if (method === "proxyLazyWebpack" || method === "LazyComponentWebpack") { const [factory] = args; result = factory(); @@ -50,16 +49,26 @@ async function runReporter() { result = await Webpack.extractAndLoadChunks(code, matcher); if (result === false) result = null; + } else if (method === "mapMangledModule") { + const [code, mapper] = args; + + result = Webpack.mapMangledModule(code, mapper); + if (Object.keys(result).length !== Object.keys(mapper).length) throw new Error("Webpack Find Fail"); } else { // @ts-ignore result = Webpack[method](...args); } - if (result == null || (result.$$vencordInternal != null && result.$$vencordInternal() == null)) throw "a rock at ben shapiro"; + if (result == null || (result.$$vencordInternal != null && result.$$vencordInternal() == null)) throw new Error("Webpack Find Fail"); } catch (e) { let logMessage = searchType; if (method === "find" || method === "proxyLazyWebpack" || method === "LazyComponentWebpack") logMessage += `(${args[0].toString().slice(0, 147)}...)`; else if (method === "extractAndLoadChunks") logMessage += `([${args[0].map(arg => `"${arg}"`).join(", ")}], ${args[1].toString()})`; + else if (method === "mapMangledModule") { + const failedMappings = Object.keys(args[1]).filter(key => result?.[key] == null); + + logMessage += `("${args[0]}", {\n${failedMappings.map(mapping => `\t${mapping}: ${args[1][mapping].toString().slice(0, 147)}...`).join(",\n")}\n})`; + } else logMessage += `(${args.map(arg => `"${arg}"`).join(", ")})`; ReporterLogger.log("Webpack Find Fail:", logMessage); diff --git a/src/webpack/webpack.ts b/src/webpack/webpack.ts index b536063e8..f776ab1c3 100644 --- a/src/webpack/webpack.ts +++ b/src/webpack/webpack.ts @@ -279,7 +279,7 @@ export function findModuleFactory(...code: string[]) { return wreq.m[id]; } -export const lazyWebpackSearchHistory = [] as Array<["find" | "findByProps" | "findByCode" | "findStore" | "findComponent" | "findComponentByCode" | "findExportedComponent" | "waitFor" | "waitForComponent" | "waitForStore" | "proxyLazyWebpack" | "LazyComponentWebpack" | "extractAndLoadChunks", any[]]>; +export const lazyWebpackSearchHistory = [] as Array<["find" | "findByProps" | "findByCode" | "findStore" | "findComponent" | "findComponentByCode" | "findExportedComponent" | "waitFor" | "waitForComponent" | "waitForStore" | "proxyLazyWebpack" | "LazyComponentWebpack" | "extractAndLoadChunks" | "mapMangledModule", any[]]>; /** * This is just a wrapper around {@link proxyLazy} to make our reporter test for your webpack finds. @@ -483,6 +483,8 @@ export const mapMangledModule = traceFunction("mapMangledModule", function mapMa * }) */ export function mapMangledModuleLazy(code: string, mappers: Record): Record { + if (IS_REPORTER) lazyWebpackSearchHistory.push(["mapMangledModule", [code, mappers]]); + return proxyLazy(() => mapMangledModule(code, mappers)); } From c7e4bec94099e9f92a4402e56a87214e8817b053 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Thu, 20 Jun 2024 19:48:37 +0200 Subject: [PATCH 22/24] Plugin Page: add indicator for excluded plugins --- scripts/build/build.mjs | 20 ++- scripts/build/common.mjs | 59 +++++++-- scripts/generatePluginList.ts | 2 +- src/components/PluginSettings/index.tsx | 154 ++++++++++++++--------- src/modules.d.ts | 1 + src/plugins/appleMusic.desktop/index.tsx | 2 +- src/plugins/xsOverlay.desktop/index.ts | 2 +- 7 files changed, 156 insertions(+), 84 deletions(-) diff --git a/scripts/build/build.mjs b/scripts/build/build.mjs index fcf56f66c..817c2cec3 100755 --- a/scripts/build/build.mjs +++ b/scripts/build/build.mjs @@ -21,7 +21,7 @@ import esbuild from "esbuild"; import { readdir } from "fs/promises"; import { join } from "path"; -import { BUILD_TIMESTAMP, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, VERSION, watch } from "./common.mjs"; +import { BUILD_TIMESTAMP, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, resolvePluginName, VERSION, watch } from "./common.mjs"; const defines = { IS_STANDALONE, @@ -76,22 +76,20 @@ const globNativesPlugin = { for (const dir of pluginDirs) { const dirPath = join("src", dir); if (!await exists(dirPath)) continue; - const plugins = await readdir(dirPath); - for (const p of plugins) { - const nativePath = join(dirPath, p, "native.ts"); - const indexNativePath = join(dirPath, p, "native/index.ts"); + const plugins = await readdir(dirPath, { withFileTypes: true }); + for (const file of plugins) { + const fileName = file.name; + const nativePath = join(dirPath, fileName, "native.ts"); + const indexNativePath = join(dirPath, fileName, "native/index.ts"); if (!(await exists(nativePath)) && !(await exists(indexNativePath))) continue; - const nameParts = p.split("."); - const namePartsWithoutTarget = nameParts.length === 1 ? nameParts : nameParts.slice(0, -1); - // pluginName.thing.desktop -> PluginName.thing - const cleanPluginName = p[0].toUpperCase() + namePartsWithoutTarget.join(".").slice(1); + const pluginName = await resolvePluginName(dirPath, file); const mod = `p${i}`; - code += `import * as ${mod} from "./${dir}/${p}/native";\n`; - natives += `${JSON.stringify(cleanPluginName)}:${mod},\n`; + code += `import * as ${mod} from "./${dir}/${fileName}/native";\n`; + natives += `${JSON.stringify(pluginName)}:${mod},\n`; i++; } } diff --git a/scripts/build/common.mjs b/scripts/build/common.mjs index eb7ab905b..c46a559a7 100644 --- a/scripts/build/common.mjs +++ b/scripts/build/common.mjs @@ -53,6 +53,32 @@ export const banner = { `.trim() }; +const PluginDefinitionNameMatcher = /definePlugin\(\{\s*(["'])?name\1:\s*(["'`])(.+?)\2/; +/** + * @param {string} base + * @param {import("fs").Dirent} dirent + */ +export async function resolvePluginName(base, dirent) { + const fullPath = join(base, dirent.name); + const content = dirent.isFile() + ? await readFile(fullPath, "utf-8") + : await (async () => { + for (const file of ["index.ts", "index.tsx"]) { + try { + return await readFile(join(fullPath, file), "utf-8"); + } catch { + continue; + } + } + throw new Error(`Invalid plugin ${fullPath}: could not resolve entry point`); + })(); + + return PluginDefinitionNameMatcher.exec(content)?.[3] + ?? (() => { + throw new Error(`Invalid plugin ${fullPath}: must contain definePlugin call with simple string name property as first property`); + })(); +} + export async function exists(path) { return await access(path, FsConstants.F_OK) .then(() => true) @@ -88,14 +114,16 @@ export const globPlugins = kind => ({ build.onLoad({ filter, namespace: "import-plugins" }, async () => { const pluginDirs = ["plugins/_api", "plugins/_core", "plugins", "userplugins"]; let code = ""; - let plugins = "\n"; - let meta = "\n"; + let pluginsCode = "\n"; + let metaCode = "\n"; + let excludedCode = "\n"; let i = 0; for (const dir of pluginDirs) { const userPlugin = dir === "userplugins"; - if (!await exists(`./src/${dir}`)) continue; - const files = await readdir(`./src/${dir}`, { withFileTypes: true }); + const fullDir = `./src/${dir}`; + if (!await exists(fullDir)) continue; + const files = await readdir(fullDir, { withFileTypes: true }); for (const file of files) { const fileName = file.name; if (fileName.startsWith("_") || fileName.startsWith(".")) continue; @@ -104,23 +132,30 @@ export const globPlugins = kind => ({ const target = getPluginTarget(fileName); if (target && !IS_REPORTER) { - if (target === "dev" && !watch) continue; - if (target === "web" && kind === "discordDesktop") continue; - if (target === "desktop" && kind === "web") continue; - if (target === "discordDesktop" && kind !== "discordDesktop") continue; - if (target === "vencordDesktop" && kind !== "vencordDesktop") continue; + const excluded = + (target === "dev" && !IS_DEV) || + (target === "web" && kind === "discordDesktop") || + (target === "desktop" && kind === "web") || + (target === "discordDesktop" && kind !== "discordDesktop") || + (target === "vencordDesktop" && kind !== "vencordDesktop"); + + if (excluded) { + const name = await resolvePluginName(fullDir, file); + excludedCode += `${JSON.stringify(name)}:${JSON.stringify(target)},\n`; + continue; + } } const folderName = `src/${dir}/${fileName}`.replace(/^src\/plugins\//, ""); const mod = `p${i}`; code += `import ${mod} from "./${dir}/${fileName.replace(/\.tsx?$/, "")}";\n`; - plugins += `[${mod}.name]:${mod},\n`; - meta += `[${mod}.name]:${JSON.stringify({ folderName, userPlugin })},\n`; // TODO: add excluded plugins to display in the UI? + pluginsCode += `[${mod}.name]:${mod},\n`; + metaCode += `[${mod}.name]:${JSON.stringify({ folderName, userPlugin })},\n`; // TODO: add excluded plugins to display in the UI? i++; } } - code += `export default {${plugins}};export const PluginMeta={${meta}};`; + code += `export default {${pluginsCode}};export const PluginMeta={${metaCode}};export const ExcludedPlugins={${excludedCode}};`; return { contents: code, resolveDir: "./src" diff --git a/scripts/generatePluginList.ts b/scripts/generatePluginList.ts index e8aa33a46..3d7c16c01 100644 --- a/scripts/generatePluginList.ts +++ b/scripts/generatePluginList.ts @@ -39,7 +39,7 @@ interface PluginData { hasCommands: boolean; required: boolean; enabledByDefault: boolean; - target: "discordDesktop" | "vencordDesktop" | "web" | "dev"; + target: "discordDesktop" | "vencordDesktop" | "desktop" | "web" | "dev"; filePath: string; } diff --git a/src/components/PluginSettings/index.tsx b/src/components/PluginSettings/index.tsx index 978d2e85a..c659e7838 100644 --- a/src/components/PluginSettings/index.tsx +++ b/src/components/PluginSettings/index.tsx @@ -35,9 +35,9 @@ import { openModalLazy } from "@utils/modal"; import { useAwaiter } from "@utils/react"; import { Plugin } from "@utils/types"; import { findByPropsLazy } from "@webpack"; -import { Alerts, Button, Card, Forms, lodash, Parser, React, Select, Text, TextInput, Toasts, Tooltip } from "@webpack/common"; +import { Alerts, Button, Card, Forms, lodash, Parser, React, Select, Text, TextInput, Toasts, Tooltip, useMemo } from "@webpack/common"; -import Plugins from "~plugins"; +import Plugins, { ExcludedPlugins } from "~plugins"; // Avoid circular dependency const { startDependenciesRecursive, startPlugin, stopPlugin } = proxyLazy(() => require("../../plugins")); @@ -177,6 +177,37 @@ const enum SearchStatus { NEW } +function ExcludedPluginsList({ search }: { search: string; }) { + const matchingExcludedPlugins = Object.entries(ExcludedPlugins) + .filter(([name]) => name.toLowerCase().includes(search)); + + const ExcludedReasons: Record<"web" | "discordDesktop" | "vencordDesktop" | "desktop" | "dev", string> = { + desktop: "Discord Desktop app or Vesktop", + discordDesktop: "Discord Desktop app", + vencordDesktop: "Vesktop app", + web: "Vesktop app and the Web version of Discord", + dev: "Developer version of Vencord" + }; + + return ( + + {matchingExcludedPlugins.length + ? <> + Are you looking for: +
    + {matchingExcludedPlugins.map(([name, reason]) => ( +
  • + {name}: Only available on the {ExcludedReasons[reason]} +
  • + ))} +
+ + : "No plugins meet the search criteria." + } +
+ ); +} + export default function PluginSettings() { const settings = useSettings(); const changes = React.useMemo(() => new ChangeList(), []); @@ -215,26 +246,27 @@ export default function PluginSettings() { return o; }, []); - const sortedPlugins = React.useMemo(() => Object.values(Plugins) + const sortedPlugins = useMemo(() => Object.values(Plugins) .sort((a, b) => a.name.localeCompare(b.name)), []); const [searchValue, setSearchValue] = React.useState({ value: "", status: SearchStatus.ALL }); + const search = searchValue.value.toLowerCase(); const onSearch = (query: string) => setSearchValue(prev => ({ ...prev, value: query })); const onStatusChange = (status: SearchStatus) => setSearchValue(prev => ({ ...prev, status })); const pluginFilter = (plugin: typeof Plugins[keyof typeof Plugins]) => { - const enabled = settings.plugins[plugin.name]?.enabled; - if (enabled && searchValue.status === SearchStatus.DISABLED) return false; - if (!enabled && searchValue.status === SearchStatus.ENABLED) return false; - if (searchValue.status === SearchStatus.NEW && !newPlugins?.includes(plugin.name)) return false; - if (!searchValue.value.length) return true; + const { status } = searchValue; + const enabled = Vencord.Plugins.isPluginEnabled(plugin.name); + if (enabled && status === SearchStatus.DISABLED) return false; + if (!enabled && status === SearchStatus.ENABLED) return false; + if (status === SearchStatus.NEW && !newPlugins?.includes(plugin.name)) return false; + if (!search.length) return true; - const v = searchValue.value.toLowerCase(); return ( - plugin.name.toLowerCase().includes(v) || - plugin.description.toLowerCase().includes(v) || - plugin.tags?.some(t => t.toLowerCase().includes(v)) + plugin.name.toLowerCase().includes(search) || + plugin.description.toLowerCase().includes(search) || + plugin.tags?.some(t => t.toLowerCase().includes(search)) ); }; @@ -255,54 +287,48 @@ export default function PluginSettings() { return lodash.isEqual(newPlugins, sortedPluginNames) ? [] : newPlugins; })); - type P = JSX.Element | JSX.Element[]; - let plugins: P, requiredPlugins: P; - if (sortedPlugins?.length) { - plugins = []; - requiredPlugins = []; + const plugins = [] as JSX.Element[]; + const requiredPlugins = [] as JSX.Element[]; - const showApi = searchValue.value === "API"; - for (const p of sortedPlugins) { - if (p.hidden || (!p.options && p.name.endsWith("API") && !showApi)) - continue; + const showApi = searchValue.value.includes("API"); + for (const p of sortedPlugins) { + if (p.hidden || (!p.options && p.name.endsWith("API") && !showApi)) + continue; - if (!pluginFilter(p)) continue; + if (!pluginFilter(p)) continue; - const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled); + const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled); - if (isRequired) { - const tooltipText = p.required - ? "This plugin is required for Vencord to function." - : makeDependencyList(depMap[p.name]?.filter(d => settings.plugins[d].enabled)); - - requiredPlugins.push( - - {({ onMouseLeave, onMouseEnter }) => ( - changes.handleChange(name)} - disabled={true} - plugin={p} - /> - )} - - ); - } else { - plugins.push( - changes.handleChange(name)} - disabled={false} - plugin={p} - isNew={newPlugins?.includes(p.name)} - key={p.name} - /> - ); - } + if (isRequired) { + const tooltipText = p.required + ? "This plugin is required for Vencord to function." + : makeDependencyList(depMap[p.name]?.filter(d => settings.plugins[d].enabled)); + requiredPlugins.push( + + {({ onMouseLeave, onMouseEnter }) => ( + changes.handleChange(name)} + disabled={true} + plugin={p} + key={p.name} + /> + )} + + ); + } else { + plugins.push( + changes.handleChange(name)} + disabled={false} + plugin={p} + isNew={newPlugins?.includes(p.name)} + key={p.name} + /> + ); } - } else { - plugins = requiredPlugins = No plugins meet search criteria.; } return ( @@ -333,9 +359,18 @@ export default function PluginSettings() { Plugins -
- {plugins} -
+ {plugins.length || requiredPlugins.length + ? ( +
+ {plugins.length + ? plugins + : No plugins meet the search criteria. + } +
+ ) + : + } + @@ -343,7 +378,10 @@ export default function PluginSettings() { Required Plugins
- {requiredPlugins} + {requiredPlugins.length + ? requiredPlugins + : No plugins meet the search criteria. + }
); diff --git a/src/modules.d.ts b/src/modules.d.ts index 70ffcfb91..7566a5bf4 100644 --- a/src/modules.d.ts +++ b/src/modules.d.ts @@ -26,6 +26,7 @@ declare module "~plugins" { folderName: string; userPlugin: boolean; }>; + export const ExcludedPlugins: Record; } declare module "~pluginNatives" { diff --git a/src/plugins/appleMusic.desktop/index.tsx b/src/plugins/appleMusic.desktop/index.tsx index 0d81204e9..6fa989cdd 100644 --- a/src/plugins/appleMusic.desktop/index.tsx +++ b/src/plugins/appleMusic.desktop/index.tsx @@ -9,7 +9,7 @@ import { Devs } from "@utils/constants"; import definePlugin, { OptionType, PluginNative, ReporterTestable } from "@utils/types"; import { ApplicationAssetUtils, FluxDispatcher, Forms } from "@webpack/common"; -const Native = VencordNative.pluginHelpers.AppleMusic as PluginNative; +const Native = VencordNative.pluginHelpers.AppleMusicRichPresence as PluginNative; interface ActivityAssets { large_image?: string; diff --git a/src/plugins/xsOverlay.desktop/index.ts b/src/plugins/xsOverlay.desktop/index.ts index a68373a6a..b42d20210 100644 --- a/src/plugins/xsOverlay.desktop/index.ts +++ b/src/plugins/xsOverlay.desktop/index.ts @@ -136,7 +136,7 @@ const settings = definePluginSettings({ }, }); -const Native = VencordNative.pluginHelpers.XsOverlay as PluginNative; +const Native = VencordNative.pluginHelpers.XSOverlay as PluginNative; export default definePlugin({ name: "XSOverlay", From 7dc1d4c498f200092fceb6654663000827cea67d Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Fri, 21 Jun 2024 03:59:38 -0300 Subject: [PATCH 23/24] ReverseImageSearch: Fix duplicate find --- src/plugins/reverseImageSearch/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/reverseImageSearch/index.tsx b/src/plugins/reverseImageSearch/index.tsx index 415dc13d8..728156b2b 100644 --- a/src/plugins/reverseImageSearch/index.tsx +++ b/src/plugins/reverseImageSearch/index.tsx @@ -108,7 +108,7 @@ export default definePlugin({ patches: [ { - find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL", + find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL,shouldHideMediaOptions", replacement: { match: /favoriteableType:\i,(?<=(\i)\.getAttribute\("data-type"\).+?)/, replace: (m, target) => `${m}reverseImageSearchType:${target}.getAttribute("data-role"),` From ef512e6ea18c14f3b89914f32cd04d185896979c Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Fri, 21 Jun 2024 04:30:12 -0300 Subject: [PATCH 24/24] forgot this --- src/plugins/consoleShortcuts/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/consoleShortcuts/index.ts b/src/plugins/consoleShortcuts/index.ts index 2ce4f0696..a856d0a0f 100644 --- a/src/plugins/consoleShortcuts/index.ts +++ b/src/plugins/consoleShortcuts/index.ts @@ -24,7 +24,7 @@ import { canonicalizeMatch, canonicalizeReplace, canonicalizeReplacement } from import { SYM_PROXY_INNER_GET, SYM_PROXY_INNER_VALUE } from "@utils/proxyInner"; import definePlugin, { PluginNative, StartAt } from "@utils/types"; import * as Webpack from "@webpack"; -import { cacheFindAll, extract, filters, findModuleId, search } from "@webpack"; +import { cacheFindAll, extract, filters, search } from "@webpack"; import * as Common from "@webpack/common"; import { loadLazyChunks } from "debug/loadLazyChunks"; import type { ComponentType } from "react"; @@ -83,7 +83,7 @@ function makeShortcuts() { wreq: { getter: () => Webpack.wreq }, wpsearch: search, wpex: extract, - wpexs: (code: string) => extract(findModuleId(code)!), + wpexs: (code: string) => extract(Webpack.cacheFindModuleId(code)!), loadLazyChunks: IS_DEV ? loadLazyChunks : () => { throw new Error("loadLazyChunks is dev only."); }, find, findAll: cacheFindAll,