fcs
2025-04-10 0163870d662dc5b7d69ceff977490ede594f7d82
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
/* eslint-disable global-require, no-use-before-define */
 
'use strict';
 
/**
 * This callback will be called to transform a script to JavaScript.
 *
 * @callback compileCallback
 * @param {string} code - Script code to transform to JavaScript.
 * @param {string} filename - Filename of this script.
 * @return {string} JavaScript code that represents the script code.
 */
 
/**
 * This callback will be called to resolve a module if it couldn't be found.
 *
 * @callback resolveCallback
 * @param {string} moduleName - Name of the module to resolve.
 * @param {string} dirname - Name of the current directory.
 * @return {(string|undefined)} The file or directory to use to load the requested module.
 */
 
const fs = require('fs');
const vm = require('vm');
const pa = require('path');
const {EventEmitter} = require('events');
const {INSPECT_MAX_BYTES} = require('buffer');
const helpers = require('./helpers.js');
const importModuleDynamically = () => {
    // We can't throw an error object here because since vm.Script doesn't store a context, we can't properly contextify that error object.
    // eslint-disable-next-line no-throw-literal
    throw 'Dynamic imports are not allowed.';
};
 
const MODULE_PREFIX = '(function (exports, require, module, __filename, __dirname) { ';
const STRICT_MODULE_PREFIX = MODULE_PREFIX + '"use strict"; ';
const MODULE_SUFFIX = '\n});';
 
/**
 * Load a script from a file and compile it.
 * 
 * @private
 * @param {string} filename - File to load and compile to a script.
 * @param {string} prefix - Prefix for the script.
 * @param {string} suffix - Suffix for the script.
 * @return {vm.Script} The compiled script.
 */
function loadAndCompileScript(filename, prefix, suffix) {
    const data = fs.readFileSync(filename, 'utf8');
    return new vm.Script(prefix + data + suffix, {
        filename,
        displayErrors: false,
        importModuleDynamically
    });
}
 
/**
 * Cache where we can cache some things
 * 
 * @private
 * @property {?compileCallback} coffeeScriptCompiler - The coffee script compiler or null if not yet used.
 * @property {?Object} timeoutContext - The context used for the timeout functionality of null if not yet used.
 * @property {?vm.Script} timeoutScript - The compiled script used for the timeout functionality of null if not yet used.
 * @property {vm.Script} contextifyScript - The compiled script used to setup a sandbox.
 * @property {?vm.Script} sandboxScript - The compiled script used to setup the NodeVM require mechanism of null if not yet used.
 * @property {?vm.Script} hookScript - The compiled script used to setup the async hooking functionality.
 * @property {?vm.Script} getGlobalScript - The compiled script used to get the global sandbox object.
 * @property {?vm.Script} getGeneratorFunctionScript - The compiled script used to get the generator function constructor.
 * @property {?vm.Script} getAsyncFunctionScript - The compiled script used to get the async function constructor.
 * @property {?vm.Script} getAsyncGeneratorFunctionScript - The compiled script used to get the async generator function constructor.
 */
const CACHE = {
    coffeeScriptCompiler: null,
    timeoutContext: null,
    timeoutScript: null,
    contextifyScript: loadAndCompileScript(`${__dirname}/contextify.js`, '(function(require, host) { ', '\n})'),
    sandboxScript: null,
    hookScript: null,
    getGlobalScript: null,
    getGeneratorFunctionScript: null,
    getAsyncFunctionScript: null,
    getAsyncGeneratorFunctionScript: null,
};
 
/**
 * Default run options for vm.Script.runInContext
 * 
 * @private
 */
const DEFAULT_RUN_OPTIONS = {displayErrors: false, importModuleDynamically};
 
/**
 * Returns the cached coffee script compiler or loads it
 * if it is not found in the cache.
 * 
 * @private
 * @return {compileCallback} The coffee script compiler.
 * @throws {VMError} If the coffee-script module can't be found.
 */
function getCoffeeScriptCompiler() {
    if (!CACHE.coffeeScriptCompiler) {
        try {
            const coffeeScript = require('coffee-script');
            CACHE.coffeeScriptCompiler = (code, filename) => {
                return coffeeScript.compile(code, {header: false, bare: true});
            };
        } catch (e) {
            throw new VMError('Coffee-Script compiler is not installed.');
        }
    }
    return CACHE.coffeeScriptCompiler;
}
 
/**
 * The JavaScript compiler, just a identity function.
 * 
 * @private
 * @type {compileCallback}
 * @param {string} code - The JavaScript code.
 * @param {string} filename - Filename of this script.
 * @return {string} The code.
 */
function jsCompiler(code, filename) {
    return removeShebang(code);
}
 
/**
 * Look up the compiler for a specific name.
 * 
 * @private
 * @param {(string|compileCallback)} compiler - A compile callback or the name of the compiler.
 * @return {compileCallback} The resolved compiler.
 * @throws {VMError} If the compiler is unknown or the coffee script module was needed and couldn't be found.
 */
function lookupCompiler(compiler) {
    if ('function' === typeof compiler) return compiler;
    switch (compiler) {
        case 'coffeescript':
        case 'coffee-script':
        case 'cs':
        case 'text/coffeescript':
            return getCoffeeScriptCompiler();
        case 'javascript':
        case 'java-script':
        case 'js':
        case 'text/javascript':
            return jsCompiler;
        default:
            throw new VMError(`Unsupported compiler '${compiler}'.`);
    }
}
 
/**
 * Remove the shebang from source code.
 * 
 * @private
 * @param {string} code - Code from which to remove the shebang.
 * @return {string} code without the shebang.
 */
function removeShebang(code) {
    if (!code.startsWith('#!')) return code;
    return '//' + code.substr(2);
}
 
/**
 * Class Script
 *
 * @public
 */
class VMScript {
 
    /**
     * The script code with wrapping. If set will invalidate the cache.<br>
     * Writable only for backwards compatibility.
     * 
     * @public
     * @readonly
     * @member {string} code
     * @memberOf VMScript#
     */
 
    /**
     * The filename used for this script.
     * 
     * @public
     * @readonly
     * @since v3.9.0
     * @member {string} filename
     * @memberOf VMScript#
     */
 
    /**
     * The line offset use for stack traces.
     * 
     * @public
     * @readonly
     * @since v3.9.0
     * @member {number} lineOffset
     * @memberOf VMScript#
     */
 
    /**
     * The column offset use for stack traces.
     * 
     * @public
     * @readonly
     * @since v3.9.0
     * @member {number} columnOffset
     * @memberOf VMScript#
     */
 
    /**
     * The compiler to use to get the JavaScript code.
     * 
     * @public
     * @readonly
     * @since v3.9.0
     * @member {(string|compileCallback)} compiler
     * @memberOf VMScript#
     */
 
    /**
     * The prefix for the script.
     * 
     * @private
     * @member {string} _prefix
     * @memberOf VMScript#
     */
 
    /**
     * The suffix for the script.
     * 
     * @private
     * @member {string} _suffix
     * @memberOf VMScript#
     */
 
    /**
     * The compiled vm.Script for the VM or if not compiled <code>null</code>.
     * 
     * @private
     * @member {?vm.Script} _compiledVM
     * @memberOf VMScript#
     */
 
    /**
     * The compiled vm.Script for the NodeVM or if not compiled <code>null</code>.
     * 
     * @private
     * @member {?vm.Script} _compiledNodeVM
     * @memberOf VMScript#
     */
 
    /**
     * The compiled vm.Script for the NodeVM in strict mode or if not compiled <code>null</code>.
     * 
     * @private
     * @member {?vm.Script} _compiledNodeVMStrict
     * @memberOf VMScript#
     */
 
    /**
     * The resolved compiler to use to get the JavaScript code.
     * 
     * @private
     * @readonly
     * @member {compileCallback} _compiler
     * @memberOf VMScript#
     */
 
    /**
     * The script to run without wrapping.
     * 
     * @private
     * @member {string} _code
     * @memberOf VMScript#
     */
 
    /**
     * Create VMScript instance.
     *
     * @public
     * @param {string} code - Code to run.
     * @param {(string|Object)} [options] - Options map or filename.
     * @param {string} [options.filename="vm.js"] - Filename that shows up in any stack traces produced from this script.
     * @param {number} [options.lineOffset=0] - Passed to vm.Script options.
     * @param {number} [options.columnOffset=0] - Passed to vm.Script options.
     * @param {(string|compileCallback)} [options.compiler="javascript"] - The compiler to use.
     * @throws {VMError} If the compiler is unknown or if coffee-script was requested but the module not found.
     */
    constructor(code, options) {
        const sCode = `${code}`;
        let useFileName;
        let useOptions;
        if (arguments.length === 2) {
            if (typeof options === 'object' && options.toString === Object.prototype.toString) {
                useOptions = options || {};
                useFileName = useOptions.filename;
            } else {
                useOptions = {};
                useFileName = options;
            }
        } else if (arguments.length > 2) {
            // We do it this way so that there are no more arguments in the function.
            // eslint-disable-next-line prefer-rest-params
            useOptions = arguments[2] || {};
            useFileName = options || useOptions.filename;
        } else {
            useOptions = {};
        }
 
        const {
            compiler = 'javascript',
            lineOffset = 0,
            columnOffset = 0
        } = useOptions;
 
        // Throw if the compiler is unknown.
        const resolvedCompiler = lookupCompiler(compiler);
 
        Object.defineProperties(this, {
            code: {
                // Put this here so that it is enumerable, and looks like a property.
                get() {
                    return this._prefix + this._code + this._suffix;
                },
                set(value) {
                    const strNewCode = String(value);
                    if (strNewCode === this._code && this._prefix === '' && this._suffix === '') return;
                    this._code = strNewCode;
                    this._prefix = '';
                    this._suffix = '';
                    this._compiledVM = null;
                    this._compiledNodeVM = null;
                    this._compiledCode = null;
                },
                enumerable: true
            },
            filename: {
                value: useFileName || 'vm.js',
                enumerable: true
            },
            lineOffset: {
                value: lineOffset,
                enumerable: true
            },
            columnOffset: {
                value: columnOffset,
                enumerable: true
            },
            compiler: {
                value: compiler,
                enumerable: true
            },
            _code: {
                value: sCode,
                writable: true
            },
            _prefix: {
                value: '',
                writable: true
            },
            _suffix: {
                value: '',
                writable: true
            },
            _compiledVM: {
                value: null,
                writable: true
            },
            _compiledNodeVM: {
                value: null,
                writable: true
            },
            _compiledNodeVMStrict: {
                value: null,
                writable: true
            },
            _compiledCode: {
                value: null,
                writable: true
            },
            _compiler: {value: resolvedCompiler}
        });
    }
 
    /**
     * Wraps the code.<br>
     * This will replace the old wrapping.<br>
     * Will invalidate the code cache.
     *
     * @public
     * @deprecated Since v3.9.0. Wrap your code before passing it into the VMScript object.
     * @param {string} prefix - String that will be appended before the script code.
     * @param {script} suffix - String that will be appended behind the script code.
     * @return {this} This for chaining.
     * @throws {TypeError} If prefix or suffix is a Symbol.
     */
    wrap(prefix, suffix) {
        const strPrefix = `${prefix}`;
        const strSuffix = `${suffix}`;
        if (this._prefix === strPrefix && this._suffix === strSuffix) return this;
        this._prefix = strPrefix;
        this._suffix = strSuffix;
        this._compiledVM = null;
        this._compiledNodeVM = null;
        this._compiledNodeVMStrict = null;
        return this;
    }
 
    /**
     * Compile this script. <br>
     * This is useful to detect syntax errors in the script.
     *
     * @public
     * @return {this} This for chaining.
     * @throws {SyntaxError} If there is a syntax error in the script.
     */
    compile() {
        this._compileVM();
        return this;
    }
 
    /**
     * Get the compiled code.
     * 
     * @private
     * @return {string} The code.
     */
    getCompiledCode() {
        if (!this._compiledCode) {
            this._compiledCode = this._compiler(this._prefix + removeShebang(this._code) + this._suffix, this.filename);
        }
        return this._compiledCode;
    }
 
    /**
     * Compiles this script to a vm.Script.
     * 
     * @private
     * @param {string} prefix - JavaScript code that will be used as prefix.
     * @param {string} suffix - JavaScript code that will be used as suffix.
     * @return {vm.Script} The compiled vm.Script.
     * @throws {SyntaxError} If there is a syntax error in the script.
     */
    _compile(prefix, suffix) {
        return new vm.Script(prefix + this.getCompiledCode() + suffix, {
            filename: this.filename,
            displayErrors: false,
            lineOffset: this.lineOffset,
            columnOffset: this.columnOffset,
            importModuleDynamically
        });
    }
 
    /**
     * Will return the cached version of the script intended for VM or compile it.
     * 
     * @private
     * @return {vm.Script} The compiled script
     * @throws {SyntaxError} If there is a syntax error in the script.
     */
    _compileVM() {
        let script = this._compiledVM;
        if (!script) {
            this._compiledVM = script = this._compile('', '');
        }
        return script;
    }
 
    /**
     * Will return the cached version of the script intended for NodeVM or compile it.
     * 
     * @private
     * @return {vm.Script} The compiled script
     * @throws {SyntaxError} If there is a syntax error in the script.
     */
    _compileNodeVM() {
        let script = this._compiledNodeVM;
        if (!script) {
            this._compiledNodeVM = script = this._compile(MODULE_PREFIX, MODULE_SUFFIX);
        }
        return script;
    }
 
    /**
     * Will return the cached version of the script intended for NodeVM in strict mode or compile it.
     * 
     * @private
     * @return {vm.Script} The compiled script
     * @throws {SyntaxError} If there is a syntax error in the script.
     */
    _compileNodeVMStrict() {
        let script = this._compiledNodeVMStrict;
        if (!script) {
            this._compiledNodeVMStrict = script = this._compile(STRICT_MODULE_PREFIX, MODULE_SUFFIX);
        }
        return script;
    }
 
}
 
/**
 * 
 * This callback will be called and has a specific time to finish.<br>
 * No parameters will be supplied.<br>
 * If parameters are required, use a closure.
 * 
 * @private
 * @callback runWithTimeout
 * @return {*} 
 * 
 */
 
/**
 * Run a function with a specific timeout.
 * 
 * @private
 * @param {runWithTimeout} fn - Function to run with the specific timeout.
 * @param {number} timeout - The amount of time to give the function to finish.
 * @return {*} The value returned by the function.
 * @throws {Error} If the function took to long.
 */
function doWithTimeout(fn, timeout) {
    let ctx = CACHE.timeoutContext;
    let script = CACHE.timeoutScript;
    if (!ctx) {
        CACHE.timeoutContext = ctx = vm.createContext();
        CACHE.timeoutScript = script = new vm.Script('fn()', {
            filename: 'timeout_bridge.js',
            displayErrors: false,
            importModuleDynamically
        });
    }
    ctx.fn = fn;
    try {
        return script.runInContext(ctx, {
            displayErrors: false,
            importModuleDynamically,
            timeout
        });
    } finally {
        ctx.fn = null;
    }
}
 
function tryCompile(args) {
    const code = args[args.length - 1];
    const params = args.slice(0, -1);
    vm.compileFunction(code, params);
}
 
function makeCheckHook(checkAsync, checkImport) {
    if (!checkAsync && !checkImport) return null;
    return (hook, args) => {
        if (hook === 'function' || hook === 'generator_function' || hook === 'eval' || hook === 'run' ||
            (!checkAsync && (hook === 'async_function' || hook === 'async_generator_function'))) {
            if (hook === 'eval') {
                const script = args[0];
                args = [script];
                if (typeof(script) !== 'string') return args;
            } else {
                // Next line throws on Symbol, this is the same behavior as function constructor calls
                args = args.map(arg => `${arg}`);
            }
            const hasAsync = checkAsync && args.findIndex(arg => /\basync\b/.test(arg)) !== -1;
            const hasImport = checkImport && args.findIndex(arg => /\bimport\b/.test(arg)) !== -1;
            if (!hasAsync && !hasImport) return args;
            const mapped = args.map(arg => {
                if (hasAsync) arg = arg.replace(/async/g, 'a\\u0073ync');
                if (hasImport) arg = arg.replace(/import/g, 'i\\u006dport');
                return arg;
            });
            try {
                tryCompile(mapped);
            } catch (u) {
                // Some random syntax error or error because of async or import.
 
                // First report real syntax errors
                tryCompile(args);
 
                if (hasAsync && hasImport) {
                    const mapped2 = args.map(arg => arg.replace(/async/g, 'a\\u0073ync'));
                    try {
                        tryCompile(mapped2);
                    } catch (e) {
                        throw new VMError('Async not available');
                    }
                    throw new VMError('Dynamic Import not supported');
                }
                if (hasAsync) {
                    // Then async error
                    throw new VMError('Async not available');
                }
                throw new VMError('Dynamic Import not supported');
            }
            return args;
        }
        if (checkAsync) throw new VMError('Async not available');
        return args;
    };
}
 
/**
 * Class VM.
 *
 * @public
 */
class VM extends EventEmitter {
 
    /**
     * The timeout for {@link VM#run} calls.
     *
     * @public
     * @since v3.9.0
     * @member {number} timeout
     * @memberOf VM#
     */
 
    /**
     * Get the global sandbox object.
     *
     * @public
     * @readonly
     * @since v3.9.0
     * @member {Object} sandbox
     * @memberOf VM#
     */
 
    /**
     * The compiler to use to get the JavaScript code.
     * 
     * @public
     * @readonly
     * @since v3.9.0
     * @member {(string|compileCallback)} compiler
     * @memberOf VM#
     */
 
    /**
     * The context for this sandbox.
     * 
     * @private
     * @readonly
     * @member {Object} _context
     * @memberOf VM#
     */
 
    /**
     * The internal methods for this sandbox.
     * 
     * @private
     * @readonly
     * @member {{Contextify: Object, Decontextify: Object, Buffer: Object, sandbox:Object}} _internal
     * @memberOf VM#
     */
 
    /**
     * The resolved compiler to use to get the JavaScript code.
     * 
     * @private
     * @readonly
     * @member {compileCallback} _compiler
     * @memberOf VM#
     */
 
    /**
     * The hook called when some events occurs.
     * 
     * @private
     * @readonly
     * @since v3.9.2
     * @member {Function} _hook
     * @memberOf VM#
     */
 
    /**
     * Create a new VM instance.
     *
     * @public
     * @param {Object} [options] - VM options.
     * @param {number} [options.timeout] - The amount of time until a call to {@link VM#run} will timeout.
     * @param {Object} [options.sandbox] - Objects that will be copied into the global object of the sandbox.
     * @param {(string|compileCallback)} [options.compiler="javascript"] - The compiler to use.
     * @param {boolean} [options.eval=true] - Allow the dynamic evaluation of code via eval(code) or Function(code)().<br>
     * Only available for node v10+.
     * @param {boolean} [options.wasm=true] - Allow to run wasm code.<br>
     * Only available for node v10+.
     * @param {boolean} [options.fixAsync=false] - Filters for async functions.
     * @throws {VMError} If the compiler is unknown.
     */
    constructor(options = {}) {
        super();
 
        // Read all options
        const {
            timeout,
            sandbox,
            compiler = 'javascript'
        } = options;
        const allowEval = options.eval !== false;
        const allowWasm = options.wasm !== false;
        const fixAsync = !!options.fixAsync;
 
        // Early error if sandbox is not an object.
        if (sandbox && 'object' !== typeof sandbox) {
            throw new VMError('Sandbox must be object.');
        }
 
        // Early error if compiler can't be found.
        const resolvedCompiler = lookupCompiler(compiler);
 
        // Create a new context for this vm.
        const _context = vm.createContext(undefined, {
            codeGeneration: {
                strings: allowEval,
                wasm: allowWasm
            }
        });
 
        // Create the bridge between the host and the sandbox.
        const _internal = CACHE.contextifyScript.runInContext(_context, DEFAULT_RUN_OPTIONS).call(_context, require, HOST);
 
        const hook = makeCheckHook(fixAsync, true);
 
        // Define the properties of this object.
        // Use Object.defineProperties here to be able to
        // hide and set properties write only.
        Object.defineProperties(this, {
            timeout: {
                value: timeout,
                writable: true,
                enumerable: true
            },
            compiler: {
                value: compiler,
                enumerable: true
            },
            sandbox: {
                value: _internal.sandbox,
                enumerable: true
            },
            _context: {value: _context},
            _internal: {value: _internal},
            _compiler: {value: resolvedCompiler},
            _hook: {value: hook}
        });
 
        if (hook) {
            if (!CACHE.hookScript) {
                CACHE.hookScript = loadAndCompileScript(`${__dirname}/fixasync.js`, '(function() { ', '\n})');
                CACHE.getGlobalScript = new vm.Script('this', {
                    filename: 'get_global.js',
                    displayErrors: false,
                    importModuleDynamically
                });
                try {
                    CACHE.getGeneratorFunctionScript = new vm.Script('(function*(){}).constructor', {
                        filename: 'get_generator_function.js',
                        displayErrors: false,
                        importModuleDynamically
                    });
                } catch (ex) {}
                try {
                    CACHE.getAsyncFunctionScript = new vm.Script('(async function(){}).constructor', {
                        filename: 'get_async_function.js',
                        displayErrors: false,
                        importModuleDynamically
                    });
                } catch (ex) {}
                try {
                    CACHE.getAsyncGeneratorFunctionScript = new vm.Script('(async function*(){}).constructor', {
                        filename: 'get_async_generator_function.js',
                        displayErrors: false,
                        importModuleDynamically
                    });
                } catch (ex) {}
            }
            const internal = {
                __proto__: null,
                global: CACHE.getGlobalScript.runInContext(_context, DEFAULT_RUN_OPTIONS),
                internal: _internal,
                host: HOST,
                hook
            };
            if (CACHE.getGeneratorFunctionScript) {
                try {
                    internal.GeneratorFunction = CACHE.getGeneratorFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS);
                } catch (ex) {}
            }
            if (CACHE.getAsyncFunctionScript) {
                try {
                    internal.AsyncFunction = CACHE.getAsyncFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS);
                } catch (ex) {}
            }
            if (CACHE.getAsyncGeneratorFunctionScript) {
                try {
                    internal.AsyncGeneratorFunction = CACHE.getAsyncGeneratorFunctionScript.runInContext(_context, DEFAULT_RUN_OPTIONS);
                } catch (ex) {}
            }
            CACHE.hookScript.runInContext(_context, DEFAULT_RUN_OPTIONS).call(internal);
        }
 
        // prepare global sandbox
        if (sandbox) {
            this.setGlobals(sandbox);
        }
    }
 
    /**
     * Adds all the values to the globals.
     * 
     * @public
     * @since v3.9.0
     * @param {Object} values - All values that will be added to the globals.
     * @return {this} This for chaining.
     * @throws {*} If the setter of a global throws an exception it is propagated. And the remaining globals will not be written.
     */
    setGlobals(values) {
        for (const name in values) {
            if (Object.prototype.hasOwnProperty.call(values, name)) {
                this._internal.Contextify.setGlobal(name, values[name]);
            }
        }
        return this;
    }
 
    /**
     * Set a global value.
     * 
     * @public
     * @since v3.9.0
     * @param {string} name - The name of the global.
     * @param {*} value - The value of the global.
     * @return {this} This for chaining.
     * @throws {*} If the setter of the global throws an exception it is propagated.
     */
    setGlobal(name, value) {
        this._internal.Contextify.setGlobal(name, value);
        return this;
    }
 
    /**
     * Get a global value.
     * 
     * @public
     * @since v3.9.0
     * @param {string} name - The name of the global.
     * @return {*} The value of the global.
     * @throws {*} If the getter of the global throws an exception it is propagated.
     */
    getGlobal(name) {
        return this._internal.Contextify.getGlobal(name);
    }
 
    /**
     * Freezes the object inside VM making it read-only. Not available for primitive values.
     *
     * @public
     * @param {*} value - Object to freeze.
     * @param {string} [globalName] - Whether to add the object to global.
     * @return {*} Object to freeze.
     * @throws {*} If the setter of the global throws an exception it is propagated.
     */
    freeze(value, globalName) {
        this._internal.Contextify.readonly(value);
        if (globalName) this._internal.Contextify.setGlobal(globalName, value);
        return value;
    }
 
    /**
     * Protects the object inside VM making impossible to set functions as it's properties. Not available for primitive values.
     *
     * @public
     * @param {*} value - Object to protect.
     * @param {string} [globalName] - Whether to add the object to global.
     * @return {*} Object to protect.
     * @throws {*} If the setter of the global throws an exception it is propagated.
     */
    protect(value, globalName) {
        this._internal.Contextify.protected(value);
        if (globalName) this._internal.Contextify.setGlobal(globalName, value);
        return value;
    }
 
    /**
     * Run the code in VM.
     *
     * @public
     * @param {(string|VMScript)} code - Code to run.
     * @param {string} [filename="vm.js"] - Filename that shows up in any stack traces produced from this script.<br>
     * This is only used if code is a String.
     * @return {*} Result of executed code.
     * @throws {SyntaxError} If there is a syntax error in the script.
     * @throws {Error} An error is thrown when the script took to long and there is a timeout.
     * @throws {*} If the script execution terminated with an exception it is propagated.
     */
    run(code, filename) {
        let script;
        if (code instanceof VMScript) {
            if (this._hook) {
                const scriptCode = code.getCompiledCode();
                const changed = this._hook('run', [scriptCode])[0];
                if (changed === scriptCode) {
                    script = code._compileVM();
                } else {
                    script = new vm.Script(changed, {
                        filename: code.filename,
                        displayErrors: false,
                        importModuleDynamically
                    });
                }
            } else {
                script = code._compileVM();
            }
        } else {
            const useFileName = filename || 'vm.js';
            let scriptCode = this._compiler(code, useFileName);
            if (this._hook) {
                scriptCode = this._hook('run', [scriptCode])[0];
            }
            // Compile the script here so that we don't need to create a instance of VMScript.
            script = new vm.Script(scriptCode, {
                filename: useFileName,
                displayErrors: false,
                importModuleDynamically
            });
        }
 
        if (!this.timeout) {
            // If no timeout is given, directly run the script.
            try {
                return this._internal.Decontextify.value(script.runInContext(this._context, DEFAULT_RUN_OPTIONS));
            } catch (e) {
                throw this._internal.Decontextify.value(e);
            }
        }
 
        return doWithTimeout(()=>{
            try {
                return this._internal.Decontextify.value(script.runInContext(this._context, DEFAULT_RUN_OPTIONS));
            } catch (e) {
                throw this._internal.Decontextify.value(e);
            }
        }, this.timeout);
    }
 
    /**
     * Run the code in VM.
     *
     * @public
     * @since v3.9.0
     * @param {string} filename - Filename of file to load and execute in a NodeVM.
     * @return {*} Result of executed code.
     * @throws {Error} If filename is not a valid filename.
     * @throws {SyntaxError} If there is a syntax error in the script.
     * @throws {Error} An error is thrown when the script took to long and there is a timeout.
     * @throws {*} If the script execution terminated with an exception it is propagated.
     */
    runFile(filename) {
        const resolvedFilename = pa.resolve(filename);
 
        if (!fs.existsSync(resolvedFilename)) {
            throw new VMError(`Script '${filename}' not found.`);
        }
 
        if (fs.statSync(resolvedFilename).isDirectory()) {
            throw new VMError('Script must be file, got directory.');
        }
 
        return this.run(fs.readFileSync(resolvedFilename, 'utf8'), resolvedFilename);
    }
 
}
 
/**
 * Event caused by a <code>console.debug</code> call if <code>options.console="redirect"</code> is specified.
 *
 * @public
 * @event NodeVM."console.debug"
 * @type {...*}
 */
 
/**
 * Event caused by a <code>console.log</code> call if <code>options.console="redirect"</code> is specified.
 *
 * @public
 * @event NodeVM."console.log"
 * @type {...*}
 */
 
/**
 * Event caused by a <code>console.info</code> call if <code>options.console="redirect"</code> is specified.
 *
 * @public
 * @event NodeVM."console.info"
 * @type {...*}
 */
 
/**
 * Event caused by a <code>console.warn</code> call if <code>options.console="redirect"</code> is specified.
 *
 * @public
 * @event NodeVM."console.warn"
 * @type {...*}
 */
 
/**
 * Event caused by a <code>console.error</code> call if <code>options.console="redirect"</code> is specified.
 *
 * @public
 * @event NodeVM."console.error"
 * @type {...*}
 */
 
/**
 * Event caused by a <code>console.dir</code> call if <code>options.console="redirect"</code> is specified.
 *
 * @public
 * @event NodeVM."console.dir"
 * @type {...*}
 */
 
/**
 * Event caused by a <code>console.trace</code> call if <code>options.console="redirect"</code> is specified.
 *
 * @public
 * @event NodeVM."console.trace"
 * @type {...*}
 */
 
/**
 * Class NodeVM.
 *
 * @public
 * @extends {VM}
 * @extends {EventEmitter}
 */
class NodeVM extends VM {
 
    /**
     * Create a new NodeVM instance.<br>
     *
     * Unlike VM, NodeVM lets you use require same way like in regular node.<br>
     * 
     * However, it does not use the timeout.
     *
     * @public
     * @param {Object} [options] - VM options.
     * @param {Object} [options.sandbox] - Objects that will be copied into the global object of the sandbox.
     * @param {(string|compileCallback)} [options.compiler="javascript"] - The compiler to use.
     * @param {boolean} [options.eval=true] - Allow the dynamic evaluation of code via eval(code) or Function(code)().<br>
     * Only available for node v10+.
     * @param {boolean} [options.wasm=true] - Allow to run wasm code.<br>
     * Only available for node v10+.
     * @param {("inherit"|"redirect"|"off")} [options.console="inherit"] - Sets the behavior of the console in the sandbox.
     * <code>inherit</code> to enable console, <code>redirect</code> to redirect to events, <code>off</code> to disable console.
     * @param {Object|boolean} [options.require=false] - Allow require inside the sandbox.
     * @param {(boolean|string[]|Object)} [options.require.external=false] - true, an array of allowed external modules or an object.
     * @param {(string[])} [options.require.external.modules] - Array of allowed external modules. Also supports wildcards, so specifying ['@scope/*-ver-??], 
     * for instance, will allow using all modules having a name of the form @scope/something-ver-aa, @scope/other-ver-11, etc.
     * @param {boolean} [options.require.external.transitive=false] - Boolean which indicates if transitive dependencies of external modules are allowed.
     * @param {string[]} [options.require.builtin=[]] - Array of allowed builtin modules, accepts ["*"] for all.
     * @param {(string|string[])} [options.require.root] - Restricted path(s) where local modules can be required. If omitted every path is allowed.
     * @param {Object} [options.require.mock] - Collection of mock modules (both external or builtin).
     * @param {("host"|"sandbox")} [options.require.context="host"] - <code>host</code> to require modules in host and proxy them to sandbox.
     * <code>sandbox</code> to load, compile and require modules in sandbox.
     * Builtin modules except <code>events</code> always required in host and proxied to sandbox.
     * @param {string[]} [options.require.import] - Array of modules to be loaded into NodeVM on start.
     * @param {resolveCallback} [options.require.resolve] - An additional lookup function in case a module wasn't
     * found in one of the traditional node lookup paths.
     * @param {boolean} [options.nesting=false] - Allow nesting of VMs.
     * @param {("commonjs"|"none")} [options.wrapper="commonjs"] - <code>commonjs</code> to wrap script into CommonJS wrapper, 
     * <code>none</code> to retrieve value returned by the script.
     * @param {string[]} [options.sourceExtensions=["js"]] - Array of file extensions to treat as source code.
     * @param {string[]} [options.argv=[]] - Array of arguments passed to <code>process.argv</code>. 
     * This object will not be copied and the script can change this object.
     * @param {Object} [options.env={}] - Environment map passed to <code>process.env</code>. 
     * This object will not be copied and the script can change this object.
     * @param {boolean} [options.strict=false] - If modules should be loaded in strict mode.
     * @throws {VMError} If the compiler is unknown.
     */
    constructor(options = {}) {
        const sandbox = options.sandbox;
 
        // Throw this early
        if (sandbox && 'object' !== typeof sandbox) {
            throw new VMError('Sandbox must be object.');
        }
 
        super({compiler: options.compiler, eval: options.eval, wasm: options.wasm});
 
        // defaults
        Object.defineProperty(this, 'options', {value: {
            console: options.console || 'inherit',
            require: options.require || false,
            nesting: options.nesting || false,
            wrapper: options.wrapper || 'commonjs',
            sourceExtensions: options.sourceExtensions || ['js'],
            strict: options.strict || false
        }});
 
        let sandboxScript = CACHE.sandboxScript;
        if (!sandboxScript) {
            CACHE.sandboxScript = sandboxScript = loadAndCompileScript(`${__dirname}/sandbox.js`,
                '(function (vm, host, Contextify, Decontextify, Buffer, options) { ', '\n})');
        }
 
        const closure = sandboxScript.runInContext(this._context, DEFAULT_RUN_OPTIONS);
 
        Object.defineProperty(this, '_prepareRequire', {
            value: closure.call(this._context, this, HOST, this._internal.Contextify, this._internal.Decontextify, this._internal.Buffer, options)
        });
 
        // prepare global sandbox
        if (sandbox) {
            this.setGlobals(sandbox);
        }
 
        if (this.options.require && this.options.require.import) {
            if (Array.isArray(this.options.require.import)) {
                for (let i = 0, l = this.options.require.import.length; i < l; i++) {
                    this.require(this.options.require.import[i]);
                }
            } else {
                this.require(this.options.require.import);
            }
        }
    }
 
    /**
     * @ignore
     * @deprecated Just call the method yourself like <code>method(args);</code>
     * @param {function} method - Function to invoke.
     * @param {...*} args - Arguments to pass to the function.
     * @return {*} Return value of the function.
     * @todo Can we remove this function? It even had a bug that would use args as this parameter.
     * @throws {*} Rethrows anything the method throws.
     * @throws {VMError} If method is not a function.
     * @throws {Error} If method is a class.
     */
    call(method, ...args) {
        if ('function' === typeof method) {
            return method(...args);
        } else {
            throw new VMError('Unrecognized method type.');
        }
    }
 
    /**
     * Require a module in VM and return it's exports.
     *
     * @public
     * @param {string} module - Module name.
     * @return {*} Exported module.
     * @throws {*} If the module couldn't be found or loading it threw an error.
     */
    require(module) {
        return this.run(`module.exports = require('${module}');`, 'vm.js');
    }
 
    /**
     * Run the code in NodeVM.
     *
     * First time you run this method, code is executed same way like in node's regular `require` - it's executed with
     * `module`, `require`, `exports`, `__dirname`, `__filename` variables and expect result in `module.exports'.
     *
     * @param {(string|VMScript)} code - Code to run.
     * @param {string} [filename] - Filename that shows up in any stack traces produced from this script.<br>
     * This is only used if code is a String.
     * @return {*} Result of executed code.
     * @throws {SyntaxError} If there is a syntax error in the script.
     * @throws {*} If the script execution terminated with an exception it is propagated.
     * @fires NodeVM."console.debug"
     * @fires NodeVM."console.log"
     * @fires NodeVM."console.info"
     * @fires NodeVM."console.warn"
     * @fires NodeVM."console.error"
     * @fires NodeVM."console.dir"
     * @fires NodeVM."console.trace"
     */
    run(code, filename) {
        let dirname;
        let resolvedFilename;
        let script;
 
        if (code instanceof VMScript) {
            if (this._hook) {
                const prefix = this.options.strict ? STRICT_MODULE_PREFIX : MODULE_PREFIX;
                const scriptCode = prefix + code.getCompiledCode() + MODULE_SUFFIX;
                const changed = this._hook('run', [scriptCode])[0];
                if (changed === scriptCode) {
                    script = this.options.strict ? code._compileNodeVMStrict() : code._compileNodeVM();
                } else {
                    script = new vm.Script(changed, {
                        filename: code.filename,
                        displayErrors: false,
                        importModuleDynamically
                    });
                }
            } else {
                script = this.options.strict ? code._compileNodeVMStrict() : code._compileNodeVM();
            }
            resolvedFilename = pa.resolve(code.filename);
            dirname = pa.dirname(resolvedFilename);
        } else {
            const unresolvedFilename = filename || 'vm.js';
            if (filename) {
                resolvedFilename = pa.resolve(filename);
                dirname = pa.dirname(resolvedFilename);
            } else {
                resolvedFilename = null;
                dirname = null;
            }
            const prefix = this.options.strict ? STRICT_MODULE_PREFIX : MODULE_PREFIX;
            let scriptCode = prefix + this._compiler(code, unresolvedFilename) + MODULE_SUFFIX;
            if (this._hook) {
                scriptCode = this._hook('run', [scriptCode])[0];
            }
            script = new vm.Script(scriptCode, {
                filename: unresolvedFilename,
                displayErrors: false,
                importModuleDynamically
            });
        }
 
        const wrapper = this.options.wrapper;
        const module = this._internal.Contextify.makeModule();
 
        try {
            const closure = script.runInContext(this._context, DEFAULT_RUN_OPTIONS);
 
            const returned = closure.call(this._context, module.exports, this._prepareRequire(dirname), module, resolvedFilename, dirname);
 
            return this._internal.Decontextify.value(wrapper === 'commonjs' ? module.exports : returned);
        } catch (e) {
            throw this._internal.Decontextify.value(e);
        }
 
    }
 
    /**
     * Create NodeVM and run code inside it.
     *
     * @public
     * @static
     * @param {string} script - Code to execute.
     * @param {string} [filename] - File name (used in stack traces only).
     * @param {Object} [options] - VM options.
     * @param {string} [options.filename] - File name (used in stack traces only). Used if <code>filename</code> is omitted.
     * @return {*} Result of executed code.
     * @see {@link NodeVM} for the options.
     * @throws {SyntaxError} If there is a syntax error in the script.
     * @throws {*} If the script execution terminated with an exception it is propagated.
     */
    static code(script, filename, options) {
        let unresolvedFilename;
        if (filename != null) {
            if ('object' === typeof filename) {
                options = filename;
                unresolvedFilename = options.filename;
            } else if ('string' === typeof filename) {
                unresolvedFilename = filename;
            } else {
                throw new VMError('Invalid arguments.');
            }
        } else if ('object' === typeof options) {
            unresolvedFilename = options.filename;
        }
 
        if (arguments.length > 3) {
            throw new VMError('Invalid number of arguments.');
        }
 
        const resolvedFilename = typeof unresolvedFilename === 'string' ? pa.resolve(unresolvedFilename) : undefined;
 
        return new NodeVM(options).run(script, resolvedFilename);
    }
 
    /**
     * Create NodeVM and run script from file inside it.
     *
     * @public
     * @static
     * @param {string} filename - Filename of file to load and execute in a NodeVM.
     * @param {Object} [options] - NodeVM options.
     * @return {*} Result of executed code.
     * @see {@link NodeVM} for the options.
     * @throws {Error} If filename is not a valid filename.
     * @throws {SyntaxError} If there is a syntax error in the script.
     * @throws {*} If the script execution terminated with an exception it is propagated.
     */
    static file(filename, options) {
        const resolvedFilename = pa.resolve(filename);
 
        if (!fs.existsSync(resolvedFilename)) {
            throw new VMError(`Script '${filename}' not found.`);
        }
 
        if (fs.statSync(resolvedFilename).isDirectory()) {
            throw new VMError('Script must be file, got directory.');
        }
 
        return new NodeVM(options).run(fs.readFileSync(resolvedFilename, 'utf8'), resolvedFilename);
    }
}
 
/**
 * VMError.
 *
 * @public
 * @extends {Error}
 */
class VMError extends Error {
 
    /**
     * Create VMError instance.
     *
     * @public
     * @param {string} message - Error message.
     */
    constructor(message) {
        super(message);
 
        this.name = 'VMError';
 
        Error.captureStackTrace(this, this.constructor);
    }
}
 
/**
 * Host objects
 * 
 * @private
 */
const HOST = {
    version: parseInt(process.versions.node.split('.')[0]),
    require,
    process,
    console,
    setTimeout,
    setInterval,
    setImmediate,
    clearTimeout,
    clearInterval,
    clearImmediate,
    String,
    Number,
    Buffer,
    Boolean,
    Array,
    Date,
    Error,
    EvalError,
    RangeError,
    ReferenceError,
    SyntaxError,
    TypeError,
    URIError,
    RegExp,
    Function,
    Object,
    VMError,
    Proxy,
    Reflect,
    Map,
    WeakMap,
    Set,
    WeakSet,
    Promise,
    Symbol,
    INSPECT_MAX_BYTES,
    VM,
    NodeVM,
    helpers,
    MODULE_PREFIX,
    STRICT_MODULE_PREFIX,
    MODULE_SUFFIX
};
 
exports.VMError = VMError;
exports.NodeVM = NodeVM;
exports.VM = VM;
exports.VMScript = VMScript;