Refactor vm.runInContext

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

@ -1,48 +1,56 @@
"use strict";
const VM_VARS = {
const code = ( () => {
let preface = "";
const MODULE_VARS = {
"module": true,
"process": true,
"VM_VARS": true,
"PREFACE_VARS": true,
"generateDeclaration": true,
"runInContext": true,
"code": true,
"runInContext": true,
"source": true,
"preface": true,
};
};
Object.keys( MODULE_VARS ).forEach( name => {
const PREFACE_VARS = Object.keys( VM_VARS )
.map( name => `var ${ name } = void 0;` )
.join( " " );
preface += `var ${ name } = void 0;`;
function generateDeclaration( name ) {
} );
return ( ! VM_VARS[ name ] ? "var " : "" )
+ `${ name } = vm$context.${ name };`;
function generate( name ) {
}
return `${ ( MODULE_VARS[ name ] ? "" : "var " ) + name } = __context.${ name };`;
}
return { generate, preface };
} )();
module.exports = {
// `eval` the given code, using properties found in `context` as top-level
// variables, while hiding some variables in this module from the code.
// `eval` the given source, using properties found in `context` as top-level
// 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.
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