1 import { join } from "path"
2 import { dynamicImport } from "./dynamic-import"
3
4 /**
5 * Attempts to resolve the config file in a given root directory.
6 * @param {string} rootDir - the directory to find the config file in.
7 * @param {string} configName - the name of the config file.
8 * @return {object} an object containing the config module and its path as well as an error property if the config couldn't be loaded.
9 */
10 export async function getConfigFile<TConfig = unknown>(
11 rootDir: string,
12 configName: string
13 ): Promise<
14 | { configModule: null; configFilePath: string; error: Error }
15 | { configModule: TConfig; configFilePath: string; error: null }
16 > {
17 const configPath = join(rootDir, configName)
18
19 try {
20 const configFilePath = join(process.cwd(), rootDir, configName)
21 const resolvedExports = await dynamicImport(configPath)
22 return {
23 configModule:
24 "default" in resolvedExports && resolvedExports.default
25 ? resolvedExports.default
26 : resolvedExports,
27 configFilePath,
28 error: null,
29 }
30 } catch (e) {
31 return {
32 configModule: null,
33 configFilePath: "",
34 error: e,
35 }
36 }
37 }