Refactor vm.runInContext

master
Futago-za Ryuu 6 years ago
parent 94ca36469b
commit b8db835af9

@ -1,48 +1,56 @@
"use strict"; "use strict";
const VM_VARS = { const code = ( () => {
"module": true, let preface = "";
"process": true, const MODULE_VARS = {
"VM_VARS": true,
"PREFACE_VARS": true,
"generateDeclaration": true,
"runInContext": true,
"code": true,
"preface": true,
}; "module": true,
"process": true,
"code": true,
"runInContext": true,
"source": true,
"preface": true,
};
Object.keys( MODULE_VARS ).forEach( name => {
preface += `var ${ name } = void 0;`;
const PREFACE_VARS = Object.keys( VM_VARS ) } );
.map( name => `var ${ name } = void 0;` )
.join( " " );
function generateDeclaration( name ) { function generate( name ) {
return ( ! VM_VARS[ name ] ? "var " : "" ) return `${ ( MODULE_VARS[ name ] ? "" : "var " ) + name } = __context.${ name };`;
+ `${ name } = vm$context.${ name };`;
} }
return { generate, preface };
} )();
module.exports = { module.exports = {
// `eval` the given code, using properties found in `context` as top-level // `eval` the given source, using properties found in `context` as top-level
// variables, while hiding some variables in this module from the code. // variables, while hiding some variables in this module from the source.
// //
// Based on `vm.runInContext` found in Node.js, this is a cross-env solution. // Based on `vm.runInContext` found in Node.js, this is a cross-env solution.
runInContext( code, vm$context ) { runInContext( source, __context ) {
let preface = code.preface;
if ( typeof __context === "object" ) {
let preface = PREFACE_VARS; Object.keys( __context ).forEach( name => {
if ( typeof vm$context === "object" ) { preface += code.generate( name );
preface += Object.keys( vm$context ) } );
.map( generateDeclaration )
.join( " " );
} }
return eval( preface + code ); return eval( preface + source );
}, },

Loading…
Cancel
Save