diff --git a/package.json b/package.json index b8646fb95..0f9fdf654 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,9 @@ "license": "MIT", "main": "dist/main/index.js", "scripts": { - "build": "parcel build" + "build": "parcel build", + "watch": "parcel watch", + "check": "tsc --noEmit" }, "repository": "https://github.com/replugged-org/replugged.git", "author": "Replugged", @@ -13,22 +15,29 @@ "url": "https://github.com/replugged-org/replugged/issues" }, "devDependencies": { - "parcel": "^2.7.0" + "@types/node": "^18.7.23", + "electron": "13", + "parcel": "^2.7.0", + "typescript": "^4.8.4" }, "targets": { "main": { "context": "electron-main", - "source": "src/main/index.js", - "includeNodeModules": true + "source": "src/main/index.ts", + "includeNodeModules": { + "electron": false + } }, "preload": { "context": "electron-renderer", - "source": "src/preload.js", - "includeNodeModules": true + "source": "src/preload.ts", + "includeNodeModules": { + "electron": false + } }, "renderer": { "context": "browser", - "source": "src/renderer/index.js", + "source": "src/renderer/index.ts", "includeNodeModules": true } } diff --git a/src/main/index.js b/src/main/index.ts similarity index 57% rename from src/main/index.js rename to src/main/index.ts index 652769a89..ce71f8a01 100644 --- a/src/main/index.js +++ b/src/main/index.ts @@ -1,30 +1,42 @@ -const { dirname, join } = require("path"); +import { dirname, join } from "path"; -const electron = require("electron"); +import electron from "electron"; +import type { RepluggedWebContents } from "../types"; const electronPath = require.resolve("electron"); -const discordPath = join(dirname(require.main.filename), "..", "app.asar"); +const discordPath = join(dirname(require.main!.filename), "..", "app.asar"); const discordPackage = require(join(discordPath, "package.json")); const discordMain = join(discordPath, discordPackage.main); -require.main.filename = discordMain; +require.main!.filename = discordMain; Object.defineProperty(global, "appSettings", { set: (v /*: typeof global.appSettings*/) => { - v.set("DANGEROUS_ENABLE_DEVTOOLS_ONLY_ENABLE_IF_YOU_KNOW_WHAT_YOURE_DOING", true); - // @ts-ignore - delete global.appSettings; - global.appSettings = v; + v.set( + "DANGEROUS_ENABLE_DEVTOOLS_ONLY_ENABLE_IF_YOU_KNOW_WHAT_YOURE_DOING", + true + ); + // @ts-ignore + delete global.appSettings; + // @ts-ignore + global.appSettings = v; }, - configurable: true + configurable: true, }); // This class has to be named "BrowserWindow" exactly // https://github.com/discord/electron/blob/13-x-y/lib/browser/api/browser-window.ts#L60-L62 // Thank you Ven for pointing this out! class BrowserWindow extends electron.BrowserWindow { - constructor(opts) { + constructor( + opts: Electron.BrowserWindowConstructorOptions & { + webContents: Electron.WebContents; + webPreferences: { + nativeWindowOpen: boolean; + }; + } + ) { console.log(opts); - const originalPreload = opts.webPreferences.preload; + const originalPreload = opts.webPreferences.preload!; if (opts.webContents) { // General purpose popouts used by Discord @@ -33,13 +45,13 @@ class BrowserWindow extends electron.BrowserWindow { //opts.webPreferences.preload = join(__dirname, './preloadSplash.js'); } else if (opts.webPreferences && opts.webPreferences.offscreen) { // Overlay -// originalPreload = opts.webPreferences.preload; + // originalPreload = opts.webPreferences.preload; // opts.webPreferences.preload = join(__dirname, './preload.js'); } else if (opts.webPreferences && opts.webPreferences.preload) { //originalPreload = opts.webPreferences.preload; if (opts.webPreferences.nativeWindowOpen) { // Discord Client - opts.webPreferences.preload = join(__dirname, "../preload.js"); + opts.webPreferences.preload = join(__dirname, "../preload/index.js"); //opts.webPreferences.contextIsolation = false; // shrug } else { // Splash Screen on macOS (Host 0.0.262+) & Windows (Host 0.0.293 / 1.0.17+) @@ -48,12 +60,13 @@ class BrowserWindow extends electron.BrowserWindow { } super(opts); - this.webContents.originalPreload = originalPreload; + (this.webContents as RepluggedWebContents).originalPreload = + originalPreload; } } -const electronExports = new Proxy(electron, { - get (target, prop) { +const electronExports: typeof electron = new Proxy(electron, { + get(target, prop) { switch (prop) { case "BrowserWindow": return BrowserWindow; @@ -63,29 +76,34 @@ const electronExports = new Proxy(electron, { case "__esModule": return true; default: - return target[prop]; + return target[prop as keyof typeof electron]; } - } + }, }); -delete require.cache[electronPath].exports; -require.cache[electronPath].exports = electronExports; +delete require.cache[electronPath]!.exports; +require.cache[electronPath]!.exports = electronExports; +// @ts-ignore electron.app.setAppPath(discordPath); electron.app.name = discordPackage.name; // Copied from old codebase electron.app.once("ready", () => { // @todo: Whitelist a few domains instead of removing CSP altogether; See #386 - electron.session.defaultSession.webRequest.onHeadersReceived(({ responseHeaders }, done) => { - Object.keys(responseHeaders) - .filter(k => (/^content-security-policy/i).test(k)) - .map(k => (delete responseHeaders[k])); + electron.session.defaultSession.webRequest.onHeadersReceived( + ({ responseHeaders }, done) => { + if (!responseHeaders) return done({}); - done({ responseHeaders }); - }); + Object.keys(responseHeaders) + .filter((k) => /^content-security-policy/i.test(k)) + .map((k) => delete responseHeaders[k]); + + done({ responseHeaders }); + } + ); }); require("./ipc"); -require("module")._load(discordMain); \ No newline at end of file +require("module")._load(discordMain); diff --git a/src/main/ipc/index.js b/src/main/ipc/index.js deleted file mode 100644 index 79d80454a..000000000 --- a/src/main/ipc/index.js +++ /dev/null @@ -1,11 +0,0 @@ -const { ipcMain } = require("electron"); - -require("./plugins"); -require("./themes"); -require("./quick-css"); - -ipcMain.on('REPLUGGED_GET_DISCORD_PRELOAD', (event) => { - console.log(event); - event.returnValue = event.sender.originalPreload; -}); -// Handle requesting renderer code \ No newline at end of file diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts new file mode 100644 index 000000000..21dda4154 --- /dev/null +++ b/src/main/ipc/index.ts @@ -0,0 +1,11 @@ +import { ipcMain } from "electron"; +import "./plugins"; +import "./themes"; +import "./quick-css"; +import type { RepluggedWebContents } from "../../types"; + +ipcMain.on("REPLUGGED_GET_DISCORD_PRELOAD", (event) => { + console.log(event); + event.returnValue = (event.sender as RepluggedWebContents).originalPreload; +}); +// Handle requesting renderer code diff --git a/src/main/ipc/plugins.js b/src/main/ipc/plugins.ts similarity index 100% rename from src/main/ipc/plugins.js rename to src/main/ipc/plugins.ts diff --git a/src/main/ipc/quick-css.js b/src/main/ipc/quick-css.js deleted file mode 100644 index b1111f18b..000000000 --- a/src/main/ipc/quick-css.js +++ /dev/null @@ -1,8 +0,0 @@ -const { readFile, writeFile } = require("fs/promises"); -const { join } = require("path"); -const { ipcMain } = require("electron"); - -const cssPath = join(__dirname, "../../../settings/quickcss/main.css"); - -ipcMain.handle("REPLUGGED_GET_QUICK_CSS", () => readFile(cssPath, { encoding: "utf-8" })); -ipcMain.on("REPLUGGED_SAVE_QUICK_CSS", (_, css) => writeFile(cssPath, css, {encoding: "utf-8"})); \ No newline at end of file diff --git a/src/main/ipc/quick-css.ts b/src/main/ipc/quick-css.ts new file mode 100644 index 000000000..497ebce30 --- /dev/null +++ b/src/main/ipc/quick-css.ts @@ -0,0 +1,12 @@ +import { readFile, writeFile } from "fs/promises"; +import { join } from "path"; +import { ipcMain } from "electron"; + +const cssPath = join(__dirname, "../../../settings/quickcss/main.css"); + +ipcMain.handle("REPLUGGED_GET_QUICK_CSS", () => + readFile(cssPath, { encoding: "utf-8" }) +); +ipcMain.on("REPLUGGED_SAVE_QUICK_CSS", (_, css) => + writeFile(cssPath, css, { encoding: "utf-8" }) +); diff --git a/src/main/ipc/themes.js b/src/main/ipc/themes.ts similarity index 56% rename from src/main/ipc/themes.js rename to src/main/ipc/themes.ts index 6511165e3..c21f0abde 100644 --- a/src/main/ipc/themes.js +++ b/src/main/ipc/themes.ts @@ -5,12 +5,16 @@ IPC events: - REPLUGGED_UNINSTALL_THEME: uninstalls a theme by name */ -const { ipcMain } = require("electron"); +import { ipcMain } from "electron"; -ipcMain.handle("REPLUGGED_GET_THEME_CSS", async (event, themeName) => { - -}); +ipcMain.handle( + "REPLUGGED_GET_THEME_CSS", + async (event, themeName: string) => {} +); ipcMain.handle("REPLUGGED_LIST_THEMES", async () => {}); -ipcMain.handle("REPLUGGED_UNINSTALL_THEME", async (event, themeName) => {}); \ No newline at end of file +ipcMain.handle( + "REPLUGGED_UNINSTALL_THEME", + async (event, themeName: string) => {} +); diff --git a/src/preload.js b/src/preload.ts similarity index 59% rename from src/preload.js rename to src/preload.ts index 93088ee52..8f0f1bb77 100644 --- a/src/preload.js +++ b/src/preload.ts @@ -1,20 +1,22 @@ -const { contextBridge, ipcRenderer, webFrame } = require("electron"); +import { contextBridge, ipcRenderer, webFrame } from "electron"; const themesMap = new Map(); -let quickCSSKey; +let quickCSSKey: string; const RepluggedNative = { themes: { - enable: async (themeName) => {}, - disable: async (themeName) => {}, - load: async (themeName) => { - return ipcRenderer.invoke("REPLUGGED_GET_THEME_CSS", themeName).then(css => { - const cssKey = webFrame.insertCSS(css); - themesMap.set(themeName, cssKey); - }) + enable: async (themeName: string) => {}, + disable: async (themeName: string) => {}, + load: async (themeName: string) => { + return ipcRenderer + .invoke("REPLUGGED_GET_THEME_CSS", themeName) + .then((css) => { + const cssKey = webFrame.insertCSS(css); + themesMap.set(themeName, cssKey); + }); }, loadAll: async () => {}, - unload: (themeName) => { + unload: (themeName: string) => { webFrame.removeInsertedCSS(themesMap.get(themeName)); themesMap.delete(themeName); }, @@ -23,7 +25,7 @@ const RepluggedNative = { RepluggedNative.themes.unload(theme); } }, - reload: async (themeName) => { + reload: async (themeName: string) => { RepluggedNative.themes.unload(themeName); await RepluggedNative.themes.load(themeName); }, @@ -33,48 +35,49 @@ const RepluggedNative = { }, listEnabled: async () => {}, listDisabled: async () => {}, - uninstall: async (themeName) => { + uninstall: async (themeName: string) => { return ipcRenderer.invoke("REPLUGGED_UNINSTALL_THEME", themeName); // whether theme was successfully uninstalled - } + }, }, plugins: { - getJS: async (pluginName) => { + getJS: async (pluginName: string) => { return ipcRenderer.invoke("REPLUGGED_GET_PLUGIN_JS", pluginName); }, list: async () => { return ipcRenderer.invoke("REPLUGGED_LIST_PLUGINS"); }, - uninstall: async (pluginName) => { + uninstall: async (pluginName: string) => { return ipcRenderer.invoke("REPLUGGED_UNINSTALL_PLUGIN", pluginName); - } + }, }, quickCSS: { get: async () => ipcRenderer.invoke("REPLUGGED_GET_QUICK_CSS"), - load: async () => RepluggedNative.quickCSS.get().then(css => { - quickCSSKey = webFrame.insertCSS(css); - }), + load: async () => + RepluggedNative.quickCSS.get().then((css) => { + quickCSSKey = webFrame.insertCSS(css); + }), unload: () => webFrame.removeInsertedCSS(quickCSSKey), - save: (css) => ipcRenderer.send("REPLUGGED_SAVE_QUICK_CSS", css), + save: (css: string) => ipcRenderer.send("REPLUGGED_SAVE_QUICK_CSS", css), reload: async () => { RepluggedNative.quickCSS.unload(); return RepluggedNative.quickCSS.load(); - } + }, }, settings: { - get: (key) => {}, - set: (key, value) => {}, - has: (key) => {}, - delete: (key) => {} + get: (key: string) => {}, + set: (key: string, value: any) => {}, + has: (key: string) => {}, + delete: (key: string) => {}, }, - openDevTools: () => {}, // TODO - closeDevTools: () => {}, // TODO + openDevTools: () => {}, // TODO + closeDevTools: () => {}, // TODO - clearCache: () => {}, // maybe? - openBrowserWindow: (opts) => {} // later + clearCache: () => {}, // maybe? + openBrowserWindow: (opts: Electron.BrowserWindowConstructorOptions) => {}, // later }; contextBridge.exposeInMainWorld("RepluggedNative", RepluggedNative); @@ -89,4 +92,4 @@ if (preload) { // While we could keep the thing below...it's terrible practice to use time delay // as a substitute for handling events. -//setTimeout(() => DiscordNative.window.setDevtoolsCallbacks(null, null), 5e3); \ No newline at end of file +//setTimeout(() => DiscordNative.window.setDevtoolsCallbacks(null, null), 5e3); diff --git a/src/renderer/index.js b/src/renderer/index.js deleted file mode 100644 index 6035f2cac..000000000 --- a/src/renderer/index.js +++ /dev/null @@ -1 +0,0 @@ -window.replugged = {}; \ No newline at end of file diff --git a/src/renderer/index.ts b/src/renderer/index.ts new file mode 100644 index 000000000..42e8502fe --- /dev/null +++ b/src/renderer/index.ts @@ -0,0 +1,2 @@ +declare var replugged: {}; +window.replugged = {}; diff --git a/src/renderer/modules/injector.js b/src/renderer/modules/injector.ts similarity index 100% rename from src/renderer/modules/injector.js rename to src/renderer/modules/injector.ts diff --git a/src/renderer/modules/webpack.js b/src/renderer/modules/webpack.js deleted file mode 100644 index 1c2789737..000000000 --- a/src/renderer/modules/webpack.js +++ /dev/null @@ -1,16 +0,0 @@ -export const filters = { - byProps: () => {}, - byString: () => {} -}; - -export function getModule(filter) { - -} - -export function getByProps(...props) { - -} - -export function getByString(pattern) { - -} \ No newline at end of file diff --git a/src/renderer/modules/webpack.ts b/src/renderer/modules/webpack.ts new file mode 100644 index 000000000..729b33c7c --- /dev/null +++ b/src/renderer/modules/webpack.ts @@ -0,0 +1,12 @@ +export const filters = { + byProps: () => {}, + byString: () => {}, +}; + +export function getModule( + filter: string[] | ((defaultExport: any) => boolean) +) {} + +export function getByProps(...props: string[]) {} + +export function getByString(pattern: string) {} diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 000000000..3dbc8bd92 --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1,3 @@ +export type RepluggedWebContents = Electron.WebContents & { + originalPreload: string; +}; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 000000000..60e9cd25b --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,103 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + "jsx": "react" /* Specify what JSX code is generated. */, + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs" /* Specify what module code is generated. */, + "rootDir": "./" /* Specify the root folder within your source files. */, + "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + "noEmit": true /* Disable emitting files from a compilation. */, + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, + + /* Type Checking */ + "strict": true /* Enable all strict type-checking options. */, + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +}