node/test/parallel/test-shadow-realm-module.js
Chengzhong Wu fc2862b7f5
module: bootstrap module loaders in shadow realm
This bootstraps ESM loaders in the ShadowRealm with
`ShadowRealm.prototype.importValue` as its entry point and enables
loading ESM and CJS modules in the ShadowRealm. The module is imported
without a parent URL and resolved with the current process's working
directory.

PR-URL: https://github.com/nodejs/node/pull/48655
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
2023-11-13 22:09:47 +08:00

30 lines
1.2 KiB
JavaScript

// Flags: --experimental-shadow-realm
'use strict';
const common = require('../common');
const fixtures = require('../common/fixtures');
const assert = require('assert');
async function main() {
const realm = new ShadowRealm();
const mod = fixtures.fileURL('es-module-shadow-realm', 'state-counter.mjs');
const getCounter = await realm.importValue(mod, 'getCounter');
assert.strictEqual(getCounter(), 0);
const getCounter1 = await realm.importValue(mod, 'getCounter');
// Returned value is a newly wrapped function.
assert.notStrictEqual(getCounter, getCounter1);
// Verify that the module state is shared between two `importValue` calls.
assert.strictEqual(getCounter1(), 1);
assert.strictEqual(getCounter(), 2);
const { getCounter: getCounterThisRealm } = await import(mod);
assert.notStrictEqual(getCounterThisRealm, getCounter);
// Verify that the module state is not shared between two realms.
assert.strictEqual(getCounterThisRealm(), 0);
assert.strictEqual(getCounter(), 3);
// Verify that shadow realm rejects to import a non-existing module.
await assert.rejects(realm.importValue('non-exists', 'exports'), TypeError);
}
main().then(common.mustCall());