All Downloads are FREE. Search and download functionalities are using the official Maven repository.

li.rudin.mavenjs.core.Optimizer Maven / Gradle / Ivy

package li.rudin.mavenjs.core;

import java.io.IOException;
import java.io.InputStreamReader;

import li.rudin.mavenjs.core.util.JsRuntimeSupport;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Optimizer
{
	private static final Logger logger = LoggerFactory.getLogger(Optimizer.class);
	
	private final Context cx;
	private final ScriptableObject sharedScope;
	
	private static final ObjectMapper mapper = new ObjectMapper();

	public Optimizer() throws IOException
	{
		long start = System.currentTimeMillis();
		cx = Context.enter();

		sharedScope = cx.initStandardObjects(new JsRuntimeSupport(), true);
		
		sharedScope.defineFunctionProperties(new String[]{"print", "load"}, sharedScope.getClass(), ScriptableObject.DONTENUM);
		
		Scriptable argsObj = cx.newArray(sharedScope, new Object[] {});
		sharedScope.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM);

		cx.evaluateReader(sharedScope, new InputStreamReader(Optimizer.class.getResourceAsStream("/optimizer/env.js")), "r.js", 1, null);
		
		long diff = System.currentTimeMillis() - start;
		logger.debug("Optimizer created in {} ms", diff);
	}

	public void optimize(Object config) throws JsonProcessingException
	{
		String json = mapper.writeValueAsString(config);
		
		cx.evaluateString(sharedScope, "requirejs.optimize("+json+", print, print);", "optimize", 1, null);
	}
	
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy