compile method
Compile code to bytecode. stripSource drops function source text:
a smaller heap, but Function.prototype.toString no longer shows it.
With asModule, code is compiled as an ES module and fileName becomes
the name its importers resolve to. QuickJS resolves the module's imports
while compiling it, so the engine's module handler must be able to reach
every dependency, and compiling registers the module in the engine's
current context — compile in a scratch engine rather than repeatedly in a
long-lived one. JsModuleBundle does both for a whole import graph.
Implementation
@override
Uint8List compile(
String script,
String fileName, {
bool stripSource = false,
bool asModule = false,
}) {
_ensureEngine();
final ctx = _ctx!;
final rt = _rt!;
final scriptPtr = script.toNativeUtf8().cast<Char>();
final fileNamePtr = fileName.toNativeUtf8().cast<Char>();
final lengthPtr = calloc<IntPtr>();
final stripInfo = jsGetStripInfo(rt);
if (stripSource) jsSetStripInfo(rt, stripInfo | jsStripSource);
final value = compileWithFlagsFn(
ctx,
scriptPtr,
fileNamePtr,
asModule ? JSEvalFlag.MODULE : JSEvalFlag.GLOBAL,
lengthPtr,
);
if (stripSource) jsSetStripInfo(rt, stripInfo);
try {
if (value.address == 0) {
throw _parseJSException(ctx);
}
final length = lengthPtr.value;
return Uint8List.fromList(value.asTypedList(length));
} finally {
if (value.address != 0) {
// Allocated by QuickJS (JS_WriteObject), not libc malloc.
jsFree(ctx, value.cast());
}
calloc.free(scriptPtr);
calloc.free(fileNamePtr);
calloc.free(lengthPtr);
}
}