oracle / graaljs

A ECMAScript 2023 compliant JavaScript implementation built on GraalVM. With polyglot language interoperability support. Running Node.js applications!
Universal Permissive License v1.0
1.76k stars 188 forks source link

Error when evaluating ES module from Polyglot Source #336

Closed fredho closed 3 years ago

fredho commented 4 years ago

Hello there, I am opening a new ticket regarding ECMAScript module support per the closing comment on Issue 92. I'm using GraalVM Java11 20.1.0 Darwin as my JRE. I first came across this resource, then came across Issue 92.

When I try to load an ES module like such from Java,

try (Context ctx = Context.create()) {
    File jsFile = new File(.../index.mjs);
    Source src = Source.newBuilder("js", jsFile)
            .name("index.mjs")
            .mimeType("application/javascript+module")
            .build();
    ctx.eval(src);
...

I get the following exception on ctx.eval(src): org.graalvm.polyglot.PolyglotException: Error: Operation is not allowed for: ...index.mjs

This is the case when I have a very simple index.mjs that looks exactly like that of @pete-by's comment from 02/19.

js/module1.mjs:

export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

js/index.mjs:

import { square, diag } from "module1";
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

I don't even hit the NoSuchFileException @pete-by encountered. I have already tried few permutations of having mimetype specified and between file type .mjs and .js when building the source and hit the same issue. I'm probably doing something wrong, but I'm not sure what. Any guidance would be greatly appreciated.

I have tried transpiling my index.mjs to VanillaJS via the webpack command in this article and am able to execute in the Polyglot context as VanillaJS, but it's proving to be a time-consuming step I'd like to avoid, hence the motivation of this post.

eleinadani commented 4 years ago

@fredho we have a few examples of ES module usages in our unit tests here. In fact, one of our unit tests loads a module that is very similar to your module1.mjs. In your example code above, you should create your polyglot Context with allowIo(true), which allows the JS engine to perform IO operations.

fredho commented 4 years ago

I see, I will give this a try. Thanks.