Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,26 +42,30 @@ module.exports = (content, filename, context) => {
} else {
result = context ? vm.runInNewContext(content, context) : vm.runInThisContext(content);
}
sandbox.release();

return result;
};

function _commonjsEval(content, filename, context) {
const dirname = filename && path.dirname(filename);
const sandbox = {};
function _commonjsEval(content, incomingFilename, context) {
const hasFilename = Boolean(incomingFilename);
const dirname = hasFilename && path.dirname(incomingFilename);
const filename = hasFilename ? incomingFilename : '<anonymous>';

const sandbox = {module: null, require: null, __result: null};
const exports = {};
let contextKeys;

sandbox.module = new Module(filename || '<anonymous>', module.parent);
sandbox.module = new Module(filename, module.parent);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если прям нужно оставить parent
давай туда запихнем что-то в духе:
new Module(filename, new Module('', null));
?

sandbox.module.exports = exports;
sandbox.module.filename = filename;

if(filename) {
sandbox.module.filename = filename;
if(hasFilename) {
sandbox.module.paths = Module._nodeModulePaths(dirname);
// See: https://github.com/nodejs/node/blob/master/lib/internal/module.js#L13-L40
sandbox.require = id => sandbox.module.require(id);
sandbox.require.resolve = req => Module._resolveFilename(req, sandbox.module);
} else {
filename = '<anonymous>';
sandbox.require = filenameRequired;
}

Expand All @@ -83,6 +87,10 @@ function _commonjsEval(content, filename, context) {
Object.keys(sandbox.module.exports).length === exportKeysCount &&
Object.keys(sandbox.module).length === moduleKeysCount;

// Prevent storing all evaluated stuff in parent's chidlren
const parentChildren = module.parent.children;
sandbox.release = () => { parentChildren.splice(parentChildren.indexOf(sandbox.module), 1); };

return sandbox;
}
/**
Expand Down