Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] onWillParseMarkdown does not support "require" #362

Open
Luca-wj opened this issue Sep 22, 2024 · 0 comments
Open

[Feature Request] onWillParseMarkdown does not support "require" #362

Luca-wj opened this issue Sep 22, 2024 · 0 comments
Assignees

Comments

@Luca-wj
Copy link

Luca-wj commented Sep 22, 2024

When altering the content displayed by changing the Markdown using onWillParseMarkdown in parser.js, it is not possible to use require to load libraries, leading to significant limitations

({
  onWillParseMarkdown: async function(markdown) {
    try {
      const path = await require('path')
      return markdown  
    } catch (error) {
      return error + markdown  
    } 
  }
})

When using require, an error occurs
”ReferenceError: require is not defined“
This is because the Function interpretJS in utility.ts uses vm.runInNewContext, and require is not a global function. Therefore, it is recommended to provide users with a way to edit the context, allowing them to set up their own sandbox environment.
Here's an example: parser.js

({
    "require": require
})
,
({
    "onWillParseMarkdown": async function(markdown) {
    try {
      const path = await require('path')
      return markdown + path.join('a', 'b');
    } catch (error) {
      return error + markdown  
    } 
  }
})

The modified interpretJS

function interpretJS(text) {
    const [contextText, code] = splitObject(text);
    const context = eval(`(${contextText})`);
    vm.runInNewContext(`result = (${code})`, context);
    return context['result'];
  
  }
// split text of Object 
function splitObject(text) {
  let objectList = [];
  let braceDict = {'(': 0, ')': 0};
  let start = null;
  for (let i = 0; i < text.length; i++) {
    
    switch (text[i]) {
        case '(':
            braceDict['('] += 1
            if (start === null) {start = i;}
            break;
        case ')':
            braceDict[')'] += 1
            if (braceDict['('] === braceDict[')']) {
                objectList.push(text.slice(start, i + 1));
                start = null;
            }
            break;
        default:
    }
  }
  return objectList;
}

This allows adding parameters or global variables to the sandbox environment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants