Rework the existing API structure

This commit is contained in:
Zack Rauen 2022-08-05 19:09:23 -04:00
parent 9f2298e6cd
commit 32a1f37540
17 changed files with 1087 additions and 709 deletions

View File

@ -4,7 +4,7 @@
"node": true
},
"parserOptions": {
"ecmaVersion": 2020,
"ecmaVersion": 2022,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true

View File

@ -14,7 +14,7 @@
"lint": "eslint --ext .js common/ && npm run lint --prefix injector && npm run lint --prefix renderer",
"test": "mocha --require @babel/register --recursive \"./tests/renderer/*.js\"",
"dist": "npm run build-prod && node scripts/pack.js",
"api": "jsdoc -X renderer/src/modules/pluginapi.js > jsdoc-ast.json"
"api": "jsdoc -X -r renderer/src/modules/api/ > jsdoc-ast.json"
},
"devDependencies": {
"asar": "^3.0.3",

View File

@ -2,7 +2,7 @@ import secure from "./secure";
import patchModuleLoad from "./moduleloader";
import LoadingIcon from "./loadingicon";
import BetterDiscord from "./modules/core";
import BdApi from "./modules/pluginapi";
import BdApi from "./modules/api/index";
// Perform some setup
secure();

View File

@ -1,4 +1,4 @@
import BdApi from "./modules/pluginapi";
import BdApi from "./modules/api/index";
export default function() {
const namespace = "betterdiscord";

View File

@ -0,0 +1,64 @@
/**
* `AddonAPI` is a utility class for working with plugins and themes. Instances are accessible through the {@link BdApi}.
* @name AddonAPI
*/
class AddonAPI {
#manager;
constructor(manager) {this.#manager = manager;}
/**
* The path to the addon folder.
* @type string
*/
get folder() {return this.#manager.addonFolder;}
/**
* Determines if a particular adon is enabled.
* @param {string} idOrFile Addon id or filename.
* @returns {boolean}
*/
isEnabled(idOrFile) {return this.#manager.isEnabled(idOrFile);}
/**
* Enables the given addon.
* @param {string} idOrFile Addon id or filename.
*/
enable(idOrAddon) {return this.#manager.enableAddon(idOrAddon);}
/**
* Disables the given addon.
* @param {string} idOrFile Addon id or filename.
*/
disable(idOrAddon) {return this.#manager.disableAddon(idOrAddon);}
/**
* Toggles if a particular addon is enabled.
* @param {string} idOrFile Addon id or filename.
*/
toggle(idOrAddon) {return this.#manager.toggleAddon(idOrAddon);}
/**
* Reloads if a particular addon is enabled.
* @param {string} idOrFile Addon id or filename.
*/
reload(idOrFileOrAddon) {return this.#manager.reloadAddon(idOrFileOrAddon);}
/**
* Gets a particular addon.
* @param {string} idOrFile Addon id or filename.
* @returns {object} Addon instance
*/
get(idOrFile) {return this.#manager.getAddon(idOrFile);}
/**
* Gets all addons of this type.
* @returns {Array<object>} Array of all addon instances
*/
getAll() {return this.#manager.addonList.map(a => this.#manager.getAddon(a.id));}
}
Object.freeze(AddonAPI);
Object.freeze(AddonAPI.prototype);
export default AddonAPI;

View File

@ -0,0 +1,56 @@
import DataStore from "../datastore";
/**
* `Data` is a simple utility class for the management of plugin data. An instance is available on {@link BdApi}.
* @type Data
* @summary {@link Data} is a simple utility class for the management of plugin data.
* @name Data
*/
class Data {
constructor(callerName) {
if (!callerName) return;
this.save = this.save.bind(this, callerName);
this.load = this.load.bind(this, callerName);
this.delete = this.delete.bind(this, callerName);
}
/**
* Saves JSON-serializable data.
*
* @param {string} pluginName Name of the plugin saving data
* @param {string} key Which piece of data to store
* @param {any} data The data to be saved
* @returns
*/
save(pluginName, key, data) {
return DataStore.setPluginData(pluginName, key, data);
}
/**
* Loads previously stored data.
*
* @param {string} pluginName Name of the plugin loading data
* @param {string} key Which piece of data to load
* @returns {any} The stored data
*/
load(pluginName, key, data) {
return DataStore.setPluginData(pluginName, key, data);
}
/**
* Deletes a piece of stored data, this is different than saving as null or undefined.
*
* @param {string} pluginName Name of the plugin deleting data
* @param {string} key Which piece of data to delete
*/
delete(pluginName, key, data) {
return DataStore.setPluginData(pluginName, key, data);
}
}
Object.freeze(Data);
Object.freeze(Data.prototype);
export default Data;

View File

@ -0,0 +1,58 @@
import DOMManager from "../dommanager";
import Utilities from "../utilities";
/**
* `DOM` is a simple utility class for dom manipulation. An instance is available on {@link BdApi}.
* @type DOM
* @summary {@link DOM} is a simple utility class for dom manipulation.
* @name DOM
*/
class DOM {
constructor(callerName) {
if (!callerName) return;
this.addStyle = this.addStyle.bind(this, callerName);
this.removeStyle = this.removeStyle.bind(this, callerName);
}
/**
* Adds a `<style>` to the document with the given ID.
*
* @param {string} id ID to use for style element
* @param {string} css CSS to apply to the document
*/
addStyle(id, css) {
if (arguments.length === 3) {
id = arguments[1];
css = arguments[2];
}
DOMManager.injectStyle(id, css);
}
/**
* Removes a `<style>` from the document corresponding to the given ID.
*
* @param {string} id ID uses for the style element
*/
removeStyle(id) {
if (arguments.length === 2) id = arguments[1];
DOMManager.removeStyle(id);
}
/**
* Adds a listener for when the node is removed from the document body.
*
* @param {HTMLElement} node Node to be observed
* @param {function} callback Function to run when fired
*/
onRemoved(node, callback) {
Utilities.onRemoved(node, callback);
}
}
Object.freeze(DOM);
Object.freeze(DOM.prototype);
export default DOM;

View File

@ -0,0 +1,113 @@
import PluginManager from "../pluginmanager";
import ThemeManager from "../thememanager";
import Logger from "common/logger";
import AddonAPI from "./addonapi";
import Data from "./data";
import DOM from "./dom";
import Patcher from "./patcher";
import ReactUtils from "./reactutils";
import UI from "./ui";
import Utils from "./utils";
import Webpack from "./webpack";
import * as Legacy from "./legacy";
const bounded = new Map();
const PluginAPI = new AddonAPI(PluginManager);
const ThemeAPI = new AddonAPI(ThemeManager);
const PatcherAPI = new Patcher();
const DataAPI = new Data();
const DOMAPI = new DOM();
/**
* `BdApi` is a globally (`window.BdApi`) accessible object for use by plugins and developers to make their lives easier.
* @name BdApi
*/
export default class BdApi {
constructor(pluginName) {
if (!pluginName) return BdApi;
if (bounded.has(pluginName)) return bounded.get(pluginName);
if (typeof(pluginName) !== "string") {
Logger.error("BdApi", "Plugin name not a string, returning generic API!");
return BdApi;
}
// Re-add legacy functions
Object.assign(this, Legacy);
// Bind to pluginName
this.Patcher = new Patcher(pluginName);
this.Data = new Data(pluginName);
this.DOM = new DOM(pluginName);
bounded.set(pluginName, this);
}
// Non-bound namespaces
get Plugins() {return PluginAPI;}
get Themes() {return ThemeAPI;}
get Webpack() {return Webpack;}
get Utils() {return Utils;}
get UI() {return UI;}
get ReactUtils() {return ReactUtils;}
}
// Add legacy functions
Object.assign(BdApi, Legacy);
/**
* An instance of {@link AddonAPI} to access plugins.
* @type AddonAPI
*/
BdApi.Plugins = PluginAPI;
/**
* An instance of {@link AddonAPI} to access themes.
* @type AddonAPI
*/
BdApi.Themes = ThemeAPI;
/**
* An instance of {@link Patcher} to monkey patch functions.
* @type Patcher
*/
BdApi.Patcher = PatcherAPI;
/**
* An instance of {@link Webpack} to search for modules.
* @type Webpack
*/
BdApi.Webpack = Webpack;
/**
* An instance of {@link Data} to manage data.
* @type Data
*/
BdApi.Data = DataAPI;
/**
* An instance of {@link UI} to create interfaces.
* @type UI
*/
BdApi.UI = UI;
/**
* An instance of {@link ReactUtils} to work with React.
* @type ReactUtils
*/
BdApi.ReactUtils = ReactUtils;
/**
* An instance of {@link Utils} for general utility functions.
* @type Utils
*/
BdApi.Utils = Utils;
/**
* An instance of {@link DOM} to interact with the DOM.
* @type DOM
*/
BdApi.DOM = DOMAPI;
Object.freeze(BdApi);
Object.freeze(BdApi.prototype);

View File

@ -0,0 +1,433 @@
import {Config} from "data";
import Utilities from "../utilities";
import WebpackModules from "../webpackmodules";
import DiscordModules from "../discordmodules";
import DataStore from "../datastore";
import DOMManager from "../dommanager";
import Toasts from "../../ui/toasts";
import Notices from "../../ui/notices";
import Modals from "../../ui/modals";
import Settings from "../settingsmanager";
import Logger from "common/logger";
import Patcher from "../patcher";
import Emotes from "../../builtins/emotes/emotes";
import ipc from "../ipc";
/**
* The React module being used inside Discord.
* @type React
*/
export const React = DiscordModules.React;
/**
* The ReactDOM module being used inside Discord.
* @type ReactDOM
*/
export const ReactDOM = DiscordModules.ReactDOM;
/**
* A reference object to get BD's settings.
* @type object
* @deprecated
*/
export const settings = Settings.collections;
/**
* A reference object for BD's emotes.
* @type object
* @deprecated
*/
export const emotes = new Proxy(Emotes.Emotes, {
get(obj, category) {
if (category === "blocklist") return Emotes.blocklist;
const group = Emotes.Emotes[category];
if (!group) return undefined;
return new Proxy(group, {
get(cat, emote) {return group[emote];},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/BetterDiscord/BetterDiscord/wiki/Addon-Policies#plugins");}
});
},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/BetterDiscord/BetterDiscord/wiki/Addon-Policies#plugins");}
});
/**
* A reference string for BD's version.
* @type string
*/
export const version = Config.version;
/**
* Adds a `<style>` to the document with the given ID.
*
* @param {string} id ID to use for style element
* @param {string} css CSS to apply to the document
*/
export const injectCSS = function (id, css) {
DOMManager.injectStyle(id, css);
};
/**
* Removes a `<style>` from the document corresponding to the given ID.
*
* @param {string} id ID uses for the style element
*/
export const clearCSS = function (id) {
DOMManager.removeStyle(id);
};
/**
* Automatically creates and links a remote JS script.
*
* @deprecated
* @param {string} id ID of the script element
* @param {string} url URL of the remote script
* @returns {Promise} Resolves upon onload event
*/
export const linkJS = function (id, url) {
return DOMManager.injectScript(id, url);
};
/**
* Removes a remotely linked JS script.
*
* @deprecated
* @param {string} id ID of the script element
*/
export const unlinkJS = function (id) {
DOMManager.removeScript(id);
};
/**
* Shows a generic but very customizable modal.
*
* @param {string} title title of the modal
* @param {(string|ReactElement|Array<string|ReactElement>)} content a string of text to display in the modal
*/
export const alert = function (title, content) {
Modals.alert(title, content);
};
/**
* Shows a generic but very customizable confirmation modal with optional confirm and cancel callbacks.
*
* @param {string} title title of the modal
* @param {(string|ReactElement|Array<string|ReactElement>)} children a single or mixed array of react elements and strings. Everything is wrapped in Discord's `TextElement` component so strings will show and render properly.
* @param {object} [options] options to modify the modal
* @param {boolean} [options.danger=false] whether the main button should be red or not
* @param {string} [options.confirmText=Okay] text for the confirmation/submit button
* @param {string} [options.cancelText=Cancel] text for the cancel button
* @param {callable} [options.onConfirm=NOOP] callback to occur when clicking the submit button
* @param {callable} [options.onCancel=NOOP] callback to occur when clicking the cancel button
*/
export const showConfirmationModal = function (title, content, options = {}) {
return Modals.showConfirmationModal(title, content, options);
};
/**
* This shows a toast similar to android towards the bottom of the screen.
*
* @param {string} content The string to show in the toast.
* @param {object} options Options object. Optional parameter.
* @param {string} [options.type=""] Changes the type of the toast stylistically and semantically. Choices: "", "info", "success", "danger"/"error", "warning"/"warn". Default: ""
* @param {boolean} [options.icon=true] Determines whether the icon should show corresponding to the type. A toast without type will always have no icon. Default: true
* @param {number} [options.timeout=3000] Adjusts the time (in ms) the toast should be shown for before disappearing automatically. Default: 3000
* @param {boolean} [options.forceShow=false] Whether to force showing the toast and ignore the bd setting
*/
export const showToast = function(content, options = {}) {
Toasts.show(content, options);
};
/**
* Show a notice above discord's chat layer.
*
* @param {string|Node} content Content of the notice
* @param {object} options Options for the notice.
* @param {string} [options.type="info" | "error" | "warning" | "success"] Type for the notice. Will affect the color.
* @param {Array<{label: string, onClick: function}>} [options.buttons] Buttons that should be added next to the notice text.
* @param {number} [options.timeout=10000] Timeout until the notice is closed. Won't fire if it's set to 0;
* @returns {function}
*/
export const showNotice = function (content, options = {}) {
return Notices.show(content, options);
};
/**
* Finds a webpack module using a filter
*
* @deprecated
* @param {function} filter A filter given the exports, module, and moduleId. Returns true if the module matches.
* @returns {any} Either the matching module or `undefined`
*/
export const findModule = function(filter) {
return WebpackModules.getModule(filter);
};
/**
* Finds multple webpack modules using a filter
*
* @deprecated
* @param {function} filter A filter given the exports, module, and moduleId. Returns true if the module matches.
* @returns {Array} Either an array of matching modules or an empty array
*/
export const findAllModules = function(filter) {
return WebpackModules.getModule(filter, {first: false});
};
/**
* Finds a webpack module by own properties
*
* @deprecated
* @param {...string} props Any desired properties
* @returns {any} Either the matching module or `undefined`
*/
export const findModuleByProps = function(...props) {
return WebpackModules.getByProps(...props);
};
/**
* Finds a webpack module by own prototypes
*
* @deprecated
* @param {...string} protos Any desired prototype properties
* @returns {any} Either the matching module or `undefined`
*/
export const findModuleByPrototypes = function(...protos) {
return WebpackModules.getByPrototypes(...protos);
};
/**
* Finds a webpack module by displayName property
*
* @deprecated
* @param {string} name Desired displayName property
* @returns {any} Either the matching module or `undefined`
*/
export const findModuleByDisplayName = function(name) {
return WebpackModules.getByDisplayName(name);
};
/**
* Get the internal react data of a specified node
*
* @param {HTMLElement} node Node to get the react data from
* @returns {object|undefined} Either the found data or `undefined`
*/
export const getInternalInstance = function(node) {
return Utilities.getReactInstance(node);
};
/**
* Loads previously stored data.
*
* @param {string} pluginName Name of the plugin loading data
* @param {string} key Which piece of data to load
* @returns {any} The stored data
*/
export const loadData = function(pluginName, key) {
return DataStore.getPluginData(pluginName, key);
};
/** @alias loadData */
export const getData = loadData;
/**
* Saves JSON-serializable data.
*
* @param {string} pluginName Name of the plugin saving data
* @param {string} key Which piece of data to store
* @param {any} data The data to be saved
* @returns
*/
export const saveData = function(pluginName, key, data) {
return DataStore.setPluginData(pluginName, key, data);
};
/** @alias saveData */
export const setData = saveData;
/**
* Deletes a piece of stored data, this is different than saving as null or undefined.
*
* @param {string} pluginName Name of the plugin deleting data
* @param {string} key Which piece of data to delete
*/
export const deleteData = function(pluginName, key) {
DataStore.deletePluginData(pluginName, key);
};
/**
* This function monkey-patches a method on an object. The patching callback may be run before, after or instead of target method.
*
* - Be careful when monkey-patching. Think not only about original functionality of target method and your changes, but also about developers of other plugins, who may also patch this method before or after you. Try to change target method behaviour as little as possible, and avoid changing method signatures.
* - Display name of patched method is changed, so you can see if a function has been patched (and how many times) while debugging or in the stack trace. Also, patched methods have property `__monkeyPatched` set to `true`, in case you want to check something programmatically.
*
* @deprecated
* @param {object} what Object to be patched. You can can also pass class prototypes to patch all class instances.
* @param {string} methodName Name of the function to be patched.
* @param {object} options Options object to configure the patch.
* @param {function} [options.after] Callback that will be called after original target method call. You can modify return value here, so it will be passed to external code which calls target method. Can be combined with `before`.
* @param {function} [options.before] Callback that will be called before original target method call. You can modify arguments here, so it will be passed to original method. Can be combined with `after`.
* @param {function} [options.instead] Callback that will be called instead of original target method call. You can get access to original method using `originalMethod` parameter if you want to call it, but you do not have to. Can't be combined with `before` or `after`.
* @param {boolean} [options.once=false] Set to `true` if you want to automatically unpatch method after first call.
* @param {boolean} [options.silent=false] Set to `true` if you want to suppress log messages about patching and unpatching.
* @returns {function} A function that cancels the monkey patch
*/
export const monkeyPatch = function(what, methodName, options) {
const {before, after, instead, once = false, callerId = "BdApi"} = options;
const patchType = before ? "before" : after ? "after" : instead ? "instead" : "";
if (!patchType) return Logger.err("BdApi", "Must provide one of: after, before, instead");
const originalMethod = what[methodName];
const data = {
originalMethod: originalMethod,
callOriginalMethod: () => data.originalMethod.apply(data.thisObject, data.methodArguments)
};
data.cancelPatch = Patcher[patchType](callerId, what, methodName, (thisObject, args, returnValue) => {
data.thisObject = thisObject;
data.methodArguments = args;
data.returnValue = returnValue;
try {
const patchReturn = Reflect.apply(options[patchType], null, [data]);
if (once) data.cancelPatch();
return patchReturn;
}
catch (err) {
Logger.stacktrace(`${callerId}:monkeyPatch`, `Error in the ${patchType} of ${methodName}`, err);
}
});
return data.cancelPatch;
};
/**
* Adds a listener for when the node is removed from the document body.
*
* @param {HTMLElement} node Node to be observed
* @param {function} callback Function to run when fired
*/
export const onRemoved = function(node, callback) {
Utilities.onRemoved(node, callback);
};
/**
* Wraps a given function in a `try..catch` block.
*
* @deprecated
* @param {function} method Function to wrap
* @param {string} message Additional messasge to print when an error occurs
* @returns {function} The new wrapped function
*/
export const suppressErrors = function(method, message) {
return Utilities.suppressErrors(method, message);
};
/**
* Tests a given object to determine if it is valid JSON.
*
* @deprecated
* @param {object} data Data to be tested
* @returns {boolean} Result of the test
*/
export const testJSON = function(data) {
return Utilities.testJSON(data);
};
/**
* Gets a specific setting's status from BD
*
* @deprecated
* @param {string} [collection="settings"] Collection ID
* @param {string} category Category ID in the collection
* @param {string} id Setting ID in the category
* @returns {boolean} If the setting is enabled
*/
export const isSettingEnabled = function(collection, category, id) {
return Settings.get(collection, category, id);
};
/**
* Enable a BetterDiscord setting by ids.
*
* @deprecated
* @param {string} [collection="settings"] Collection ID
* @param {string} category Category ID in the collection
* @param {string} id Setting ID in the category
*/
export const enableSetting = function(collection, category, id) {
return Settings.set(collection, category, id, true);
};
/**
* Disables a BetterDiscord setting by ids.
*
* @deprecated
* @param {string} [collection="settings"] Collection ID
* @param {string} category Category ID in the collection
* @param {string} id Setting ID in the category
*/
export const disableSetting = function(collection, category, id) {
return Settings.set(collection, category, id, false);
};
/**
* Toggle a BetterDiscord setting by ids.
*
* @deprecated
* @param {string} [collection="settings"] Collection ID
* @param {string} category Category ID in the collection
* @param {string} id Setting ID in the category
*/
export const toggleSetting = function(collection, category, id) {
return Settings.set(collection, category, id, !Settings.get(collection, category, id));
};
/**
* Gets some data in BetterDiscord's misc data.
*
* @deprecated
* @param {string} key Key of the data to load.
* @returns {any} The stored data
*/
export const getBDData = function(key) {
return DataStore.getBDData(key);
};
/**
* Gets some data in BetterDiscord's misc data.
*
* @deprecated
* @param {string} key Key of the data to load.
* @returns {any} The stored data
*/
export const setBDData = function(key, data) {
return DataStore.setBDData(key, data);
};
/**
* Gives access to the [Electron Dialog](https://www.electronjs.org/docs/latest/api/dialog/) api.
* Returns a `Promise` that resolves to an `object` that has a `boolean` cancelled and a `filePath` string for saving and a `filePaths` string array for opening.
*
* @param {object} options Options object to configure the dialog.
* @param {"open"|"save"} [options.mode="open"] Determines whether the dialog should open or save files.
* @param {string} [options.defaultPath=~] Path the dialog should show on launch.
* @param {Array<object<string, string[]>>} [options.filters=[]] An array of [file filters](https://www.electronjs.org/docs/latest/api/structures/file-filter).
* @param {string} [options.title] Title for the titlebar.
* @param {string} [options.message] Message for the dialog.
* @param {boolean} [options.showOverwriteConfirmation=false] Whether the user should be prompted when overwriting a file.
* @param {boolean} [options.showHiddenFiles=false] Whether hidden files should be shown in the dialog.
* @param {boolean} [options.promptToCreate=false] Whether the user should be prompted to create non-existant folders.
* @param {boolean} [options.openDirectory=false] Whether the user should be able to select a directory as a target.
* @param {boolean} [options.openFile=true] Whether the user should be able to select a file as a target.
* @param {boolean} [options.multiSelections=false] Whether the user should be able to select multiple targets.
* @param {boolean} [options.modal=false] Whether the dialog should act as a modal to the main window.
* @returns {Promise<object>} Result of the dialog
*/
export const openDialog = async function (options) {
const data = await ipc.openDialog(options);
if (data.error) throw new Error(data.error);
return data;
};

View File

@ -0,0 +1,84 @@
import Logger from "common/logger";
import {default as MainPatcher} from "../patcher";
/**
* `Patcher` is a utility class for modifying existing functions. Instance is accessible through the {@link BdApi}.
* This is extremely useful for modifying the internals of Discord by adjusting return value or React renders, or arguments of internal functions.
* @type Patcher
* @summary {@link Patcher} is a utility class for modifying existing functions.
* @name Patcher
*/
class Patcher {
constructor(callerName) {
if (!callerName) return;
this.before = this.before.bind(this, callerName);
this.instead = this.instead.bind(this, callerName);
this.after = this.after.bind(this, callerName);
this.getPatchesByCaller = this.getPatchesByCaller.bind(this, callerName);
this.unpatchAll = this.unpatchAll.bind(this, callerName);
}
/**
* This method patches onto another function, allowing your code to run beforehand.
* Using this, you are also able to modify the incoming arguments before the original method is run.
* @param {string} caller Name of the caller of the patch function.
* @param {object} moduleToPatch Object with the function to be patched. Can also be an object's prototype.
* @param {string} functionName Name of the function to be patched.
* @param {function} callback Function to run before the original method. The function is given the `this` context and the `arguments` of the original function.
* @returns {function} Function that cancels the original patch.
*/
before(caller, moduleToPatch, functionName, callback) {
return MainPatcher.pushChildPatch(caller, moduleToPatch, functionName, callback, {type: "before"});
}
/**
* This method patches onto another function, allowing your code to run instead.
* Using this, you are also able to modify the return value, using the return of your code instead.
* @param {string} caller Name of the caller of the patch function.
* @param {object} moduleToPatch Object with the function to be patched. Can also be an object's prototype.
* @param {string} functionName Name of the function to be patched.
* @param {function} callback Function to run before the original method. The function is given the `this` context, `arguments` of the original function, and also the original function.
* @returns {function} Function that cancels the original patch.
*/
instead(caller, moduleToPatch, functionName, callback) {
return MainPatcher.pushChildPatch(caller, moduleToPatch, functionName, callback, {type: "instead"});
}
/**
* This method patches onto another function, allowing your code to run instead.
* Using this, you are also able to modify the return value, using the return of your code instead.
* @param {string} caller Name of the caller of the patch function.
* @param {object} moduleToPatch Object with the function to be patched. Can also be an object's prototype.
* @param {string} functionName Name of the function to be patched.
* @param {function} callback Function to run after the original method. The function is given the `this` context, the `arguments` of the original function, and the `return` value of the original function.
* @returns {function} Function that cancels the original patch.
*/
after(caller, moduleToPatch, functionName, callback) {
return MainPatcher.pushChildPatch(caller, moduleToPatch, functionName, callback, {type: "after"});
}
/**
* Returns all patches by a particular caller. The patches all have an `unpatch()` method.
* @param {string} caller ID of the original patches
* @returns {Array<function>} Array of all the patch objects.
*/
getPatchesByCaller(caller) {
if (typeof(caller) !== "string") return Logger.err("BdApi.Patcher", "Parameter 0 of getPatchesByCaller must be a string representing the caller");
return MainPatcher.getPatchesByCaller(caller);
}
/**
* Automatically cancels all patches created with a specific ID.
* @param {string} caller ID of the original patches
*/
unpatchAll(caller) {
if (typeof(caller) !== "string") return Logger.err("BdApi.Patcher", "Parameter 0 of unpatchAll must be a string representing the caller");
MainPatcher.unpatchAll(caller);
}
}
Object.freeze(Patcher);
Object.freeze(Patcher.prototype);
export default Patcher;

View File

@ -0,0 +1,26 @@
import Utilities from "../utilities";
/**
* `ReactUtils` is a utility class for interacting with React internals. Instance is accessible through the {@link BdApi}.
* This is extremely useful for interacting with the internals of the UI.
* @type ReactUtils
* @summary {@link ReactUtils} is a utility class for interacting with React internals.
* @memberof BdApi
* @name ReactUtils
*/
const ReactUtils = {
/**
* Get the internal react data of a specified node
*
* @param {HTMLElement} node Node to get the react data from
* @returns {object|undefined} Either the found data or `undefined`
*/
getInternalInstance(node) {
return Utilities.getReactInstance(node);
}
};
Object.freeze(ReactUtils);
export default ReactUtils;

View File

@ -0,0 +1,99 @@
import Modals from "../../ui/modals";
import Toasts from "../../ui/toasts";
import Notices from "../../ui/notices";
import ipc from "../ipc";
/**
* `UI` is a utility class for getting internal webpack modules. Instance is accessible through the {@link BdApi}.
* This is extremely useful for interacting with the internals of Discord.
* @type UI
* @summary {@link UI} is a utility class for getting internal webpack modules.
* @memberof BdApi
* @name UI
*/
const UI = {
/**
* Shows a generic but very customizable modal.
*
* @param {string} title title of the modal
* @param {(string|ReactElement|Array<string|ReactElement>)} content a string of text to display in the modal
*/
alert(title, content) {
Modals.alert(title, content);
},
/**
* Shows a generic but very customizable confirmation modal with optional confirm and cancel callbacks.
*
* @param {string} title title of the modal
* @param {(string|ReactElement|Array<string|ReactElement>)} children a single or mixed array of react elements and strings. Everything is wrapped in Discord's `TextElement` component so strings will show and render properly.
* @param {object} [options] options to modify the modal
* @param {boolean} [options.danger=false] whether the main button should be red or not
* @param {string} [options.confirmText=Okay] text for the confirmation/submit button
* @param {string} [options.cancelText=Cancel] text for the cancel button
* @param {callable} [options.onConfirm=NOOP] callback to occur when clicking the submit button
* @param {callable} [options.onCancel=NOOP] callback to occur when clicking the cancel button
*/
showConfirmationModal(title, content, options = {}) {
return Modals.showConfirmationModal(title, content, options);
},
/**
* This shows a toast similar to android towards the bottom of the screen.
*
* @param {string} content The string to show in the toast.
* @param {object} options Options object. Optional parameter.
* @param {string} [options.type=""] Changes the type of the toast stylistically and semantically. Choices: "", "info", "success", "danger"/"error", "warning"/"warn". Default: ""
* @param {boolean} [options.icon=true] Determines whether the icon should show corresponding to the type. A toast without type will always have no icon. Default: true
* @param {number} [options.timeout=3000] Adjusts the time (in ms) the toast should be shown for before disappearing automatically. Default: 3000
* @param {boolean} [options.forceShow=false] Whether to force showing the toast and ignore the bd setting
*/
showToast(content, options = {}) {
Toasts.show(content, options);
},
/**
* Show a notice above discord's chat layer.
*
* @param {string|Node} content Content of the notice
* @param {object} options Options for the notice.
* @param {string} [options.type="info" | "error" | "warning" | "success"] Type for the notice. Will affect the color.
* @param {Array<{label: string, onClick: function}>} [options.buttons] Buttons that should be added next to the notice text.
* @param {number} [options.timeout=10000] Timeout until the notice is closed. Won't fire if it's set to 0;
* @returns {function}
*/
showNotice(content, options = {}) {
return Notices.show(content, options);
},
/**
* Gives access to the [Electron Dialog](https://www.electronjs.org/docs/latest/api/dialog/) api.
* Returns a `Promise` that resolves to an `object` that has a `boolean` cancelled and a `filePath` string for saving and a `filePaths` string array for opening.
*
* @param {object} options Options object to configure the dialog.
* @param {"open"|"save"} [options.mode="open"] Determines whether the dialog should open or save files.
* @param {string} [options.defaultPath=~] Path the dialog should show on launch.
* @param {Array<object<string, string[]>>} [options.filters=[]] An array of [file filters](https://www.electronjs.org/docs/latest/api/structures/file-filter).
* @param {string} [options.title] Title for the titlebar.
* @param {string} [options.message] Message for the dialog.
* @param {boolean} [options.showOverwriteConfirmation=false] Whether the user should be prompted when overwriting a file.
* @param {boolean} [options.showHiddenFiles=false] Whether hidden files should be shown in the dialog.
* @param {boolean} [options.promptToCreate=false] Whether the user should be prompted to create non-existant folders.
* @param {boolean} [options.openDirectory=false] Whether the user should be able to select a directory as a target.
* @param {boolean} [options.openFile=true] Whether the user should be able to select a file as a target.
* @param {boolean} [options.multiSelections=false] Whether the user should be able to select multiple targets.
* @param {boolean} [options.modal=false] Whether the dialog should act as a modal to the main window.
* @returns {Promise<object>} Result of the dialog
*/
async openDialog(options) {
const data = await ipc.openDialog(options);
if (data.error) throw new Error(data.error);
return data;
}
};
Object.freeze(UI);
export default UI;

View File

@ -0,0 +1,38 @@
import Utilities from "../utilities";
/**
* `Utils` is a utility class for interacting with React internals. Instance is accessible through the {@link BdApi}.
* This is extremely useful for interacting with the internals of the UI.
* @type Utils
* @summary {@link Utils} is a utility class for interacting with React internals.
* @memberof BdApi
* @name Utils
*/
const Utils = {
/**
* Wraps a given function in a `try..catch` block.
*
* @deprecated
* @param {function} method Function to wrap
* @param {string} message Additional messasge to print when an error occurs
* @returns {function} The new wrapped function
*/
suppressErrors(method, message) {
return Utilities.suppressErrors(method, message);
},
/**
* Tests a given object to determine if it is valid JSON.
*
* @deprecated
* @param {object} data Data to be tested
* @returns {boolean} Result of the test
*/
testJSON(data) {
return Utilities.testJSON(data);
}
};
Object.freeze(Utils);
export default Utils;

View File

@ -0,0 +1,106 @@
import Logger from "common/logger";
import WebpackModules, {Filters} from "../webpackmodules";
/**
* `Webpack` is a utility class for getting internal webpack modules. Instance is accessible through the {@link BdApi}.
* This is extremely useful for interacting with the internals of Discord.
* @type Webpack
* @summary {@link Webpack} is a utility class for getting internal webpack modules.
* @memberof BdApi
* @name Webpack
*/
const Webpack = {
/**
* Series of {@link Filters} to be used for finding webpack modules.
* @type Filters
* @memberof Webpack
*/
Filters: {
/**
* Generates a function that filters by a set of properties.
* @param {...string} props List of property names
* @returns {function} A filter that checks for a set of properties
*/
byProps(...props) {return Filters.byProps(props);},
/**
* Generates a function that filters by a set of properties on the object's prototype.
* @param {...string} props List of property names
* @returns {function} A filter that checks for a set of properties on the object's prototype.
*/
byPrototypeFields(...props) {return Filters.byPrototypeFields(props);},
/**
* Generates a function that filters by a regex.
* @param {RegExp} search A RegExp to check on the module
* @param {function} filter Additional filter
* @returns {function} A filter that checks for a regex match
*/
byRegex(regex) {return Filters.byRegex(regex);},
/**
* Generates a function that filters by strings.
* @param {...String} strings A list of strings
* @returns {function} A filter that checks for a set of strings
*/
byStrings(...strings) {return Filters.byStrings(strings);},
/**
* Generates a function that filters by a set of properties.
* @param {string} name Name the module should have
* @returns {function} A filter that checks for a set of properties
*/
byDisplayName(name) {return Filters.byDisplayName(name);},
/**
* Generates a combined function from a list of filters.
* @param {...function} filters A list of filters
* @returns {function} Combinatory filter of all arguments
*/
combine(...filters) {return Filters.combine(filters);},
},
/**
* Finds a module using a filter function.
* @memberof Webpack
* @param {function} filter A function to use to filter modules. It is given exports, module, and moduleID. Return true to signify match.
* @param {object} [options] Whether to return only the first matching module
* @param {Boolean} [options.first=true] Whether to return only the first matching module
* @param {Boolean} [options.defaultExport=true] Whether to return default export when matching the default export
* @return {any}
*/
getModule(filter, options = {}) {
if (("first" in options) && typeof(options.first) !== "boolean") return Logger.error("BdApi.Webpack~getModule", "Unsupported type used for options.first", options.first, "boolean expected.");
if (("defaultExport" in options) && typeof(options.defaultExport) !== "boolean") return Logger.error("BdApi.Webpack~getModule", "Unsupported type used for options.defaultExport", options.defaultExport, "boolean expected.");
return WebpackModules.getModule(filter, options);
},
/**
* Finds multiple modules using multiple filters.
* @memberof Webpack
* @param {...object} queries Whether to return only the first matching module
* @param {Function} queries.filter A function to use to filter modules
* @param {Boolean} [queries.first=true] Whether to return only the first matching module
* @param {Boolean} [queries.defaultExport=true] Whether to return default export when matching the default export
* @return {any}
*/
getBulk(...queries) {return WebpackModules.getBulk(...queries);},
/**
* Finds a module that lazily loaded.
* @memberof Webpack
* @param {function} filter A function to use to filter modules. It is given exports. Return true to signify match.
* @param {object} [options] Whether to return only the first matching module
* @param {AbortSignal} [options.signal] AbortSignal of an AbortController to cancel the promise
* @param {Boolean} [options.defaultExport=true] Whether to return default export when matching the default export
* @returns {Promise<any>}
*/
waitForModule(filter, options = {}) {
if (("defaultExport" in options) && typeof(options.defaultExport) !== "boolean") return Logger.error("BdApi.Webpack~waitForModule", "Unsupported type used for options.defaultExport", options.defaultExport, "boolean expected.");
if (("signal" in options) && !(options.signal instanceof AbortSignal)) return Logger.error("BdApi.Webpack~waitForModule", "Unsupported type used for options.signal", options.signal, "AbortSignal expected.");
return WebpackModules.getLazy(filter, options);
},
};
export default Webpack;

View File

@ -1,698 +0,0 @@
import {Config} from "data";
import Utilities from "./utilities";
import WebpackModules, {Filters} from "./webpackmodules";
import DiscordModules from "./discordmodules";
import DataStore from "./datastore";
import DOMManager from "./dommanager";
import Toasts from "../ui/toasts";
import Notices from "../ui/notices";
import Modals from "../ui/modals";
import PluginManager from "./pluginmanager";
import ThemeManager from "./thememanager";
import Settings from "./settingsmanager";
import Logger from "common/logger";
import Patcher from "./patcher";
import Emotes from "../builtins/emotes/emotes";
import ipc from "./ipc";
/**
* `BdApi` is a globally (`window.BdApi`) accessible object for use by plugins and developers to make their lives easier.
* @name BdApi
*/
const BdApi = {
/**
* The React module being used inside Discord.
* @type React
* */
get React() {return DiscordModules.React;},
/**
* The ReactDOM module being used inside Discord.
* @type ReactDOM
*/
get ReactDOM() {return DiscordModules.ReactDOM;},
/**
* A reference object to get BD's settings.
* @type object
* @deprecated
*/
get settings() {return Settings.collections;},
/**
* A reference object for BD's emotes.
* @type object
* @deprecated
*/
get emotes() {
return new Proxy(Emotes.Emotes, {
get(obj, category) {
if (category === "blocklist") return Emotes.blocklist;
const group = Emotes.Emotes[category];
if (!group) return undefined;
return new Proxy(group, {
get(cat, emote) {return group[emote];},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/BetterDiscord/BetterDiscord/wiki/Addon-Policies#plugins");}
});
},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/BetterDiscord/BetterDiscord/wiki/Addon-Policies#plugins");}
});
},
/**
* A reference string for BD's version.
* @type string
*/
get version() {return Config.version;}
};
/**
* Adds a `<style>` to the document with the given ID.
*
* @param {string} id ID to use for style element
* @param {string} css CSS to apply to the document
*/
BdApi.injectCSS = function (id, css) {
DOMManager.injectStyle(id, css);
};
/**
* Removes a `<style>` from the document corresponding to the given ID.
*
* @param {string} id ID uses for the style element
*/
BdApi.clearCSS = function (id) {
DOMManager.removeStyle(id);
};
/**
* Automatically creates and links a remote JS script.
*
* @deprecated
* @param {string} id ID of the script element
* @param {string} url URL of the remote script
* @returns {Promise} Resolves upon onload event
*/
BdApi.linkJS = function (id, url) {
return DOMManager.injectScript(id, url);
};
/**
* Removes a remotely linked JS script.
*
* @deprecated
* @param {string} id ID of the script element
*/
BdApi.unlinkJS = function (id) {
DOMManager.removeScript(id);
};
/**
* Shows a generic but very customizable modal.
*
* @param {string} title title of the modal
* @param {(string|ReactElement|Array<string|ReactElement>)} content a string of text to display in the modal
*/
BdApi.alert = function (title, content) {
Modals.alert(title, content);
};
/**
* Shows a generic but very customizable confirmation modal with optional confirm and cancel callbacks.
*
* @param {string} title title of the modal
* @param {(string|ReactElement|Array<string|ReactElement>)} children a single or mixed array of react elements and strings. Everything is wrapped in Discord's `TextElement` component so strings will show and render properly.
* @param {object} [options] options to modify the modal
* @param {boolean} [options.danger=false] whether the main button should be red or not
* @param {string} [options.confirmText=Okay] text for the confirmation/submit button
* @param {string} [options.cancelText=Cancel] text for the cancel button
* @param {callable} [options.onConfirm=NOOP] callback to occur when clicking the submit button
* @param {callable} [options.onCancel=NOOP] callback to occur when clicking the cancel button
*/
BdApi.showConfirmationModal = function (title, content, options = {}) {
return Modals.showConfirmationModal(title, content, options);
};
/**
* This shows a toast similar to android towards the bottom of the screen.
*
* @param {string} content The string to show in the toast.
* @param {object} options Options object. Optional parameter.
* @param {string} [options.type=""] Changes the type of the toast stylistically and semantically. Choices: "", "info", "success", "danger"/"error", "warning"/"warn". Default: ""
* @param {boolean} [options.icon=true] Determines whether the icon should show corresponding to the type. A toast without type will always have no icon. Default: true
* @param {number} [options.timeout=3000] Adjusts the time (in ms) the toast should be shown for before disappearing automatically. Default: 3000
* @param {boolean} [options.forceShow=false] Whether to force showing the toast and ignore the bd setting
*/
BdApi.showToast = function(content, options = {}) {
Toasts.show(content, options);
};
/**
* Show a notice above discord's chat layer.
*
* @param {string|Node} content Content of the notice
* @param {object} options Options for the notice.
* @param {string} [options.type="info" | "error" | "warning" | "success"] Type for the notice. Will affect the color.
* @param {Array<{label: string, onClick: function}>} [options.buttons] Buttons that should be added next to the notice text.
* @param {number} [options.timeout=10000] Timeout until the notice is closed. Won't fire if it's set to 0;
* @returns {function}
*/
BdApi.showNotice = function (content, options = {}) {
return Notices.show(content, options);
};
/**
* Finds a webpack module using a filter
*
* @deprecated
* @param {function} filter A filter given the exports, module, and moduleId. Returns true if the module matches.
* @returns {any} Either the matching module or `undefined`
*/
BdApi.findModule = function(filter) {
return WebpackModules.getModule(filter);
};
/**
* Finds multple webpack modules using a filter
*
* @deprecated
* @param {function} filter A filter given the exports, module, and moduleId. Returns true if the module matches.
* @returns {Array} Either an array of matching modules or an empty array
*/
BdApi.findAllModules = function(filter) {
return WebpackModules.getModule(filter, {first: false});
};
/**
* Finds a webpack module by own properties
*
* @deprecated
* @param {...string} props Any desired properties
* @returns {any} Either the matching module or `undefined`
*/
BdApi.findModuleByProps = function(...props) {
return WebpackModules.getByProps(...props);
};
/**
* Finds a webpack module by own prototypes
*
* @deprecated
* @param {...string} protos Any desired prototype properties
* @returns {any} Either the matching module or `undefined`
*/
BdApi.findModuleByPrototypes = function(...protos) {
return WebpackModules.getByPrototypes(...protos);
};
/**
* Finds a webpack module by displayName property
*
* @deprecated
* @param {string} name Desired displayName property
* @returns {any} Either the matching module or `undefined`
*/
BdApi.findModuleByDisplayName = function(name) {
return WebpackModules.getByDisplayName(name);
};
/**
* Get the internal react data of a specified node
*
* @param {HTMLElement} node Node to get the react data from
* @returns {object|undefined} Either the found data or `undefined`
*/
BdApi.getInternalInstance = function(node) {
return Utilities.getReactInstance(node);
};
/**
* Loads previously stored data.
*
* @param {string} pluginName Name of the plugin loading data
* @param {string} key Which piece of data to load
* @returns {any} The stored data
*/
BdApi.loadData = function(pluginName, key) {
return DataStore.getPluginData(pluginName, key);
};
/** @alias loadData */
BdApi.getData = BdApi.loadData;
/**
* Saves JSON-serializable data.
*
* @param {string} pluginName Name of the plugin saving data
* @param {string} key Which piece of data to store
* @param {any} data The data to be saved
* @returns
*/
BdApi.saveData = function(pluginName, key, data) {
return DataStore.setPluginData(pluginName, key, data);
};
/** @alias saveData */
BdApi.setData = BdApi.saveData;
/**
* Deletes a piece of stored data, this is different than saving as null or undefined.
*
* @param {string} pluginName Name of the plugin deleting data
* @param {string} key Which piece of data to delete
*/
BdApi.deleteData = function(pluginName, key) {
DataStore.deletePluginData(pluginName, key);
};
/**
* This function monkey-patches a method on an object. The patching callback may be run before, after or instead of target method.
*
* - Be careful when monkey-patching. Think not only about original functionality of target method and your changes, but also about developers of other plugins, who may also patch this method before or after you. Try to change target method behaviour as little as possible, and avoid changing method signatures.
* - Display name of patched method is changed, so you can see if a function has been patched (and how many times) while debugging or in the stack trace. Also, patched methods have property `__monkeyPatched` set to `true`, in case you want to check something programmatically.
*
* @deprecated
* @param {object} what Object to be patched. You can can also pass class prototypes to patch all class instances.
* @param {string} methodName Name of the function to be patched.
* @param {object} options Options object to configure the patch.
* @param {function} [options.after] Callback that will be called after original target method call. You can modify return value here, so it will be passed to external code which calls target method. Can be combined with `before`.
* @param {function} [options.before] Callback that will be called before original target method call. You can modify arguments here, so it will be passed to original method. Can be combined with `after`.
* @param {function} [options.instead] Callback that will be called instead of original target method call. You can get access to original method using `originalMethod` parameter if you want to call it, but you do not have to. Can't be combined with `before` or `after`.
* @param {boolean} [options.once=false] Set to `true` if you want to automatically unpatch method after first call.
* @param {boolean} [options.silent=false] Set to `true` if you want to suppress log messages about patching and unpatching.
* @returns {function} A function that cancels the monkey patch
*/
BdApi.monkeyPatch = function(what, methodName, options) {
const {before, after, instead, once = false, callerId = "BdApi"} = options;
const patchType = before ? "before" : after ? "after" : instead ? "instead" : "";
if (!patchType) return Logger.err("BdApi", "Must provide one of: after, before, instead");
const originalMethod = what[methodName];
const data = {
originalMethod: originalMethod,
callOriginalMethod: () => data.originalMethod.apply(data.thisObject, data.methodArguments)
};
data.cancelPatch = Patcher[patchType](callerId, what, methodName, (thisObject, args, returnValue) => {
data.thisObject = thisObject;
data.methodArguments = args;
data.returnValue = returnValue;
try {
const patchReturn = Reflect.apply(options[patchType], null, [data]);
if (once) data.cancelPatch();
return patchReturn;
}
catch (err) {
Logger.stacktrace(`${callerId}:monkeyPatch`, `Error in the ${patchType} of ${methodName}`, err);
}
});
return data.cancelPatch;
};
/**
* Adds a listener for when the node is removed from the document body.
*
* @param {HTMLElement} node Node to be observed
* @param {function} callback Function to run when fired
*/
BdApi.onRemoved = function(node, callback) {
Utilities.onRemoved(node, callback);
};
/**
* Wraps a given function in a `try..catch` block.
*
* @deprecated
* @param {function} method Function to wrap
* @param {string} message Additional messasge to print when an error occurs
* @returns {function} The new wrapped function
*/
BdApi.suppressErrors = function(method, message) {
return Utilities.suppressErrors(method, message);
};
/**
* Tests a given object to determine if it is valid JSON.
*
* @deprecated
* @param {object} data Data to be tested
* @returns {boolean} Result of the test
*/
BdApi.testJSON = function(data) {
return Utilities.testJSON(data);
};
/**
* Gets a specific setting's status from BD
*
* @deprecated
* @param {string} [collection="settings"] Collection ID
* @param {string} category Category ID in the collection
* @param {string} id Setting ID in the category
* @returns {boolean} If the setting is enabled
*/
BdApi.isSettingEnabled = function(collection, category, id) {
return Settings.get(collection, category, id);
};
/**
* Enable a BetterDiscord setting by ids.
*
* @deprecated
* @param {string} [collection="settings"] Collection ID
* @param {string} category Category ID in the collection
* @param {string} id Setting ID in the category
*/
BdApi.enableSetting = function(collection, category, id) {
return Settings.set(collection, category, id, true);
};
/**
* Disables a BetterDiscord setting by ids.
*
* @deprecated
* @param {string} [collection="settings"] Collection ID
* @param {string} category Category ID in the collection
* @param {string} id Setting ID in the category
*/
BdApi.disableSetting = function(collection, category, id) {
return Settings.set(collection, category, id, false);
};
/**
* Toggle a BetterDiscord setting by ids.
*
* @deprecated
* @param {string} [collection="settings"] Collection ID
* @param {string} category Category ID in the collection
* @param {string} id Setting ID in the category
*/
BdApi.toggleSetting = function(collection, category, id) {
return Settings.set(collection, category, id, !Settings.get(collection, category, id));
};
/**
* Gets some data in BetterDiscord's misc data.
*
* @deprecated
* @param {string} key Key of the data to load.
* @returns {any} The stored data
*/
BdApi.getBDData = function(key) {
return DataStore.getBDData(key);
};
/**
* Gets some data in BetterDiscord's misc data.
*
* @deprecated
* @param {string} key Key of the data to load.
* @returns {any} The stored data
*/
BdApi.setBDData = function(key, data) {
return DataStore.setBDData(key, data);
};
/**
* Gives access to the [Electron Dialog](https://www.electronjs.org/docs/latest/api/dialog/) api.
* Returns a `Promise` that resolves to an `object` that has a `boolean` cancelled and a `filePath` string for saving and a `filePaths` string array for opening.
*
* @param {object} options Options object to configure the dialog.
* @param {"open"|"save"} [options.mode="open"] Determines whether the dialog should open or save files.
* @param {string} [options.defaultPath=~] Path the dialog should show on launch.
* @param {Array<object<string, string[]>>} [options.filters=[]] An array of [file filters](https://www.electronjs.org/docs/latest/api/structures/file-filter).
* @param {string} [options.title] Title for the titlebar.
* @param {string} [options.message] Message for the dialog.
* @param {boolean} [options.showOverwriteConfirmation=false] Whether the user should be prompted when overwriting a file.
* @param {boolean} [options.showHiddenFiles=false] Whether hidden files should be shown in the dialog.
* @param {boolean} [options.promptToCreate=false] Whether the user should be prompted to create non-existant folders.
* @param {boolean} [options.openDirectory=false] Whether the user should be able to select a directory as a target.
* @param {boolean} [options.openFile=true] Whether the user should be able to select a file as a target.
* @param {boolean} [options.multiSelections=false] Whether the user should be able to select multiple targets.
* @param {boolean} [options.modal=false] Whether the dialog should act as a modal to the main window.
* @returns {Promise<object>} Result of the dialog
*/
BdApi.openDialog = async function (options) {
const data = await ipc.openDialog(options);
if (data.error) throw new Error(data.error);
return data;
};
/**
* `AddonAPI` is a utility class for working with plugins and themes. Instances are accessible through the {@link BdApi}.
*/
class AddonAPI {
constructor(manager) {this.manager = manager;}
/**
* The path to the addon folder.
* @type string
*/
get folder() {return this.manager.addonFolder;}
/**
* Determines if a particular adon is enabled.
* @param {string} idOrFile Addon id or filename.
* @returns {boolean}
*/
isEnabled(idOrFile) {return this.manager.isEnabled(idOrFile);}
/**
* Enables the given addon.
* @param {string} idOrFile Addon id or filename.
*/
enable(idOrAddon) {return this.manager.enableAddon(idOrAddon);}
/**
* Disables the given addon.
* @param {string} idOrFile Addon id or filename.
*/
disable(idOrAddon) {return this.manager.disableAddon(idOrAddon);}
/**
* Toggles if a particular addon is enabled.
* @param {string} idOrFile Addon id or filename.
*/
toggle(idOrAddon) {return this.manager.toggleAddon(idOrAddon);}
/**
* Reloads if a particular addon is enabled.
* @param {string} idOrFile Addon id or filename.
*/
reload(idOrFileOrAddon) {return this.manager.reloadAddon(idOrFileOrAddon);}
/**
* Gets a particular addon.
* @param {string} idOrFile Addon id or filename.
* @returns {object} Addon instance
*/
get(idOrFile) {return this.manager.getAddon(idOrFile);}
/**
* Gets all addons of this type.
* @returns {Array<object>} Array of all addon instances
*/
getAll() {return this.manager.addonList.map(a => this.manager.getAddon(a.id));}
}
/**
* An instance of {@link AddonAPI} to access plugins.
* @type AddonAPI
*/
BdApi.Plugins = new AddonAPI(PluginManager);
/**
* An instance of {@link AddonAPI} to access themes.
* @type AddonAPI
*/
BdApi.Themes = new AddonAPI(ThemeManager);
/**
* `Patcher` is a utility class for modifying existing functions. Instance is accessible through the {@link BdApi}.
* This is extremely useful for modifying the internals of Discord by adjusting return value or React renders, or arguments of internal functions.
* @type Patcher
* @summary {@link Patcher} is a utility class for modifying existing functions.
*/
BdApi.Patcher = {
/**
* This function creates a version of itself that binds all `caller` parameters to your ID.
* @param {string} id ID to use for all subsequent calls
* @returns {Patcher} An instance of this patcher with all functions bound to your ID
*/
bind(id) {
return {
patch: BdApi.Patcher.patch.bind(BdApi.Patcher, id),
before: BdApi.Patcher.before.bind(BdApi.Patcher, id),
instead: BdApi.Patcher.instead.bind(BdApi.Patcher, id),
after: BdApi.Patcher.after.bind(BdApi.Patcher, id),
getPatchesByCaller: BdApi.Patcher.getPatchesByCaller.bind(BdApi.Patcher, id),
unpatchAll: BdApi.Patcher.unpatchAll.bind(BdApi.Patcher, id),
};
},
/**
* This method patches onto another function, allowing your code to run beforehand.
* Using this, you are also able to modify the incoming arguments before the original method is run.
* @param {string} caller Name of the caller of the patch function.
* @param {object} moduleToPatch Object with the function to be patched. Can also be an object's prototype.
* @param {string} functionName Name of the function to be patched.
* @param {function} callback Function to run before the original method. The function is given the `this` context and the `arguments` of the original function.
* @returns {function} Function that cancels the original patch.
*/
before(caller, moduleToPatch, functionName, callback) {
return Patcher.pushChildPatch(caller, moduleToPatch, functionName, callback, {type: "before"});
},
/**
* This method patches onto another function, allowing your code to run instead.
* Using this, you are also able to modify the return value, using the return of your code instead.
* @param {string} caller Name of the caller of the patch function.
* @param {object} moduleToPatch Object with the function to be patched. Can also be an object's prototype.
* @param {string} functionName Name of the function to be patched.
* @param {function} callback Function to run before the original method. The function is given the `this` context, `arguments` of the original function, and also the original function.
* @returns {function} Function that cancels the original patch.
*/
instead(caller, moduleToPatch, functionName, callback) {
return Patcher.pushChildPatch(caller, moduleToPatch, functionName, callback, {type: "instead"});
},
/**
* This method patches onto another function, allowing your code to run instead.
* Using this, you are also able to modify the return value, using the return of your code instead.
* @param {string} caller Name of the caller of the patch function.
* @param {object} moduleToPatch Object with the function to be patched. Can also be an object's prototype.
* @param {string} functionName Name of the function to be patched.
* @param {function} callback Function to run after the original method. The function is given the `this` context, the `arguments` of the original function, and the `return` value of the original function.
* @returns {function} Function that cancels the original patch.
*/
after(caller, moduleToPatch, functionName, callback) {
return Patcher.pushChildPatch(caller, moduleToPatch, functionName, callback, {type: "after"});
},
/**
* Returns all patches by a particular caller. The patches all have an `unpatch()` method.
* @param {string} caller ID of the original patches
* @returns {Array<function>} Array of all the patch objects.
*/
getPatchesByCaller(caller) {
if (typeof(caller) !== "string") return Logger.err("BdApi.Patcher", "Parameter 0 of getPatchesByCaller must be a string representing the caller");
return Patcher.getPatchesByCaller(caller);
},
/**
* Automatically cancels all patches created with a specific ID.
* @param {string} caller ID of the original patches
*/
unpatchAll(caller) {
if (typeof(caller) !== "string") return Logger.err("BdApi.Patcher", "Parameter 0 of unpatchAll must be a string representing the caller");
Patcher.unpatchAll(caller);
}
};
/**
* `Webpack` is a utility class for getting internal webpack modules. Instance is accessible through the {@link BdApi}.
* This is extremely useful for interacting with the internals of Discord.
* @type Webpack
* @summary {@link Webpack} is a utility class for getting internal webpack modules.
*/
BdApi.Webpack = {
/**
* Series of {@link Filters} to be used for finding webpack modules.
* @type Filters
*/
Filters: {
/**
* Generates a function that filters by a set of properties.
* @param {...string} props List of property names
* @returns {function} A filter that checks for a set of properties
*/
byProps(...props) {return Filters.byProps(props);},
/**
* Generates a function that filters by a set of properties on the object's prototype.
* @param {...string} props List of property names
* @returns {function} A filter that checks for a set of properties on the object's prototype.
*/
byPrototypeFields(...props) {return Filters.byPrototypeFields(props);},
/**
* Generates a function that filters by a regex.
* @param {RegExp} search A RegExp to check on the module
* @param {function} filter Additional filter
* @returns {function} A filter that checks for a regex match
*/
byRegex(regex) {return Filters.byRegex(regex);},
/**
* Generates a function that filters by strings.
* @param {...String} strings A list of strings
* @returns {function} A filter that checks for a set of strings
*/
byStrings(...strings) {return Filters.byStrings(strings);},
/**
* Generates a function that filters by a set of properties.
* @param {string} name Name the module should have
* @returns {function} A filter that checks for a set of properties
*/
byDisplayName(name) {return Filters.byDisplayName(name);},
/**
* Generates a combined function from a list of filters.
* @param {...function} filters A list of filters
* @returns {function} Combinatory filter of all arguments
*/
combine(...filters) {return Filters.combine(filters);},
},
/**
* Finds a module using a filter function.
* @param {function} filter A function to use to filter modules. It is given exports, module, and moduleID. Return true to signify match.
* @param {object} [options] Whether to return only the first matching module
* @param {Boolean} [options.first=true] Whether to return only the first matching module
* @param {Boolean} [options.defaultExport=true] Whether to return default export when matching the default export
* @return {any}
*/
getModule(filter, options = {}) {
if (("first" in options) && typeof(options.first) !== "boolean") return Logger.error("BdApi.Webpack~getModule", "Unsupported type used for options.first", options.first, "boolean expected.");
if (("defaultExport" in options) && typeof(options.defaultExport) !== "boolean") return Logger.error("BdApi.Webpack~getModule", "Unsupported type used for options.defaultExport", options.defaultExport, "boolean expected.");
return WebpackModules.getModule(filter, options);
},
/**
* Finds multiple modules using multiple filters.
*
* @param {...object} queries Whether to return only the first matching module
* @param {Function} queries.filter A function to use to filter modules
* @param {Boolean} [queries.first=true] Whether to return only the first matching module
* @param {Boolean} [queries.defaultExport=true] Whether to return default export when matching the default export
* @return {any}
*/
getBulk(...queries) {return WebpackModules.getBulk(...queries);},
/**
* Finds a module that lazily loaded.
* @param {function} filter A function to use to filter modules. It is given exports. Return true to signify match.
* @param {object} [options] Whether to return only the first matching module
* @param {AbortSignal} [options.signal] AbortSignal of an AbortController to cancel the promise
* @param {Boolean} [options.defaultExport=true] Whether to return default export when matching the default export
* @returns {Promise<any>}
*/
waitForModule(filter, options = {}) {
if (("defaultExport" in options) && typeof(options.defaultExport) !== "boolean") return Logger.error("BdApi.Webpack~waitForModule", "Unsupported type used for options.defaultExport", options.defaultExport, "boolean expected.");
if (("signal" in options) && !(options.signal instanceof AbortSignal)) return Logger.error("BdApi.Webpack~waitForModule", "Unsupported type used for options.signal", options.signal, "AbortSignal expected.");
return WebpackModules.getLazy(filter, options);
},
};
Object.freeze(BdApi);
Object.freeze(BdApi.Plugins);
Object.freeze(BdApi.Themes);
Object.freeze(BdApi.Patcher);
Object.freeze(BdApi.Webpack);
Object.freeze(BdApi.Webpack.Filters);
export default BdApi;

View File

@ -1,6 +1,5 @@
import {Config} from "data";
import Logger from "common/logger";
import DOM from "./domtools";
export default class Utilities {
@ -27,10 +26,6 @@ export default class Utilities {
return node.childNodes.length > 1 ? node.childNodes : node.childNodes[0];
}
static getTextArea() {
return DOM.query(".channelTextArea-1LDbYG textarea");
}
static insertText(textarea, text) {
textarea.focus();
textarea.selectionStart = 0;

View File

@ -132,6 +132,8 @@ const protect = theModule => {
return proxy;
};
const hasThrown = new Set();
export default class WebpackModules {
static find(filter, first = true) {return this.getModule(filter, {first});}
static findAll(filter) {return this.getModule(filter, {first: false});}
@ -153,7 +155,8 @@ export default class WebpackModules {
return filter(exports, module, moduleId);
}
catch (err) {
Logger.warn("WebpackModules~getModule", "Module filter threw an exception.", filter, err);
if (!hasThrown.has(filter)) Logger.warn("WebpackModules~getModule", "Module filter threw an exception.", filter, err);
hasThrown.add(filter);
return false;
}
};
@ -209,7 +212,8 @@ export default class WebpackModules {
return filter(ex, mod, moduleId);
}
catch (err) {
Logger.warn("WebpackModules~getModule", "Module filter threw an exception.", filter, err);
if (!hasThrown.has(filter)) Logger.warn("WebpackModules~getModule", "Module filter threw an exception.", filter, err);
hasThrown.add(filter);
return false;
}
};