Request for adding support for commonJS' module.exports
Hello, I would like to kindly request for adding support for handling scripts which use commonJS modules. I like the current module API with the asynchronous callback when the module is ready, it would be great if this will be extended with commonJS syntax.
Some background: currently I'm trying to use JS script, which uses commonJS modules, from the native application (written in C++) with bundled ChakraCore library in version 1.8.1 (I'm using the official nuget).
My goal is to call specific functions from the script. As module.exports is not supported in the ChakraCore I've tried to access the global object, get its parameters (in this case the function which I'm interested in). Then prepare arguments and use function reference to execute it.
Unfortunately, during invoking JsCallFunction I'm receiving an exception with a well-known access violation (0xC0000005).
The question is: does usage of a script with module.exports can cause undefined behavior? Is working on a solution with global object worth trying?
The code is simple, I'm inserting a PoC function, result checks are removed for readability purposes but all functions are returning JsNoError (0). Code snippet:
void jsTest(const std::string & defJson, const std::string & fsItem)
{
JsRuntimeHandle runtime;
JsContextRef context;
unsigned currentSourceContext = 0;
JsValueRef scriptResult;
JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime);
JsCreateContext(runtime, &context);
JsSetCurrentContext(context);
JsRunScript(script.c_str(), currentSourceContext++, L"", &scriptResult);
// script is saved in string variable, JsRunScript doesn't return error code
JsValueRef uicObject;
JsGetGlobalObject(&uicObject);
JsPropertyIdRef propId;
JsGetPropertyIdFromName(L"ScriptObj", &propId);
JsValueRef objRef;
JsGetProperty(uicObject, propId, &objRef);
bool hasProperty = false;
jsErr = JsHasProperty(uicObject, propId, &hasProperty); // property is found
// Internal property of property got above:
JsPropertyIdRef propInside;
jsErr = JsGetPropertyIdFromName(L"ObjectsFunctionName", &propInside); // name of the function to execute
JsValueRef functionRef;
jsErr = JsGetProperty(objRef, propInside, &functionRef);
JsHasProperty(uicObject, propId, &hasProperty); // function ref found
JsValueRef defJsStr;
jsErr = JsCreateString(defJson.c_str(), defJson.length(), &defJsStr); // string length: 10897 B
JsValueRef fsItemJsStr;
jsErr = JsCreateString(fsItem.c_str(), fsItem.length(), &fsItemJsStr); // string length: 128 B
JsValueRef argsArray;
unsigned short argCount = 3;
jsErr = JsCreateArray(argCount, &argsArray);
if (jsErr == JsNoError) {
JsValueRef valueHolder;
for (int argIndex = 0; argIndex < argCount; ++argIndex) {
switch (argIndex) {
case 0:
valueHolder = objRef;
break;
case 1:
valueHolder = defJsStr;
break;
case 2:
valueHolder = fsItemJsStr;
break;
default:
break;
}
JsValueRef jsIndex;
JsDoubleToNumber(argIndex, &jsIndex);
JsSetIndexedProperty(argsArray, jsIndex, valueHolder);
}
}
JsValueRef functionResult;
jsErr = JsCallFunction(functionRef, &argsArray, argCount, &functionResult);
// during this call exception occurs - access violation
JsSetCurrentContext(JS_INVALID_REFERENCE);
JsDisposeRuntime(runtime);
}
Disassembled view: Address: Unhandled exception at 0x52AA94BE. ContextAPIWrapper_Core<0,<lambda_1384bd1e534aad1012a12767fca3a5e8> >(ContextAPIWrapper::__l2::<lambda_1384bd1e534aad1012a12767fca3a5e8>)
ASM:
}
END_ENTER_SCRIPT
512071B8 lea ecx,[__enterScriptObject] ; this line throws
}
END_ENTER_SCRIPT
512071BB mov dword ptr [errCode],eax
What's interesting: when I replace argsArray initialization done via JsCreateArray with just simple:
JsValueRef argsArray[] = {objRef, defJsStr, fsItemJsStr}; I'm receiving:
Unable to get property 'indexOf' of undefined or null reference
as expected, so is my use of JsCreateArray invalid?
I would appreciate any other ideas on how to access the desired function.
Thanks, Piotr
I believe that the main error in your code at the moment is how you invoke JsCallFunction. Right now you are effectively passing it a C-style array with one entry (that entry being the javascript array argsArray, but telling it that it has argCount entries in it. The other gotcha here is that the first argument to a function is the this parameter, so your code is somewhat similar to theFunction.call(argsArray) which probably isn't what you want to do.
I suspect that this is closer to your intention:
// Assuming objRef is supposed to be the `this` argument
JsValueRef args[3] = { objRef, defJsStr, fsItemJsStr };
jsErr = JsCallFunction(functionRef, args, 3, &functionResult);
Ah, just saw your bit at the end where you mention you do that. What are you actually trying to achieve with the javascript array then? Does your script function expect to be given a single argument which is the javascript array? If so, then you want something more like
JsValueRef args[2] = { thisArg, argsArray }; // thisArg could be the javascript `undefined` if you don't have a better candidate
JsCallFunction(functionRef, args, 2, &functionResult)
A bit of background: CommonJS is kind of a hack (albeit a well-designed one), designed long before modules were a core ECMAScript feature. It involves the host wrapping the CommonJS module in a function expression, something like:
(function(exports, require, module) {
// insert your module here
})
The host calls that function passing an empty object for exports, a newly minted require function which works relative to the module (if you're implementing in JS like Node.js has then you can use a closure here), and module being an object with metadata for the module. There's no special magic going on, it's all bog-standard JS--the boilerplate is just hidden from you.
Hi @MSLaguana,
The JS function requires two arguments, I thought that I need to pass them in the array but this seems to be wrong.
The declarations is like:
function foo (firstParam, secondParam) {//...}
Hi @fatcerberus, Thanks for the background! I haven't known that as I'm kinda new to JS. I had a conversation with @MSLaguana about CommonJS and that it's all about host implementing appropriate actions. As I don't know how to deal with it and the global object is available I'm trying the current approach. Still handling this by a host seems interesting. Do you recommend further reading to get some knowledge?
A little bit of background - the java-script that I'm using is an output from browserify tool as the code itself is mainly executed by browsers.
@piotr-walczak If it helps, you can think of JsCallFunction(func, args, argLength, &result) as being similar to the javascript code result = func.apply(args), if args has argLength elements in it. In your case, to call foo(arg1,arg2) from javascript, you would need to call foo.apply([thisArg, arg1, arg2]) since the first parameter is the this parameter. The difference with using JsCallFunction is that we use a c-style array, rather than a javascript array, for the arguments, so that corresponds with
JsValueRef args[3] = {thisArg, arg1, arg2};
JsCallFunction(foo, args, 3, &result);
Does that help?
@piotr-walczak You don't necessarily have to implement it in the host - you can actually do it directly in JS (like I said there's no real magic here). Here's some pseudocode:
let source = readFileAsString(moduleFileName);
let wrappedSource = `(function(exports, require, module) { ${source}\n})`;
let wrapper = eval(wrappedSource);
let exports = {};
let module = { exports, fileName: moduleFileName, id: moduleFileName }; // etc.
// get a new require() that works relative to moduleFileName, maybe use a closure for this
let require = newRequireFunction(moduleFileName);
// execute the module
wrapper(exports, require, module);
/* read back `module.exports` here to find out what was exported */
@MSLaguana,
Yup, not it's clear, thanks for providing an example!
The JsCallFunction now returns JsErrorScriptException. The exception comes straight from the JS code, so I need to talk with devs to work it out.
Thanks!
@fatcerberus, Thanks, this is another approach, in this case adding separate support for CommonJS syntax seems to be worthless.
The pseudocode I posted above is pretty much exactly what Node.js does... well, minus some extra bells and whistles. :smile:
@MSLaguana,
I have some additional questions. ;)
You wrote that using JsCallFunction is similar to calling result = func.apply(args).
In JS *.apply() requires: fun.apply(thisArg, [argsArray]), so thisArg is seperated from the fun arguments which are passed as array. It's visible that JsCallFunction is different, because thisArg is passed in array. This is only syntax difference or there is something behind this decision?
Currently, when I'm invoking JsCallFunction, the script is returning an exception, I've used JsGetAndClearExceptionWithMetadata to get more details.
Here comes the interesting part: my friend is using the same script in swift code @ macOS. He is using JavaScriptCore library. He was able to reproduce the same exception as I'm facing when he used func.apply(thisArg, [args]) call. What's really strange, the script works as expected when he's using call() method.
Suddenly there is no exception.
As far as I was able to find, JavaScriptCore is using WebKit, so when he's using call() the JSObjectMakeFunction() is invoked.
Currently, I have no idea why there is an exception when calling apply() but there is none when using call(). The question I've got: is it possible to use ChakraCore and execute JS' call() instead of apply()? I'm curious if this gonna work also for me. I would like to get something similar to this notation: var res = objRef.functionRef.call(thisArg, first, second) which corresponds to:
function foo(first, second) {} from the object that I've under ObjRef (as JsValueRef).
.call() and .apply() do exactly the same thing. The only difference is the API surface: .call() takes a list of arguments (like a normal function call) while the other takes the argument list as an array. To illustrate:
function fun(x, y)
{
print(`x: ${x}`);
print(`y: ${y}`);
}
fun.call(undefined, 812, 1208);
/* ...does exactly the same thing as... */
fun.apply(undefined, [ 812, 1208 ]);
It would be highly irregular to get an exception in one circumstance but not the other. Are you sure you're using .apply() correctly?
@fatcerberus,
It turned out that this problem is caused by input arguments. The strings representing JSON objects have unwanted escape characters, so the script doesn't recognize them as valid JSON.
eg.: {\"id\":\"msId3\",\"text\":\"void\"}.