| import findUp from 'next/dist/compiled/find-up' |
| import { readFile } from 'fs/promises' |
| import JSON5 from 'next/dist/compiled/json5' |
| import { pathToFileURL } from 'url' |
|
|
| type RecursivePartial<T> = { |
| [P in keyof T]?: RecursivePartial<T[P]> |
| } |
|
|
| export function findConfigPath( |
| dir: string, |
| key: string |
| ): Promise<string | undefined> { |
| |
| |
| return findUp( |
| [ |
| `.${key}rc.json`, |
| `${key}.config.json`, |
| `.${key}rc.js`, |
| `${key}.config.js`, |
| `${key}.config.mjs`, |
| `${key}.config.cjs`, |
| ], |
| { |
| cwd: dir, |
| } |
| ) |
| } |
|
|
| |
| |
| |
| export async function findConfig<T>( |
| directory: string, |
| key: string, |
| _returnFile?: boolean |
| ): Promise<RecursivePartial<T> | null> { |
| |
| const packageJsonPath = await findUp('package.json', { cwd: directory }) |
| let isESM = false |
|
|
| if (packageJsonPath) { |
| try { |
| const packageJsonStr = await readFile(packageJsonPath, 'utf8') |
| const packageJson = JSON.parse(packageJsonStr) as { |
| [key: string]: string |
| } |
|
|
| if (typeof packageJson !== 'object') { |
| throw new Error() |
| } |
|
|
| if (packageJson.type === 'module') { |
| isESM = true |
| } |
|
|
| if (packageJson[key] != null && typeof packageJson[key] === 'object') { |
| return packageJson[key] |
| } |
| } catch { |
| |
| } |
| } |
|
|
| const filePath = await findConfigPath(directory, key) |
|
|
| const esmImport = (path: string) => { |
| |
| |
| if (process.platform === 'win32' && !process.env.JEST_WORKER_ID) { |
| |
| |
| return import(pathToFileURL(path).toString()) |
| } else { |
| return import(path) |
| } |
| } |
|
|
| if (filePath) { |
| if (filePath.endsWith('.js')) { |
| if (isESM) { |
| return (await esmImport(filePath)).default |
| } else { |
| return require(filePath) |
| } |
| } else if (filePath.endsWith('.mjs')) { |
| return (await esmImport(filePath)).default |
| } else if (filePath.endsWith('.cjs')) { |
| return require(filePath) |
| } |
|
|
| |
| |
| const fileContents = await readFile(filePath, 'utf8') |
| return JSON5.parse(fileContents) |
| } |
|
|
| return null |
| } |
|
|