@@ -2,6 +2,20 @@ import type { Config } from './types'
2
2
import { resolve } from 'node:path'
3
3
import { deepMerge } from './utils'
4
4
5
+ /**
6
+ * Attempts to load a config file from a specific path
7
+ */
8
+ async function tryLoadConfig < T > ( configPath : string , defaultConfig : T ) : Promise < T | null > {
9
+ try {
10
+ const importedConfig = await import ( configPath )
11
+ const loadedConfig = importedConfig . default || importedConfig
12
+ return deepMerge ( defaultConfig , loadedConfig ) as T
13
+ }
14
+ catch {
15
+ return null
16
+ }
17
+ }
18
+
5
19
/**
6
20
* Load Config
7
21
*
@@ -31,33 +45,32 @@ export async function loadConfig<T>({
31
45
'Content-Type' : 'application/json' ,
32
46
} ,
33
47
} : Config < T > ) : Promise < T > {
34
- // If running in a server (Bun) environment, load the config from the file system
48
+ // If running in a server environment, load the config from the file system
35
49
if ( typeof window === 'undefined' ) {
36
- try {
37
- // back 3 times to get out of node_modules into the root directory, assuming the config is in the root directory
38
- const configPath = resolve ( cwd || '../../../' , `${ name } .config` )
39
- const importedConfig = await import ( configPath )
40
- const loadedConfig = importedConfig . default || importedConfig
41
-
42
- return deepMerge ( defaultConfig , loadedConfig ) as T
43
- }
44
- // eslint-disable-next-line unused-imports/no-unused-vars
45
- catch ( error : any ) {
46
- try {
47
- const dotConfigPath = resolve ( cwd || '../../../' , `.${ name } .config` )
48
- const importedConfig = await import ( dotConfigPath )
49
- const loadedConfig = importedConfig . default || importedConfig
50
+ const baseDir = cwd || '../../../'
50
51
51
- return deepMerge ( defaultConfig , loadedConfig ) as T
52
- }
53
- catch ( error ) {
54
- console . error ( 'Failed to load client config:' , error )
52
+ // Try loading config in order of preference
53
+ const configPaths = [
54
+ `${ name } .config` ,
55
+ `.${ name } .config` ,
56
+ name ,
57
+ `.${ name } ` ,
58
+ ]
55
59
56
- return defaultConfig
60
+ for ( const configPath of configPaths ) {
61
+ const fullPath = resolve ( baseDir , configPath )
62
+ const config = await tryLoadConfig ( fullPath , defaultConfig )
63
+ if ( config !== null ) {
64
+ return config
57
65
}
58
66
}
67
+
68
+ console . error ( 'Failed to load client config from any expected location' )
69
+
70
+ return defaultConfig
59
71
}
60
72
73
+ // Browser environment checks
61
74
if ( ! endpoint ) {
62
75
console . warn ( 'An API endpoint is required to load the client config.' )
63
76
return defaultConfig
0 commit comments