Method to execute JS code securely, with control over starting/stopping and also exposing specific API’s to the code

I’m using blockly in my electron app, and I wanted a way to be able to execute the user’s code. I originally inserted a script into the HTML with the generated code from my preload file, but I’m not able to stop the code from running, because from what I see I can’t just stop a script during execution.

The blockly docs recommend using JS-Interpreter. However, after looking through the docs I have a few reservations which I’m not sure about:

  1. I want to be able to have access to some libraries which I include in my HTML as scripts linked to online resources, and since it’s sandboxed I don’t think I can.
  2. I also want to be able to require(‘path’), and import some classes which I define in a different JS file in my project. I currently just use require to import them, but since they’re sandboxed I’m not sure if I’ll be able to access them. I can see how allowing the user to require(‘fs’) could be very destructive, but if possible it would be great to only allow access to a few libraries.
  3. The docs state JS-Interpreter as running “about 200 times slower than native JavaScript.” I would like to be able to run programs faster than that, as the kind of program the user would generate might take a few minutes with the script injection method.

Is there a different way to execute JS while being able to access the libraries, import classes, and also run without a significant performance loss?