11import debugLib from 'debug' ;
2+ import { readFileSync } from 'node:fs' ; // I don't like using synchronous versions, but until we migrate to ESM, we have to.
3+ import path from 'node:path' ;
24
35interface Config {
46 tracksUserType : string ;
@@ -9,19 +11,35 @@ interface Config {
911
1012const debug = debugLib ( '@automattic/vip:lib:cli:config' ) ;
1113
12- let configFromFile : Config ;
13- try {
14- // Get `local` config first; this will only exist in dev as it's npmignore-d.
15- // eslint-disable-next-line @typescript-eslint/no-var-requires
16- configFromFile = require ( '../../../config/config.local.json' ) as Config ;
14+ export function loadConfigFile ( ) : Config | null {
15+ const paths = [
16+ // Get `local` config first; this will only exist in dev as it's npmignore-d.
17+ path . join ( __dirname , '../../../config/config.local.json' ) ,
18+ path . join ( __dirname , '../../../config/config.publish.json' ) ,
19+ ] ;
1720
18- debug ( 'Loaded config data from config.local.json' ) ;
19- } catch {
20- // Fall back to `publish` config file.
21- // eslint-disable-next-line @typescript-eslint/no-var-requires
22- configFromFile = require ( '../../../config/config.publish.json' ) as Config ;
21+ for ( const filePath of paths ) {
22+ try {
23+ const data = readFileSync ( filePath , 'utf-8' ) ;
24+ debug ( `Found config file at ${ filePath } ` ) ;
25+ return JSON . parse ( data ) as Config ;
26+ } catch ( err ) {
27+ if ( ! ( err instanceof Error ) || ! ( 'code' in err ) || err . code !== 'ENOENT' ) {
28+ debug ( `Error reading config file at ${ filePath } :` , err ) ;
29+ }
30+ }
31+ }
2332
24- debug ( 'Loaded config data from config.publish.json' ) ;
33+ return null ;
2534}
2635
27- export default configFromFile ;
36+ const configFromFile = loadConfigFile ( ) ;
37+ if ( null === configFromFile ) {
38+ // This should not happen because `config/config.publish.json` is always present.
39+ console . error ( 'FATAL ERROR: Could not find a valid configuration file' ) ;
40+ process . exit ( 1 ) ;
41+ }
42+
43+ // Without this, TypeScript will export `configFromFile` as `Config | null`
44+ const exportedConfig : Config = configFromFile ;
45+ export default exportedConfig ;
0 commit comments