/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

const upath = require( 'upath' );
const { pathToFileURL } = require( 'url' );

/**
 * Loads the specified module using `import()` call.
 *
 * @param {String} modulePath
 * @returns {Promise.<Function>}
 */
module.exports = async function importModule( modulePath ) {
	const modulePathAsFileURL = getPathAsFileURL( modulePath );

	return ( await import( modulePathAsFileURL ) ).default;
};

function getPathAsFileURL( modulePath ) {
	const extension = upath.extname( modulePath );

	if ( extension === '.js' || extension === '.mjs' || extension === '.cjs' ) {
		return pathToFileURL( modulePath );
	}

	return pathToFileURL( modulePath + '.js' );
}
