11import { homedir } from "node:os" ;
22import { join } from "node:path" ;
33import { mkdir , rename , readFile , writeFile } from "node:fs/promises" ;
4+ import { z } from "zod" ;
45
56export type ConfigScope = "global" | "local" ;
67
7- export interface WalletConfig {
8- type : string ;
9- [ key : string ] : unknown ;
10- }
8+ export const WalletConfigSchema = z . object ( { type : z . string ( ) } ) . passthrough ( ) ;
119
12- export interface Config {
13- wallet : WalletConfig ;
14- env ?: Record < string , number | string > ;
15- }
10+ export const ConfigSchema = z . object ( {
11+ wallet : WalletConfigSchema ,
12+ env : z . record ( z . string ( ) , z . union ( [ z . number ( ) , z . string ( ) ] ) ) . optional ( ) ,
13+ } ) ;
14+
15+ export type WalletConfig = z . infer < typeof WalletConfigSchema > ;
16+ export type Config = z . infer < typeof ConfigSchema > ;
1617
1718function getConfigDir ( scope : ConfigScope ) : string {
1819 return scope === "local" ? join ( process . cwd ( ) , ".use-agently" ) : join ( homedir ( ) , ".use-agently" ) ;
@@ -29,13 +30,21 @@ async function loadConfigFromPath(configPath: string): Promise<Config | undefine
2930 } catch {
3031 return undefined ;
3132 }
33+ let raw : unknown ;
3234 try {
33- return JSON . parse ( contents ) as Config ;
35+ raw = JSON . parse ( contents ) ;
3436 } catch {
3537 throw new Error (
3638 `Config file at ${ configPath } contains invalid JSON. Please fix or delete it and run \`use-agently init\`.` ,
3739 ) ;
3840 }
41+ const result = ConfigSchema . safeParse ( raw ) ;
42+ if ( ! result . success ) {
43+ throw new Error (
44+ `Config file at ${ configPath } has an invalid format. Please fix or delete it and run \`use-agently init\`.` ,
45+ ) ;
46+ }
47+ return result . data ;
3948}
4049
4150export async function loadConfig ( scope ?: ConfigScope ) : Promise < Config | undefined > {
0 commit comments