@@ -1130,21 +1130,35 @@ export default class Runtime {
11301130 // Like requireModule but async-safe: pre-loads ESM transitive dependencies
11311131 // before executing the CJS module so that require() calls inside it that
11321132 // resolve to ESM files succeed (they are served from the ESM cache).
1133- async requireModuleWithEsmPreload < T = unknown > (
1134- from : string ,
1135- moduleName ?: string ,
1136- ) : Promise < T > {
1133+ // Preload all ESM deps reachable from the given CJS entry and arm the
1134+ // CJS-as-ESM flag so a subsequent synchronous requireModule() can serve
1135+ // those deps from the ESM registry. Must be paired with leaveCjsEsmContext()
1136+ // once requireModule returns. This two-step API lets callers (e.g.
1137+ // jestAdapter) put the await *before* the test file is loaded, preserving
1138+ // jest-circus's async-definition detection (which relies on no microtask
1139+ // flush happening between requireModule() and run_start being dispatched).
1140+ async enterCjsEsmContext ( from : string , moduleName ?: string ) : Promise < void > {
11371141 if ( runtimeSupportsVmModules ) {
11381142 const modulePath = this . _resolveCjsModule ( from , moduleName ) ;
11391143 await this . _preloadEsmDependencies ( modulePath ) ;
11401144 this . _resolvingCjsAsEsm = true ;
1141- try {
1142- return this . requireModule < T > ( from , moduleName ) ;
1143- } finally {
1144- this . _resolvingCjsAsEsm = false ;
1145- }
11461145 }
1147- return this . requireModule < T > ( from , moduleName ) ;
1146+ }
1147+
1148+ leaveCjsEsmContext ( ) : void {
1149+ this . _resolvingCjsAsEsm = false ;
1150+ }
1151+
1152+ async requireModuleWithEsmPreload < T = unknown > (
1153+ from : string ,
1154+ moduleName ?: string ,
1155+ ) : Promise < T > {
1156+ await this . enterCjsEsmContext ( from , moduleName ) ;
1157+ try {
1158+ return this . requireModule < T > ( from , moduleName ) ;
1159+ } finally {
1160+ this . leaveCjsEsmContext ( ) ;
1161+ }
11481162 }
11491163
11501164 requireInternalModule < T = unknown > ( from : string , to ?: string ) : T {
0 commit comments