`--import` order is wrong when one of the modules imports a module

Version

v20.9.0

Platform

Linux XXXXXXX 5.15.90.1-microsoft-standard-WSL2 #1 SMP Fri Jan 27 02:56:13 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

Subsystem

module

What steps will reproduce the bug?

  1. Run git clone https://github.com/giltayar/import-order-bug.git
  2. Run the following command:
$ node --import ./a.mjs --import ./b.mjs main.mjs
a...
b...

The output here makes sense, as the order of execution of a.js and b.js is first a then b

  1. Go to a.js and uncomment the first line (with import './sub.mjs). Note that sub.mjs is an empty file.

Now run the same command again:

$ node --import ./a.mjs --import ./b.mjs main.mjs
b...
a...

This doesn't make sense: the order of execution of the imports shouldn't change if one of the modules has an import and the other doesn't.

How often does it reproduce? Is there a required condition?

Every time.

What is the expected behavior? Why is that the expected behavior?

The order of the execution of the modules in --import should not change based on whether they are importing another module or not.

What do you see instead?

The order of the execution of the modules in --import changes based on whether they are importing another module or not.

Additional information

This stumped me for 3 hours when modifying my ESM loaders talk for NodeConf EU and the new register didn't work with loader chaining. It took me 3 hours to figure out that the chaining didn't change, but the execution order in --import does, and that it has nothing to do with loaders.