|
|
@ -1,48 +1,56 @@ |
|
|
|
"use strict"; |
|
|
|
|
|
|
|
const VM_VARS = { |
|
|
|
const code = ( () => { |
|
|
|
|
|
|
|
"module": true, |
|
|
|
"process": true, |
|
|
|
"VM_VARS": true, |
|
|
|
"PREFACE_VARS": true, |
|
|
|
"generateDeclaration": true, |
|
|
|
"runInContext": true, |
|
|
|
"code": true, |
|
|
|
"preface": true, |
|
|
|
let preface = ""; |
|
|
|
const MODULE_VARS = { |
|
|
|
|
|
|
|
}; |
|
|
|
"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 " : "" ) |
|
|
|
+ `${ name } = vm$context.${ 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 ); |
|
|
|
|
|
|
|
|
|
|
|
}, |
|
|
|