@@ -5,6 +5,7 @@ const { Object, SafeWeakMap } = primordials;
55const { getOptionValue } = require ( 'internal/options' ) ;
66const { Buffer } = require ( 'buffer' ) ;
77const { ERR_MANIFEST_ASSERT_INTEGRITY } = require ( 'internal/errors' ) . codes ;
8+ const path = require ( 'path' ) ;
89
910function prepareMainThreadExecution ( expandArgv1 = false ) {
1011 // Patch the process object with legacy properties and normalizations
@@ -437,11 +438,70 @@ function loadPreloadModules() {
437438 }
438439}
439440
441+ function resolveMainPath ( main ) {
442+ const { toRealPath, Module : CJSModule } =
443+ require ( 'internal/modules/cjs/loader' ) ;
444+
445+ // Note extension resolution for the main entry point can be deprecated in a
446+ // future major.
447+ let mainPath = CJSModule . _findPath ( path . resolve ( main ) , null , true ) ;
448+ if ( ! mainPath )
449+ return ;
450+
451+ const preserveSymlinksMain = getOptionValue ( '--preserve-symlinks-main' ) ;
452+ if ( ! preserveSymlinksMain )
453+ mainPath = toRealPath ( mainPath ) ;
454+
455+ return mainPath ;
456+ }
457+
458+ function shouldUseESMLoader ( mainPath ) {
459+ const experimentalModules = getOptionValue ( '--experimental-modules' ) ;
460+ if ( ! experimentalModules )
461+ return false ;
462+ const userLoader = getOptionValue ( '--experimental-loader' ) ;
463+ if ( userLoader )
464+ return true ;
465+ // Determine the module format of the main
466+ if ( mainPath && mainPath . endsWith ( '.mjs' ) )
467+ return true ;
468+ if ( ! mainPath || mainPath . endsWith ( '.cjs' ) )
469+ return false ;
470+ const { readPackageScope } = require ( 'internal/modules/cjs/loader' ) ;
471+ const pkg = readPackageScope ( mainPath ) ;
472+ return pkg && pkg . data . type === 'module' ;
473+ }
474+
475+ function runMainESM ( mainPath ) {
476+ const esmLoader = require ( 'internal/process/esm_loader' ) ;
477+ const { pathToFileURL } = require ( 'internal/url' ) ;
478+ const { hasUncaughtExceptionCaptureCallback } =
479+ require ( 'internal/process/execution' ) ;
480+ return ( esmLoader . initializeLoader ( ) || Promise . resolve ( ) ) . then ( ( ) => {
481+ const main = path . isAbsolute ( mainPath ) ?
482+ pathToFileURL ( mainPath ) . href : mainPath ;
483+ return esmLoader . ESMLoader . import ( main ) . catch ( ( e ) => {
484+ if ( hasUncaughtExceptionCaptureCallback ( ) ) {
485+ process . _fatalException ( e ) ;
486+ return ;
487+ }
488+ internalBinding ( 'errors' ) . triggerUncaughtException (
489+ e ,
490+ true /* fromPromise */
491+ ) ;
492+ } ) ;
493+ } ) ;
494+ }
495+
496+
440497module . exports = {
441498 patchProcessObject,
499+ resolveMainPath,
500+ runMainESM,
442501 setupCoverageHooks,
443502 setupWarningHandler,
444503 setupDebugEnv,
504+ shouldUseESMLoader,
445505 prepareMainThreadExecution,
446506 initializeDeprecations,
447507 initializeESMLoader,
0 commit comments