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

Require context bounded #56

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
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
10 changes: 9 additions & 1 deletion lib/vm.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,17 @@ const COMMON_CONTEXT = vm.createContext(
})
);

const contextifiedRequire = (context) => (module) => {
if (Reflect.has(context, module)) return Reflect.get(context, module);
return undefined;
};

const createContext = (context, preventEscape = false) => {
if (!context) return EMPTY_CONTEXT;
return vm.createContext(context, preventEscape ? CONTEXT_OPTIONS : {});
return vm.createContext(
{ ...context, require: contextifiedRequire(context) },
preventEscape ? CONTEXT_OPTIONS : {}
);
};

class MetaScript {
Expand Down
13 changes: 12 additions & 1 deletion test/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,22 @@ metatests.test('Create custom context', async (test) => {
sandbox.global = sandbox;
const context = metavm.createContext(sandbox);
test.strictSame(context.field, 'value');
test.strictSame(Object.keys(context), ['field', 'global']);
test.strictSame(Object.keys(context), ['field', 'global', 'require']);
test.strictSame(context.global, sandbox);
test.end();
});

metatests.test('Require binded to custom context', async (test) => {
const sandbox = { field: 'value' };
sandbox.global = sandbox;
const context = metavm.createContext(sandbox);
const src = `({ exist: require('field'), notExist: require('nothing') })`;
const ms = metavm.createScript('Example', src, { context });
test.strictSame('value', ms.exports.exist);
test.strictSame(undefined, ms.exports.notExist);
test.end();
});

metatests.test('Call undefined as a function', async (test) => {
const filePath = path.join(examples, 'undef.js');
const ms = await metavm.readScript(filePath);
Expand Down