Skip to content

Commit

Permalink
Add metavm.NODE_CONTEXT
Browse files Browse the repository at this point in the history
PR-URL: #109
  • Loading branch information
tshemsedinov committed Jul 31, 2023
1 parent 1073e2b commit d0f7cd7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 25 deletions.
50 changes: 26 additions & 24 deletions metavm.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,32 @@ const MODULE_TYPE = {
COMMONJS: 2,
};

const EMPTY_CONTEXT = vm.createContext(Object.freeze({}), CONTEXT_OPTIONS);
const DEFAULT = {
AbortController,
Event,
EventTarget,
MessageChannel,
MessageEvent,
MessagePort,
Buffer,
URL,
URLSearchParams,
TextDecoder,
TextEncoder,
queueMicrotask,
setTimeout,
setImmediate,
setInterval,
clearTimeout,
clearImmediate,
clearInterval,
};

const COMMON_CONTEXT = vm.createContext(
Object.freeze({
AbortController,
Event,
EventTarget,
MessageChannel,
MessageEvent,
MessagePort,
Buffer,
URL,
URLSearchParams,
TextDecoder,
TextEncoder,
console,
queueMicrotask,
setTimeout,
setImmediate,
setInterval,
clearTimeout,
clearImmediate,
clearInterval,
}),
);
const NODE = { global, console, process };

const EMPTY_CONTEXT = vm.createContext(Object.freeze({}), CONTEXT_OPTIONS);
const COMMON_CONTEXT = vm.createContext(Object.freeze({ ...DEFAULT }));
const NODE_CONTEXT = vm.createContext(Object.freeze({ ...DEFAULT, ...NODE }));

class MetavmError extends Error {}

Expand Down Expand Up @@ -163,6 +164,7 @@ module.exports = {
createScript,
EMPTY_CONTEXT,
COMMON_CONTEXT,
NODE_CONTEXT,
MODULE_TYPE,
readScript,
};
12 changes: 11 additions & 1 deletion test/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,9 @@ metatests.test('Create default context', async (test) => {
metatests.test('Create common context', async (test) => {
const context = metavm.createContext(metavm.COMMON_CONTEXT);
test.strictSame(typeof context, 'object');
test.strictSame(context.console, console);
test.strictSame(context.global, undefined);
test.strictSame(context.console, undefined);
test.strictSame(context.process, undefined);
test.strictSame(context.AbortController, AbortController);
test.strictSame(context.Buffer, Buffer);
test.strictSame(context.Event, Event);
Expand All @@ -241,6 +242,15 @@ metatests.test('Create common context', async (test) => {
test.end();
});

metatests.test('Create nodejs context', async (test) => {
const context = metavm.createContext(metavm.NODE_CONTEXT);
test.strictSame(typeof context, 'object');
test.strictSame(context.global, global);
test.strictSame(context.console, console);
test.strictSame(context.process, process);
test.end();
});

metatests.test('Create custom context', async (test) => {
const sandbox = { field: 'value' };
sandbox.global = sandbox;
Expand Down

0 comments on commit d0f7cd7

Please sign in to comment.