This repository has been archived on 2023-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
ScriptCraft/src/main/java/com/thebrokenrail/scriptcraft/core/quickjs/QuickJSModules.java

89 lines
3.1 KiB
Java

package com.thebrokenrail.scriptcraft.core.quickjs;
import com.thebrokenrail.scriptcraft.core.ScriptCraftCore;
import com.thebrokenrail.scriptcraft.core.ScriptCraftEntryPoint;
import net.fabricmc.loader.api.FabricLoader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
@SuppressWarnings("unused")
public class QuickJSModules {
public static String loadModule(String name) {
List<ScriptCraftEntryPoint> mods = FabricLoader.getInstance().getEntrypoints(ScriptCraftCore.NAMESPACE, ScriptCraftEntryPoint.class);
for (ScriptCraftEntryPoint mod : mods) {
//noinspection CatchMayIgnoreException
try {
InputStream stream = mod.getClass().getResourceAsStream(File.separator + ScriptCraftCore.NAMESPACE + File.separator + name);
if (stream != null) {
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader(stream))) {
int c;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
stream.close();
return textBuilder.toString();
}
} catch (IOException e) {
}
}
return null;
}
private static final String[] SUPPORTED_EXTENSIONS;
static {
final String[] supportedExtensions = new String[]{"", ".js", ".json", ".mjs"};
SUPPORTED_EXTENSIONS = new String[supportedExtensions.length * 2];
for (int i = 0; i < supportedExtensions.length; i++) {
SUPPORTED_EXTENSIONS[i + supportedExtensions.length] = File.separator + "index" + supportedExtensions[i];
SUPPORTED_EXTENSIONS[i] = supportedExtensions[i];
}
}
private static final String[] BUILTIN_MODULES = new String[]{"scriptcraft-core"};
public static String normalizeModule(String baseName, String name) {
if (Arrays.asList(BUILTIN_MODULES).contains(name)) {
return name;
}
String normalizedPath;
baseName = baseName.replaceAll("/", File.separator);
name = name.replaceAll("/", File.separator);
if (name.startsWith(".")) {
Path parentPath = Paths.get(baseName).getParent();
if (parentPath == null) {
parentPath = Paths.get(File.separator);
}
normalizedPath = Paths.get(parentPath.toString(), name).normalize().toString();
if (normalizedPath.charAt(0) == File.separatorChar) {
normalizedPath = normalizedPath.substring(1);
}
} else {
normalizedPath = name;
}
for (String extension : SUPPORTED_EXTENSIONS) {
if (loadModule(normalizedPath + extension) != null) {
return normalizedPath + extension;
}
}
return null;
}
}