code-interpreter icon indicating copy to clipboard operation
code-interpreter copied to clipboard

Support ES6 modules in JS runtime and top-level await

Open mlejva opened this issue 1 year ago • 3 comments

The JavaScript runtime is currently based on ijavascript kernel runtime. ijavascript kernel doesn't support import. Ideally, we should fix it and import should just work. Less ideally (and the "less" is big here), we need to put a disclaimer here for users.

Similarly with await. The await doesn't work in the top most scope. Eg running this code

const fs = require('node:fs');
const fetch = require('node-fetch');

console.log('Hello');

const url = 'https://jsonplaceholder.typicode.com/posts/1';

// Fetch data from the API
const response = await fetch(url);
const data = await response.text();
console.log(data);

will produce the following error

ExecutionError {
  name: 'SyntaxError',
  value: 'await is only valid in async functions and the top level bodies of modules',
  tracebackRaw: [
    'evalmachine.<anonymous>:10',
    'const response = await fetch(url);',
    '                 ^^^^^',
    '',
    'SyntaxError: await is only valid in async functions and the top level bodies of modules',
    '    at new Script (node:vm:94:7)',
    '    at createScript (node:vm:250:10)',
    '    at Object.runInThisContext (node:vm:298:10)',
    '    at run ([eval]:1020:15)',
    '    at onRunRequest ([eval]:864:18)',
    '    at onMessage ([eval]:828:13)',
    '    at process.emit (node:events:517:28)',
    '    at emit (node:internal/child_process:944:14)',
    '    at process.processTicksAndRejections (node:internal/process/task_queues:83:21)'
  ]
}

Deno's Jupyter kernel would tick both boxes (import and top-level await): https://blog.jupyter.org/bringing-modern-javascript-to-the-jupyter-notebook-fc998095081e

We'd need to check if NPM dependencies work out of the box for users

mlejva avatar Aug 08 '24 19:08 mlejva