NeilFraser/JS-Interpreter

Replace string with regexp return undefined

DanieleRosada opened this issue · 2 comments

Replace with regexp return undefined and not expected result.
Could someone help me, please?

Example: https://stackblitz.com/edit/typescript-thsokx?file=index.ts

I can recreate this issue locally.

My initial finding is that if you call myInterpreter.run(); twice in succession, at the end of the second call myInterpreter.value is correctly set. Looks like run is exiting one step too early with the signature of an async function.

Shouldn't be difficult to figure out now...

Oh, working as intended! string.replace is an async function in the JS-Interpreter. To defend against malicious regular expressions it has to spin up a worker thread to do that computation.

There are two solutions available to you. If a malicious user is unable to specify an arbitrary regular expression, then you can add this line:
myInterpreter.REGEXP_MODE = 1;
From that point on, string.replace becomes a regular synchronous function and your existing code will work fine. For more information about REGEX_MODE, see this page:
https://neil.fraser.name/software/JS-Interpreter/demos/regexp.html

On the other hand, you want to defend against pathological regular expressions and/or support other asynchronous functions, you just need to modify your code to check the return value of run. If it's true you need to call a setTimeout to give the async worker a chance to complete, then call run again. This code works:

var transform = "'10/10/2020'.replace(/\\//g, '');";
var myInterpreter = new Interpreter(transform);

function runTillDone() {
  if (myInterpreter.run()) {
    setTimeout(runTillDone, 100);
  } else {
    whenDone();
  }
}

function whenDone() {
  const appDiv: HTMLElement = document.getElementById('app');
  appDiv.innerHTML = myInterpreter.value;
}

runTillDone();