From 221080cd65961590f8ce353d14a3d6154612eef8 Mon Sep 17 00:00:00 2001 From: AliusDieMorietur Date: Sun, 18 Apr 2021 12:09:17 +0300 Subject: [PATCH 1/2] add context-bounded require --- lib/vm.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/vm.js b/lib/vm.js index 4a2fcba..5795a97 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -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 { From a4f198270a028f07b83a0abbf096d56845720171 Mon Sep 17 00:00:00 2001 From: AliusDieMorietur Date: Sun, 18 Apr 2021 12:09:29 +0300 Subject: [PATCH 2/2] add tests --- test/unit.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/test/unit.js b/test/unit.js index 27e88d0..0ff9524 100644 --- a/test/unit.js +++ b/test/unit.js @@ -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);