11import { type ParseError , parse as parseJsoncRaw , printParseErrorCode } from 'jsonc-parser' ;
22import pc from 'picocolors' ;
33import * as R from 'ramda' ;
4- import type { z } from 'zod' ;
4+ import { z } from 'zod' ;
55import { fromError } from 'zod-validation-error' ;
66
77export const deprecatedCLIOptions = {
@@ -97,6 +97,41 @@ export function parseJsonc<T>(content: string): T {
9797 return result ;
9898}
9999
100+ /**
101+ * Recursively extracts default values from a Zod schema.
102+ *
103+ * Fields with `.default()` return their default value, nested objects are
104+ * traversed recursively, optional/nullable wrappers are unwrapped, and
105+ * single-value literals return their literal value. Fields without a
106+ * resolvable default are omitted from the result.
107+ *
108+ * @template T - The Zod schema type.
109+ * @param schema - The Zod schema to extract default values from.
110+ * @returns The default values described by the schema.
111+ */
112+ export function getSchemaDefaults < T extends z . ZodType > ( schema : T ) : Partial < z . infer < T > > {
113+ return getDefaultValue ( schema ) as Partial < z . infer < T > > ;
114+ }
115+
116+ function getDefaultValue ( schema : z . ZodType ) : unknown {
117+ if ( schema instanceof z . ZodDefault ) {
118+ return schema . def . defaultValue ;
119+ }
120+ if ( schema instanceof z . ZodOptional || schema instanceof z . ZodNullable ) {
121+ return getDefaultValue ( schema . def . innerType as z . ZodType ) ;
122+ }
123+ if ( schema instanceof z . ZodObject ) {
124+ const entries = Object . entries ( schema . shape )
125+ . map ( ( [ key , value ] ) => [ key , getDefaultValue ( value as z . ZodType ) ] as const )
126+ . filter ( ( [ , value ] ) => value !== undefined ) ;
127+ return Object . fromEntries ( entries ) ;
128+ }
129+ if ( schema instanceof z . ZodLiteral && schema . def . values . length === 1 ) {
130+ return schema . def . values [ 0 ] ;
131+ }
132+ return undefined ;
133+ }
134+
100135export function parseConfig < T > ( configFile : string ) : T {
101136 if ( ! configFile ) {
102137 return { } as T ;
@@ -109,3 +144,12 @@ export function parseConfig<T>(configFile: string): T {
109144 throw new Error ( validationError ?. toString ( ) ) ;
110145 }
111146}
147+
148+ // export function getDefaults<Schema extends z.ZodObject>(schema: Schema) {
149+ // return Object.fromEntries(
150+ // Object.entries(schema.shape).map(([key, value]) => {
151+ // if (value instanceof z.ZodDefault) return [key, (value.def.defaultValue as () => unknown)()];
152+ // return [key, undefined];
153+ // }),
154+ // );
155+ // }
0 commit comments