Skip to content

Commit

Permalink
Implement metarequire
Browse files Browse the repository at this point in the history
Refs: #34
  • Loading branch information
AliusDieMorietur authored and tshemsedinov committed Apr 11, 2022
1 parent d8fbcf2 commit 7796807
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions metavm.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
'use strict';

const vm = require('vm');
const fs = require('fs').promises;
const fs = require('fs');
const fsp = fs.promises;
const path = require('path');

const RUN_OPTIONS = { timeout: 5000, displayErrors: false };
Expand Down Expand Up @@ -49,7 +50,7 @@ class MetaScript {
const createScript = (name, src, options) => new MetaScript(name, src, options);

const readScript = async (filePath, options) => {
const src = await fs.readFile(filePath, 'utf8');
const src = await fsp.readFile(filePath, 'utf8');
if (src === '') throw new SyntaxError(`File ${filePath} is empty`);
const name =
options && options.filename
Expand All @@ -59,11 +60,28 @@ const readScript = async (filePath, options) => {
return script;
};

const metarequire = (context, permitted = {}) => {
const require = (module) => {
if (Reflect.has(permitted, module)) {
return Reflect.get(permitted, module);
}
try {
const src = fs.readFileSync(module, 'utf8');
const script = createScript(module, src, { context });
return script;
} catch {
throw new Error(`Cannot find module: '${module}'`);
}
};
return require;
};

module.exports = {
createContext,
MetaScript,
createScript,
EMPTY_CONTEXT,
COMMON_CONTEXT,
readScript,
metarequire,
};

0 comments on commit 7796807

Please sign in to comment.