Skip to content
10 changes: 8 additions & 2 deletions packages/bruno-js/src/sandbox/node-vm/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,15 @@ async function runScriptInNodeVm({
const wrappedScript = wrapScriptInClosure(script, SANDBOX.NODEVM);
let compiledScript;
try {
compiledScript = new vm.Script(wrappedScript, {
const scriptOptions = {
filename: vmFilename
});
};

if (vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER) {
scriptOptions.importModuleDynamically = vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
}

compiledScript = new vm.Script(wrappedScript, scriptOptions);
} catch (error) {
// V8 puts "filename:line" as the first line of syntax error stacks.
// Parse it so the error formatter can map to the correct source location.
Expand Down
24 changes: 23 additions & 1 deletion packages/bruno-js/src/sandbox/node-vm/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const { describe, it, expect, beforeEach, afterEach } = require('@jest/globals')
const fs = require('fs');
const path = require('path');
const os = require('os');
const vm = require('node:vm');
const { runScriptInNodeVm } = require('./index');

describe('node-vm sandbox', () => {
Expand Down Expand Up @@ -777,7 +778,7 @@ describe('node-vm sandbox', () => {
expect(context.bru.setVar).toHaveBeenCalledWith('result', 'cjs-100');
});

it('should fail when loading .mjs files (ES modules)', async () => {
it('should fail when requiring .mjs files (ES modules)', async () => {
const nodeModulesDir = path.join(collectionPath, 'node_modules', 'mjs-ext-module');
fs.mkdirSync(nodeModulesDir, { recursive: true });
fs.writeFileSync(
Expand All @@ -800,6 +801,27 @@ describe('node-vm sandbox', () => {
).rejects.toThrow();
});

it('should dynamically import .mjs files from node-vm scripts', async () => {
fs.writeFileSync(
path.join(collectionPath, 'esm-helper.mjs'),
'export function makeGreeting(name) { return `hello ${name} from esm`; }'
);

const script = `
const helper = await import('./esm-helper.mjs');
bru.setVar('result', helper.makeGreeting('bruno'));
`;

const context = {
bru: { setVar: jest.fn() },
console: console
};

await runScriptInNodeVm({ script, context, collectionPath, scriptingConfig: {} });

expect(context.bru.setVar).toHaveBeenCalledWith('result', 'hello bruno from esm');
});

it('should load module with package.json main field', async () => {
const nodeModulesDir = path.join(collectionPath, 'node_modules', 'custom-main');
fs.mkdirSync(path.join(nodeModulesDir, 'lib'), { recursive: true });
Expand Down