1'use strict'; 2 3const { 4 ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING, 5} = require('internal/errors').codes; 6const { Loader } = require('internal/modules/esm/loader'); 7const { 8 hasUncaughtExceptionCaptureCallback, 9} = require('internal/process/execution'); 10const { pathToFileURL } = require('internal/url'); 11const { 12 getModuleFromWrap, 13} = require('internal/vm/module'); 14const { getOptionValue } = require('internal/options'); 15const userLoader = getOptionValue('--experimental-loader'); 16 17exports.initializeImportMetaObject = function(wrap, meta) { 18 const { callbackMap } = internalBinding('module_wrap'); 19 if (callbackMap.has(wrap)) { 20 const { initializeImportMeta } = callbackMap.get(wrap); 21 if (initializeImportMeta !== undefined) { 22 initializeImportMeta(meta, getModuleFromWrap(wrap) || wrap); 23 } 24 } 25}; 26 27exports.importModuleDynamicallyCallback = async function(wrap, specifier) { 28 const { callbackMap } = internalBinding('module_wrap'); 29 if (callbackMap.has(wrap)) { 30 const { importModuleDynamically } = callbackMap.get(wrap); 31 if (importModuleDynamically !== undefined) { 32 return importModuleDynamically( 33 specifier, getModuleFromWrap(wrap) || wrap); 34 } 35 } 36 throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING(); 37}; 38 39let ESMLoader = new Loader(); 40exports.ESMLoader = ESMLoader; 41 42async function initializeLoader() { 43 if (!userLoader) 44 return; 45 let cwd; 46 try { 47 cwd = process.cwd() + '/'; 48 } catch { 49 cwd = 'file:///'; 50 } 51 // If --experimental-loader is specified, create a loader with user hooks. 52 // Otherwise create the default loader. 53 const { emitExperimentalWarning } = require('internal/util'); 54 emitExperimentalWarning('--experimental-loader'); 55 return (async () => { 56 const hooks = 57 await ESMLoader.import(userLoader, pathToFileURL(cwd).href); 58 ESMLoader = new Loader(); 59 ESMLoader.hook(hooks); 60 ESMLoader.runGlobalPreloadCode(); 61 return exports.ESMLoader = ESMLoader; 62 })(); 63} 64 65exports.loadESM = async function loadESM(callback) { 66 try { 67 await initializeLoader(); 68 await callback(ESMLoader); 69 } catch (err) { 70 if (hasUncaughtExceptionCaptureCallback()) { 71 process._fatalException(err); 72 return; 73 } 74 internalBinding('errors').triggerUncaughtException( 75 err, 76 true /* fromPromise */ 77 ); 78 } 79}; 80