Skip to content

Commit

Permalink
further code refactoring to comply with codebeat
Browse files Browse the repository at this point in the history
  • Loading branch information
nktnet committed Oct 21, 2023
1 parent b656617 commit ae11b8e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
36 changes: 21 additions & 15 deletions src/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,31 @@ export const getCallerDirname = (): string => {
* Find the module file path by checking for available extensions
* as defined by VALID_FILE_EXTENSIONS
*
* @param {string} modulePath - The path to the module
* @param {string} basePath - The base path for the module
* @returns {string} The resolved file path
* @throws {Error} If the file is not found
* @param {string} filePath The absolute path to the file
* @returns {string} The resolved file path with appended extension
* @throws {Error} If the file path does not match any valid extensions
*/
export const findModuleFile = (modulePath: string, basePath: string): string => {
const filePath = path.join(basePath, modulePath);
if (fs.existsSync(filePath)) {
return filePath;
}
if (!path.extname(filePath)) {
for (const ext of VALID_FILE_EXTENSIONS) {
const extFilePath = path.join(basePath, `${modulePath}${ext}`);
if (fs.existsSync(extFilePath)) {
return extFilePath;
}
const findFileWithExtensions = (filePath: string): string => {
for (const ext of VALID_FILE_EXTENSIONS) {
const extFilePath = `${filePath}${ext}`;
if (fs.existsSync(extFilePath)) {
return extFilePath;
}
}
throw new Error(
`No such file '${filePath}' with matching extensions [${VALID_FILE_EXTENSIONS}]`
);
};

/**
* Find the module file path
*
* @param {string} modulePath - The path to the module
* @param {string} basePath - The base path for the module
* @returns {string} The resolved file path
* @throws {Error} If the file is not found
*/
export const findModuleFile = (basePath: string, modulePath: string): string => {
const filePath = path.join(basePath, modulePath);
return fs.existsSync(filePath) ? filePath : findFileWithExtensions(filePath);
};
2 changes: 1 addition & 1 deletion src/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const esmImport = (modulePath: string, options: Options) => {
*/
const importSync = (id: string, options: Options = {}) => {
const basePath = options.basePath ?? getCallerDirname();
const modulePath = /^\.\.?\//.test(id) ? findModuleFile(id, basePath) : id;
const modulePath = /^\.\.?\//.test(id) ? findModuleFile(basePath, id) : id;
const importedModule = esmImport(modulePath, options);

if (Object.keys(importedModule).length > 0) {
Expand Down

0 comments on commit ae11b8e

Please sign in to comment.