Archive eaglerforge-injector (tool, 1.8.8, clean-with-notes)

This commit is contained in:
2026-11-27 22:15:15 -06:00
parent 5f406cdc02
commit 606dab7e6e
91 changed files with 9667 additions and 0 deletions
+437
View File
@@ -0,0 +1,437 @@
var assets = {
modapi_guikit: null,
modapi_postinit: null,
modapi_modloader: null,
PatchesRegistry: null,
EFServer: null,
minify: null
};
if (globalThis.process) {
assets.modapi_guikit = require("./modgui").modapi_guikit;
assets.modapi_postinit = require("./postinit").modapi_postinit;
assets.modapi_modloader = require("./modloader").modapi_modloader;
assets.PatchesRegistry = require("./patches").PatchesRegistry;
assets.EFServer = require("./efserver").EFServer;
assets.minify = require("./minify").minify;
} else {
assets.PatchesRegistry = PatchesRegistry;
assets.minify = minify;
assets.EFServer = EFServer;
assets.modapi_postinit = modapi_postinit;
assets.modapi_modloader = modapi_modloader;
assets.modapi_guikit = modapi_guikit;
}
var modapi_preinit = `globalThis.ModAPI ||= {};
ModAPI.hooks ||= {};
ModAPI.hooks.freezeCallstack = false;
ModAPI.hooks._rippedData ||= [];
ModAPI.hooks._rippedInterfaceMap ||= {};
ModAPI.hooks._teavm ||= {};
ModAPI.hooks._rippedConstructors ||= {};
ModAPI.hooks._rippedInternalConstructors ||= {};
ModAPI.hooks.methods ||= {};
ModAPI.hooks._rippedMethodTypeMap ||= {};
ModAPI.hooks._postInit ||= ()=>{};
ModAPI.hooks._rippedStaticProperties ||= {};
ModAPI.hooks._rippedStaticIndexer ||= {};
`;
var freezeCallstack = `if(ModAPI.hooks.freezeCallstack){return false};`;
const EFIConfig = {
ModAPIVersion: "v2.7.97", //also change in package.json
doEaglerforge: true,
verbose: false,
doServerExtras: false,
doMinify: false,
doMinifyPlus: false
}
if (globalThis.process) {
var backgroundLog = (x) => {
if (EFIConfig.verbose) {
console.log(x);
}
};
var alert = console.error;
var confirm = console.warn;
}
function wait(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve(); }, ms);
});
}
function _status(x) {
if (globalThis.process) {
return console.log(x);
}
backgroundLog(x, true);
document.querySelector("#status").innerText = x;
}
function entriesToStaticVariableProxy(entries, prefix, clinitList) {
prefix = prefix.replace(
"var ",
""
);
if (entries.length === 0) {
return `ModAPI.hooks._rippedStaticProperties[\`${prefix}\`]={};`;
}
if (clinitList.includes(prefix + "_$callClinit")) {
entries.push({
name: "$callClinit",
variable: prefix + "_$callClinit"
});
}
var getComponents = "";
entries.forEach((entry) => {
getComponents += `
case \`${entry.name}\`: return ${entry.variable};`;
});
getComponents += `
default: return Reflect.get(a,b,c);`
var setComponents = "";
entries.forEach((entry) => {
setComponents += `
case \`${entry.name}\`: ${entry.variable} = c; break;`;
});
setComponents += ` default: a[b]=c;`
/*/
ModAPI.hooks._rippedStaticIndexer[\`${prefix.replace(
"var ",
""
)}\`] = [${entries
.flatMap((x) => {
return '"' + x.name + '"';
})
.join(",")}];
/*/
var proxy = `ModAPI.hooks._rippedStaticProperties[\`${prefix.replace(
"var ",
""
)}\`] = new Proxy({${entries
.flatMap((x) => {
return '"' + x.name + '"';
})
.join(":null,") + (entries.length > 0 ? ":null" : "")
}}, {
get: function (a,b,c) {
switch (b) {
${getComponents}
}
},
set: function (a,b,c) {
switch (b) {
${setComponents}
}
return true;
}
});`;
return proxy;
}
async function processClasses(string, parser) {
_status("Running EaglerForgeInjector " + EFIConfig.ModAPIVersion);
if (string.includes("__eaglerforgeinjector_installation_flag__")) {
backgroundLog("Detected input containing EFI installation flag.", true);
return alert("this file already has EaglerForge injected in it, you nonce.\nif you're trying to update, you need a vanilla file.")
}
if (!string.includes("function nmc_Minecraft_startGame(")) {
backgroundLog("Detected invalid input.\nPlease ensure file is unsigned, unminified and unobfuscated.", true);
return alert("This file does not match the requirements for EaglerForgeInjector. (not unminified & unobfuscated). Check info.")
}
if (EFIConfig.doMinify) {
if (!confirm("The minify step is extremely slow, especially on lower-end devices, and can take upwards of 15 minutes.") && !module) {
return;
}
backgroundLog("[MINIFY] Minify warning bypassed.");
if (globalThis.process) {
await wait(1000);
}
}
_status("Beginning patch process...");
await wait(50);
var patchedFile = string;
patchedFile = patchedFile.replaceAll(
`(function(root, module) {`,
`${modapi_preinit}
(function(root, module) {`
);
patchedFile = patchedFile.replaceAll(
`var main;(function(){`,
`${modapi_preinit}
var main;(function(){`
);
_status("Patching threads and reflect metadata...");
await wait(50);
patchedFile = patchedFile
.replace("\r", "")
.replace(
"var main;\n(function() {",
modapi_preinit + "var main;\n(function() {"
);
backgroundLog("[JSPATCH] Adding pre-init script");
patchedFile = patchedFile.replace(
/function \$rt_metadata\(data\)( ?){/gm,
`function $rt_metadata(data) {
/*/EaglerForge Client Patch/*/
ModAPI.hooks._rippedData.push(data);
/*/EaglerForge Client Patch/*/`
);
backgroundLog("[JSPATCH] Redirecting $rt_metadata to ModAPI.hooks._rippedData");
patchedFile = patchedFile.replaceAll(
`return thread != null && thread.isResuming()`,
(match) => {
return freezeCallstack + match;
}
);
backgroundLog("[JSPATCH] Freeze-callstack patch on TeaVMThread.isResuming()");
patchedFile = patchedFile.replaceAll(
`return thread != null && thread.isSuspending();`,
(match) => {
return freezeCallstack + match;
}
);
backgroundLog("[JSPATCH] Freeze-callstack patch on TeaVMThread.isSuspending()");
patchedFile = patchedFile.replaceAll(
`return $rt_currentNativeThread;`,
(match) => {
return (
`if(ModAPI.hooks.freezeCallstack){return {isResuming: ()=>{false}, isSuspending: ()=>{false}, push: (a)=>{}, pop: ()=>{console.warn("Frozen stack was popped, context is now unstable.")}}};` +
match
);
}
);
backgroundLog("[JSPATCH] Freeze-callstack patch thread getter");
patchedFile = patchedFile.replaceAll("function TeaVMThread(", "globalThis.ModAPI.hooks.TeaVMThread = TeaVMThread;\nfunction TeaVMThread(");
_status("Getting clinit list...");
var clinitList = [...patchedFile.matchAll(/^[\t ]*function \S+?_\S+?_\$callClinit\(/gm)].map(x => x[0].replaceAll("function ", "").replaceAll("(", "").trim());
_status("Extracting constructors and methods...");
await wait(50);
const extractConstructorRegex =
/^\s*function (\S*?)__init_\d*?\((?!\$)/gm;
const extractConstructorFullNameRegex =
/function (\S*?)__init_[0-9]*/gm;
patchedFile = patchedFile.replaceAll(
extractConstructorRegex,
(match) => {
var fullName = match.match(extractConstructorFullNameRegex);
fullName = fullName[0].replace("function ", "");
return (
`ModAPI.hooks._rippedConstructors[\`${fullName}\`] = ${fullName};
` + match
);
}
);
backgroundLog("-> Extract contructor 1");
const extractInternalConstructorRegex =
/^\s*function (\S*?)__init_\d*?\(\$this/gm; //same as extract constructor regex, but only allow $this as first argument
patchedFile = patchedFile.replaceAll(
extractInternalConstructorRegex,
(match) => {
var fullName = match.match(extractConstructorFullNameRegex);
fullName = fullName[0].replace("function ", "");
return (
`ModAPI.hooks._rippedInternalConstructors[\`${fullName}\`] = ${fullName};
` + match
);
}
);
backgroundLog("-> Extract contructor 2");
const extractInstanceMethodRegex =
/^[\t ]*function \S+?_\S+?_\S+?\((\$this)?/gm; // /^[\t ]*function \S+?_\S+?_\S+?\(\$this/gm
const extractInstanceMethodFullNameRegex = /function (\S*?)\(/gm; // /function (\S*?)\(\$this/gm
patchedFile = patchedFile.replaceAll(
extractInstanceMethodRegex,
(match) => {
if (
match.includes("__init_") ||
match.includes("__clinit_") ||
match.includes("_$callClinit")
) {
return match;
}
var fullName = match.match(extractInstanceMethodFullNameRegex);
fullName = fullName[0].replace("function ", "").replace("(", "");
return (
`function ${fullName}(...args) {
return ModAPI.hooks.methods[\`${fullName}\`].apply(this, args);
}
ModAPI.hooks._rippedMethodTypeMap[\`${fullName}\`] = \`${match.endsWith("($this") ? "instance" : "static"
}\`;
ModAPI.hooks.methods[\`${fullName}\`]=` +
match.replace(fullName + "(", "(")
);
}
);
backgroundLog("-> Extract instance methods");
backgroundLog("-> Expose instance methods");
var staticVariables = [
...patchedFile.matchAll(/var \S+?_\S+?_\S+? = /gm),
].flatMap((x) => {
return x[0];
}).filter(x => {
return (!x.includes("$_clinit_$")) && (!x.includes("$lambda$"))
});
backgroundLog("-> Extract static variables");
//Also stores classes from $rt_classWithoutFields(0)
patchedFile = patchedFile.replaceAll(
/var \S+?_\S+? = \$rt_classWithoutFields\(\S*?\);/gm,
function (match) {
var prefix = match.replaceAll(
/ = \$rt_classWithoutFields\(\S*?\);/gm,
""
);
var entries = [];
staticVariables.forEach((entry) => {
if (entry.startsWith(prefix)) {
var variableName = entry
.replace("var ", "")
.replace(" = ", "");
var segments = variableName.split("_");
segments.splice(0, 2);
var name = segments.join("_");
entries.push({
name: name,
variable: variableName,
});
}
});
var proxy = entriesToStaticVariableProxy(entries, prefix, clinitList);
var shortPrefix = prefix.replace(
"var ",
""
);
return match + `ModAPI.hooks._rippedInterfaceMap[\`${shortPrefix}\`]=${shortPrefix};` + proxy;
}
);
//Edge cases. sigh
//Done: add support for static properties on classes with constructors like this: function nmcg_GuiMainMenu() {
backgroundLog("-> Expose static variables");
patchedFile = patchedFile.replaceAll(
/function [a-z]+?_([a-zA-Z0-9\$]+?)\(\) \{/gm,
(match) => {
var prefix = "var " + match.replace("function ", "").replace("() {", "");
var entries = [];
staticVariables.forEach((entry) => {
if (entry.startsWith(prefix)) {
var variableName = entry
.replace("var ", "")
.replace(" = ", "");
var segments = variableName.split("_");
segments.splice(0, 2);
var name = segments.join("_");
entries.push({
name: name,
variable: variableName,
});
}
});
var proxy = entriesToStaticVariableProxy(entries, prefix, clinitList);
return proxy + "\n" + match;
}
);
_status("Extracting teavm internals...");
await wait(50);
patchedFile = patchedFile.replaceAll(
/function \$rt_\S+?\(/gm,
(match) => {
var name = match.replace("function ", "");
name = name.substring(0, name.length - 1);
return (
`ModAPI.hooks._teavm[\`${name}\`]=${name};
` + match
);
}
);
_status("Applying bonus patches from patch registry...");
await wait(50);
patchedFile = assets.PatchesRegistry.patchFile(patchedFile);
if (EFIConfig.doMinify) {
_status("Shrinking file...");
await wait(50);
if (globalThis.process) {
let _minify = assets.minify;
patchedFile = await _minify(patchedFile, parser, EFIConfig);
} else {
patchedFile = await minify(patchedFile, parser, EFIConfig);
}
}
_status("Injecting scripts...");
await wait(50);
// 1.12 check is using nleit_MainClass, because peyton felt like renaming stuff. annoying, but useful too ig
patchedFile = patchedFile.replace(
` id="game_frame">`,
` id="game_frame">
\<script id="modapi_patchesreg_events"\>${assets.PatchesRegistry.getEventInjectorCode()};\<\/script\>
\<script id="modapi_postinit"\>${assets.modapi_postinit.replace("__modapi_version_code__", EFIConfig.ModAPIVersion)}\<\/script\>
\<script id="modapi_modloader"\>${assets.modapi_modloader}\<\/script\>
\<script id="modapi_guikit"\>${assets.modapi_guikit}\<\/script\>
\<script id="modapi_postinit_data"\>globalThis.modapi_postinit = \`${assets.modapi_postinit.replaceAll("\\", "\\\\")}\`\<\/script\>
\<script id="libserverside"\>{"._|_libserverside_|_."}\<\/script\>
\<script id="__eaglerforgeinjector_installation_flag__"\>console.log("Thank you for using EaglerForge!");\<\/script\>`
);
backgroundLog("[HTML] Injecting script files");
patchedFile = patchedFile.replace(`<title>EaglercraftX`, `<title>EFI ${EFIConfig.ModAPIVersion} on`);
patchedFile = patchedFile.replace(`<title>Eaglercraft`, `<title>EFI ${EFIConfig.ModAPIVersion} on`);
backgroundLog("[HTML] Injecting title");
patchedFile = patchedFile.replaceAll(/main\(\);\s*?}/gm, (match) => {
return match.replace("main();", "main();ModAPI.hooks._postInit();");
});
backgroundLog("[HTML] Injecting main function");
_status("Done, awaiting input...");
await wait(50);
return patchedFile;
}
async function patchClient(string, parser) {
var patchedFile = string;
if (EFIConfig.doEaglerforge) {
patchedFile = await processClasses(patchedFile, parser);
} else if (EFIConfig.doMinify) {
patchedFile = await minify(patchedFile, parser, EFIConfig);
}
if (!patchedFile) {
return;
}
if (EFIConfig.doServerExtras) {
patchedFile = patchedFile.replace(`{"._|_libserverside_|_."}`, `(${assets.EFServer.toString()})()`);
backgroundLog("[EFSERVER] Injecting libserverside corelib");
patchedFile = patchedFile.replace("<title>EFI", "<title>EF Server");
backgroundLog("[EFSERVER] Patching title");
} else {
patchedFile.replace(`{"._|_libserverside_|_."}`, "");
}
return patchedFile;
}
if (globalThis.process) {
module.exports = {
patchClient: patchClient,
conf: EFIConfig
}
}
+290
View File
@@ -0,0 +1,290 @@
function EFServer() {
ModAPI.meta.title("Server Manager");
ModAPI.meta.version("a0");
ModAPI.meta.description("_");
ModAPI.meta.credits("ZXMushroom63 & radmanplays");
const gui = document.createElement("div");
gui.innerText = "EFSERVER CONSOLE";
gui.style.background = "black";
gui.style.fontFamily = "sans-serif";
gui.style.zIndex = 254;
gui.style.position = "fixed";
gui.style.display = "none";
gui.style.height = "calc(100vh - 1rem - 4px)";
gui.style.overflowY = "scroll";
gui.style.color = "white";
gui.style.top = gui.style.left = gui.style.bottom = gui.style.right = 0;
document.documentElement.appendChild(gui);
var cmdbox = document.createElement("input");
cmdbox.style.position = "absolute";
cmdbox.style.left = "0";
cmdbox.style.bottom = "0";
cmdbox.style.right = "0";
cmdbox.style.position = "inline-block";
cmdbox.style.border = "0";
cmdbox.style.borderTop = "2px solid white";
cmdbox.style.background = "black";
cmdbox.style.zIndex = 255;
cmdbox.style.color = "white";
cmdbox.style.height = "1rem";
cmdbox.type = "text";
cmdbox.addEventListener("keydown", (e) => {
e.stopPropagation();
e.stopImmediatePropagation();
}, true);
cmdbox.addEventListener("keyup", (e) => {
e.stopPropagation();
e.stopImmediatePropagation();
if (e.key === "Enter") {
e.preventDefault();
toServer("chat", cmdbox.value);
cmdbox.value = "";
}
}, true);
document.documentElement.appendChild(cmdbox);
function worldUpdate() {
if (ModAPI.mc && ModAPI.mc.theWorld) {
ModAPI.hooks.methods.nmcs_GameSettings_saveOptions = ()=>{};
ModAPI.settings.limitFramerate = 1;
ModAPI.settings.enableVsync = 0;
showgui();
openSharedWorld()
} else {
hidegui();
}
}
setInterval(() => {
worldUpdate();
}, 100);
function showgui() {
gui.style.opacity = "1";
gui.style.display = "block";
cmdbox.style.opacity = "1";
cmdbox.style.display = "block";
}
function hidegui() {
gui.style.opacity = "0";
gui.style.display = "none";
cmdbox.style.opacity = "0";
cmdbox.style.display = "none";
}
function EFB2__defineExecCmdAsGlobal() {
var getServer = ModAPI.reflect.getClassById("net.minecraft.server.MinecraftServer").staticMethods.getServer.method;
globalThis.efb2__executeCommandAs = function efb2__executeCommandAs($commandsender, command, feedback) {
var server = getServer();
if (!server) { return };
var commandManager = server.$commandManager;
//lie a bit
var x = $commandsender.$canCommandSenderUseCommand;
$commandsender.$canCommandSenderUseCommand = () => 1;
var y = $commandsender.$sendCommandFeedback;
$commandsender.$sendCommandFeedback = feedback ? () => 1 : () => 0;
try {
commandManager.$executeCommand($commandsender, ModAPI.util.str(command));
} catch (error) {
console.error(error);
}
$commandsender.$canCommandSenderUseCommand = x;
$commandsender.$sendCommandFeedback = y;
}
}
ModAPI.dedicatedServer.appendCode(EFB2__defineExecCmdAsGlobal);
ModAPI.hooks.methods.nmc_LoadingScreenRenderer_eaglerShow = ()=>{};
var opening = false;
function openSharedWorld() {
var platform = ModAPI.reflect.getClassById("net.lax1dude.eaglercraft.v1_8.internal.PlatformWebRTC");
if (!opening && ModAPI.mc.theWorld && !ModAPI.hooks.methods.nlevsl_LANServerController_isLANOpen()) {
platform.staticVariables.rtcLANServer = ModAPI.reflect.getClassById("net.lax1dude.eaglercraft.v1_8.internal.PlatformWebRTC$LANServer").constructors[0]();
var worldName = ModAPI.util.unstr(ModAPI.mc.thePlayer.getName().getRef()) + "'s World";
opening = true;
ModAPI.promisify(ModAPI.hooks.methods.nlevsl_LANServerController_shareToLAN)({
$accept: (status)=>{
gui.innerText += "\n" + ModAPI.util.ustr(status);
}
}, ModAPI.util.str(worldName), 0).then(code => {
opening = true; //change to false later
if (code != null) {
ModAPI.hooks.methods.nlevs_SingleplayerServerController_configureLAN(ModAPI.mc.playerController.currentGameType.getRef(), 0);
var msg = "code: " + ModAPI.util.ustr(code) + " relay: " + ModAPI.util.ustr(ModAPI.hooks.methods.nlevsl_LANServerController_getCurrentURI());
alert(msg);
gui.innerText += "\n" + msg;
}
});
} else {
return;
}
}
/*
NETWORKING OPCODES
chat - bidirectional, send chat to server/client
*/
function toServer(opcode, data) {
client_comms_channel.postMessage({
opcode: opcode,
audience: "server",
data: data,
});
}
var token = crypto.randomUUID();
const clientMessageHandlers = {
chat: function (data) {
if (gui.scrollHeight > (innerHeight * 5)) {
gui.innerText = "Console cleared. Logs were over 5 pages long.";
}
gui.innerText += "\n" + data.replaceAll("§r", "");
gui.scrollTop = gui.scrollHeight;
},
};
var client_comms_channel = new BroadcastChannel("efserv:" + token);
client_comms_channel.addEventListener("message", (ev) => {
if (ev.data.audience !== "client") {
return;
}
if (clientMessageHandlers[ev.data.opcode]) {
clientMessageHandlers[ev.data.opcode](ev.data.data);
}
});
ModAPI.dedicatedServer.appendCode(
`globalThis.efhost_security_token = "${token}";`
);
ModAPI.dedicatedServer.appendCode(function () {
var comms = new BroadcastChannel(
"efserv:" + globalThis.efhost_security_token
);
function toClient(opcode, data) {
comms.postMessage({
opcode: opcode,
audience: "client",
data: data,
});
}
function getHostPlayer() {
var host = null;
ModAPI.server.getRef().$worldServers.data.forEach((world) => {
host ||= world.$playerEntities.$array1.data.find((player) => {
if (!player) {
return;
}
var nameKey = ModAPI.util.getNearestProperty(
player.$gameProfile,
"$name"
);
return ModAPI.util.ustr(player.$gameProfile[nameKey]) === "HOST";
});
});
return host;
}
const messageHandlers = {
chat: function (data) {
var host = getHostPlayer();
if (!host) {
return;
}
host.$addChatMessage = (comp)=>{toClient("chat", ModAPI.util.ustr(comp.$getUnformattedText()))};
efb2__executeCommandAs(getHostPlayer(), data, true);
},
};
comms.addEventListener("message", (ev) => {
if (ev.data.audience !== "server") {
return;
}
if (messageHandlers[ev.data.opcode]) {
messageHandlers[ev.data.opcode](ev.data.data);
}
});
var oldLog = ModAPI.hooks.methods.nlevl_Logger_log;
ModAPI.hooks.methods.nlevl_Logger_log = function (...args) {
toClient("chat", ModAPI.util.ustr(args[2]));
return oldLog.apply(this, args);
};
ModAPI.addEventListener("tick", ()=>{
var host = ModAPI.util.wrap(getHostPlayer());
if (!host) {
return;
}
host.posY = -10;
host.posX = 0;
host.posZ = 0;
host.capabilities.disableDamage = 1;
host.capabilities.isCreativeMode = 1;
host.capabilities.isFlying = 1;
host.motionY = 0;
host.motionX = 0;
host.motionZ = 0;
host.isDead = 0;
host.setHealth(20);
});
});
function renameButton(array, originalName, newName) {
array.find(
(x) => ModAPI.util.ustr(x.displayString.getRef()) === originalName
).displayString = ModAPI.util.str(newName);
}
const mainmenuinit = ModAPI.hooks.methods.nmcg_GuiMainMenu_initGui;
ModAPI.hooks.methods.nmcg_GuiMainMenu_initGui = function (...args) {
var result = mainmenuinit.apply(this, args);
var wrappedGuiObject = ModAPI.util.wrap(args[0], args[0], false, false);
wrappedGuiObject.splashText = ModAPI.util.str("Server Hosting Mode");
var btnarray = wrappedGuiObject.buttonList.array1;
renameButton(btnarray, "Singleplayer", "Host Server");
return result;
};
const GuiSelectWorldinit = ModAPI.hooks.methods.nmcg_GuiSelectWorld_initGui;
ModAPI.hooks.methods.nmcg_GuiSelectWorld_initGui = function (...args) {
var result = GuiSelectWorldinit.apply(this, args);
var wrappedGuiObject = ModAPI.util.wrap(args[0], args[0], false, false);
var btnarray = wrappedGuiObject.buttonList.array1.data;
//renameButton(btnarray, "Create", "Create Server");
return result;
};
const mainmenuactions = ModAPI.hooks.methods.nmcg_GuiMainMenu_actionPerformed;
ModAPI.hooks.methods.nmcg_GuiMainMenu_actionPerformed = function (...args) {
ModAPI.hooks.methods.nlevp_EaglerProfile_setName(ModAPI.util.str("HOST"));
var idKey = ModAPI.util.getNearestProperty(args[1], "$id");
var guiButtonid = args[1][idKey];
var blockedIds = [2]; // put the blocked/disabled button ids in there
if (blockedIds.includes(guiButtonid)) {
return 0;
}
return mainmenuactions.apply(this, args);
};
// disable rendering
ModAPI.hooks.methods.nmcr_EntityRenderer_renderWorld = () => { };
}
if (globalThis.process) {
module.exports = {
EFServer: EFServer
}
}
+72
View File
@@ -0,0 +1,72 @@
if (!globalThis.Babel) {
globalThis.Babel = require("@babel/core");
}
function wait(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve(); }, ms);
});
}
const MINIFY = function () {
return {
visitor: {
Identifier(path) {
if (path.node.name === "$ptr") {
path.node.name = "r";
}
if (path.node.name === "$tmp") {
path.node.name = "m";
}
if (path.node.name === "$thread") {
path.node.name = "t";
}
},
}
};
};
async function minify(input, parser, EFIConfig) {
var _status = globalThis._status || console.log;
let isHtml = true;
let inputHtml = input;
if (!input.trim().startsWith('<')) {
isHtml = false;
inputHtml = `<script>${input}</script>`;
}
_status("[MINIFY] Parsing html...");
await wait(50);
const doc = parser.parseFromString(inputHtml, 'text/html');
const scriptTags = doc.getElementsByTagName('script');
await wait(200); //trying to get chrome to gc
for (let i = 0; i < scriptTags.length; i++) {
const scriptTag = scriptTags[i];
const code = scriptTag.textContent;
_status("[MINIFY] Transpiling script #" + (i + 1) + " of length " + Math.round(code.length / 1000) + "k...");
await wait(150);
const output = Babel.transform(code, {
plugins: EFIConfig.doMinifyPlus ? [
MINIFY()
] : []
});
scriptTag.textContent = output.code;
await wait(10);
}
_status("[MINIFY] Job complete!");
await wait(50);
if (isHtml) {
return globalThis.process ? doc.toString() : doc.documentElement.outerHTML;
} else {
return doc.querySelector('script').textContent;
}
}
if (globalThis.process) {
module.exports = {
minify: minify
}
}
+325
View File
@@ -0,0 +1,325 @@
const modapi_guikit = "(" + (() => {
// ModAPI GUI made by TheIdiotPlays
// https://github.com/TheIdiotPlays
var splashes = [
"Now with A.I.D.S (automatically injected dedicated server)",
"Only causes death 90% of the time!",
"HTML is better.",
"https://github.com/EaglerForge",
"hey you should check out https://github.com/ZXMushroom63/scratch-gui",
"99% of people stop gambling before they win big.",
"Now with free estradiol!",
"Now with H.I.V (Hyper Injected Virtual-debugger)",
"asdasd",
"Star us on GitHub to support us! https://github.com/EaglerForge/EaglerForgeInjector"
];
var gui = `<div id="modapi_gui_container">
<header>
<h1 class="title">EaglerForge Mod Manager</h1>
<h4>
<!-- Now with with A.I.D.S. (automatically injected dedicated server)! -->
{splash_msg}
</h4>
<h5>
Warning: installing malicious mods can delete your worlds, ip-grab you, or even download more serious malware onto your computer. The EaglerForge developers are not liable for any damage caused by the use of EaglerForge and its related tools.
</h5>
</header>
<table id="modapi_gui_modTable">
<thead>
<tr>
<td>
Mod
</td>
<td class="nothing"></td>
<td>
Controls
</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="controls">
<button class="button" onclick="window.modapi_uploadmod()">Upload Mod (.js)</button>
<button class="button" onclick="window.modapi_addmod()">Add Mod From URL</button>
<button class="button" style="text-shadow: 0px 0px 10px rgba(255, 0, 0, 0.5)" onclick="window.modapi_clearmods()">Clear All Mods</button>
<button class="button _doneButton" onclick="this.parentElement.parentElement.remove();">Done</button>
</div>
<span>(reload to apply changes)</span>
<footer>
<p>
GUI by <a href="https://github.com/TheIdiotPlays">TheIdiotPlays</a>
</p>
<p>
Modloader linker by
<a href="https://github.com/ZXMushroom63">ZXMushroom63</a>
</p>
<p>
API by <a href="https://github.com/ZXMushroom63">ZXMushroom63,</a> <a href="https://leah.chromebooks.lol">Leah Anderson,</a> and <a href="https://github.com/radmanplays">radmanplays</a>
</p>
</footer>
<style>
#modapi_gui_container td:not(.nothing):not(:has(.button)) {
padding: 0.5rem 1.5rem;
margin: 0.5rem;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
#modapi_gui_container td.nothing {
user-select: none;
opacity: 0;
width: 5rem;
}
#modapi_gui_container td {
text-align: center;
}
#modapi_gui_container h4, #modapi_gui_container h5 {
padding-bottom: 0;
margin-bottom: 0;
}
#modapi_gui_container h5 {
color: white;
text-shadow: 0px 0px 10px rgba(255,0,0,0.5);
font-size: 0.75rem;
}
#modapi_gui_container a {
color: white;
transition: 1s;
}
#modapi_gui_container a:hover {
color: lightblue;
}
#modapi_gui_container {
overflow-y: scroll;
overflow-x: hidden;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
height: 100vh;
width: 100vw;
position: fixed;
z-index: 127;
top: 0;
left: 0;
font-family: sans-serif;
background: white;
}
#modapi_gui_container header {
background-color: #333;
width: 100%;
padding: 1rem 0;
text-align: center;
color: white;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#modapi_gui_container .title {
font-size: 3rem;
margin: 0;
font-weight: 700;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}
#modapi_gui_container .controls {
display: flex;
gap: 1rem;
margin-bottom: 2rem;
flex-wrap: wrap;
justify-content: center;
width: 100%;
}
#modapi_gui_container .button {
background-color: #555;
color: white;
padding: 12px 24px;
font-size: 1rem;
font-weight: 600;
border: none;
border-radius: 2px;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.2s ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
#modapi_gui_container .button:hover {
background-color: #777;
transform: translateY(-2px);
}
#modapi_gui_container footer {
width: 100%;
padding: 1rem;
background-color: #333;
text-align: center;
color: white;
font-size: 1.25rem;
box-shadow: 0 -4px 6px rgba(0, 0, 0, 0.1);
}
#modapi_gui_modTable {
min-width: 40vw;
}
</style>
</div>`;
async function fileToText(file) {
return new Promise((res, rej) => {
var fr = new FileReader();
fr.addEventListener("error", (e) => { rej(e); });
fr.addEventListener("load", (e) => { res(fr.result); });
fr.readAsText(file);
});
}
window.modapi_displayModGui = async function (cb) {
if (!getMods) {
return;
}
if (document.querySelector("#modapi_gui_container")) {
cb ||= document.querySelector("#modapi_gui_container")._cb;
document.querySelector("#modapi_gui_container").remove();
}
var element = document.createElement("div");
element.innerHTML = gui.replace("{splash_msg}", splashes[Math.floor(Math.random() * splashes.length)]);
document.body.appendChild(element);
document.querySelector("#modapi_gui_container")._cb = cb;
var modsList = await getMods();
var tbody = document.querySelector("#modapi_gui_container #modapi_gui_modTable tbody");
tbody.innerHTML = "";
modsList.forEach((modtxt, i) => {
if (!modtxt) { return }
var hash = ModAPI.util.hashCode(modtxt);
var tr = document.createElement("tr");
var mod = document.createElement("td");
if (ModAPI.meta._titleMap[hash]) {
//Mod has metadata
if (ModAPI.meta._iconMap[hash]) {
var img = document.createElement("img");
img.style.width = "48px";
img.style.height = "48px";
img.style.imageRendering = "pixelated";
img.src = ModAPI.meta._iconMap[hash];
mod.appendChild(img);
}
var h4 = document.createElement("h4");
h4.style.margin = 0;
h4.style.padding = 0;
h4.innerText = ModAPI.meta._titleMap[hash] + (ModAPI.meta._versionMap[hash] ? " " + ModAPI.meta._versionMap[hash] : "");
mod.appendChild(h4);
if (ModAPI.meta._developerMap[hash]) {
var h6 = document.createElement("h6");
h6.style.margin = 0;
h6.style.padding = 0;
h6.innerText = ModAPI.meta._developerMap[hash];
mod.appendChild(h6);
}
if (ModAPI.meta._descriptionMap[hash]) {
var span = document.createElement("span");
span.style.fontSize = "0.65rem";
span.innerText = ModAPI.meta._descriptionMap[hash];
mod.appendChild(span);
}
} else {
//Mod does not have metadata
if (modtxt.length > 125) {
try {
mod.innerText = modtxt.match(/data:text\/\S+?;fs=\S+;/m)[0]
} catch (error) {
mod.innerText = "Unknown Mod.";
}
} else { mod.innerText = modtxt; }
}
var spacer = document.createElement("td");
spacer.classList.add("nothing");
var controls = document.createElement("td");
var deleteBtn = document.createElement("button");
deleteBtn.innerText = "Delete";
deleteBtn.style.height = "3rem";
deleteBtn.addEventListener("click", async () => {
await removeMod(i);
window.modapi_displayModGui();
});
deleteBtn.classList.add("button");
controls.appendChild(deleteBtn);
if (typeof ModAPI.meta._configMap[hash] === "function") {
var configBtn = document.createElement("button");
configBtn.innerText = "Config";
configBtn.style.height = "3rem";
configBtn.style.marginLeft = "1rem";
configBtn.addEventListener("click", async () => {
ModAPI.meta._configMap[hash]();
});
configBtn.classList.add("button");
controls.appendChild(configBtn);
}
tr.appendChild(mod);
tr.appendChild(spacer);
tr.appendChild(controls);
tbody.appendChild(tr);
});
var once = false;
if (cb) {
document.querySelector("#modapi_gui_container ._doneButton").addEventListener("mousedown", ()=>{
if (once) {
return;
}
once = true;
cb();
document.querySelector("#modapi_gui_container").remove();
})
}
}
window.modapi_clearmods = async () => {
await resetMods();
window.modapi_displayModGui();
}
window.modapi_addmod = async () => {
var mod = window.prompt("Paste in the URL of the mod you wish to add: ");
if (!mod || mod.length === 0) {
return;
}
await addMod(mod);
window.modapi_displayModGui();
}
window.modapi_uploadmod = async () => {
var f = document.createElement("input");
f.type = "file";
f.accept = "text/javascript";
f.multiple = true;
f.addEventListener("input", async () => {
if (f.files.length < 1) {
return;
}
for (let i = 0; i < f.files.length; i++) {
await addFileMod(f.files[i].name, (await fileToText(f.files[i])));
}
window.modapi_displayModGui();
});
f.click();
}
}).toString() + ")();";
if (globalThis.process) {
module.exports = {
modapi_guikit: modapi_guikit
}
}
@@ -0,0 +1,261 @@
const modapi_modloader = "(" + (() => {
globalThis.promisifyIDBRequest = function promisifyIDBRequest(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
globalThis.getDatabase = async function getDatabase() {
const dbRequest = indexedDB.open("EF_MODS");
const db = await promisifyIDBRequest(dbRequest);
if (!db.objectStoreNames.contains("filesystem")) {
db.close();
const version = db.version + 1;
const upgradeRequest = indexedDB.open("EF_MODS", version);
upgradeRequest.onupgradeneeded = (event) => {
const upgradedDb = event.target.result;
upgradedDb.createObjectStore("filesystem");
};
return promisifyIDBRequest(upgradeRequest);
}
return db;
}
globalThis.getMods = async function getMods() {
const db = await getDatabase();
const transaction = db.transaction(["filesystem"], "readonly");
const objectStore = transaction.objectStore("filesystem");
const object = await promisifyIDBRequest(objectStore.get("mods.txt"));
var out = object ? (await object.text()).split("|").toSorted() : [];
db.close();
return out;
}
globalThis.getMod = async function getMod(mod) {
const db = await getDatabase();
const transaction = db.transaction(["filesystem"], "readonly");
const objectStore = transaction.objectStore("filesystem");
const object = await promisifyIDBRequest(objectStore.get("mods/" + mod));
var out = object ? (await object.text()) : "";
db.close();
return out;
}
globalThis.saveMods = async function saveMods(mods) {
const db = await getDatabase();
const transaction = db.transaction(["filesystem"], "readwrite");
const objectStore = transaction.objectStore("filesystem");
const encoder = new TextEncoder();
const modsData = encoder.encode(mods.toSorted().join("|"));
const modsBlob = new Blob([modsData], { type: "text/plain" });
await promisifyIDBRequest(objectStore.put(modsBlob, "mods.txt"));
db.close();
}
globalThis.addMod = async function addMod(mod) {
const mods = await getMods();
mods.push("web@" + mod);
await saveMods(mods);
}
globalThis.addFileMod = async function addFileMod(mod, textContents) {
const mods = await getMods();
if (mods.includes(mod)) {
await removeMod(mods.indexOf(mod));
} else {
mods.push(mod);
}
await saveMods(mods);
const db = await getDatabase();
const transaction = db.transaction(["filesystem"], "readwrite");
const objectStore = transaction.objectStore("filesystem");
const encoder = new TextEncoder();
const modsData = encoder.encode(textContents);
const modsBlob = new Blob([modsData], { type: "text/plain" });
await promisifyIDBRequest(objectStore.put(modsBlob, "mods/" + mod));
db.close();
}
globalThis.removeMod = async function removeMod(index) {
const mods = await getMods();
if (index >= 0 && index < mods.length) {
var deleted = mods.splice(index, 1)[0];
await saveMods(mods);
if (!deleted.startsWith("web@")) {
const db = await getDatabase();
const transaction = db.transaction(["filesystem"], "readwrite");
const objectStore = transaction.objectStore("filesystem");
await promisifyIDBRequest(objectStore.delete("mods/" + deleted));
db.close();
}
}
}
globalThis.resetMods = async function resetMods() {
console.log("Resetting mods...");
const db = await getDatabase();
const transaction = db.transaction(["filesystem"], "readwrite");
const objectStore = transaction.objectStore("filesystem");
await promisifyIDBRequest(objectStore.clear());
console.log("Mods reset");
db.close();
}
globalThis.modLoader = async function modLoader(modsArr = []) {
if (!window.eaglerMLoaderMainRun) {
var searchParams = new URLSearchParams(location.search);
searchParams.getAll("mod").forEach((modToAdd) => {
console.log(
"[EaglerML] Adding mod to loadlist from search params: " + modToAdd
);
modsArr.push("web@" + modToAdd);
});
searchParams.getAll("plugin").forEach((modToAdd) => {
console.log(
"[EaglerML] Adding mod to loadlist from search params: " + modToAdd
);
modsArr.push("web@" + modToAdd);
});
if (
!!eaglercraftXOpts &&
!!eaglercraftXOpts.Mods &&
Array.isArray(eaglercraftXOpts.Mods)
) {
eaglercraftXOpts.Mods.forEach((modToAdd) => {
console.log(
"[EaglerML] Adding mod to loadlist from eaglercraftXOpts: " +
modToAdd
);
modsArr.push("web@" + modToAdd);
});
}
console.log("[EaglerML] Searching in iDB");
try {
var idbMods = await getMods();
modsArr = modsArr.concat(idbMods
.filter(x => { return x && x.length > 0 })
);
} catch (error) {
console.error(error);
}
window.eaglerMLoaderMainRun = true;
}
if (window.noLoadMods === true) {
modsArr.splice(0, modsArr.length);
}
function checkModsLoaded(totalLoaded, identifier) {
console.log(
"[EaglerML] Checking if mods are finished :: " +
totalLoaded +
"/" +
modsArr.length
);
if (totalLoaded >= modsArr.length) {
clearInterval(identifier);
window.ModGracePeriod = false;
if (
window.eaglerMLoaderMainRun &&
ModAPI &&
ModAPI.events &&
ModAPI.events.callEvent
) {
ModAPI.events.callEvent("load", {});
}
console.log(
"[EaglerML] Checking if mods are finished :: All mods loaded! Grace period off."
);
}
}
function methodB(currentMod) {
try {
console.log("[EaglerML] Loading " + currentMod + " via method B.");
var script = document.createElement("script");
script.setAttribute("data-hash", ModAPI.util.hashCode("web@" + currentMod));
script.src = currentMod;
script.setAttribute("data-isMod", "true");
script.onerror = () => {
console.log(
"[EaglerML] Failed to load " + currentMod + " via method B!"
);
script.remove();
totalLoaded++;
};
script.onload = () => {
console.log(
"[EaglerML] Successfully loaded " + currentMod + " via method B."
);
totalLoaded++;
};
document.body.appendChild(script);
} catch (error) {
console.log(
"[EaglerML] Oh no! The mod " + currentMod + " failed to load!"
);
totalLoaded++;
}
}
window.ModGracePeriod = true;
var totalLoaded = 0;
var loaderCheckInterval = null;
modsArr.sort();
for (let i = 0; i < modsArr.length; i++) {
let currentMod = modsArr[i];
var isIDBMod = !currentMod.startsWith("web@");
if (!isIDBMod) {
currentMod = currentMod.replace("web@", "");
}
console.log("[EaglerML] Starting " + currentMod);
try {
var responseText = isIDBMod ? await getMod(currentMod) : await (await fetch(currentMod)).text();
console.log("[EaglerML] Loading " + currentMod + " via method A.");
var script = document.createElement("script");
script.setAttribute("data-hash", ModAPI.util.hashCode((isIDBMod ? "" : "web@") + currentMod));
try {
script.src =
"data:text/javascript," + encodeURIComponent(responseText);
} catch (error) {
methodB(currentMod);
return;
}
script.setAttribute("data-isMod", "true");
script.onerror = () => {
console.log(
"[EaglerML] Failed to load " + currentMod + " via method A!"
);
script.remove();
totalLoaded++;
};
script.onload = () => {
console.log(
"[EaglerML] Successfully loaded " + currentMod + " via method A."
);
totalLoaded++;
};
document.body.appendChild(script);
} catch (error) {
methodB(currentMod);
}
}
loaderCheckInterval = setInterval(() => {
checkModsLoaded(totalLoaded, loaderCheckInterval);
}, 500);
console.log(
"[EaglerML] Starting to load " + modsArr.length + " mods..."
);
window.returnTotalLoadedMods = function returnTotalLoadedMods() {
return totalLoaded;
};
};
}).toString() + ")();"
if (globalThis.process) {
module.exports = {
modapi_modloader: modapi_modloader
}
}
@@ -0,0 +1,44 @@
class PatchesRegistry {
static patchFns = []
static patchedEventNames = []
static getEventInjectorCode() {
return "globalThis.modapi_specialevents = [" + PatchesRegistry.patchedEventNames.flatMap(x=>`\`${x}\``).join(",") + "];";
}
static patchFile(x) {
var current = x;
PatchesRegistry.patchFns.forEach(fn => {
current = fn(current);
});
return current;
}
static addPatch(fn) {
PatchesRegistry.patchFns.push(fn);
}
static regSpecialEvent(x) {
PatchesRegistry.patchedEventNames.push(x);
}
}
// PatchesRegistry.regSpecialEvent("test");
// PatchesRegistry.addPatch(function (input) {
// var output = input;
// return output;
// })
PatchesRegistry.regSpecialEvent("render");
PatchesRegistry.addPatch(function (input) {
var output = input.replaceAll(
/continue main;\s+?}\s+?if\s?\(!\$this.\$renderHand\)/gm
,
`continue main;
}
ModAPI.events.callEvent("render",{partialTicks:$partialTicks})
if (!$this.$renderHand)`
);
return output;
});
if (globalThis.process) {
module.exports = {
PatchesRegistry: PatchesRegistry
}
}
File diff suppressed because it is too large Load Diff