File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ const fs = require ( 'node:fs' ) . promises ;
4+ const vm = require ( 'node:vm' ) ;
5+
6+ const RUN_OPTIONS = { timeout : 5000 , displayErrors : false } ;
7+
8+ const pseudoRequire = ( name ) => {
9+ console . log ( `Intercepted require: ${ name } ` ) ;
10+ } ;
11+
12+ const load = async ( filePath , sandbox ) => {
13+ const src = await fs . readFile ( filePath , 'utf8' ) ;
14+ const code = `(require, module, __filename, __dirname) => {\n${ src } \n}` ;
15+ const script = new vm . Script ( code ) ;
16+ const context = vm . createContext ( Object . freeze ( { ...sandbox } ) ) ;
17+ const wrapper = script . runInContext ( context , RUN_OPTIONS ) ;
18+ const module = { } ;
19+ wrapper ( pseudoRequire , module , filePath , __dirname ) ;
20+ return module . exports ;
21+ } ;
22+
23+ const main = async ( ) => {
24+ const sandbox = { Map : class PseudoMap { } } ;
25+ const exported = await load ( './1-export.js' , sandbox ) ;
26+ console . log ( exported ) ;
27+ } ;
28+
29+ main ( ) ;
You can’t perform that action at this time.
0 commit comments