@zod-utils/core 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,6 +35,8 @@ npm install @zod-utils/core zod
35
35
 
36
36
  Extract all default values from a Zod object schema. Only extracts fields that explicitly have `.default()` on them.
37
37
 
38
+ **Transform support:** Works with schemas that have `.transform()` - extracts defaults from the input type.
39
+
38
40
  ```typescript
39
41
  import { getSchemaDefaults } from "@zod-utils/core";
40
42
  import { z } from "zod";
@@ -137,9 +139,11 @@ requiresValidInput(middleName); // false - user can leave null
137
139
 
138
140
  ### `getPrimitiveType(field)`
139
141
 
140
- Get the primitive type of a Zod field by unwrapping optional/nullable wrappers.
142
+ Get the primitive type of a Zod field by unwrapping optional/nullable/transform wrappers.
141
143
  Stops at arrays without unwrapping them.
142
144
 
145
+ **Transform support:** Automatically unwraps `.transform()` to get the underlying input type.
146
+
143
147
  ```typescript
144
148
  import { getPrimitiveType } from "@zod-utils/core";
145
149
  import { z } from "zod";
@@ -151,6 +155,11 @@ const primitive = getPrimitiveType(field);
151
155
  const arrayField = z.array(z.string()).optional();
152
156
  const arrayPrimitive = getPrimitiveType(arrayField);
153
157
  // Returns the ZodArray (stops at arrays)
158
+
159
+ // Transform support
160
+ const transformed = z.string().transform((val) => val.toUpperCase());
161
+ const primitiveFromTransform = getPrimitiveType(transformed);
162
+ // Returns the underlying ZodString (unwraps the transform)
154
163
  ```
155
164
 
156
165
  ---
@@ -172,34 +181,40 @@ withoutDefault.parse(undefined); // throws error
172
181
 
173
182
  ---
174
183
 
175
- ### `extractDefault(field)`
184
+ ### `extractDefaultValue(field)`
176
185
 
177
- Extract the default value from a Zod field (recursively unwraps optional/nullable/union layers).
186
+ Extract the default value from a Zod field (recursively unwraps optional/nullable/union/transform layers).
178
187
 
179
188
  **Union handling:** For union types, extracts the default from the first option. If the first option has no default, returns `undefined` (defaults in other union options are not checked).
180
189
 
190
+ **Transform support:** Automatically unwraps `.transform()` to get the input type's default value.
191
+
181
192
  ```typescript
182
- import { extractDefault } from "@zod-utils/core";
193
+ import { extractDefaultValue } from "@zod-utils/core";
183
194
  import { z } from "zod";
184
195
 
185
196
  // Basic usage
186
197
  const field = z.string().optional().default("hello");
187
- extractDefault(field); // 'hello'
198
+ extractDefaultValue(field); // 'hello'
188
199
 
189
200
  const noDefault = z.string();
190
- extractDefault(noDefault); // undefined
201
+ extractDefaultValue(noDefault); // undefined
191
202
 
192
203
  // Union with default in first option
193
204
  const unionField = z.union([z.string().default('hello'), z.number()]);
194
- extractDefault(unionField); // 'hello'
205
+ extractDefaultValue(unionField); // 'hello'
195
206
 
196
207
  // Union with default in second option (only checks first)
197
208
  const unionField2 = z.union([z.string(), z.number().default(42)]);
198
- extractDefault(unionField2); // undefined
209
+ extractDefaultValue(unionField2); // undefined
199
210
 
200
211
  // Union wrapped in optional
201
212
  const wrappedUnion = z.union([z.string().default('test'), z.number()]).optional();
202
- extractDefault(wrappedUnion); // 'test'
213
+ extractDefaultValue(wrappedUnion); // 'test'
214
+
215
+ // Transform support - extracts input default, not output
216
+ const transformed = z.string().default('hello').transform((val) => val.toUpperCase());
217
+ extractDefaultValue(transformed); // 'hello' (not 'HELLO')
203
218
  ```
204
219
 
205
220
  ---
@@ -319,6 +334,8 @@ const editSchema = extractDiscriminatedSchema({
319
334
 
320
335
  Extract a single field from a Zod object or discriminated union schema.
321
336
 
337
+ **Transform support:** Works with schemas that have `.transform()` - extracts fields from the input type.
338
+
322
339
  ```typescript
323
340
  import { extractFieldFromSchema } from "@zod-utils/core";
324
341
  import { z } from "zod";
@@ -367,6 +384,20 @@ const fieldWithoutDiscriminator = extractFieldFromSchema({
367
384
  fieldName: 'name',
368
385
  });
369
386
  // Returns: undefined (need discriminator to know which variant)
387
+
388
+ // Works with transforms - extracts from input type
389
+ const transformedSchema = z
390
+ .object({
391
+ name: z.string(),
392
+ age: z.number(),
393
+ })
394
+ .transform((data) => ({ ...data, computed: true }));
395
+
396
+ const nameFromTransformed = extractFieldFromSchema({
397
+ schema: transformedSchema,
398
+ fieldName: 'name',
399
+ });
400
+ // Returns: ZodString (from the input type, not affected by transform)
370
401
  ```
371
402
 
372
403
  **Discriminated union support:** When extracting fields from discriminated unions, you must provide the `discriminator` option with `key` and `value` to specify which variant to use.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as z from 'zod';
2
2
  import { util, z as z$1 } from 'zod';
3
- import { $InferUnionOutput, $ZodCheckLessThanDef, $ZodCheckGreaterThanDef, $ZodCheckMultipleOfDef, $ZodCheckNumberFormatDef, $ZodCheckBigIntFormatDef, $ZodCheckMaxSizeDef, $ZodCheckMinSizeDef, $ZodCheckSizeEqualsDef, $ZodCheckMaxLengthDef, $ZodCheckMinLengthDef, $ZodCheckLengthEqualsDef, $ZodCheckStringFormatDef, $ZodCheckRegexDef, $ZodCheckLowerCaseDef, $ZodCheckUpperCaseDef, $ZodCheckIncludesDef, $ZodCheckStartsWithDef, $ZodCheckEndsWithDef, $ZodCheckPropertyDef, $ZodCheckMimeTypeDef, $ZodCheckOverwriteDef } from 'zod/v4/core';
3
+ import { $InferUnionInput, $ZodCheckLessThanDef, $ZodCheckGreaterThanDef, $ZodCheckMultipleOfDef, $ZodCheckNumberFormatDef, $ZodCheckBigIntFormatDef, $ZodCheckMaxSizeDef, $ZodCheckMinSizeDef, $ZodCheckSizeEqualsDef, $ZodCheckMaxLengthDef, $ZodCheckMinLengthDef, $ZodCheckLengthEqualsDef, $ZodCheckStringFormatDef, $ZodCheckRegexDef, $ZodCheckLowerCaseDef, $ZodCheckUpperCaseDef, $ZodCheckIncludesDef, $ZodCheckStartsWithDef, $ZodCheckEndsWithDef, $ZodCheckPropertyDef, $ZodCheckMimeTypeDef, $ZodCheckOverwriteDef } from 'zod/v4/core';
4
4
 
5
5
  /**
6
6
  * Simplifies complex TypeScript types for better IDE hover tooltips and error messages.
@@ -35,8 +35,8 @@ import { $InferUnionOutput, $ZodCheckLessThanDef, $ZodCheckGreaterThanDef, $ZodC
35
35
  * const schema = z.object({ id: z.string() })
36
36
  * .merge(z.object({ name: z.string() }));
37
37
  *
38
- * type InferredType = z.infer<typeof schema>; // May show complex type
39
- * type SimplifiedType = Simplify<z.infer<typeof schema>>;
38
+ * type InferredType = z.input<typeof schema>; // May show complex type
39
+ * type SimplifiedType = Simplify<z.input<typeof schema>>;
40
40
  * // Shows clear: { id: string; name: string }
41
41
  * ```
42
42
  *
@@ -64,7 +64,7 @@ type Simplify<T> = {
64
64
  * Basic usage with default value
65
65
  * ```typescript
66
66
  * const field = z.string().default('hello');
67
- * const defaultValue = extractDefault(field);
67
+ * const defaultValue = extractDefaultValue(field);
68
68
  * // Result: 'hello'
69
69
  * ```
70
70
  *
@@ -72,7 +72,7 @@ type Simplify<T> = {
72
72
  * Unwrapping optional/nullable layers
73
73
  * ```typescript
74
74
  * const field = z.string().default('world').optional();
75
- * const defaultValue = extractDefault(field);
75
+ * const defaultValue = extractDefaultValue(field);
76
76
  * // Result: 'world' (unwraps optional to find default)
77
77
  * ```
78
78
  *
@@ -80,7 +80,7 @@ type Simplify<T> = {
80
80
  * Union with only nullish types stripped to single type
81
81
  * ```typescript
82
82
  * const field = z.union([z.string().default('hello'), z.null()]);
83
- * const defaultValue = extractDefault(field);
83
+ * const defaultValue = extractDefaultValue(field);
84
84
  * // Result: 'hello' (null stripped, leaving only string)
85
85
  * ```
86
86
  *
@@ -88,7 +88,7 @@ type Simplify<T> = {
88
88
  * Union with multiple non-nullish types
89
89
  * ```typescript
90
90
  * const field = z.union([z.string().default('hello'), z.number()]);
91
- * const defaultValue = extractDefault(field);
91
+ * const defaultValue = extractDefaultValue(field);
92
92
  * // Result: undefined (multiple non-nullish types - no default extracted)
93
93
  * ```
94
94
  *
@@ -96,7 +96,7 @@ type Simplify<T> = {
96
96
  * Field without default
97
97
  * ```typescript
98
98
  * const field = z.string().optional();
99
- * const defaultValue = extractDefault(field);
99
+ * const defaultValue = extractDefaultValue(field);
100
100
  * // Result: undefined
101
101
  * ```
102
102
  *
@@ -104,7 +104,7 @@ type Simplify<T> = {
104
104
  * @see {@link tryStripNullishOnly} for union nullish stripping logic
105
105
  * @since 0.1.0
106
106
  */
107
- declare function extractDefault<T extends z.ZodTypeAny>(field: T): z.infer<T> | undefined;
107
+ declare function extractDefaultValue<T extends z.ZodType>(field: T): z.input<T> | undefined;
108
108
  /**
109
109
  * Extracts default values from a Zod object schema, returning only fields with explicit `.default()`.
110
110
  *
@@ -174,17 +174,17 @@ declare function extractDefault<T extends z.ZodTypeAny>(field: T): z.infer<T> |
174
174
  * <Input type="number" value={field.value ?? ''} />
175
175
  * ```
176
176
  *
177
- * @see {@link extractDefault} for extracting defaults from individual fields
177
+ * @see {@link extractDefaultValue} for extracting defaults from individual fields
178
178
  * @since 0.1.0
179
179
  */
180
- declare function getSchemaDefaults<TSchema extends z.ZodObject | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.infer<TSchema> & string, TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] & util.Literal>(schema: TSchema, options?: {
180
+ declare function getSchemaDefaults<TSchema extends z.ZodType, TDiscriminatorKey extends keyof z.input<TSchema> & string, TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] & util.Literal>(schema: TSchema, options?: {
181
181
  discriminator?: {
182
182
  key: TDiscriminatorKey;
183
183
  value: TDiscriminatorValue;
184
184
  };
185
- }): Simplify<Partial<z.infer<TSchema>>>;
185
+ }): Simplify<Partial<z.input<TSchema>>>;
186
186
 
187
- declare function extractFieldFromSchema<TSchema extends z$1.ZodObject | z$1.ZodDiscriminatedUnion, TName extends keyof Extract<Required<z$1.infer<TSchema>>, Record<TDiscriminatorKey, TDiscriminatorValue>>, TDiscriminatorKey extends keyof z$1.infer<TSchema> & string, TDiscriminatorValue extends z$1.infer<TSchema>[TDiscriminatorKey] & util.Literal>({ schema, fieldName, discriminator, }: {
187
+ declare function extractFieldFromSchema<TSchema extends z$1.ZodType, TName extends keyof Extract<Required<z$1.input<TSchema>>, Record<TDiscriminatorKey, TDiscriminatorValue>>, TDiscriminatorKey extends keyof z$1.input<TSchema> & string, TDiscriminatorValue extends z$1.input<TSchema>[TDiscriminatorKey] & util.Literal>({ schema, fieldName, discriminator, }: {
188
188
  schema: TSchema;
189
189
  fieldName: TName;
190
190
  discriminator?: {
@@ -560,10 +560,10 @@ declare function getFieldChecks<T extends z.ZodTypeAny>(field: T): Array<ZodUnio
560
560
  * type CreateSchema = ExtractZodUnionMember<typeof schema, 'mode', 'create'>;
561
561
  * ```
562
562
  */
563
- type ExtractZodUnionMember<TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.infer<TSchema> & string, TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] & util.Literal> = TSchema extends z.ZodUnion<infer Options> ? Options extends readonly [
563
+ type ExtractZodUnionMember<TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.input<TSchema> & string, TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] & util.Literal> = TSchema extends z.ZodUnion<infer Options> ? Options extends readonly [
564
564
  infer First extends z.ZodTypeAny,
565
565
  ...infer Rest extends z.ZodTypeAny[]
566
- ] ? First extends z.ZodObject<infer Shape> ? TDiscriminatorKey extends keyof Shape ? Shape[TDiscriminatorKey] extends z.ZodLiteral<TDiscriminatorValue> ? First : Rest extends [] ? never : TDiscriminatorValue extends $InferUnionOutput<Rest[number]>[TDiscriminatorKey] ? ExtractZodUnionMember<z.ZodUnion<Rest>, TDiscriminatorKey, TDiscriminatorValue> : never : Rest extends [] ? never : TDiscriminatorValue extends $InferUnionOutput<Rest[number]>[TDiscriminatorKey] ? ExtractZodUnionMember<z.ZodUnion<Rest>, TDiscriminatorKey, TDiscriminatorValue> : never : never : never : never;
566
+ ] ? First extends z.ZodObject<infer Shape> ? TDiscriminatorKey extends keyof Shape ? Shape[TDiscriminatorKey] extends z.ZodLiteral<TDiscriminatorValue> ? First : Rest extends [] ? never : TDiscriminatorValue extends $InferUnionInput<Rest[number]>[TDiscriminatorKey] ? ExtractZodUnionMember<z.ZodUnion<Rest>, TDiscriminatorKey, TDiscriminatorValue> : never : Rest extends [] ? never : TDiscriminatorValue extends $InferUnionInput<Rest[number]>[TDiscriminatorKey] ? ExtractZodUnionMember<z.ZodUnion<Rest>, TDiscriminatorKey, TDiscriminatorValue> : never : never : never : never;
567
567
  /**
568
568
  * Extracts a specific schema option from a discriminated union based on the discriminator field value.
569
569
  *
@@ -682,10 +682,10 @@ type ExtractZodUnionMember<TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,
682
682
  * @see {@link ExtractZodUnionMember} for the type-level extraction logic
683
683
  * @since 0.6.0
684
684
  */
685
- declare const extractDiscriminatedSchema: <TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.infer<TSchema> & string, TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] & util.Literal>({ schema, key, value, }: {
685
+ declare const extractDiscriminatedSchema: <TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.input<TSchema> & string, TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] & util.Literal>({ schema, key, value, }: {
686
686
  schema: TSchema;
687
687
  key: TDiscriminatorKey;
688
688
  value: TDiscriminatorValue;
689
689
  }) => ExtractZodUnionMember<TSchema, TDiscriminatorKey, TDiscriminatorValue> | undefined;
690
690
 
691
- export { type Simplify, type ZodUnionCheck, canUnwrap, extractDefault, extractDiscriminatedSchema, extractFieldFromSchema, getFieldChecks, getPrimitiveType, getSchemaDefaults, removeDefault, requiresValidInput, tryStripNullishOnly };
691
+ export { type Simplify, type ZodUnionCheck, canUnwrap, extractDefaultValue, extractDiscriminatedSchema, extractFieldFromSchema, getFieldChecks, getPrimitiveType, getSchemaDefaults, removeDefault, requiresValidInput, tryStripNullishOnly };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as z from 'zod';
2
2
  import { util, z as z$1 } from 'zod';
3
- import { $InferUnionOutput, $ZodCheckLessThanDef, $ZodCheckGreaterThanDef, $ZodCheckMultipleOfDef, $ZodCheckNumberFormatDef, $ZodCheckBigIntFormatDef, $ZodCheckMaxSizeDef, $ZodCheckMinSizeDef, $ZodCheckSizeEqualsDef, $ZodCheckMaxLengthDef, $ZodCheckMinLengthDef, $ZodCheckLengthEqualsDef, $ZodCheckStringFormatDef, $ZodCheckRegexDef, $ZodCheckLowerCaseDef, $ZodCheckUpperCaseDef, $ZodCheckIncludesDef, $ZodCheckStartsWithDef, $ZodCheckEndsWithDef, $ZodCheckPropertyDef, $ZodCheckMimeTypeDef, $ZodCheckOverwriteDef } from 'zod/v4/core';
3
+ import { $InferUnionInput, $ZodCheckLessThanDef, $ZodCheckGreaterThanDef, $ZodCheckMultipleOfDef, $ZodCheckNumberFormatDef, $ZodCheckBigIntFormatDef, $ZodCheckMaxSizeDef, $ZodCheckMinSizeDef, $ZodCheckSizeEqualsDef, $ZodCheckMaxLengthDef, $ZodCheckMinLengthDef, $ZodCheckLengthEqualsDef, $ZodCheckStringFormatDef, $ZodCheckRegexDef, $ZodCheckLowerCaseDef, $ZodCheckUpperCaseDef, $ZodCheckIncludesDef, $ZodCheckStartsWithDef, $ZodCheckEndsWithDef, $ZodCheckPropertyDef, $ZodCheckMimeTypeDef, $ZodCheckOverwriteDef } from 'zod/v4/core';
4
4
 
5
5
  /**
6
6
  * Simplifies complex TypeScript types for better IDE hover tooltips and error messages.
@@ -35,8 +35,8 @@ import { $InferUnionOutput, $ZodCheckLessThanDef, $ZodCheckGreaterThanDef, $ZodC
35
35
  * const schema = z.object({ id: z.string() })
36
36
  * .merge(z.object({ name: z.string() }));
37
37
  *
38
- * type InferredType = z.infer<typeof schema>; // May show complex type
39
- * type SimplifiedType = Simplify<z.infer<typeof schema>>;
38
+ * type InferredType = z.input<typeof schema>; // May show complex type
39
+ * type SimplifiedType = Simplify<z.input<typeof schema>>;
40
40
  * // Shows clear: { id: string; name: string }
41
41
  * ```
42
42
  *
@@ -64,7 +64,7 @@ type Simplify<T> = {
64
64
  * Basic usage with default value
65
65
  * ```typescript
66
66
  * const field = z.string().default('hello');
67
- * const defaultValue = extractDefault(field);
67
+ * const defaultValue = extractDefaultValue(field);
68
68
  * // Result: 'hello'
69
69
  * ```
70
70
  *
@@ -72,7 +72,7 @@ type Simplify<T> = {
72
72
  * Unwrapping optional/nullable layers
73
73
  * ```typescript
74
74
  * const field = z.string().default('world').optional();
75
- * const defaultValue = extractDefault(field);
75
+ * const defaultValue = extractDefaultValue(field);
76
76
  * // Result: 'world' (unwraps optional to find default)
77
77
  * ```
78
78
  *
@@ -80,7 +80,7 @@ type Simplify<T> = {
80
80
  * Union with only nullish types stripped to single type
81
81
  * ```typescript
82
82
  * const field = z.union([z.string().default('hello'), z.null()]);
83
- * const defaultValue = extractDefault(field);
83
+ * const defaultValue = extractDefaultValue(field);
84
84
  * // Result: 'hello' (null stripped, leaving only string)
85
85
  * ```
86
86
  *
@@ -88,7 +88,7 @@ type Simplify<T> = {
88
88
  * Union with multiple non-nullish types
89
89
  * ```typescript
90
90
  * const field = z.union([z.string().default('hello'), z.number()]);
91
- * const defaultValue = extractDefault(field);
91
+ * const defaultValue = extractDefaultValue(field);
92
92
  * // Result: undefined (multiple non-nullish types - no default extracted)
93
93
  * ```
94
94
  *
@@ -96,7 +96,7 @@ type Simplify<T> = {
96
96
  * Field without default
97
97
  * ```typescript
98
98
  * const field = z.string().optional();
99
- * const defaultValue = extractDefault(field);
99
+ * const defaultValue = extractDefaultValue(field);
100
100
  * // Result: undefined
101
101
  * ```
102
102
  *
@@ -104,7 +104,7 @@ type Simplify<T> = {
104
104
  * @see {@link tryStripNullishOnly} for union nullish stripping logic
105
105
  * @since 0.1.0
106
106
  */
107
- declare function extractDefault<T extends z.ZodTypeAny>(field: T): z.infer<T> | undefined;
107
+ declare function extractDefaultValue<T extends z.ZodType>(field: T): z.input<T> | undefined;
108
108
  /**
109
109
  * Extracts default values from a Zod object schema, returning only fields with explicit `.default()`.
110
110
  *
@@ -174,17 +174,17 @@ declare function extractDefault<T extends z.ZodTypeAny>(field: T): z.infer<T> |
174
174
  * <Input type="number" value={field.value ?? ''} />
175
175
  * ```
176
176
  *
177
- * @see {@link extractDefault} for extracting defaults from individual fields
177
+ * @see {@link extractDefaultValue} for extracting defaults from individual fields
178
178
  * @since 0.1.0
179
179
  */
180
- declare function getSchemaDefaults<TSchema extends z.ZodObject | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.infer<TSchema> & string, TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] & util.Literal>(schema: TSchema, options?: {
180
+ declare function getSchemaDefaults<TSchema extends z.ZodType, TDiscriminatorKey extends keyof z.input<TSchema> & string, TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] & util.Literal>(schema: TSchema, options?: {
181
181
  discriminator?: {
182
182
  key: TDiscriminatorKey;
183
183
  value: TDiscriminatorValue;
184
184
  };
185
- }): Simplify<Partial<z.infer<TSchema>>>;
185
+ }): Simplify<Partial<z.input<TSchema>>>;
186
186
 
187
- declare function extractFieldFromSchema<TSchema extends z$1.ZodObject | z$1.ZodDiscriminatedUnion, TName extends keyof Extract<Required<z$1.infer<TSchema>>, Record<TDiscriminatorKey, TDiscriminatorValue>>, TDiscriminatorKey extends keyof z$1.infer<TSchema> & string, TDiscriminatorValue extends z$1.infer<TSchema>[TDiscriminatorKey] & util.Literal>({ schema, fieldName, discriminator, }: {
187
+ declare function extractFieldFromSchema<TSchema extends z$1.ZodType, TName extends keyof Extract<Required<z$1.input<TSchema>>, Record<TDiscriminatorKey, TDiscriminatorValue>>, TDiscriminatorKey extends keyof z$1.input<TSchema> & string, TDiscriminatorValue extends z$1.input<TSchema>[TDiscriminatorKey] & util.Literal>({ schema, fieldName, discriminator, }: {
188
188
  schema: TSchema;
189
189
  fieldName: TName;
190
190
  discriminator?: {
@@ -560,10 +560,10 @@ declare function getFieldChecks<T extends z.ZodTypeAny>(field: T): Array<ZodUnio
560
560
  * type CreateSchema = ExtractZodUnionMember<typeof schema, 'mode', 'create'>;
561
561
  * ```
562
562
  */
563
- type ExtractZodUnionMember<TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.infer<TSchema> & string, TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] & util.Literal> = TSchema extends z.ZodUnion<infer Options> ? Options extends readonly [
563
+ type ExtractZodUnionMember<TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.input<TSchema> & string, TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] & util.Literal> = TSchema extends z.ZodUnion<infer Options> ? Options extends readonly [
564
564
  infer First extends z.ZodTypeAny,
565
565
  ...infer Rest extends z.ZodTypeAny[]
566
- ] ? First extends z.ZodObject<infer Shape> ? TDiscriminatorKey extends keyof Shape ? Shape[TDiscriminatorKey] extends z.ZodLiteral<TDiscriminatorValue> ? First : Rest extends [] ? never : TDiscriminatorValue extends $InferUnionOutput<Rest[number]>[TDiscriminatorKey] ? ExtractZodUnionMember<z.ZodUnion<Rest>, TDiscriminatorKey, TDiscriminatorValue> : never : Rest extends [] ? never : TDiscriminatorValue extends $InferUnionOutput<Rest[number]>[TDiscriminatorKey] ? ExtractZodUnionMember<z.ZodUnion<Rest>, TDiscriminatorKey, TDiscriminatorValue> : never : never : never : never;
566
+ ] ? First extends z.ZodObject<infer Shape> ? TDiscriminatorKey extends keyof Shape ? Shape[TDiscriminatorKey] extends z.ZodLiteral<TDiscriminatorValue> ? First : Rest extends [] ? never : TDiscriminatorValue extends $InferUnionInput<Rest[number]>[TDiscriminatorKey] ? ExtractZodUnionMember<z.ZodUnion<Rest>, TDiscriminatorKey, TDiscriminatorValue> : never : Rest extends [] ? never : TDiscriminatorValue extends $InferUnionInput<Rest[number]>[TDiscriminatorKey] ? ExtractZodUnionMember<z.ZodUnion<Rest>, TDiscriminatorKey, TDiscriminatorValue> : never : never : never : never;
567
567
  /**
568
568
  * Extracts a specific schema option from a discriminated union based on the discriminator field value.
569
569
  *
@@ -682,10 +682,10 @@ type ExtractZodUnionMember<TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,
682
682
  * @see {@link ExtractZodUnionMember} for the type-level extraction logic
683
683
  * @since 0.6.0
684
684
  */
685
- declare const extractDiscriminatedSchema: <TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.infer<TSchema> & string, TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] & util.Literal>({ schema, key, value, }: {
685
+ declare const extractDiscriminatedSchema: <TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion, TDiscriminatorKey extends keyof z.input<TSchema> & string, TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] & util.Literal>({ schema, key, value, }: {
686
686
  schema: TSchema;
687
687
  key: TDiscriminatorKey;
688
688
  value: TDiscriminatorValue;
689
689
  }) => ExtractZodUnionMember<TSchema, TDiscriminatorKey, TDiscriminatorValue> | undefined;
690
690
 
691
- export { type Simplify, type ZodUnionCheck, canUnwrap, extractDefault, extractDiscriminatedSchema, extractFieldFromSchema, getFieldChecks, getPrimitiveType, getSchemaDefaults, removeDefault, requiresValidInput, tryStripNullishOnly };
691
+ export { type Simplify, type ZodUnionCheck, canUnwrap, extractDefaultValue, extractDiscriminatedSchema, extractFieldFromSchema, getFieldChecks, getPrimitiveType, getSchemaDefaults, removeDefault, requiresValidInput, tryStripNullishOnly };
package/dist/index.js CHANGED
@@ -68,6 +68,9 @@ var getPrimitiveType = (field) => {
68
68
  }
69
69
  return field;
70
70
  }
71
+ if (field instanceof z__namespace.ZodPipe && field.def.in instanceof z__namespace.ZodType) {
72
+ return getPrimitiveType(field.def.in);
73
+ }
71
74
  return field;
72
75
  };
73
76
  function removeDefault(field) {
@@ -121,39 +124,43 @@ var extractDiscriminatedSchema = ({
121
124
  };
122
125
 
123
126
  // src/defaults.ts
124
- function extractDefault(field) {
127
+ function extractDefaultValue(field) {
125
128
  if (field instanceof z__namespace.ZodDefault) {
126
129
  return field.def.defaultValue;
127
130
  }
128
131
  if (canUnwrap(field)) {
129
- return extractDefault(field.unwrap());
132
+ return extractDefaultValue(field.unwrap());
130
133
  }
131
134
  if (field instanceof z__namespace.ZodUnion) {
132
135
  const unwrapped = tryStripNullishOnly(field);
133
136
  if (unwrapped !== false) {
134
- return extractDefault(unwrapped);
137
+ return extractDefaultValue(unwrapped);
135
138
  }
136
139
  return void 0;
137
140
  }
141
+ if (field instanceof z__namespace.ZodPipe && field.def.in instanceof z__namespace.ZodType) {
142
+ return extractDefaultValue(field.def.in);
143
+ }
138
144
  return void 0;
139
145
  }
140
146
  function getSchemaDefaults(schema, options) {
147
+ const primitiveSchema = getPrimitiveType(schema);
141
148
  let targetSchema;
142
- if (schema instanceof z__namespace.ZodDiscriminatedUnion) {
149
+ if (primitiveSchema instanceof z__namespace.ZodDiscriminatedUnion) {
143
150
  if (options == null ? void 0 : options.discriminator) {
144
151
  targetSchema = extractDiscriminatedSchema(__spreadValues({
145
- schema
152
+ schema: primitiveSchema
146
153
  }, options.discriminator));
147
154
  }
148
- } else {
149
- targetSchema = schema;
155
+ } else if (primitiveSchema instanceof z__namespace.ZodObject) {
156
+ targetSchema = primitiveSchema;
150
157
  }
151
158
  const defaults = {};
152
159
  if (targetSchema) {
153
160
  for (const key in targetSchema.shape) {
154
161
  const field = targetSchema.shape[key];
155
162
  if (!field) continue;
156
- const defaultValue = extractDefault(field);
163
+ const defaultValue = extractDefaultValue(field);
157
164
  if (defaultValue !== void 0) {
158
165
  defaults[key] = defaultValue;
159
166
  }
@@ -167,14 +174,15 @@ function extractFieldFromSchema({
167
174
  discriminator
168
175
  }) {
169
176
  let targetSchema;
170
- if (schema instanceof z.z.ZodDiscriminatedUnion) {
177
+ const primitiveSchema = getPrimitiveType(schema);
178
+ if (primitiveSchema instanceof z.z.ZodDiscriminatedUnion) {
171
179
  if (discriminator) {
172
180
  targetSchema = extractDiscriminatedSchema(__spreadValues({
173
- schema
181
+ schema: primitiveSchema
174
182
  }, discriminator));
175
183
  }
176
- } else {
177
- targetSchema = schema;
184
+ } else if (primitiveSchema instanceof z.z.ZodObject) {
185
+ targetSchema = primitiveSchema;
178
186
  }
179
187
  if (!targetSchema) return void 0;
180
188
  const field = targetSchema.shape[String(fieldName)];
@@ -182,7 +190,7 @@ function extractFieldFromSchema({
182
190
  }
183
191
 
184
192
  exports.canUnwrap = canUnwrap;
185
- exports.extractDefault = extractDefault;
193
+ exports.extractDefaultValue = extractDefaultValue;
186
194
  exports.extractDiscriminatedSchema = extractDiscriminatedSchema;
187
195
  exports.extractFieldFromSchema = extractFieldFromSchema;
188
196
  exports.getFieldChecks = getFieldChecks;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema.ts","../src/defaults.ts","../src/field.ts"],"names":["z","z2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDO,SAAS,UACd,KAAA,EACqC;AACrC,EAAA,OAAO,QAAA,IAAY,KAAA,IAAS,OAAO,KAAA,CAAM,MAAA,KAAW,UAAA;AACtD;AAuCO,SAAS,oBAAoB,KAAA,EAAwC;AAC1E,EAAA,IAAI,iBAAmBA,YAAA,CAAA,QAAA,EAAU;AAC/B,IAAA,MAAM,YAAA,GAAe,CAAC,GAAG,KAAA,CAAM,IAAI,OAAO,CAAA;AAE1C,IAAA,MAAM,kBAAkB,YAAA,CAAa,MAAA;AAAA,MACnC,CAAC,MAAA,KACC,EAAE,MAAA,YAAoBA,YAAA,CAAA,OAAA,CAAA,IAAY,EAAE,MAAA,YAAoBA,YAAA,CAAA,YAAA;AAAA,KAC5D;AAGA,IAAA,MAAM,WAAA,GAAc,gBAAgB,CAAC,CAAA;AACrC,IAAA,IAAI,WAAA,IAAe,eAAA,CAAgB,MAAA,KAAW,CAAA,EAAG;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A,CAAa,KAAA,CAAM,GAAG,CAAA;AACpC,MAAA,IAAI,CAAC,KAAA,EAAO;AAEZ,MAAA,MAAM,YAAA,GAAe,eAAe,KAAK,CAAA;AACzC,MAAA,IAAI,iBAAiB,MAAA,EAAW;AAC9B,QAAA,QAAA,CAAS,GAAG,CAAA,GAAI,YAAA;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAGA,EAAA,OAAO,QAAA;AACT;AC9MO,SAAS,sBAAA,CASd;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAA,EAOG;AACD,EAAA,IAAI,YAAA;AAEJ,EAAA,IAAI,MAAA,YAAkBD,IAAE,qBAAA,EAAuB;AAC7C,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,YAAA,GAAe,0BAAA,CAA2B,cAAA,CAAA;AAAA,QACxC;AAAA,OAAA,EACG,aAAA,CACJ,CAAA;AAAA,IACH;AAAA,EACF,CAAA,MAAO;AACL,IAAA,YAAA,GAAe,MAAA;AAAA,EACjB;AAEA,EAAA,IAAI,CAAC,cAAc,OAAO,MAAA;AAE1B,EAAA,MAAM,KAAA,GAAmB,YAAA,CAAa,KAAA,CAAM,MAAA,CAAO,SAAS,CAAC,CAAA;AAE7D,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["import type { util } from 'zod';\nimport * as z from 'zod';\nimport type {\n $InferUnionOutput,\n $ZodCheckBigIntFormatDef,\n $ZodCheckEndsWithDef,\n $ZodCheckGreaterThanDef,\n $ZodCheckIncludesDef,\n $ZodCheckLengthEqualsDef,\n $ZodCheckLessThanDef,\n $ZodCheckLowerCaseDef,\n $ZodCheckMaxLengthDef,\n $ZodCheckMaxSizeDef,\n $ZodCheckMimeTypeDef,\n $ZodCheckMinLengthDef,\n $ZodCheckMinSizeDef,\n $ZodCheckMultipleOfDef,\n $ZodCheckNumberFormatDef,\n $ZodCheckOverwriteDef,\n $ZodCheckPropertyDef,\n $ZodCheckRegexDef,\n $ZodCheckSizeEqualsDef,\n $ZodCheckStartsWithDef,\n $ZodCheckStringFormatDef,\n $ZodCheckUpperCaseDef,\n} from 'zod/v4/core';\n\n/**\n * Type representing a Zod type that has an unwrap method\n */\ntype Unwrappable = { unwrap: () => z.ZodTypeAny };\n\n/**\n * Type guard to check if a Zod field can be unwrapped (has wrapper types like optional, nullable, default).\n *\n * This checks whether a Zod type has an `unwrap()` method, which is present on wrapper types\n * like `ZodOptional`, `ZodNullable`, `ZodDefault`, and others.\n *\n * @param field - The Zod field to check\n * @returns True if the field has an unwrap method, false otherwise\n *\n * @example\n * ```typescript\n * const optionalField = z.string().optional();\n * console.log(canUnwrap(optionalField)); // true\n *\n * const plainField = z.string();\n * console.log(canUnwrap(plainField)); // false\n * ```\n *\n * @since 0.1.0\n */\nexport function canUnwrap(\n field: z.ZodTypeAny,\n): field is z.ZodTypeAny & Unwrappable {\n return 'unwrap' in field && typeof field.unwrap === 'function';\n}\n\n/**\n * Attempts to strip nullish types from a union and return the single remaining type.\n *\n * This function filters out `ZodNull` and `ZodUndefined` from union types. If exactly\n * one type remains after filtering, it returns that unwrapped type. Otherwise, it returns\n * `false` to indicate the union couldn't be simplified to a single type.\n *\n * @param field - The Zod field to process\n * @returns The unwrapped type if only one remains, otherwise `false`\n *\n * @example\n * Union with only nullish types filtered - returns single type\n * ```typescript\n * const field = z.union([z.string(), z.null(), z.undefined()]);\n * const result = tryStripNullishOnly(field);\n * // Result: z.string() (unwrapped)\n * ```\n *\n * @example\n * Union with multiple non-nullish types - returns false\n * ```typescript\n * const field = z.union([z.string(), z.number()]);\n * const result = tryStripNullishOnly(field);\n * // Result: false (cannot simplify to single type)\n * ```\n *\n * @example\n * Non-union type - returns false\n * ```typescript\n * const field = z.string();\n * const result = tryStripNullishOnly(field);\n * // Result: false (not a union)\n * ```\n *\n * @see {@link getPrimitiveType} for unwrapping wrapper types\n * @since 0.5.0\n */\nexport function tryStripNullishOnly(field: z.ZodTypeAny): z.ZodType | false {\n if (field instanceof z.ZodUnion) {\n const unionOptions = [...field.def.options];\n\n const filteredOptions = unionOptions.filter(\n (option): option is z.ZodType =>\n !(option instanceof z.ZodNull) && !(option instanceof z.ZodUndefined),\n );\n\n // If exactly one option remains, return it unwrapped\n const firstOption = filteredOptions[0];\n if (firstOption && filteredOptions.length === 1) {\n return firstOption;\n }\n }\n\n // Not a union, or couldn't simplify to single type\n return false;\n}\n\n/**\n * Gets the underlying primitive type of a Zod field by recursively unwrapping wrapper types.\n *\n * This function removes wrapper layers (optional, nullable, default) to reveal the base type.\n * **Important:** It stops at array types without unwrapping them, treating arrays as primitives.\n *\n * **Union handling:** For union types, strips nullish types (null/undefined) first. If only one\n * type remains after stripping, unwraps to that type. If multiple non-nullish types remain,\n * returns the union as-is (does not unwrap).\n *\n * @template T - The Zod type to unwrap\n * @param field - The Zod field to unwrap\n * @returns The unwrapped primitive Zod type\n *\n * @example\n * Unwrapping to string primitive\n * ```typescript\n * const field = z.string().optional().nullable();\n * const primitive = getPrimitiveType(field);\n * // Result: z.string() (unwrapped all wrappers)\n * ```\n *\n * @example\n * Stopping at array type\n * ```typescript\n * const field = z.array(z.string()).optional();\n * const primitive = getPrimitiveType(field);\n * // Result: z.array(z.string()) (stops at array, doesn't unwrap it)\n * ```\n *\n * @example\n * Unwrapping defaults\n * ```typescript\n * const field = z.number().default(0).optional();\n * const primitive = getPrimitiveType(field);\n * // Result: z.number()\n * ```\n *\n * @example\n * Union with only nullish types stripped to single type\n * ```typescript\n * const field = z.union([z.string(), z.null()]);\n * const primitive = getPrimitiveType(field);\n * // Result: z.string() (null stripped, leaving only string)\n * ```\n *\n * @example\n * Union with multiple non-nullish types\n * ```typescript\n * const field = z.union([z.string(), z.number()]);\n * const primitive = getPrimitiveType(field);\n * // Result: z.union([z.string(), z.number()]) (returned as-is)\n * ```\n *\n * @see {@link canUnwrap} for checking if a field can be unwrapped\n * @see {@link tryStripNullishOnly} for union nullish stripping logic\n * @since 0.1.0\n */\nexport const getPrimitiveType = <T extends z.ZodType>(\n field: T,\n): z.ZodTypeAny => {\n // Stop at arrays - don't unwrap them\n if (field instanceof z.ZodArray) {\n return field;\n }\n\n if (canUnwrap(field)) {\n return getPrimitiveType(field.unwrap());\n }\n\n if (field instanceof z.ZodUnion) {\n const unwrapped = tryStripNullishOnly(field);\n if (unwrapped !== false) {\n return getPrimitiveType(unwrapped);\n }\n\n // Multiple non-nullish types or all nullish - return union as-is\n return field;\n }\n\n return field;\n};\n\ntype StripZodDefault<T> = T extends z.ZodDefault<infer Inner>\n ? StripZodDefault<Inner>\n : T extends z.ZodOptional<infer Inner>\n ? z.ZodOptional<StripZodDefault<Inner>>\n : T extends z.ZodNullable<infer Inner>\n ? z.ZodNullable<StripZodDefault<Inner>>\n : T;\n\n/**\n * Removes default values from a Zod field while preserving other wrapper types.\n *\n * This function recursively removes `ZodDefault` wrappers from a field, while maintaining\n * `optional()` and `nullable()` wrappers. Useful for scenarios where you want to check\n * field requirements without considering default values.\n *\n * @template T - The Zod type to process\n * @param field - The Zod field to remove defaults from\n * @returns The field without defaults but with optional/nullable preserved\n *\n * @example\n * Removing simple default\n * ```typescript\n * const field = z.string().default('hello');\n * const withoutDefault = removeDefault(field);\n * // Result: z.string()\n * ```\n *\n * @example\n * Preserving optional wrapper\n * ```typescript\n * const field = z.string().default('hello').optional();\n * const withoutDefault = removeDefault(field);\n * // Result: z.string().optional()\n * ```\n *\n * @example\n * Nested defaults\n * ```typescript\n * const field = z.string().default('inner').nullable().default('outer');\n * const withoutDefault = removeDefault(field);\n * // Result: z.string().nullable()\n * ```\n *\n * @see {@link requiresValidInput} for usage with requirement checking\n * @since 0.1.0\n */\nexport function removeDefault<T extends z.ZodType>(\n field: T,\n): StripZodDefault<T> {\n if (field instanceof z.ZodDefault) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field.unwrap() as StripZodDefault<T>;\n }\n\n if ('innerType' in field.def && field.def.innerType instanceof z.ZodType) {\n const inner = removeDefault(field.def.innerType);\n // Reconstruct the wrapper with the modified inner type\n if (field instanceof z.ZodOptional) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return inner.optional() as unknown as StripZodDefault<T>;\n }\n if (field instanceof z.ZodNullable) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return inner.nullable() as unknown as StripZodDefault<T>;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field as StripZodDefault<T>;\n}\n\n/**\n * Determines if a field will show validation errors when the user submits empty or invalid input.\n *\n * This is useful for form UIs to indicate which fields require valid user input (e.g., showing\n * asterisks, validation states). The key insight: **defaults are just initial values** - they\n * don't prevent validation errors if the user clears the field.\n *\n * **Real-world example:**\n * ```typescript\n * // Marital status field with default but validation rules\n * const maritalStatus = z.string().min(1).default('single');\n *\n * // Initial: field shows \"single\" (from default)\n * // User deletes the value → field is now empty string\n * // User submits form → validation fails because .min(1) rejects empty strings\n * // requiresValidInput(maritalStatus) → true (shows * indicator, validation error)\n * ```\n *\n * **How it works:**\n * 1. Removes `.default()` wrappers (defaults are initial values, not validation rules)\n * 2. Tests if the underlying schema accepts empty/invalid input:\n * - `undefined` (via `.optional()`)\n * - `null` (via `.nullable()`)\n * - Empty string (plain `z.string()` without `.min(1)` or `.nonempty()`)\n * - Empty array (plain `z.array()` without `.min(1)` or `.nonempty()`)\n * 3. Returns `true` if validation will fail, `false` if empty input is accepted\n *\n * @template T - The Zod type to check\n * @param field - The Zod field to check\n * @returns True if the field will show validation errors on empty/invalid input, false otherwise\n *\n * @example\n * User name field - required, no default\n * ```typescript\n * const userName = z.string().min(1);\n * requiresValidInput(userName); // true - will error if user submits empty\n * ```\n *\n * @example\n * Marital status - required WITH default\n * ```typescript\n * const maritalStatus = z.string().min(1).default('single');\n * requiresValidInput(maritalStatus); // true - will error if user clears and submits\n * ```\n *\n * @example\n * Age with default - requires valid input\n * ```typescript\n * const age = z.number().default(0);\n * requiresValidInput(age); // true - numbers reject empty strings\n * ```\n *\n * @example\n * Optional bio field - doesn't require input\n * ```typescript\n * const bio = z.string().optional();\n * requiresValidInput(bio); // false - user can leave empty\n * ```\n *\n * @example\n * String with default but NO validation - doesn't require input\n * ```typescript\n * const notes = z.string().default('N/A');\n * requiresValidInput(notes); // false - plain z.string() accepts empty strings\n * ```\n *\n * @example\n * Nullable field - doesn't require input\n * ```typescript\n * const middleName = z.string().nullable();\n * requiresValidInput(middleName); // false - user can leave null\n * ```\n *\n * @see {@link removeDefault} for understanding how defaults are handled\n * @see {@link getPrimitiveType} for understanding type unwrapping\n * @since 0.1.0\n */\nexport const requiresValidInput = <T extends z.ZodType>(field: T) => {\n const defaultRemovedField = removeDefault(field);\n if (!(defaultRemovedField instanceof z.ZodType)) {\n return false;\n }\n\n const undefinedResult = defaultRemovedField.safeParse(undefined).success;\n\n // Check if field accepts null (nullable)\n const nullResult = defaultRemovedField.safeParse(null).success;\n\n const primitiveType = getPrimitiveType(defaultRemovedField);\n\n const emptyStringResult =\n primitiveType.type === 'string' &&\n defaultRemovedField.safeParse('').success;\n\n const emptyArrayResult =\n primitiveType.type === 'array' && defaultRemovedField.safeParse([]).success;\n\n return (\n !undefinedResult && !nullResult && !emptyStringResult && !emptyArrayResult\n );\n};\n\n/**\n * Union type of all Zod check definition types.\n *\n * Includes all validation check types supported by Zod v4:\n * - **Length checks**: `min_length`, `max_length`, `length_equals` (strings, arrays)\n * - **Size checks**: `min_size`, `max_size`, `size_equals` (files, sets, maps)\n * - **Numeric checks**: `greater_than`, `less_than`, `multiple_of`\n * - **Format checks**: `number_format` (int32, float64, etc.), `bigint_format`, `string_format` (email, url, uuid, etc.)\n * - **String pattern checks**: `regex`, `lowercase`, `uppercase`, `includes`, `starts_with`, `ends_with`\n * - **Other checks**: `property`, `mime_type`, `overwrite`\n *\n * @since 0.4.0\n */\nexport type ZodUnionCheck =\n | $ZodCheckLessThanDef\n | $ZodCheckGreaterThanDef\n | $ZodCheckMultipleOfDef\n | $ZodCheckNumberFormatDef\n | $ZodCheckBigIntFormatDef\n | $ZodCheckMaxSizeDef\n | $ZodCheckMinSizeDef\n | $ZodCheckSizeEqualsDef\n | $ZodCheckMaxLengthDef\n | $ZodCheckMinLengthDef\n | $ZodCheckLengthEqualsDef\n | $ZodCheckStringFormatDef\n | $ZodCheckRegexDef\n | $ZodCheckLowerCaseDef\n | $ZodCheckUpperCaseDef\n | $ZodCheckIncludesDef\n | $ZodCheckStartsWithDef\n | $ZodCheckEndsWithDef\n | $ZodCheckPropertyDef\n | $ZodCheckMimeTypeDef\n | $ZodCheckOverwriteDef;\n\n/**\n * Extracts all validation check definitions from a Zod schema field.\n *\n * This function analyzes a Zod field and returns all check definitions as defined\n * by Zod's internal structure. Returns Zod's raw check definition objects directly,\n * including all properties like `check`, `minimum`, `maximum`, `value`, `inclusive`,\n * `format`, `pattern`, etc.\n *\n * **Unwrapping behavior:** Automatically unwraps optional, nullable, and default layers.\n * For unions, checks only the first option (same as other schema utilities).\n *\n * **Supported check types:** Returns any of the 21 check types defined in {@link ZodUnionCheck},\n * including length, size, numeric range, format validation, string patterns, and more.\n *\n * @template T - The Zod type to extract checks from\n * @param field - The Zod field to analyze\n * @returns Array of Zod check definition objects (see {@link ZodUnionCheck})\n *\n * @example\n * String with length constraints\n * ```typescript\n * const username = z.string().min(3).max(20);\n * const checks = getFieldChecks(username);\n * // [\n * // { check: 'min_length', minimum: 3, when: [Function], ... },\n * // { check: 'max_length', maximum: 20, when: [Function], ... }\n * // ]\n * ```\n *\n * @example\n * Number with range constraints\n * ```typescript\n * const age = z.number().min(18).max(120);\n * const checks = getFieldChecks(age);\n * // [\n * // { check: 'greater_than', value: 18, inclusive: true, when: [Function], ... },\n * // { check: 'less_than', value: 120, inclusive: true, when: [Function], ... }\n * // ]\n * ```\n *\n * @example\n * Array with item count constraints\n * ```typescript\n * const tags = z.array(z.string()).min(1).max(5);\n * const checks = getFieldChecks(tags);\n * // [\n * // { check: 'min_length', minimum: 1, ... },\n * // { check: 'max_length', maximum: 5, ... }\n * // ]\n * ```\n *\n * @example\n * String with format validation\n * ```typescript\n * const email = z.string().email();\n * const checks = getFieldChecks(email);\n * // [\n * // { check: 'string_format', format: 'email', ... }\n * // ]\n * ```\n *\n * @example\n * Unwrapping optional/nullable/default layers\n * ```typescript\n * const bio = z.string().min(10).max(500).optional();\n * const checks = getFieldChecks(bio);\n * // [\n * // { check: 'min_length', minimum: 10, ... },\n * // { check: 'max_length', maximum: 500, ... }\n * // ]\n * ```\n *\n * @see {@link ZodUnionCheck} for all supported check types\n * @since 0.4.0\n */\nexport function getFieldChecks<T extends z.ZodTypeAny>(\n field: T,\n): Array<ZodUnionCheck> {\n const primitiveType = getPrimitiveType(field);\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return (primitiveType.def.checks?.map((check) => check._zod.def) ||\n []) as Array<ZodUnionCheck>;\n}\n\n/**\n * Recursively extracts the exact schema type from a discriminated union based on the discriminator value.\n *\n * This advanced TypeScript utility type walks through a union's options tuple at compile-time,\n * checking each schema against the discriminator field and value, and returns the exact matching\n * schema type (not a union of all options).\n *\n * **How it works:**\n * 1. Extracts the options tuple from the union using `infer Options`\n * 2. Destructure into head (`First`) and tail (`Rest`) using tuple pattern matching\n * 3. Checks if `First` is a ZodObject with the matching discriminator field and value\n * 4. If match found, returns `First` (the exact schema type)\n * 5. If no match, recursively processes `Rest` until a match is found or list is exhausted\n *\n * **Type narrowing magic:**\n * - Input: `z.discriminatedUnion('type', [SchemaA, SchemaB, SchemaC])`\n * - Discriminator value: `'a'` (matches SchemaA)\n * - Output: `SchemaA` (exact type, not `SchemaA | SchemaB | SchemaC`)\n *\n * @template TSchema - The ZodUnion or ZodDiscriminatedUnion type\n * @template TDiscriminatorKey - The discriminator field name (e.g., \"type\", \"mode\")\n * @template TDiscriminatorValue - The specific discriminator value (e.g., \"create\", \"edit\")\n * @returns The exact matching schema type, or `never` if no match found\n *\n * @example\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string() }),\n * z.object({ mode: z.literal('edit'), id: z.number() }),\n * ]);\n *\n * // Exact type: z.object({ mode: z.literal('create'), name: z.string() })\n * type CreateSchema = ExtractZodUnionMember<typeof schema, 'mode', 'create'>;\n * ```\n */\ntype ExtractZodUnionMember<\n TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.infer<TSchema> & string,\n TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] &\n util.Literal,\n> = TSchema extends z.ZodUnion<infer Options>\n ? Options extends readonly [\n infer First extends z.ZodTypeAny,\n ...infer Rest extends z.ZodTypeAny[],\n ]\n ? First extends z.ZodObject<infer Shape>\n ? TDiscriminatorKey extends keyof Shape\n ? Shape[TDiscriminatorKey] extends z.ZodLiteral<TDiscriminatorValue>\n ? First\n : Rest extends []\n ? never\n : TDiscriminatorValue extends $InferUnionOutput<\n Rest[number]\n >[TDiscriminatorKey]\n ? ExtractZodUnionMember<\n z.ZodUnion<Rest>,\n TDiscriminatorKey,\n TDiscriminatorValue\n >\n : never\n : Rest extends []\n ? never\n : TDiscriminatorValue extends $InferUnionOutput<\n Rest[number]\n >[TDiscriminatorKey]\n ? ExtractZodUnionMember<\n z.ZodUnion<Rest>,\n TDiscriminatorKey,\n TDiscriminatorValue\n >\n : never\n : never\n : never\n : never;\n\n/**\n * Extracts a specific schema option from a discriminated union based on the discriminator field value.\n *\n * This function finds and returns the **exact matching schema** from a `ZodDiscriminatedUnion` by\n * comparing the discriminator field value. It's used internally by {@link getSchemaDefaults} to\n * extract defaults from the correct schema variant in a discriminated union.\n *\n * **Key feature:** Returns the **exact schema type**, not a union of all options, thanks to the\n * {@link ExtractZodUnionMember} recursive type utility. This enables precise type narrowing at\n * compile-time based on the discriminator value.\n *\n * **How it works:**\n * 1. Iterates through all options in the discriminated union at runtime\n * 2. For each option, validates it's a ZodObject and checks if the discriminator field matches\n * 3. Returns the first matching schema with its exact type narrowed at compile-time\n * 4. Returns `undefined` if no match found or if option is not a ZodObject\n *\n * @template TSchema - The ZodUnion or ZodDiscriminatedUnion schema type\n * @template TDiscriminatorKey - The discriminator field name (string key of the inferred union type)\n * @template TDiscriminatorValue - The specific discriminator value to match (literal type)\n * @param params - Parameters object\n * @param params.schema - The discriminated union schema to search\n * @param params.discriminatorKey - The discriminator field name (e.g., \"mode\", \"type\")\n * @param params.discriminatorValue - The discriminator value to match (e.g., \"create\", \"edit\")\n * @returns The exact matching schema option (with precise type), or `undefined` if not found\n *\n * @example\n * Basic discriminated union - create/edit mode\n * ```typescript\n * const userSchema = z.discriminatedUnion('mode', [\n * z.object({\n * mode: z.literal('create'),\n * name: z.string(),\n * age: z.number().optional(),\n * }),\n * z.object({\n * mode: z.literal('edit'),\n * id: z.number(),\n * name: z.string().optional(),\n * }),\n * ]);\n *\n * // Extract the \"create\" schema\n * const createSchema = extractDiscriminatedSchema({\n * schema: userSchema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'create',\n * });\n * // Result: z.object({ mode: z.literal('create'), name: z.string(), age: z.number().optional() })\n *\n * // Extract the \"edit\" schema\n * const editSchema = extractDiscriminatedSchema({\n * schema: userSchema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'edit',\n * });\n * // Result: z.object({ mode: z.literal('edit'), id: z.number(), name: z.string().optional() })\n * ```\n *\n * @example\n * Type-based discrimination\n * ```typescript\n * const eventSchema = z.discriminatedUnion('type', [\n * z.object({ type: z.literal('click'), x: z.number(), y: z.number() }),\n * z.object({ type: z.literal('keypress'), key: z.string() }),\n * ]);\n *\n * const clickSchema = extractDiscriminatedSchema({\n * schema: eventSchema,\n * discriminatorKey: 'type',\n * discriminatorValue: 'click',\n * });\n * // Result: z.object({ type: z.literal('click'), x: z.number(), y: z.number() })\n * ```\n *\n * @example\n * Invalid discriminator value\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string() }),\n * ]);\n *\n * const result = extractDiscriminatedSchema({\n * schema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'invalid', // doesn't match any option\n * });\n * // Result: undefined\n * ```\n *\n * @example\n * Type narrowing demonstration\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string(), age: z.number() }),\n * z.object({ mode: z.literal('edit'), id: z.number(), bio: z.string() }),\n * ]);\n *\n * const createSchema = extractDiscriminatedSchema({\n * schema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'create',\n * });\n *\n * // Type is EXACTLY: z.object({ mode: z.literal('create'), name: z.string(), age: z.number() })\n * // NOT: z.object({ mode: ..., ... }) | z.object({ mode: ..., ... }) | undefined\n *\n * if (createSchema) {\n * createSchema.shape.age; // ✅ TypeScript knows 'age' exists\n * createSchema.shape.name; // ✅ TypeScript knows 'name' exists\n * // createSchema.shape.id; // ❌ TypeScript error: 'id' doesn't exist on 'create' schema\n * }\n * ```\n *\n * @see {@link getSchemaDefaults} for usage with discriminated unions\n * @see {@link ExtractZodUnionMember} for the type-level extraction logic\n * @since 0.6.0\n */\nexport const extractDiscriminatedSchema = <\n TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.infer<TSchema> & string,\n TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>({\n schema,\n key,\n value,\n}: {\n schema: TSchema;\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n}) => {\n return schema.options.find(\n (\n option,\n ): option is ExtractZodUnionMember<\n TSchema,\n TDiscriminatorKey,\n TDiscriminatorValue\n > => {\n if (option instanceof z.ZodObject) {\n const targetField = option.shape[String(key)];\n if (!targetField) return false;\n\n const parseResult = targetField.safeParse(value);\n return parseResult.success;\n }\n return false;\n },\n );\n};\n","import type { util } from 'zod';\nimport * as z from 'zod';\nimport {\n canUnwrap,\n extractDiscriminatedSchema,\n tryStripNullishOnly,\n} from './schema';\nimport type { Simplify } from './types';\n\n/**\n * Extracts the default value from a Zod field, recursively unwrapping optional, nullable, and union layers.\n *\n * This function traverses through wrapper types (like `ZodOptional`, `ZodNullable`, `ZodUnion`) to find\n * the underlying `ZodDefault` and returns its default value. If no default is found, returns `undefined`.\n *\n * **Union handling:** For union types, strips nullish types (null/undefined) first. If only one type\n * remains after stripping, extracts the default from that type. If multiple non-nullish types remain,\n * returns `undefined` (does not extract from any option).\n *\n * @template T - The Zod type to extract default from\n * @param field - The Zod field to extract default from\n * @returns The default value if present, undefined otherwise\n *\n * @example\n * Basic usage with default value\n * ```typescript\n * const field = z.string().default('hello');\n * const defaultValue = extractDefault(field);\n * // Result: 'hello'\n * ```\n *\n * @example\n * Unwrapping optional/nullable layers\n * ```typescript\n * const field = z.string().default('world').optional();\n * const defaultValue = extractDefault(field);\n * // Result: 'world' (unwraps optional to find default)\n * ```\n *\n * @example\n * Union with only nullish types stripped to single type\n * ```typescript\n * const field = z.union([z.string().default('hello'), z.null()]);\n * const defaultValue = extractDefault(field);\n * // Result: 'hello' (null stripped, leaving only string)\n * ```\n *\n * @example\n * Union with multiple non-nullish types\n * ```typescript\n * const field = z.union([z.string().default('hello'), z.number()]);\n * const defaultValue = extractDefault(field);\n * // Result: undefined (multiple non-nullish types - no default extracted)\n * ```\n *\n * @example\n * Field without default\n * ```typescript\n * const field = z.string().optional();\n * const defaultValue = extractDefault(field);\n * // Result: undefined\n * ```\n *\n * @see {@link getSchemaDefaults} for extracting defaults from entire schemas\n * @see {@link tryStripNullishOnly} for union nullish stripping logic\n * @since 0.1.0\n */\nexport function extractDefault<T extends z.ZodTypeAny>(\n field: T,\n): z.infer<T> | undefined {\n if (field instanceof z.ZodDefault) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field.def.defaultValue as z.infer<T>;\n }\n\n if (canUnwrap(field)) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefault(field.unwrap()) as z.infer<T>;\n }\n\n if (field instanceof z.ZodUnion) {\n const unwrapped = tryStripNullishOnly(field);\n if (unwrapped !== false) {\n // Successfully unwrapped to single type\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefault(unwrapped) as z.infer<T>;\n }\n\n // Multiple non-nullish types or all nullish - no default\n return undefined;\n }\n\n return undefined;\n}\n\n/**\n * Extracts default values from a Zod object schema, returning only fields with explicit `.default()`.\n *\n * This function traverses the schema and collects fields that have explicit default values.\n * Fields without defaults are excluded from the result.\n *\n * **Important:** Nested defaults are NOT extracted unless the parent object also has\n * an explicit `.default()`. This is by design to match Zod's default value behavior.\n *\n * **Component handling:** For form inputs without explicit defaults (like `z.string()` or `z.number()`),\n * use the `?? ''` pattern in your components: `<Input value={field.value ?? ''} />`\n *\n * @template TSchema - The Zod object schema type\n * @param targetSchema - The Zod object schema to extract defaults from\n * @returns A partial object containing only fields with explicit default values\n *\n * @example\n * Basic usage - only explicit defaults\n * ```typescript\n * const schema = z.object({\n * name: z.string(), // no default → NOT included\n * age: z.number(), // no default → NOT included\n * role: z.string().default('user'), // explicit default → included\n * count: z.number().default(0), // explicit default → included\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { role: 'user', count: 0 }\n * ```\n *\n * @example\n * Nested objects with defaults\n * ```typescript\n * const schema = z.object({\n * user: z.object({\n * name: z.string().default('Guest')\n * }).default({ name: 'Guest' }), // ✅ Extracted because parent has .default()\n *\n * settings: z.object({\n * theme: z.string().default('light')\n * }), // ❌ NOT extracted - parent has no .default()\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { user: { name: 'Guest' } }\n * ```\n *\n * @example\n * Unwrapping optional/nullable fields\n * ```typescript\n * const schema = z.object({\n * title: z.string().default('Untitled').optional(),\n * count: z.number().default(0).nullable(),\n * name: z.string().optional(), // no default → NOT included\n * age: z.number().optional(), // no default → NOT included\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { title: 'Untitled', count: 0 }\n * ```\n *\n * @example\n * Component usage for fields without defaults\n * ```typescript\n * // For string/number fields without defaults, handle in components:\n * <Input value={field.value ?? ''} />\n * <Input type=\"number\" value={field.value ?? ''} />\n * ```\n *\n * @see {@link extractDefault} for extracting defaults from individual fields\n * @since 0.1.0\n */\nexport function getSchemaDefaults<\n TSchema extends z.ZodObject | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.infer<TSchema> & string,\n TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>(\n schema: TSchema,\n options?: {\n discriminator?: {\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n };\n },\n): Simplify<Partial<z.infer<TSchema>>> {\n let targetSchema: z.ZodObject | undefined;\n if (schema instanceof z.ZodDiscriminatedUnion) {\n if (options?.discriminator) {\n targetSchema = extractDiscriminatedSchema({\n schema,\n ...options.discriminator,\n });\n }\n } else {\n targetSchema = schema;\n }\n\n const defaults: Record<string, unknown> = {};\n\n if (targetSchema) {\n for (const key in targetSchema.shape) {\n const field = targetSchema.shape[key];\n if (!field) continue;\n\n const defaultValue = extractDefault(field);\n if (defaultValue !== undefined) {\n defaults[key] = defaultValue;\n }\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return defaults as Partial<z.infer<TSchema>>;\n}\n","import { type util, z } from 'zod';\nimport { extractDiscriminatedSchema } from './schema';\n\nexport function extractFieldFromSchema<\n TSchema extends z.ZodObject | z.ZodDiscriminatedUnion,\n TName extends keyof Extract<\n Required<z.infer<TSchema>>,\n Record<TDiscriminatorKey, TDiscriminatorValue>\n >,\n TDiscriminatorKey extends keyof z.infer<TSchema> & string,\n TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>({\n schema,\n fieldName,\n discriminator,\n}: {\n schema: TSchema;\n fieldName: TName;\n discriminator?: {\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n };\n}) {\n let targetSchema: z.ZodObject | undefined;\n\n if (schema instanceof z.ZodDiscriminatedUnion) {\n if (discriminator) {\n targetSchema = extractDiscriminatedSchema({\n schema,\n ...discriminator,\n });\n }\n } else {\n targetSchema = schema;\n }\n\n if (!targetSchema) return undefined;\n\n const field: z.ZodType = targetSchema.shape[String(fieldName)];\n\n return field;\n}\n"]}
1
+ {"version":3,"sources":["../src/schema.ts","../src/defaults.ts","../src/field.ts"],"names":["z","z2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDO,SAAS,UACd,KAAA,EACqC;AACrC,EAAA,OAAO,QAAA,IAAY,KAAA,IAAS,OAAO,KAAA,CAAM,MAAA,KAAW,UAAA;AACtD;AAuCO,SAAS,oBAAoB,KAAA,EAAwC;AAC1E,EAAA,IAAI,iBAAmBA,YAAA,CAAA,QAAA,EAAU;AAC/B,IAAA,MAAM,YAAA,GAAe,CAAC,GAAG,KAAA,CAAM,IAAI,OAAO,CAAA;AAE1C,IAAA,MAAM,kBAAkB,YAAA,CAAa,MAAA;AAAA,MACnC,CAAC,MAAA,KACC,EAAE,MAAA,YAAoBA,YAAA,CAAA,OAAA,CAAA,IAAY,EAAE,MAAA,YAAoBA,YAAA,CAAA,YAAA;AAAA,KAC5D;AAGA,IAAA,MAAM,WAAA,GAAc,gBAAgB,CAAC,CAAA;AACrC,IAAA,IAAI,WAAA,IAAe,eAAA,CAAgB,MAAA,KAAW,CAAA,EAAG;AAC/C,MAAA,OAAO,WAAA;AAAA,IACT;AAAA,EACF;AAGA,EAAA,OAAO,KAAA;AACT;AA4DO,IAAM,gBAAA,GAAmB,CAC9B,KAAA,KACiB;AAEjB,EAAA,IAAI,iBAAmBA,YAAA,CAAA,QAAA,EAAU;AAC/B,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,IAAI,SAAA,CAAU,KAAK,CAAA,EAAG;AACpB,IAAA,OAAO,gBAAA,CAAiB,KAAA,CAAM,MAAA,EAAQ,CAAA;AAAA,EACxC;AAEA,EAAA,IAAI,iBAAmBA,YAAA,CAAA,QAAA,EAAU;AAC/B,IAAA,MAAM,SAAA,GAAY,oBAAoB,KAAK,CAAA;AAC3C,IAAA,IAAI,cAA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EAAO;AACpC,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,KAAA,CAAM,GAAG,CAAA;AACpC,MAAA,IAAI,CAAC,KAAA,EAAO;AAEZ,MAAA,MAAM,YAAA,GAAe,oBAAoB,KAAK,CAAA;AAC9C,MAAA,IAAI,iBAAiB,MAAA,EAAW;AAC9B,QAAA,QAAA,CAAS,GAAG,CAAA,GAAI,YAAA;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAGA,EAAA,OAAO,QAAA;AACT;ACvNO,SAAS,sBAAA,CASd;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAA,EAOG;AACD,EAAA,IAAI,YAAA;AAGJ,EAAA,MAAM,eAAA,GAAkB,iBAAiB,MAAM,CAAA;AAE/C,EAAA,IAAI,eAAA,YAA2BD,IAAE,qBAAA,EAAuB;AACtD,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,YAAA,GAAe,0BAAA,CAA2B,cAAA,CAAA;AAAA,QACxC,MAAA,EAAQ;AAAA,OAAA,EACL,aAAA,CACJ,CAAA;AAAA,IACH;AAAA,EACF,CAAA,MAAA,IAAW,eAAA,YAA2BA,GAAAA,CAAE,SAAA,EAAW;AACjD,IAAA,YAAA,GAAe,eAAA;AAAA,EACjB;AAEA,EAAA,IAAI,CAAC,cAAc,OAAO,MAAA;AAE1B,EAAA,MAAM,KAAA,GAAmB,YAAA,CAAa,KAAA,CAAM,MAAA,CAAO,SAAS,CAAC,CAAA;AAE7D,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["import type { util } from 'zod';\nimport * as z from 'zod';\nimport type {\n $InferUnionInput,\n $ZodCheckBigIntFormatDef,\n $ZodCheckEndsWithDef,\n $ZodCheckGreaterThanDef,\n $ZodCheckIncludesDef,\n $ZodCheckLengthEqualsDef,\n $ZodCheckLessThanDef,\n $ZodCheckLowerCaseDef,\n $ZodCheckMaxLengthDef,\n $ZodCheckMaxSizeDef,\n $ZodCheckMimeTypeDef,\n $ZodCheckMinLengthDef,\n $ZodCheckMinSizeDef,\n $ZodCheckMultipleOfDef,\n $ZodCheckNumberFormatDef,\n $ZodCheckOverwriteDef,\n $ZodCheckPropertyDef,\n $ZodCheckRegexDef,\n $ZodCheckSizeEqualsDef,\n $ZodCheckStartsWithDef,\n $ZodCheckStringFormatDef,\n $ZodCheckUpperCaseDef,\n} from 'zod/v4/core';\n\n/**\n * Type representing a Zod type that has an unwrap method\n */\ntype Unwrappable = { unwrap: () => z.ZodTypeAny };\n\n/**\n * Type guard to check if a Zod field can be unwrapped (has wrapper types like optional, nullable, default).\n *\n * This checks whether a Zod type has an `unwrap()` method, which is present on wrapper types\n * like `ZodOptional`, `ZodNullable`, `ZodDefault`, and others.\n *\n * @param field - The Zod field to check\n * @returns True if the field has an unwrap method, false otherwise\n *\n * @example\n * ```typescript\n * const optionalField = z.string().optional();\n * console.log(canUnwrap(optionalField)); // true\n *\n * const plainField = z.string();\n * console.log(canUnwrap(plainField)); // false\n * ```\n *\n * @since 0.1.0\n */\nexport function canUnwrap(\n field: z.ZodTypeAny,\n): field is z.ZodTypeAny & Unwrappable {\n return 'unwrap' in field && typeof field.unwrap === 'function';\n}\n\n/**\n * Attempts to strip nullish types from a union and return the single remaining type.\n *\n * This function filters out `ZodNull` and `ZodUndefined` from union types. If exactly\n * one type remains after filtering, it returns that unwrapped type. Otherwise, it returns\n * `false` to indicate the union couldn't be simplified to a single type.\n *\n * @param field - The Zod field to process\n * @returns The unwrapped type if only one remains, otherwise `false`\n *\n * @example\n * Union with only nullish types filtered - returns single type\n * ```typescript\n * const field = z.union([z.string(), z.null(), z.undefined()]);\n * const result = tryStripNullishOnly(field);\n * // Result: z.string() (unwrapped)\n * ```\n *\n * @example\n * Union with multiple non-nullish types - returns false\n * ```typescript\n * const field = z.union([z.string(), z.number()]);\n * const result = tryStripNullishOnly(field);\n * // Result: false (cannot simplify to single type)\n * ```\n *\n * @example\n * Non-union type - returns false\n * ```typescript\n * const field = z.string();\n * const result = tryStripNullishOnly(field);\n * // Result: false (not a union)\n * ```\n *\n * @see {@link getPrimitiveType} for unwrapping wrapper types\n * @since 0.5.0\n */\nexport function tryStripNullishOnly(field: z.ZodTypeAny): z.ZodType | false {\n if (field instanceof z.ZodUnion) {\n const unionOptions = [...field.def.options];\n\n const filteredOptions = unionOptions.filter(\n (option): option is z.ZodType =>\n !(option instanceof z.ZodNull) && !(option instanceof z.ZodUndefined),\n );\n\n // If exactly one option remains, return it unwrapped\n const firstOption = filteredOptions[0];\n if (firstOption && filteredOptions.length === 1) {\n return firstOption;\n }\n }\n\n // Not a union, or couldn't simplify to single type\n return false;\n}\n\n/**\n * Gets the underlying primitive type of a Zod field by recursively unwrapping wrapper types.\n *\n * This function removes wrapper layers (optional, nullable, default) to reveal the base type.\n * **Important:** It stops at array types without unwrapping them, treating arrays as primitives.\n *\n * **Union handling:** For union types, strips nullish types (null/undefined) first. If only one\n * type remains after stripping, unwraps to that type. If multiple non-nullish types remain,\n * returns the union as-is (does not unwrap).\n *\n * @template T - The Zod type to unwrap\n * @param field - The Zod field to unwrap\n * @returns The unwrapped primitive Zod type\n *\n * @example\n * Unwrapping to string primitive\n * ```typescript\n * const field = z.string().optional().nullable();\n * const primitive = getPrimitiveType(field);\n * // Result: z.string() (unwrapped all wrappers)\n * ```\n *\n * @example\n * Stopping at array type\n * ```typescript\n * const field = z.array(z.string()).optional();\n * const primitive = getPrimitiveType(field);\n * // Result: z.array(z.string()) (stops at array, doesn't unwrap it)\n * ```\n *\n * @example\n * Unwrapping defaults\n * ```typescript\n * const field = z.number().default(0).optional();\n * const primitive = getPrimitiveType(field);\n * // Result: z.number()\n * ```\n *\n * @example\n * Union with only nullish types stripped to single type\n * ```typescript\n * const field = z.union([z.string(), z.null()]);\n * const primitive = getPrimitiveType(field);\n * // Result: z.string() (null stripped, leaving only string)\n * ```\n *\n * @example\n * Union with multiple non-nullish types\n * ```typescript\n * const field = z.union([z.string(), z.number()]);\n * const primitive = getPrimitiveType(field);\n * // Result: z.union([z.string(), z.number()]) (returned as-is)\n * ```\n *\n * @see {@link canUnwrap} for checking if a field can be unwrapped\n * @see {@link tryStripNullishOnly} for union nullish stripping logic\n * @since 0.1.0\n */\nexport const getPrimitiveType = <T extends z.ZodType>(\n field: T,\n): z.ZodTypeAny => {\n // Stop at arrays - don't unwrap them\n if (field instanceof z.ZodArray) {\n return field;\n }\n\n if (canUnwrap(field)) {\n return getPrimitiveType(field.unwrap());\n }\n\n if (field instanceof z.ZodUnion) {\n const unwrapped = tryStripNullishOnly(field);\n if (unwrapped !== false) {\n return getPrimitiveType(unwrapped);\n }\n\n // Multiple non-nullish types or all nullish - return union as-is\n return field;\n }\n\n if (field instanceof z.ZodPipe && field.def.in instanceof z.ZodType) {\n return getPrimitiveType(field.def.in);\n }\n\n return field;\n};\n\ntype StripZodDefault<T> = T extends z.ZodDefault<infer Inner>\n ? StripZodDefault<Inner>\n : T extends z.ZodOptional<infer Inner>\n ? z.ZodOptional<StripZodDefault<Inner>>\n : T extends z.ZodNullable<infer Inner>\n ? z.ZodNullable<StripZodDefault<Inner>>\n : T;\n\n/**\n * Removes default values from a Zod field while preserving other wrapper types.\n *\n * This function recursively removes `ZodDefault` wrappers from a field, while maintaining\n * `optional()` and `nullable()` wrappers. Useful for scenarios where you want to check\n * field requirements without considering default values.\n *\n * @template T - The Zod type to process\n * @param field - The Zod field to remove defaults from\n * @returns The field without defaults but with optional/nullable preserved\n *\n * @example\n * Removing simple default\n * ```typescript\n * const field = z.string().default('hello');\n * const withoutDefault = removeDefault(field);\n * // Result: z.string()\n * ```\n *\n * @example\n * Preserving optional wrapper\n * ```typescript\n * const field = z.string().default('hello').optional();\n * const withoutDefault = removeDefault(field);\n * // Result: z.string().optional()\n * ```\n *\n * @example\n * Nested defaults\n * ```typescript\n * const field = z.string().default('inner').nullable().default('outer');\n * const withoutDefault = removeDefault(field);\n * // Result: z.string().nullable()\n * ```\n *\n * @see {@link requiresValidInput} for usage with requirement checking\n * @since 0.1.0\n */\nexport function removeDefault<T extends z.ZodType>(\n field: T,\n): StripZodDefault<T> {\n if (field instanceof z.ZodDefault) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field.unwrap() as StripZodDefault<T>;\n }\n\n if ('innerType' in field.def && field.def.innerType instanceof z.ZodType) {\n const inner = removeDefault(field.def.innerType);\n // Reconstruct the wrapper with the modified inner type\n if (field instanceof z.ZodOptional) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return inner.optional() as unknown as StripZodDefault<T>;\n }\n if (field instanceof z.ZodNullable) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return inner.nullable() as unknown as StripZodDefault<T>;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field as StripZodDefault<T>;\n}\n\n/**\n * Determines if a field will show validation errors when the user submits empty or invalid input.\n *\n * This is useful for form UIs to indicate which fields require valid user input (e.g., showing\n * asterisks, validation states). The key insight: **defaults are just initial values** - they\n * don't prevent validation errors if the user clears the field.\n *\n * **Real-world example:**\n * ```typescript\n * // Marital status field with default but validation rules\n * const maritalStatus = z.string().min(1).default('single');\n *\n * // Initial: field shows \"single\" (from default)\n * // User deletes the value → field is now empty string\n * // User submits form → validation fails because .min(1) rejects empty strings\n * // requiresValidInput(maritalStatus) → true (shows * indicator, validation error)\n * ```\n *\n * **How it works:**\n * 1. Removes `.default()` wrappers (defaults are initial values, not validation rules)\n * 2. Tests if the underlying schema accepts empty/invalid input:\n * - `undefined` (via `.optional()`)\n * - `null` (via `.nullable()`)\n * - Empty string (plain `z.string()` without `.min(1)` or `.nonempty()`)\n * - Empty array (plain `z.array()` without `.min(1)` or `.nonempty()`)\n * 3. Returns `true` if validation will fail, `false` if empty input is accepted\n *\n * @template T - The Zod type to check\n * @param field - The Zod field to check\n * @returns True if the field will show validation errors on empty/invalid input, false otherwise\n *\n * @example\n * User name field - required, no default\n * ```typescript\n * const userName = z.string().min(1);\n * requiresValidInput(userName); // true - will error if user submits empty\n * ```\n *\n * @example\n * Marital status - required WITH default\n * ```typescript\n * const maritalStatus = z.string().min(1).default('single');\n * requiresValidInput(maritalStatus); // true - will error if user clears and submits\n * ```\n *\n * @example\n * Age with default - requires valid input\n * ```typescript\n * const age = z.number().default(0);\n * requiresValidInput(age); // true - numbers reject empty strings\n * ```\n *\n * @example\n * Optional bio field - doesn't require input\n * ```typescript\n * const bio = z.string().optional();\n * requiresValidInput(bio); // false - user can leave empty\n * ```\n *\n * @example\n * String with default but NO validation - doesn't require input\n * ```typescript\n * const notes = z.string().default('N/A');\n * requiresValidInput(notes); // false - plain z.string() accepts empty strings\n * ```\n *\n * @example\n * Nullable field - doesn't require input\n * ```typescript\n * const middleName = z.string().nullable();\n * requiresValidInput(middleName); // false - user can leave null\n * ```\n *\n * @see {@link removeDefault} for understanding how defaults are handled\n * @see {@link getPrimitiveType} for understanding type unwrapping\n * @since 0.1.0\n */\nexport const requiresValidInput = <T extends z.ZodType>(field: T) => {\n const defaultRemovedField = removeDefault(field);\n if (!(defaultRemovedField instanceof z.ZodType)) {\n return false;\n }\n\n const undefinedResult = defaultRemovedField.safeParse(undefined).success;\n\n // Check if field accepts null (nullable)\n const nullResult = defaultRemovedField.safeParse(null).success;\n\n const primitiveType = getPrimitiveType(defaultRemovedField);\n\n const emptyStringResult =\n primitiveType.type === 'string' &&\n defaultRemovedField.safeParse('').success;\n\n const emptyArrayResult =\n primitiveType.type === 'array' && defaultRemovedField.safeParse([]).success;\n\n return (\n !undefinedResult && !nullResult && !emptyStringResult && !emptyArrayResult\n );\n};\n\n/**\n * Union type of all Zod check definition types.\n *\n * Includes all validation check types supported by Zod v4:\n * - **Length checks**: `min_length`, `max_length`, `length_equals` (strings, arrays)\n * - **Size checks**: `min_size`, `max_size`, `size_equals` (files, sets, maps)\n * - **Numeric checks**: `greater_than`, `less_than`, `multiple_of`\n * - **Format checks**: `number_format` (int32, float64, etc.), `bigint_format`, `string_format` (email, url, uuid, etc.)\n * - **String pattern checks**: `regex`, `lowercase`, `uppercase`, `includes`, `starts_with`, `ends_with`\n * - **Other checks**: `property`, `mime_type`, `overwrite`\n *\n * @since 0.4.0\n */\nexport type ZodUnionCheck =\n | $ZodCheckLessThanDef\n | $ZodCheckGreaterThanDef\n | $ZodCheckMultipleOfDef\n | $ZodCheckNumberFormatDef\n | $ZodCheckBigIntFormatDef\n | $ZodCheckMaxSizeDef\n | $ZodCheckMinSizeDef\n | $ZodCheckSizeEqualsDef\n | $ZodCheckMaxLengthDef\n | $ZodCheckMinLengthDef\n | $ZodCheckLengthEqualsDef\n | $ZodCheckStringFormatDef\n | $ZodCheckRegexDef\n | $ZodCheckLowerCaseDef\n | $ZodCheckUpperCaseDef\n | $ZodCheckIncludesDef\n | $ZodCheckStartsWithDef\n | $ZodCheckEndsWithDef\n | $ZodCheckPropertyDef\n | $ZodCheckMimeTypeDef\n | $ZodCheckOverwriteDef;\n\n/**\n * Extracts all validation check definitions from a Zod schema field.\n *\n * This function analyzes a Zod field and returns all check definitions as defined\n * by Zod's internal structure. Returns Zod's raw check definition objects directly,\n * including all properties like `check`, `minimum`, `maximum`, `value`, `inclusive`,\n * `format`, `pattern`, etc.\n *\n * **Unwrapping behavior:** Automatically unwraps optional, nullable, and default layers.\n * For unions, checks only the first option (same as other schema utilities).\n *\n * **Supported check types:** Returns any of the 21 check types defined in {@link ZodUnionCheck},\n * including length, size, numeric range, format validation, string patterns, and more.\n *\n * @template T - The Zod type to extract checks from\n * @param field - The Zod field to analyze\n * @returns Array of Zod check definition objects (see {@link ZodUnionCheck})\n *\n * @example\n * String with length constraints\n * ```typescript\n * const username = z.string().min(3).max(20);\n * const checks = getFieldChecks(username);\n * // [\n * // { check: 'min_length', minimum: 3, when: [Function], ... },\n * // { check: 'max_length', maximum: 20, when: [Function], ... }\n * // ]\n * ```\n *\n * @example\n * Number with range constraints\n * ```typescript\n * const age = z.number().min(18).max(120);\n * const checks = getFieldChecks(age);\n * // [\n * // { check: 'greater_than', value: 18, inclusive: true, when: [Function], ... },\n * // { check: 'less_than', value: 120, inclusive: true, when: [Function], ... }\n * // ]\n * ```\n *\n * @example\n * Array with item count constraints\n * ```typescript\n * const tags = z.array(z.string()).min(1).max(5);\n * const checks = getFieldChecks(tags);\n * // [\n * // { check: 'min_length', minimum: 1, ... },\n * // { check: 'max_length', maximum: 5, ... }\n * // ]\n * ```\n *\n * @example\n * String with format validation\n * ```typescript\n * const email = z.string().email();\n * const checks = getFieldChecks(email);\n * // [\n * // { check: 'string_format', format: 'email', ... }\n * // ]\n * ```\n *\n * @example\n * Unwrapping optional/nullable/default layers\n * ```typescript\n * const bio = z.string().min(10).max(500).optional();\n * const checks = getFieldChecks(bio);\n * // [\n * // { check: 'min_length', minimum: 10, ... },\n * // { check: 'max_length', maximum: 500, ... }\n * // ]\n * ```\n *\n * @see {@link ZodUnionCheck} for all supported check types\n * @since 0.4.0\n */\nexport function getFieldChecks<T extends z.ZodTypeAny>(\n field: T,\n): Array<ZodUnionCheck> {\n const primitiveType = getPrimitiveType(field);\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return (primitiveType.def.checks?.map((check) => check._zod.def) ||\n []) as Array<ZodUnionCheck>;\n}\n\n/**\n * Recursively extracts the exact schema type from a discriminated union based on the discriminator value.\n *\n * This advanced TypeScript utility type walks through a union's options tuple at compile-time,\n * checking each schema against the discriminator field and value, and returns the exact matching\n * schema type (not a union of all options).\n *\n * **How it works:**\n * 1. Extracts the options tuple from the union using `infer Options`\n * 2. Destructure into head (`First`) and tail (`Rest`) using tuple pattern matching\n * 3. Checks if `First` is a ZodObject with the matching discriminator field and value\n * 4. If match found, returns `First` (the exact schema type)\n * 5. If no match, recursively processes `Rest` until a match is found or list is exhausted\n *\n * **Type narrowing magic:**\n * - Input: `z.discriminatedUnion('type', [SchemaA, SchemaB, SchemaC])`\n * - Discriminator value: `'a'` (matches SchemaA)\n * - Output: `SchemaA` (exact type, not `SchemaA | SchemaB | SchemaC`)\n *\n * @template TSchema - The ZodUnion or ZodDiscriminatedUnion type\n * @template TDiscriminatorKey - The discriminator field name (e.g., \"type\", \"mode\")\n * @template TDiscriminatorValue - The specific discriminator value (e.g., \"create\", \"edit\")\n * @returns The exact matching schema type, or `never` if no match found\n *\n * @example\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string() }),\n * z.object({ mode: z.literal('edit'), id: z.number() }),\n * ]);\n *\n * // Exact type: z.object({ mode: z.literal('create'), name: z.string() })\n * type CreateSchema = ExtractZodUnionMember<typeof schema, 'mode', 'create'>;\n * ```\n */\ntype ExtractZodUnionMember<\n TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.input<TSchema> & string,\n TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] &\n util.Literal,\n> = TSchema extends z.ZodUnion<infer Options>\n ? Options extends readonly [\n infer First extends z.ZodTypeAny,\n ...infer Rest extends z.ZodTypeAny[],\n ]\n ? First extends z.ZodObject<infer Shape>\n ? TDiscriminatorKey extends keyof Shape\n ? Shape[TDiscriminatorKey] extends z.ZodLiteral<TDiscriminatorValue>\n ? First\n : Rest extends []\n ? never\n : TDiscriminatorValue extends $InferUnionInput<\n Rest[number]\n >[TDiscriminatorKey]\n ? ExtractZodUnionMember<\n z.ZodUnion<Rest>,\n TDiscriminatorKey,\n TDiscriminatorValue\n >\n : never\n : Rest extends []\n ? never\n : TDiscriminatorValue extends $InferUnionInput<\n Rest[number]\n >[TDiscriminatorKey]\n ? ExtractZodUnionMember<\n z.ZodUnion<Rest>,\n TDiscriminatorKey,\n TDiscriminatorValue\n >\n : never\n : never\n : never\n : never;\n\n/**\n * Extracts a specific schema option from a discriminated union based on the discriminator field value.\n *\n * This function finds and returns the **exact matching schema** from a `ZodDiscriminatedUnion` by\n * comparing the discriminator field value. It's used internally by {@link getSchemaDefaults} to\n * extract defaults from the correct schema variant in a discriminated union.\n *\n * **Key feature:** Returns the **exact schema type**, not a union of all options, thanks to the\n * {@link ExtractZodUnionMember} recursive type utility. This enables precise type narrowing at\n * compile-time based on the discriminator value.\n *\n * **How it works:**\n * 1. Iterates through all options in the discriminated union at runtime\n * 2. For each option, validates it's a ZodObject and checks if the discriminator field matches\n * 3. Returns the first matching schema with its exact type narrowed at compile-time\n * 4. Returns `undefined` if no match found or if option is not a ZodObject\n *\n * @template TSchema - The ZodUnion or ZodDiscriminatedUnion schema type\n * @template TDiscriminatorKey - The discriminator field name (string key of the inferred union type)\n * @template TDiscriminatorValue - The specific discriminator value to match (literal type)\n * @param params - Parameters object\n * @param params.schema - The discriminated union schema to search\n * @param params.discriminatorKey - The discriminator field name (e.g., \"mode\", \"type\")\n * @param params.discriminatorValue - The discriminator value to match (e.g., \"create\", \"edit\")\n * @returns The exact matching schema option (with precise type), or `undefined` if not found\n *\n * @example\n * Basic discriminated union - create/edit mode\n * ```typescript\n * const userSchema = z.discriminatedUnion('mode', [\n * z.object({\n * mode: z.literal('create'),\n * name: z.string(),\n * age: z.number().optional(),\n * }),\n * z.object({\n * mode: z.literal('edit'),\n * id: z.number(),\n * name: z.string().optional(),\n * }),\n * ]);\n *\n * // Extract the \"create\" schema\n * const createSchema = extractDiscriminatedSchema({\n * schema: userSchema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'create',\n * });\n * // Result: z.object({ mode: z.literal('create'), name: z.string(), age: z.number().optional() })\n *\n * // Extract the \"edit\" schema\n * const editSchema = extractDiscriminatedSchema({\n * schema: userSchema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'edit',\n * });\n * // Result: z.object({ mode: z.literal('edit'), id: z.number(), name: z.string().optional() })\n * ```\n *\n * @example\n * Type-based discrimination\n * ```typescript\n * const eventSchema = z.discriminatedUnion('type', [\n * z.object({ type: z.literal('click'), x: z.number(), y: z.number() }),\n * z.object({ type: z.literal('keypress'), key: z.string() }),\n * ]);\n *\n * const clickSchema = extractDiscriminatedSchema({\n * schema: eventSchema,\n * discriminatorKey: 'type',\n * discriminatorValue: 'click',\n * });\n * // Result: z.object({ type: z.literal('click'), x: z.number(), y: z.number() })\n * ```\n *\n * @example\n * Invalid discriminator value\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string() }),\n * ]);\n *\n * const result = extractDiscriminatedSchema({\n * schema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'invalid', // doesn't match any option\n * });\n * // Result: undefined\n * ```\n *\n * @example\n * Type narrowing demonstration\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string(), age: z.number() }),\n * z.object({ mode: z.literal('edit'), id: z.number(), bio: z.string() }),\n * ]);\n *\n * const createSchema = extractDiscriminatedSchema({\n * schema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'create',\n * });\n *\n * // Type is EXACTLY: z.object({ mode: z.literal('create'), name: z.string(), age: z.number() })\n * // NOT: z.object({ mode: ..., ... }) | z.object({ mode: ..., ... }) | undefined\n *\n * if (createSchema) {\n * createSchema.shape.age; // ✅ TypeScript knows 'age' exists\n * createSchema.shape.name; // ✅ TypeScript knows 'name' exists\n * // createSchema.shape.id; // ❌ TypeScript error: 'id' doesn't exist on 'create' schema\n * }\n * ```\n *\n * @see {@link getSchemaDefaults} for usage with discriminated unions\n * @see {@link ExtractZodUnionMember} for the type-level extraction logic\n * @since 0.6.0\n */\nexport const extractDiscriminatedSchema = <\n TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.input<TSchema> & string,\n TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>({\n schema,\n key,\n value,\n}: {\n schema: TSchema;\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n}) => {\n return schema.options.find(\n (\n option,\n ): option is ExtractZodUnionMember<\n TSchema,\n TDiscriminatorKey,\n TDiscriminatorValue\n > => {\n if (option instanceof z.ZodObject) {\n const targetField = option.shape[String(key)];\n if (!targetField) return false;\n\n const parseResult = targetField.safeParse(value);\n return parseResult.success;\n }\n return false;\n },\n );\n};\n","import type { util } from 'zod';\nimport * as z from 'zod';\nimport {\n canUnwrap,\n extractDiscriminatedSchema,\n getPrimitiveType,\n tryStripNullishOnly,\n} from './schema';\nimport type { Simplify } from './types';\n\n/**\n * Extracts the default value from a Zod field, recursively unwrapping optional, nullable, and union layers.\n *\n * This function traverses through wrapper types (like `ZodOptional`, `ZodNullable`, `ZodUnion`) to find\n * the underlying `ZodDefault` and returns its default value. If no default is found, returns `undefined`.\n *\n * **Union handling:** For union types, strips nullish types (null/undefined) first. If only one type\n * remains after stripping, extracts the default from that type. If multiple non-nullish types remain,\n * returns `undefined` (does not extract from any option).\n *\n * @template T - The Zod type to extract default from\n * @param field - The Zod field to extract default from\n * @returns The default value if present, undefined otherwise\n *\n * @example\n * Basic usage with default value\n * ```typescript\n * const field = z.string().default('hello');\n * const defaultValue = extractDefaultValue(field);\n * // Result: 'hello'\n * ```\n *\n * @example\n * Unwrapping optional/nullable layers\n * ```typescript\n * const field = z.string().default('world').optional();\n * const defaultValue = extractDefaultValue(field);\n * // Result: 'world' (unwraps optional to find default)\n * ```\n *\n * @example\n * Union with only nullish types stripped to single type\n * ```typescript\n * const field = z.union([z.string().default('hello'), z.null()]);\n * const defaultValue = extractDefaultValue(field);\n * // Result: 'hello' (null stripped, leaving only string)\n * ```\n *\n * @example\n * Union with multiple non-nullish types\n * ```typescript\n * const field = z.union([z.string().default('hello'), z.number()]);\n * const defaultValue = extractDefaultValue(field);\n * // Result: undefined (multiple non-nullish types - no default extracted)\n * ```\n *\n * @example\n * Field without default\n * ```typescript\n * const field = z.string().optional();\n * const defaultValue = extractDefaultValue(field);\n * // Result: undefined\n * ```\n *\n * @see {@link getSchemaDefaults} for extracting defaults from entire schemas\n * @see {@link tryStripNullishOnly} for union nullish stripping logic\n * @since 0.1.0\n */\nexport function extractDefaultValue<T extends z.ZodType>(\n field: T,\n): z.input<T> | undefined {\n if (field instanceof z.ZodDefault) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field.def.defaultValue as z.input<T>;\n }\n\n if (canUnwrap(field)) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefaultValue(field.unwrap()) as z.input<T>;\n }\n\n if (field instanceof z.ZodUnion) {\n const unwrapped = tryStripNullishOnly(field);\n if (unwrapped !== false) {\n // Successfully unwrapped to single type\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefaultValue(unwrapped) as z.input<T>;\n }\n\n // Multiple non-nullish types or all nullish - no default\n return undefined;\n }\n\n if (field instanceof z.ZodPipe && field.def.in instanceof z.ZodType) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefaultValue(field.def.in) as z.input<T>;\n }\n\n return undefined;\n}\n\n/**\n * Extracts default values from a Zod object schema, returning only fields with explicit `.default()`.\n *\n * This function traverses the schema and collects fields that have explicit default values.\n * Fields without defaults are excluded from the result.\n *\n * **Important:** Nested defaults are NOT extracted unless the parent object also has\n * an explicit `.default()`. This is by design to match Zod's default value behavior.\n *\n * **Component handling:** For form inputs without explicit defaults (like `z.string()` or `z.number()`),\n * use the `?? ''` pattern in your components: `<Input value={field.value ?? ''} />`\n *\n * @template TSchema - The Zod object schema type\n * @param targetSchema - The Zod object schema to extract defaults from\n * @returns A partial object containing only fields with explicit default values\n *\n * @example\n * Basic usage - only explicit defaults\n * ```typescript\n * const schema = z.object({\n * name: z.string(), // no default → NOT included\n * age: z.number(), // no default → NOT included\n * role: z.string().default('user'), // explicit default → included\n * count: z.number().default(0), // explicit default → included\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { role: 'user', count: 0 }\n * ```\n *\n * @example\n * Nested objects with defaults\n * ```typescript\n * const schema = z.object({\n * user: z.object({\n * name: z.string().default('Guest')\n * }).default({ name: 'Guest' }), // ✅ Extracted because parent has .default()\n *\n * settings: z.object({\n * theme: z.string().default('light')\n * }), // ❌ NOT extracted - parent has no .default()\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { user: { name: 'Guest' } }\n * ```\n *\n * @example\n * Unwrapping optional/nullable fields\n * ```typescript\n * const schema = z.object({\n * title: z.string().default('Untitled').optional(),\n * count: z.number().default(0).nullable(),\n * name: z.string().optional(), // no default → NOT included\n * age: z.number().optional(), // no default → NOT included\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { title: 'Untitled', count: 0 }\n * ```\n *\n * @example\n * Component usage for fields without defaults\n * ```typescript\n * // For string/number fields without defaults, handle in components:\n * <Input value={field.value ?? ''} />\n * <Input type=\"number\" value={field.value ?? ''} />\n * ```\n *\n * @see {@link extractDefaultValue} for extracting defaults from individual fields\n * @since 0.1.0\n */\nexport function getSchemaDefaults<\n TSchema extends z.ZodType,\n TDiscriminatorKey extends keyof z.input<TSchema> & string,\n TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>(\n schema: TSchema,\n options?: {\n discriminator?: {\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n };\n },\n): Simplify<Partial<z.input<TSchema>>> {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const primitiveSchema = getPrimitiveType(schema) as TSchema;\n\n let targetSchema: z.ZodObject | undefined;\n if (primitiveSchema instanceof z.ZodDiscriminatedUnion) {\n if (options?.discriminator) {\n targetSchema = extractDiscriminatedSchema({\n schema: primitiveSchema,\n ...options.discriminator,\n });\n }\n } else if (primitiveSchema instanceof z.ZodObject) {\n targetSchema = primitiveSchema;\n }\n\n const defaults: Record<string, unknown> = {};\n\n if (targetSchema) {\n for (const key in targetSchema.shape) {\n const field = targetSchema.shape[key];\n if (!field) continue;\n\n const defaultValue = extractDefaultValue(field);\n if (defaultValue !== undefined) {\n defaults[key] = defaultValue;\n }\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return defaults as Partial<z.input<TSchema>>;\n}\n","import { type util, z } from 'zod';\nimport { extractDiscriminatedSchema, getPrimitiveType } from './schema';\n\nexport function extractFieldFromSchema<\n TSchema extends z.ZodType,\n TName extends keyof Extract<\n Required<z.input<TSchema>>,\n Record<TDiscriminatorKey, TDiscriminatorValue>\n >,\n TDiscriminatorKey extends keyof z.input<TSchema> & string,\n TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>({\n schema,\n fieldName,\n discriminator,\n}: {\n schema: TSchema;\n fieldName: TName;\n discriminator?: {\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n };\n}) {\n let targetSchema: z.ZodObject | undefined;\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const primitiveSchema = getPrimitiveType(schema) as TSchema;\n\n if (primitiveSchema instanceof z.ZodDiscriminatedUnion) {\n if (discriminator) {\n targetSchema = extractDiscriminatedSchema({\n schema: primitiveSchema,\n ...discriminator,\n });\n }\n } else if (primitiveSchema instanceof z.ZodObject) {\n targetSchema = primitiveSchema;\n }\n\n if (!targetSchema) return undefined;\n\n const field: z.ZodType = targetSchema.shape[String(fieldName)];\n\n return field;\n}\n"]}
package/dist/index.mjs CHANGED
@@ -47,6 +47,9 @@ var getPrimitiveType = (field) => {
47
47
  }
48
48
  return field;
49
49
  }
50
+ if (field instanceof z.ZodPipe && field.def.in instanceof z.ZodType) {
51
+ return getPrimitiveType(field.def.in);
52
+ }
50
53
  return field;
51
54
  };
52
55
  function removeDefault(field) {
@@ -100,39 +103,43 @@ var extractDiscriminatedSchema = ({
100
103
  };
101
104
 
102
105
  // src/defaults.ts
103
- function extractDefault(field) {
106
+ function extractDefaultValue(field) {
104
107
  if (field instanceof z.ZodDefault) {
105
108
  return field.def.defaultValue;
106
109
  }
107
110
  if (canUnwrap(field)) {
108
- return extractDefault(field.unwrap());
111
+ return extractDefaultValue(field.unwrap());
109
112
  }
110
113
  if (field instanceof z.ZodUnion) {
111
114
  const unwrapped = tryStripNullishOnly(field);
112
115
  if (unwrapped !== false) {
113
- return extractDefault(unwrapped);
116
+ return extractDefaultValue(unwrapped);
114
117
  }
115
118
  return void 0;
116
119
  }
120
+ if (field instanceof z.ZodPipe && field.def.in instanceof z.ZodType) {
121
+ return extractDefaultValue(field.def.in);
122
+ }
117
123
  return void 0;
118
124
  }
119
125
  function getSchemaDefaults(schema, options) {
126
+ const primitiveSchema = getPrimitiveType(schema);
120
127
  let targetSchema;
121
- if (schema instanceof z.ZodDiscriminatedUnion) {
128
+ if (primitiveSchema instanceof z.ZodDiscriminatedUnion) {
122
129
  if (options == null ? void 0 : options.discriminator) {
123
130
  targetSchema = extractDiscriminatedSchema(__spreadValues({
124
- schema
131
+ schema: primitiveSchema
125
132
  }, options.discriminator));
126
133
  }
127
- } else {
128
- targetSchema = schema;
134
+ } else if (primitiveSchema instanceof z.ZodObject) {
135
+ targetSchema = primitiveSchema;
129
136
  }
130
137
  const defaults = {};
131
138
  if (targetSchema) {
132
139
  for (const key in targetSchema.shape) {
133
140
  const field = targetSchema.shape[key];
134
141
  if (!field) continue;
135
- const defaultValue = extractDefault(field);
142
+ const defaultValue = extractDefaultValue(field);
136
143
  if (defaultValue !== void 0) {
137
144
  defaults[key] = defaultValue;
138
145
  }
@@ -146,20 +153,21 @@ function extractFieldFromSchema({
146
153
  discriminator
147
154
  }) {
148
155
  let targetSchema;
149
- if (schema instanceof z$1.ZodDiscriminatedUnion) {
156
+ const primitiveSchema = getPrimitiveType(schema);
157
+ if (primitiveSchema instanceof z$1.ZodDiscriminatedUnion) {
150
158
  if (discriminator) {
151
159
  targetSchema = extractDiscriminatedSchema(__spreadValues({
152
- schema
160
+ schema: primitiveSchema
153
161
  }, discriminator));
154
162
  }
155
- } else {
156
- targetSchema = schema;
163
+ } else if (primitiveSchema instanceof z$1.ZodObject) {
164
+ targetSchema = primitiveSchema;
157
165
  }
158
166
  if (!targetSchema) return void 0;
159
167
  const field = targetSchema.shape[String(fieldName)];
160
168
  return field;
161
169
  }
162
170
 
163
- export { canUnwrap, extractDefault, extractDiscriminatedSchema, extractFieldFromSchema, getFieldChecks, getPrimitiveType, getSchemaDefaults, removeDefault, requiresValidInput, tryStripNullishOnly };
171
+ export { canUnwrap, extractDefaultValue, extractDiscriminatedSchema, extractFieldFromSchema, getFieldChecks, getPrimitiveType, getSchemaDefaults, removeDefault, requiresValidInput, tryStripNullishOnly };
164
172
  //# sourceMappingURL=index.mjs.map
165
173
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema.ts","../src/defaults.ts","../src/field.ts"],"names":["z2","z"],"mappings":";;;;;;;;;;;;;;;;;;;AAoDO,SAAS,UACd,KAAA,EACqC;AACrC,EAAA,OAAO,QAAA,IAAY,KAAA,IAAS,OAAO,KAAA,CAAM,MAAA,KAAW,UAAA;AACtD;AAuCO,SAAS,oBAAoB,KAAA,EAAwC;AAC1E,EAAA,IAAI,iBAAmB,CAAA,CAAA,QAAA,EAAU;AAC/B,IAAA,MAAM,YAAA,GAAe,CAAC,GAAG,KAAA,CAAM,IAAI,OAAO,CAAA;AAE1C,IAAA,MAAM,kBAAkB,YAAA,CAAa,MAAA;AAAA,MACnC,CAAC,MAAA,KACC,EAAE,MAAA,YAAoB,CAAA,CAAA,OAAA,CAAA,IAAY,EAAE,MAAA,YAAoB,CAAA,CAAA,YAAA;AAAA,KAC5D;AAGA,IAAA,MAAM,WAAA,GAAc,gBAAgB,CAAC,CAAA;AACrC,IAAA,IAAI,WAAA,IAAe,eAAA,CAAgB,MAAA,KAAW,CAAA,EAAG;AAC/C,MAAA,OAAO,WAAA;AAAA,IACT;AAAA,EACF;AAGA,EAAA,OAAO,KAAA;AACT;AA4DO,IAAM,gBAAA,GAAmB,CAC9B,KAAA,KACiB;AAEjB,EAAA,IAAI,iBAAmB,CAAA,CAAA,QAAA,EAAU;AAC/B,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,IAAI,SAAA,CAAU,KAAK,CAAA,EAAG;AACpB,IAAA,OAAO,gBAAA,CAAiB,KAAA,CAAM,MAAA,EAAQ,CAAA;AAAA,EAC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F,CAAA,EAOG;AACD,EAAA,IAAI,YAAA;AAEJ,EAAA,IAAI,MAAA,YAAkBC,IAAE,qBAAA,EAAuB;AAC7C,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,YAAA,GAAe,0BAAA,CAA2B,cAAA,CAAA;AAAA,QACxC;AAAA,OAAA,EACG,aAAA,CACJ,CAAA;AAAA,IACH;AAAA,EACF,CAAA,MAAO;AACL,IAAA,YAAA,GAAe,MAAA;AAAA,EACjB;AAEA,EAAA,IAAI,CAAC,cAAc,OAAO,MAAA;AAE1B,EAAA,MAAM,KAAA,GAAmB,YAAA,CAAa,KAAA,CAAM,MAAA,CAAO,SAAS,CAAC,CAAA;AAE7D,EAAA,OAAO,KAAA;AACT","file":"index.mjs","sourcesContent":["import type { util } from 'zod';\nimport * as z from 'zod';\nimport type {\n $InferUnionOutput,\n $ZodCheckBigIntFormatDef,\n $ZodCheckEndsWithDef,\n $ZodCheckGreaterThanDef,\n $ZodCheckIncludesDef,\n $ZodCheckLengthEqualsDef,\n $ZodCheckLessThanDef,\n $ZodCheckLowerCaseDef,\n $ZodCheckMaxLengthDef,\n $ZodCheckMaxSizeDef,\n $ZodCheckMimeTypeDef,\n $ZodCheckMinLengthDef,\n $ZodCheckMinSizeDef,\n $ZodCheckMultipleOfDef,\n $ZodCheckNumberFormatDef,\n $ZodCheckOverwriteDef,\n $ZodCheckPropertyDef,\n $ZodCheckRegexDef,\n $ZodCheckSizeEqualsDef,\n $ZodCheckStartsWithDef,\n $ZodCheckStringFormatDef,\n $ZodCheckUpperCaseDef,\n} from 'zod/v4/core';\n\n/**\n * Type representing a Zod type that has an unwrap method\n */\ntype Unwrappable = { unwrap: () => z.ZodTypeAny };\n\n/**\n * Type guard to check if a Zod field can be unwrapped (has wrapper types like optional, nullable, default).\n *\n * This checks whether a Zod type has an `unwrap()` method, which is present on wrapper types\n * like `ZodOptional`, `ZodNullable`, `ZodDefault`, and others.\n *\n * @param field - The Zod field to check\n * @returns True if the field has an unwrap method, false otherwise\n *\n * @example\n * ```typescript\n * const optionalField = z.string().optional();\n * console.log(canUnwrap(optionalField)); // true\n *\n * const plainField = z.string();\n * console.log(canUnwrap(plainField)); // false\n * ```\n *\n * @since 0.1.0\n */\nexport function canUnwrap(\n field: z.ZodTypeAny,\n): field is z.ZodTypeAny & Unwrappable {\n return 'unwrap' in field && typeof field.unwrap === 'function';\n}\n\n/**\n * Attempts to strip nullish types from a union and return the single remaining type.\n *\n * This function filters out `ZodNull` and `ZodUndefined` from union types. If exactly\n * one type remains after filtering, it returns that unwrapped type. Otherwise, it returns\n * `false` to indicate the union couldn't be simplified to a single type.\n *\n * @param field - The Zod field to process\n * @returns The unwrapped type if only one remains, otherwise `false`\n *\n * @example\n * Union with only nullish types filtered - returns single type\n * ```typescript\n * const field = z.union([z.string(), z.null(), z.undefined()]);\n * const result = tryStripNullishOnly(field);\n * // Result: z.string() (unwrapped)\n * ```\n *\n * @example\n * Union with multiple non-nullish types - returns false\n * ```typescript\n * const field = z.union([z.string(), z.number()]);\n * const result = tryStripNullishOnly(field);\n * // Result: false (cannot simplify to single type)\n * ```\n *\n * @example\n * Non-union type - returns false\n * ```typescript\n * const field = z.string();\n * const result = tryStripNullishOnly(field);\n * // Result: false (not a union)\n * ```\n *\n * @see {@link getPrimitiveType} for unwrapping wrapper types\n * @since 0.5.0\n */\nexport function tryStripNullishOnly(field: z.ZodTypeAny): z.ZodType | false {\n if (field instanceof z.ZodUnion) {\n const unionOptions = [...field.def.options];\n\n const filteredOptions = unionOptions.filter(\n (option): option is z.ZodType =>\n !(option instanceof z.ZodNull) && !(option instanceof z.ZodUndefined),\n );\n\n // If exactly one option remains, return it unwrapped\n const firstOption = filteredOptions[0];\n if (firstOption && filteredOptions.length === 1) {\n return firstOption;\n }\n }\n\n // Not a union, or couldn't simplify to single type\n return false;\n}\n\n/**\n * Gets the underlying primitive type of a Zod field by recursively unwrapping wrapper types.\n *\n * This function removes wrapper layers (optional, nullable, default) to reveal the base type.\n * **Important:** It stops at array types without unwrapping them, treating arrays as primitives.\n *\n * **Union handling:** For union types, strips nullish types (null/undefined) first. If only one\n * type remains after stripping, unwraps to that type. If multiple non-nullish types remain,\n * returns the union as-is (does not unwrap).\n *\n * @template T - The Zod type to unwrap\n * @param field - The Zod field to unwrap\n * @returns The unwrapped primitive Zod type\n *\n * @example\n * Unwrapping to string primitive\n * ```typescript\n * const field = z.string().optional().nullable();\n * const primitive = getPrimitiveType(field);\n * // Result: z.string() (unwrapped all wrappers)\n * ```\n *\n * @example\n * Stopping at array type\n * ```typescript\n * const field = z.array(z.string()).optional();\n * const primitive = getPrimitiveType(field);\n * // Result: z.array(z.string()) (stops at array, doesn't unwrap it)\n * ```\n *\n * @example\n * Unwrapping defaults\n * ```typescript\n * const field = z.number().default(0).optional();\n * const primitive = getPrimitiveType(field);\n * // Result: z.number()\n * ```\n *\n * @example\n * Union with only nullish types stripped to single type\n * ```typescript\n * const field = z.union([z.string(), z.null()]);\n * const primitive = getPrimitiveType(field);\n * // Result: z.string() (null stripped, leaving only string)\n * ```\n *\n * @example\n * Union with multiple non-nullish types\n * ```typescript\n * const field = z.union([z.string(), z.number()]);\n * const primitive = getPrimitiveType(field);\n * // Result: z.union([z.string(), z.number()]) (returned as-is)\n * ```\n *\n * @see {@link canUnwrap} for checking if a field can be unwrapped\n * @see {@link tryStripNullishOnly} for union nullish stripping logic\n * @since 0.1.0\n */\nexport const getPrimitiveType = <T extends z.ZodType>(\n field: T,\n): z.ZodTypeAny => {\n // Stop at arrays - don't unwrap them\n if (field instanceof z.ZodArray) {\n return field;\n }\n\n if (canUnwrap(field)) {\n return getPrimitiveType(field.unwrap());\n }\n\n if (field instanceof z.ZodUnion) {\n const unwrapped = tryStripNullishOnly(field);\n if (unwrapped !== false) {\n return getPrimitiveType(unwrapped);\n }\n\n // Multiple non-nullish types or all nullish - return union as-is\n return field;\n }\n\n return field;\n};\n\ntype StripZodDefault<T> = T extends z.ZodDefault<infer Inner>\n ? StripZodDefault<Inner>\n : T extends z.ZodOptional<infer Inner>\n ? z.ZodOptional<StripZodDefault<Inner>>\n : T extends z.ZodNullable<infer Inner>\n ? z.ZodNullable<StripZodDefault<Inner>>\n : T;\n\n/**\n * Removes default values from a Zod field while preserving other wrapper types.\n *\n * This function recursively removes `ZodDefault` wrappers from a field, while maintaining\n * `optional()` and `nullable()` wrappers. Useful for scenarios where you want to check\n * field requirements without considering default values.\n *\n * @template T - The Zod type to process\n * @param field - The Zod field to remove defaults from\n * @returns The field without defaults but with optional/nullable preserved\n *\n * @example\n * Removing simple default\n * ```typescript\n * const field = z.string().default('hello');\n * const withoutDefault = removeDefault(field);\n * // Result: z.string()\n * ```\n *\n * @example\n * Preserving optional wrapper\n * ```typescript\n * const field = z.string().default('hello').optional();\n * const withoutDefault = removeDefault(field);\n * // Result: z.string().optional()\n * ```\n *\n * @example\n * Nested defaults\n * ```typescript\n * const field = z.string().default('inner').nullable().default('outer');\n * const withoutDefault = removeDefault(field);\n * // Result: z.string().nullable()\n * ```\n *\n * @see {@link requiresValidInput} for usage with requirement checking\n * @since 0.1.0\n */\nexport function removeDefault<T extends z.ZodType>(\n field: T,\n): StripZodDefault<T> {\n if (field instanceof z.ZodDefault) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field.unwrap() as StripZodDefault<T>;\n }\n\n if ('innerType' in field.def && field.def.innerType instanceof z.ZodType) {\n const inner = removeDefault(field.def.innerType);\n // Reconstruct the wrapper with the modified inner type\n if (field instanceof z.ZodOptional) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return inner.optional() as unknown as StripZodDefault<T>;\n }\n if (field instanceof z.ZodNullable) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return inner.nullable() as unknown as StripZodDefault<T>;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field as StripZodDefault<T>;\n}\n\n/**\n * Determines if a field will show validation errors when the user submits empty or invalid input.\n *\n * This is useful for form UIs to indicate which fields require valid user input (e.g., showing\n * asterisks, validation states). The key insight: **defaults are just initial values** - they\n * don't prevent validation errors if the user clears the field.\n *\n * **Real-world example:**\n * ```typescript\n * // Marital status field with default but validation rules\n * const maritalStatus = z.string().min(1).default('single');\n *\n * // Initial: field shows \"single\" (from default)\n * // User deletes the value → field is now empty string\n * // User submits form → validation fails because .min(1) rejects empty strings\n * // requiresValidInput(maritalStatus) → true (shows * indicator, validation error)\n * ```\n *\n * **How it works:**\n * 1. Removes `.default()` wrappers (defaults are initial values, not validation rules)\n * 2. Tests if the underlying schema accepts empty/invalid input:\n * - `undefined` (via `.optional()`)\n * - `null` (via `.nullable()`)\n * - Empty string (plain `z.string()` without `.min(1)` or `.nonempty()`)\n * - Empty array (plain `z.array()` without `.min(1)` or `.nonempty()`)\n * 3. Returns `true` if validation will fail, `false` if empty input is accepted\n *\n * @template T - The Zod type to check\n * @param field - The Zod field to check\n * @returns True if the field will show validation errors on empty/invalid input, false otherwise\n *\n * @example\n * User name field - required, no default\n * ```typescript\n * const userName = z.string().min(1);\n * requiresValidInput(userName); // true - will error if user submits empty\n * ```\n *\n * @example\n * Marital status - required WITH default\n * ```typescript\n * const maritalStatus = z.string().min(1).default('single');\n * requiresValidInput(maritalStatus); // true - will error if user clears and submits\n * ```\n *\n * @example\n * Age with default - requires valid input\n * ```typescript\n * const age = z.number().default(0);\n * requiresValidInput(age); // true - numbers reject empty strings\n * ```\n *\n * @example\n * Optional bio field - doesn't require input\n * ```typescript\n * const bio = z.string().optional();\n * requiresValidInput(bio); // false - user can leave empty\n * ```\n *\n * @example\n * String with default but NO validation - doesn't require input\n * ```typescript\n * const notes = z.string().default('N/A');\n * requiresValidInput(notes); // false - plain z.string() accepts empty strings\n * ```\n *\n * @example\n * Nullable field - doesn't require input\n * ```typescript\n * const middleName = z.string().nullable();\n * requiresValidInput(middleName); // false - user can leave null\n * ```\n *\n * @see {@link removeDefault} for understanding how defaults are handled\n * @see {@link getPrimitiveType} for understanding type unwrapping\n * @since 0.1.0\n */\nexport const requiresValidInput = <T extends z.ZodType>(field: T) => {\n const defaultRemovedField = removeDefault(field);\n if (!(defaultRemovedField instanceof z.ZodType)) {\n return false;\n }\n\n const undefinedResult = defaultRemovedField.safeParse(undefined).success;\n\n // Check if field accepts null (nullable)\n const nullResult = defaultRemovedField.safeParse(null).success;\n\n const primitiveType = getPrimitiveType(defaultRemovedField);\n\n const emptyStringResult =\n primitiveType.type === 'string' &&\n defaultRemovedField.safeParse('').success;\n\n const emptyArrayResult =\n primitiveType.type === 'array' && defaultRemovedField.safeParse([]).success;\n\n return (\n !undefinedResult && !nullResult && !emptyStringResult && !emptyArrayResult\n );\n};\n\n/**\n * Union type of all Zod check definition types.\n *\n * Includes all validation check types supported by Zod v4:\n * - **Length checks**: `min_length`, `max_length`, `length_equals` (strings, arrays)\n * - **Size checks**: `min_size`, `max_size`, `size_equals` (files, sets, maps)\n * - **Numeric checks**: `greater_than`, `less_than`, `multiple_of`\n * - **Format checks**: `number_format` (int32, float64, etc.), `bigint_format`, `string_format` (email, url, uuid, etc.)\n * - **String pattern checks**: `regex`, `lowercase`, `uppercase`, `includes`, `starts_with`, `ends_with`\n * - **Other checks**: `property`, `mime_type`, `overwrite`\n *\n * @since 0.4.0\n */\nexport type ZodUnionCheck =\n | $ZodCheckLessThanDef\n | $ZodCheckGreaterThanDef\n | $ZodCheckMultipleOfDef\n | $ZodCheckNumberFormatDef\n | $ZodCheckBigIntFormatDef\n | $ZodCheckMaxSizeDef\n | $ZodCheckMinSizeDef\n | $ZodCheckSizeEqualsDef\n | $ZodCheckMaxLengthDef\n | $ZodCheckMinLengthDef\n | $ZodCheckLengthEqualsDef\n | $ZodCheckStringFormatDef\n | $ZodCheckRegexDef\n | $ZodCheckLowerCaseDef\n | $ZodCheckUpperCaseDef\n | $ZodCheckIncludesDef\n | $ZodCheckStartsWithDef\n | $ZodCheckEndsWithDef\n | $ZodCheckPropertyDef\n | $ZodCheckMimeTypeDef\n | $ZodCheckOverwriteDef;\n\n/**\n * Extracts all validation check definitions from a Zod schema field.\n *\n * This function analyzes a Zod field and returns all check definitions as defined\n * by Zod's internal structure. Returns Zod's raw check definition objects directly,\n * including all properties like `check`, `minimum`, `maximum`, `value`, `inclusive`,\n * `format`, `pattern`, etc.\n *\n * **Unwrapping behavior:** Automatically unwraps optional, nullable, and default layers.\n * For unions, checks only the first option (same as other schema utilities).\n *\n * **Supported check types:** Returns any of the 21 check types defined in {@link ZodUnionCheck},\n * including length, size, numeric range, format validation, string patterns, and more.\n *\n * @template T - The Zod type to extract checks from\n * @param field - The Zod field to analyze\n * @returns Array of Zod check definition objects (see {@link ZodUnionCheck})\n *\n * @example\n * String with length constraints\n * ```typescript\n * const username = z.string().min(3).max(20);\n * const checks = getFieldChecks(username);\n * // [\n * // { check: 'min_length', minimum: 3, when: [Function], ... },\n * // { check: 'max_length', maximum: 20, when: [Function], ... }\n * // ]\n * ```\n *\n * @example\n * Number with range constraints\n * ```typescript\n * const age = z.number().min(18).max(120);\n * const checks = getFieldChecks(age);\n * // [\n * // { check: 'greater_than', value: 18, inclusive: true, when: [Function], ... },\n * // { check: 'less_than', value: 120, inclusive: true, when: [Function], ... }\n * // ]\n * ```\n *\n * @example\n * Array with item count constraints\n * ```typescript\n * const tags = z.array(z.string()).min(1).max(5);\n * const checks = getFieldChecks(tags);\n * // [\n * // { check: 'min_length', minimum: 1, ... },\n * // { check: 'max_length', maximum: 5, ... }\n * // ]\n * ```\n *\n * @example\n * String with format validation\n * ```typescript\n * const email = z.string().email();\n * const checks = getFieldChecks(email);\n * // [\n * // { check: 'string_format', format: 'email', ... }\n * // ]\n * ```\n *\n * @example\n * Unwrapping optional/nullable/default layers\n * ```typescript\n * const bio = z.string().min(10).max(500).optional();\n * const checks = getFieldChecks(bio);\n * // [\n * // { check: 'min_length', minimum: 10, ... },\n * // { check: 'max_length', maximum: 500, ... }\n * // ]\n * ```\n *\n * @see {@link ZodUnionCheck} for all supported check types\n * @since 0.4.0\n */\nexport function getFieldChecks<T extends z.ZodTypeAny>(\n field: T,\n): Array<ZodUnionCheck> {\n const primitiveType = getPrimitiveType(field);\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return (primitiveType.def.checks?.map((check) => check._zod.def) ||\n []) as Array<ZodUnionCheck>;\n}\n\n/**\n * Recursively extracts the exact schema type from a discriminated union based on the discriminator value.\n *\n * This advanced TypeScript utility type walks through a union's options tuple at compile-time,\n * checking each schema against the discriminator field and value, and returns the exact matching\n * schema type (not a union of all options).\n *\n * **How it works:**\n * 1. Extracts the options tuple from the union using `infer Options`\n * 2. Destructure into head (`First`) and tail (`Rest`) using tuple pattern matching\n * 3. Checks if `First` is a ZodObject with the matching discriminator field and value\n * 4. If match found, returns `First` (the exact schema type)\n * 5. If no match, recursively processes `Rest` until a match is found or list is exhausted\n *\n * **Type narrowing magic:**\n * - Input: `z.discriminatedUnion('type', [SchemaA, SchemaB, SchemaC])`\n * - Discriminator value: `'a'` (matches SchemaA)\n * - Output: `SchemaA` (exact type, not `SchemaA | SchemaB | SchemaC`)\n *\n * @template TSchema - The ZodUnion or ZodDiscriminatedUnion type\n * @template TDiscriminatorKey - The discriminator field name (e.g., \"type\", \"mode\")\n * @template TDiscriminatorValue - The specific discriminator value (e.g., \"create\", \"edit\")\n * @returns The exact matching schema type, or `never` if no match found\n *\n * @example\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string() }),\n * z.object({ mode: z.literal('edit'), id: z.number() }),\n * ]);\n *\n * // Exact type: z.object({ mode: z.literal('create'), name: z.string() })\n * type CreateSchema = ExtractZodUnionMember<typeof schema, 'mode', 'create'>;\n * ```\n */\ntype ExtractZodUnionMember<\n TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.infer<TSchema> & string,\n TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] &\n util.Literal,\n> = TSchema extends z.ZodUnion<infer Options>\n ? Options extends readonly [\n infer First extends z.ZodTypeAny,\n ...infer Rest extends z.ZodTypeAny[],\n ]\n ? First extends z.ZodObject<infer Shape>\n ? TDiscriminatorKey extends keyof Shape\n ? Shape[TDiscriminatorKey] extends z.ZodLiteral<TDiscriminatorValue>\n ? First\n : Rest extends []\n ? never\n : TDiscriminatorValue extends $InferUnionOutput<\n Rest[number]\n >[TDiscriminatorKey]\n ? ExtractZodUnionMember<\n z.ZodUnion<Rest>,\n TDiscriminatorKey,\n TDiscriminatorValue\n >\n : never\n : Rest extends []\n ? never\n : TDiscriminatorValue extends $InferUnionOutput<\n Rest[number]\n >[TDiscriminatorKey]\n ? ExtractZodUnionMember<\n z.ZodUnion<Rest>,\n TDiscriminatorKey,\n TDiscriminatorValue\n >\n : never\n : never\n : never\n : never;\n\n/**\n * Extracts a specific schema option from a discriminated union based on the discriminator field value.\n *\n * This function finds and returns the **exact matching schema** from a `ZodDiscriminatedUnion` by\n * comparing the discriminator field value. It's used internally by {@link getSchemaDefaults} to\n * extract defaults from the correct schema variant in a discriminated union.\n *\n * **Key feature:** Returns the **exact schema type**, not a union of all options, thanks to the\n * {@link ExtractZodUnionMember} recursive type utility. This enables precise type narrowing at\n * compile-time based on the discriminator value.\n *\n * **How it works:**\n * 1. Iterates through all options in the discriminated union at runtime\n * 2. For each option, validates it's a ZodObject and checks if the discriminator field matches\n * 3. Returns the first matching schema with its exact type narrowed at compile-time\n * 4. Returns `undefined` if no match found or if option is not a ZodObject\n *\n * @template TSchema - The ZodUnion or ZodDiscriminatedUnion schema type\n * @template TDiscriminatorKey - The discriminator field name (string key of the inferred union type)\n * @template TDiscriminatorValue - The specific discriminator value to match (literal type)\n * @param params - Parameters object\n * @param params.schema - The discriminated union schema to search\n * @param params.discriminatorKey - The discriminator field name (e.g., \"mode\", \"type\")\n * @param params.discriminatorValue - The discriminator value to match (e.g., \"create\", \"edit\")\n * @returns The exact matching schema option (with precise type), or `undefined` if not found\n *\n * @example\n * Basic discriminated union - create/edit mode\n * ```typescript\n * const userSchema = z.discriminatedUnion('mode', [\n * z.object({\n * mode: z.literal('create'),\n * name: z.string(),\n * age: z.number().optional(),\n * }),\n * z.object({\n * mode: z.literal('edit'),\n * id: z.number(),\n * name: z.string().optional(),\n * }),\n * ]);\n *\n * // Extract the \"create\" schema\n * const createSchema = extractDiscriminatedSchema({\n * schema: userSchema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'create',\n * });\n * // Result: z.object({ mode: z.literal('create'), name: z.string(), age: z.number().optional() })\n *\n * // Extract the \"edit\" schema\n * const editSchema = extractDiscriminatedSchema({\n * schema: userSchema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'edit',\n * });\n * // Result: z.object({ mode: z.literal('edit'), id: z.number(), name: z.string().optional() })\n * ```\n *\n * @example\n * Type-based discrimination\n * ```typescript\n * const eventSchema = z.discriminatedUnion('type', [\n * z.object({ type: z.literal('click'), x: z.number(), y: z.number() }),\n * z.object({ type: z.literal('keypress'), key: z.string() }),\n * ]);\n *\n * const clickSchema = extractDiscriminatedSchema({\n * schema: eventSchema,\n * discriminatorKey: 'type',\n * discriminatorValue: 'click',\n * });\n * // Result: z.object({ type: z.literal('click'), x: z.number(), y: z.number() })\n * ```\n *\n * @example\n * Invalid discriminator value\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string() }),\n * ]);\n *\n * const result = extractDiscriminatedSchema({\n * schema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'invalid', // doesn't match any option\n * });\n * // Result: undefined\n * ```\n *\n * @example\n * Type narrowing demonstration\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string(), age: z.number() }),\n * z.object({ mode: z.literal('edit'), id: z.number(), bio: z.string() }),\n * ]);\n *\n * const createSchema = extractDiscriminatedSchema({\n * schema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'create',\n * });\n *\n * // Type is EXACTLY: z.object({ mode: z.literal('create'), name: z.string(), age: z.number() })\n * // NOT: z.object({ mode: ..., ... }) | z.object({ mode: ..., ... }) | undefined\n *\n * if (createSchema) {\n * createSchema.shape.age; // ✅ TypeScript knows 'age' exists\n * createSchema.shape.name; // ✅ TypeScript knows 'name' exists\n * // createSchema.shape.id; // ❌ TypeScript error: 'id' doesn't exist on 'create' schema\n * }\n * ```\n *\n * @see {@link getSchemaDefaults} for usage with discriminated unions\n * @see {@link ExtractZodUnionMember} for the type-level extraction logic\n * @since 0.6.0\n */\nexport const extractDiscriminatedSchema = <\n TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.infer<TSchema> & string,\n TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>({\n schema,\n key,\n value,\n}: {\n schema: TSchema;\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n}) => {\n return schema.options.find(\n (\n option,\n ): option is ExtractZodUnionMember<\n TSchema,\n TDiscriminatorKey,\n TDiscriminatorValue\n > => {\n if (option instanceof z.ZodObject) {\n const targetField = option.shape[String(key)];\n if (!targetField) return false;\n\n const parseResult = targetField.safeParse(value);\n return parseResult.success;\n }\n return false;\n },\n );\n};\n","import type { util } from 'zod';\nimport * as z from 'zod';\nimport {\n canUnwrap,\n extractDiscriminatedSchema,\n tryStripNullishOnly,\n} from './schema';\nimport type { Simplify } from './types';\n\n/**\n * Extracts the default value from a Zod field, recursively unwrapping optional, nullable, and union layers.\n *\n * This function traverses through wrapper types (like `ZodOptional`, `ZodNullable`, `ZodUnion`) to find\n * the underlying `ZodDefault` and returns its default value. If no default is found, returns `undefined`.\n *\n * **Union handling:** For union types, strips nullish types (null/undefined) first. If only one type\n * remains after stripping, extracts the default from that type. If multiple non-nullish types remain,\n * returns `undefined` (does not extract from any option).\n *\n * @template T - The Zod type to extract default from\n * @param field - The Zod field to extract default from\n * @returns The default value if present, undefined otherwise\n *\n * @example\n * Basic usage with default value\n * ```typescript\n * const field = z.string().default('hello');\n * const defaultValue = extractDefault(field);\n * // Result: 'hello'\n * ```\n *\n * @example\n * Unwrapping optional/nullable layers\n * ```typescript\n * const field = z.string().default('world').optional();\n * const defaultValue = extractDefault(field);\n * // Result: 'world' (unwraps optional to find default)\n * ```\n *\n * @example\n * Union with only nullish types stripped to single type\n * ```typescript\n * const field = z.union([z.string().default('hello'), z.null()]);\n * const defaultValue = extractDefault(field);\n * // Result: 'hello' (null stripped, leaving only string)\n * ```\n *\n * @example\n * Union with multiple non-nullish types\n * ```typescript\n * const field = z.union([z.string().default('hello'), z.number()]);\n * const defaultValue = extractDefault(field);\n * // Result: undefined (multiple non-nullish types - no default extracted)\n * ```\n *\n * @example\n * Field without default\n * ```typescript\n * const field = z.string().optional();\n * const defaultValue = extractDefault(field);\n * // Result: undefined\n * ```\n *\n * @see {@link getSchemaDefaults} for extracting defaults from entire schemas\n * @see {@link tryStripNullishOnly} for union nullish stripping logic\n * @since 0.1.0\n */\nexport function extractDefault<T extends z.ZodTypeAny>(\n field: T,\n): z.infer<T> | undefined {\n if (field instanceof z.ZodDefault) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field.def.defaultValue as z.infer<T>;\n }\n\n if (canUnwrap(field)) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefault(field.unwrap()) as z.infer<T>;\n }\n\n if (field instanceof z.ZodUnion) {\n const unwrapped = tryStripNullishOnly(field);\n if (unwrapped !== false) {\n // Successfully unwrapped to single type\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefault(unwrapped) as z.infer<T>;\n }\n\n // Multiple non-nullish types or all nullish - no default\n return undefined;\n }\n\n return undefined;\n}\n\n/**\n * Extracts default values from a Zod object schema, returning only fields with explicit `.default()`.\n *\n * This function traverses the schema and collects fields that have explicit default values.\n * Fields without defaults are excluded from the result.\n *\n * **Important:** Nested defaults are NOT extracted unless the parent object also has\n * an explicit `.default()`. This is by design to match Zod's default value behavior.\n *\n * **Component handling:** For form inputs without explicit defaults (like `z.string()` or `z.number()`),\n * use the `?? ''` pattern in your components: `<Input value={field.value ?? ''} />`\n *\n * @template TSchema - The Zod object schema type\n * @param targetSchema - The Zod object schema to extract defaults from\n * @returns A partial object containing only fields with explicit default values\n *\n * @example\n * Basic usage - only explicit defaults\n * ```typescript\n * const schema = z.object({\n * name: z.string(), // no default → NOT included\n * age: z.number(), // no default → NOT included\n * role: z.string().default('user'), // explicit default → included\n * count: z.number().default(0), // explicit default → included\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { role: 'user', count: 0 }\n * ```\n *\n * @example\n * Nested objects with defaults\n * ```typescript\n * const schema = z.object({\n * user: z.object({\n * name: z.string().default('Guest')\n * }).default({ name: 'Guest' }), // ✅ Extracted because parent has .default()\n *\n * settings: z.object({\n * theme: z.string().default('light')\n * }), // ❌ NOT extracted - parent has no .default()\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { user: { name: 'Guest' } }\n * ```\n *\n * @example\n * Unwrapping optional/nullable fields\n * ```typescript\n * const schema = z.object({\n * title: z.string().default('Untitled').optional(),\n * count: z.number().default(0).nullable(),\n * name: z.string().optional(), // no default → NOT included\n * age: z.number().optional(), // no default → NOT included\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { title: 'Untitled', count: 0 }\n * ```\n *\n * @example\n * Component usage for fields without defaults\n * ```typescript\n * // For string/number fields without defaults, handle in components:\n * <Input value={field.value ?? ''} />\n * <Input type=\"number\" value={field.value ?? ''} />\n * ```\n *\n * @see {@link extractDefault} for extracting defaults from individual fields\n * @since 0.1.0\n */\nexport function getSchemaDefaults<\n TSchema extends z.ZodObject | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.infer<TSchema> & string,\n TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>(\n schema: TSchema,\n options?: {\n discriminator?: {\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n };\n },\n): Simplify<Partial<z.infer<TSchema>>> {\n let targetSchema: z.ZodObject | undefined;\n if (schema instanceof z.ZodDiscriminatedUnion) {\n if (options?.discriminator) {\n targetSchema = extractDiscriminatedSchema({\n schema,\n ...options.discriminator,\n });\n }\n } else {\n targetSchema = schema;\n }\n\n const defaults: Record<string, unknown> = {};\n\n if (targetSchema) {\n for (const key in targetSchema.shape) {\n const field = targetSchema.shape[key];\n if (!field) continue;\n\n const defaultValue = extractDefault(field);\n if (defaultValue !== undefined) {\n defaults[key] = defaultValue;\n }\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return defaults as Partial<z.infer<TSchema>>;\n}\n","import { type util, z } from 'zod';\nimport { extractDiscriminatedSchema } from './schema';\n\nexport function extractFieldFromSchema<\n TSchema extends z.ZodObject | z.ZodDiscriminatedUnion,\n TName extends keyof Extract<\n Required<z.infer<TSchema>>,\n Record<TDiscriminatorKey, TDiscriminatorValue>\n >,\n TDiscriminatorKey extends keyof z.infer<TSchema> & string,\n TDiscriminatorValue extends z.infer<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>({\n schema,\n fieldName,\n discriminator,\n}: {\n schema: TSchema;\n fieldName: TName;\n discriminator?: {\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n };\n}) {\n let targetSchema: z.ZodObject | undefined;\n\n if (schema instanceof z.ZodDiscriminatedUnion) {\n if (discriminator) {\n targetSchema = extractDiscriminatedSchema({\n schema,\n ...discriminator,\n });\n }\n } else {\n targetSchema = schema;\n }\n\n if (!targetSchema) return undefined;\n\n const field: z.ZodType = targetSchema.shape[String(fieldName)];\n\n return field;\n}\n"]}
1
+ {"version":3,"sources":["../src/schema.ts","../src/defaults.ts","../src/field.ts"],"names":["z2","z"],"mappings":";;;;;;;;;;;;;;;;;;;AAoDO,SAAS,UACd,KAAA,EACqC;AACrC,EAAA,OAAO,QAAA,IAAY,KAAA,IAAS,OAAO,KAAA,CAAM,MAAA,KAAW,UAAA;AACtD;AAuCO,SAAS,oBAAoB,KAAA,EAAwC;AAC1E,EAAA,I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ACA;AACF,CAAA,EAOG;AACD,EAAA,IAAI,YAAA;AAGJ,EAAA,MAAM,eAAA,GAAkB,iBAAiB,MAAM,CAAA;AAE/C,EAAA,IAAI,eAAA,YAA2BC,IAAE,qBAAA,EAAuB;AACtD,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,YAAA,GAAe,0BAAA,CAA2B,cAAA,CAAA;AAAA,QACxC,MAAA,EAAQ;AAAA,OAAA,EACL,aAAA,CACJ,CAAA;AAAA,IACH;AAAA,EACF,CAAA,MAAA,IAAW,eAAA,YAA2BA,GAAAA,CAAE,SAAA,EAAW;AACjD,IAAA,YAAA,GAAe,eAAA;AAAA,EACjB;AAEA,EAAA,IAAI,CAAC,cAAc,OAAO,MAAA;AAE1B,EAAA,MAAM,KAAA,GAAmB,YAAA,CAAa,KAAA,CAAM,MAAA,CAAO,SAAS,CAAC,CAAA;AAE7D,EAAA,OAAO,KAAA;AACT","file":"index.mjs","sourcesContent":["import type { util } from 'zod';\nimport * as z from 'zod';\nimport type {\n $InferUnionInput,\n $ZodCheckBigIntFormatDef,\n $ZodCheckEndsWithDef,\n $ZodCheckGreaterThanDef,\n $ZodCheckIncludesDef,\n $ZodCheckLengthEqualsDef,\n $ZodCheckLessThanDef,\n $ZodCheckLowerCaseDef,\n $ZodCheckMaxLengthDef,\n $ZodCheckMaxSizeDef,\n $ZodCheckMimeTypeDef,\n $ZodCheckMinLengthDef,\n $ZodCheckMinSizeDef,\n $ZodCheckMultipleOfDef,\n $ZodCheckNumberFormatDef,\n $ZodCheckOverwriteDef,\n $ZodCheckPropertyDef,\n $ZodCheckRegexDef,\n $ZodCheckSizeEqualsDef,\n $ZodCheckStartsWithDef,\n $ZodCheckStringFormatDef,\n $ZodCheckUpperCaseDef,\n} from 'zod/v4/core';\n\n/**\n * Type representing a Zod type that has an unwrap method\n */\ntype Unwrappable = { unwrap: () => z.ZodTypeAny };\n\n/**\n * Type guard to check if a Zod field can be unwrapped (has wrapper types like optional, nullable, default).\n *\n * This checks whether a Zod type has an `unwrap()` method, which is present on wrapper types\n * like `ZodOptional`, `ZodNullable`, `ZodDefault`, and others.\n *\n * @param field - The Zod field to check\n * @returns True if the field has an unwrap method, false otherwise\n *\n * @example\n * ```typescript\n * const optionalField = z.string().optional();\n * console.log(canUnwrap(optionalField)); // true\n *\n * const plainField = z.string();\n * console.log(canUnwrap(plainField)); // false\n * ```\n *\n * @since 0.1.0\n */\nexport function canUnwrap(\n field: z.ZodTypeAny,\n): field is z.ZodTypeAny & Unwrappable {\n return 'unwrap' in field && typeof field.unwrap === 'function';\n}\n\n/**\n * Attempts to strip nullish types from a union and return the single remaining type.\n *\n * This function filters out `ZodNull` and `ZodUndefined` from union types. If exactly\n * one type remains after filtering, it returns that unwrapped type. Otherwise, it returns\n * `false` to indicate the union couldn't be simplified to a single type.\n *\n * @param field - The Zod field to process\n * @returns The unwrapped type if only one remains, otherwise `false`\n *\n * @example\n * Union with only nullish types filtered - returns single type\n * ```typescript\n * const field = z.union([z.string(), z.null(), z.undefined()]);\n * const result = tryStripNullishOnly(field);\n * // Result: z.string() (unwrapped)\n * ```\n *\n * @example\n * Union with multiple non-nullish types - returns false\n * ```typescript\n * const field = z.union([z.string(), z.number()]);\n * const result = tryStripNullishOnly(field);\n * // Result: false (cannot simplify to single type)\n * ```\n *\n * @example\n * Non-union type - returns false\n * ```typescript\n * const field = z.string();\n * const result = tryStripNullishOnly(field);\n * // Result: false (not a union)\n * ```\n *\n * @see {@link getPrimitiveType} for unwrapping wrapper types\n * @since 0.5.0\n */\nexport function tryStripNullishOnly(field: z.ZodTypeAny): z.ZodType | false {\n if (field instanceof z.ZodUnion) {\n const unionOptions = [...field.def.options];\n\n const filteredOptions = unionOptions.filter(\n (option): option is z.ZodType =>\n !(option instanceof z.ZodNull) && !(option instanceof z.ZodUndefined),\n );\n\n // If exactly one option remains, return it unwrapped\n const firstOption = filteredOptions[0];\n if (firstOption && filteredOptions.length === 1) {\n return firstOption;\n }\n }\n\n // Not a union, or couldn't simplify to single type\n return false;\n}\n\n/**\n * Gets the underlying primitive type of a Zod field by recursively unwrapping wrapper types.\n *\n * This function removes wrapper layers (optional, nullable, default) to reveal the base type.\n * **Important:** It stops at array types without unwrapping them, treating arrays as primitives.\n *\n * **Union handling:** For union types, strips nullish types (null/undefined) first. If only one\n * type remains after stripping, unwraps to that type. If multiple non-nullish types remain,\n * returns the union as-is (does not unwrap).\n *\n * @template T - The Zod type to unwrap\n * @param field - The Zod field to unwrap\n * @returns The unwrapped primitive Zod type\n *\n * @example\n * Unwrapping to string primitive\n * ```typescript\n * const field = z.string().optional().nullable();\n * const primitive = getPrimitiveType(field);\n * // Result: z.string() (unwrapped all wrappers)\n * ```\n *\n * @example\n * Stopping at array type\n * ```typescript\n * const field = z.array(z.string()).optional();\n * const primitive = getPrimitiveType(field);\n * // Result: z.array(z.string()) (stops at array, doesn't unwrap it)\n * ```\n *\n * @example\n * Unwrapping defaults\n * ```typescript\n * const field = z.number().default(0).optional();\n * const primitive = getPrimitiveType(field);\n * // Result: z.number()\n * ```\n *\n * @example\n * Union with only nullish types stripped to single type\n * ```typescript\n * const field = z.union([z.string(), z.null()]);\n * const primitive = getPrimitiveType(field);\n * // Result: z.string() (null stripped, leaving only string)\n * ```\n *\n * @example\n * Union with multiple non-nullish types\n * ```typescript\n * const field = z.union([z.string(), z.number()]);\n * const primitive = getPrimitiveType(field);\n * // Result: z.union([z.string(), z.number()]) (returned as-is)\n * ```\n *\n * @see {@link canUnwrap} for checking if a field can be unwrapped\n * @see {@link tryStripNullishOnly} for union nullish stripping logic\n * @since 0.1.0\n */\nexport const getPrimitiveType = <T extends z.ZodType>(\n field: T,\n): z.ZodTypeAny => {\n // Stop at arrays - don't unwrap them\n if (field instanceof z.ZodArray) {\n return field;\n }\n\n if (canUnwrap(field)) {\n return getPrimitiveType(field.unwrap());\n }\n\n if (field instanceof z.ZodUnion) {\n const unwrapped = tryStripNullishOnly(field);\n if (unwrapped !== false) {\n return getPrimitiveType(unwrapped);\n }\n\n // Multiple non-nullish types or all nullish - return union as-is\n return field;\n }\n\n if (field instanceof z.ZodPipe && field.def.in instanceof z.ZodType) {\n return getPrimitiveType(field.def.in);\n }\n\n return field;\n};\n\ntype StripZodDefault<T> = T extends z.ZodDefault<infer Inner>\n ? StripZodDefault<Inner>\n : T extends z.ZodOptional<infer Inner>\n ? z.ZodOptional<StripZodDefault<Inner>>\n : T extends z.ZodNullable<infer Inner>\n ? z.ZodNullable<StripZodDefault<Inner>>\n : T;\n\n/**\n * Removes default values from a Zod field while preserving other wrapper types.\n *\n * This function recursively removes `ZodDefault` wrappers from a field, while maintaining\n * `optional()` and `nullable()` wrappers. Useful for scenarios where you want to check\n * field requirements without considering default values.\n *\n * @template T - The Zod type to process\n * @param field - The Zod field to remove defaults from\n * @returns The field without defaults but with optional/nullable preserved\n *\n * @example\n * Removing simple default\n * ```typescript\n * const field = z.string().default('hello');\n * const withoutDefault = removeDefault(field);\n * // Result: z.string()\n * ```\n *\n * @example\n * Preserving optional wrapper\n * ```typescript\n * const field = z.string().default('hello').optional();\n * const withoutDefault = removeDefault(field);\n * // Result: z.string().optional()\n * ```\n *\n * @example\n * Nested defaults\n * ```typescript\n * const field = z.string().default('inner').nullable().default('outer');\n * const withoutDefault = removeDefault(field);\n * // Result: z.string().nullable()\n * ```\n *\n * @see {@link requiresValidInput} for usage with requirement checking\n * @since 0.1.0\n */\nexport function removeDefault<T extends z.ZodType>(\n field: T,\n): StripZodDefault<T> {\n if (field instanceof z.ZodDefault) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field.unwrap() as StripZodDefault<T>;\n }\n\n if ('innerType' in field.def && field.def.innerType instanceof z.ZodType) {\n const inner = removeDefault(field.def.innerType);\n // Reconstruct the wrapper with the modified inner type\n if (field instanceof z.ZodOptional) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return inner.optional() as unknown as StripZodDefault<T>;\n }\n if (field instanceof z.ZodNullable) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return inner.nullable() as unknown as StripZodDefault<T>;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field as StripZodDefault<T>;\n}\n\n/**\n * Determines if a field will show validation errors when the user submits empty or invalid input.\n *\n * This is useful for form UIs to indicate which fields require valid user input (e.g., showing\n * asterisks, validation states). The key insight: **defaults are just initial values** - they\n * don't prevent validation errors if the user clears the field.\n *\n * **Real-world example:**\n * ```typescript\n * // Marital status field with default but validation rules\n * const maritalStatus = z.string().min(1).default('single');\n *\n * // Initial: field shows \"single\" (from default)\n * // User deletes the value → field is now empty string\n * // User submits form → validation fails because .min(1) rejects empty strings\n * // requiresValidInput(maritalStatus) → true (shows * indicator, validation error)\n * ```\n *\n * **How it works:**\n * 1. Removes `.default()` wrappers (defaults are initial values, not validation rules)\n * 2. Tests if the underlying schema accepts empty/invalid input:\n * - `undefined` (via `.optional()`)\n * - `null` (via `.nullable()`)\n * - Empty string (plain `z.string()` without `.min(1)` or `.nonempty()`)\n * - Empty array (plain `z.array()` without `.min(1)` or `.nonempty()`)\n * 3. Returns `true` if validation will fail, `false` if empty input is accepted\n *\n * @template T - The Zod type to check\n * @param field - The Zod field to check\n * @returns True if the field will show validation errors on empty/invalid input, false otherwise\n *\n * @example\n * User name field - required, no default\n * ```typescript\n * const userName = z.string().min(1);\n * requiresValidInput(userName); // true - will error if user submits empty\n * ```\n *\n * @example\n * Marital status - required WITH default\n * ```typescript\n * const maritalStatus = z.string().min(1).default('single');\n * requiresValidInput(maritalStatus); // true - will error if user clears and submits\n * ```\n *\n * @example\n * Age with default - requires valid input\n * ```typescript\n * const age = z.number().default(0);\n * requiresValidInput(age); // true - numbers reject empty strings\n * ```\n *\n * @example\n * Optional bio field - doesn't require input\n * ```typescript\n * const bio = z.string().optional();\n * requiresValidInput(bio); // false - user can leave empty\n * ```\n *\n * @example\n * String with default but NO validation - doesn't require input\n * ```typescript\n * const notes = z.string().default('N/A');\n * requiresValidInput(notes); // false - plain z.string() accepts empty strings\n * ```\n *\n * @example\n * Nullable field - doesn't require input\n * ```typescript\n * const middleName = z.string().nullable();\n * requiresValidInput(middleName); // false - user can leave null\n * ```\n *\n * @see {@link removeDefault} for understanding how defaults are handled\n * @see {@link getPrimitiveType} for understanding type unwrapping\n * @since 0.1.0\n */\nexport const requiresValidInput = <T extends z.ZodType>(field: T) => {\n const defaultRemovedField = removeDefault(field);\n if (!(defaultRemovedField instanceof z.ZodType)) {\n return false;\n }\n\n const undefinedResult = defaultRemovedField.safeParse(undefined).success;\n\n // Check if field accepts null (nullable)\n const nullResult = defaultRemovedField.safeParse(null).success;\n\n const primitiveType = getPrimitiveType(defaultRemovedField);\n\n const emptyStringResult =\n primitiveType.type === 'string' &&\n defaultRemovedField.safeParse('').success;\n\n const emptyArrayResult =\n primitiveType.type === 'array' && defaultRemovedField.safeParse([]).success;\n\n return (\n !undefinedResult && !nullResult && !emptyStringResult && !emptyArrayResult\n );\n};\n\n/**\n * Union type of all Zod check definition types.\n *\n * Includes all validation check types supported by Zod v4:\n * - **Length checks**: `min_length`, `max_length`, `length_equals` (strings, arrays)\n * - **Size checks**: `min_size`, `max_size`, `size_equals` (files, sets, maps)\n * - **Numeric checks**: `greater_than`, `less_than`, `multiple_of`\n * - **Format checks**: `number_format` (int32, float64, etc.), `bigint_format`, `string_format` (email, url, uuid, etc.)\n * - **String pattern checks**: `regex`, `lowercase`, `uppercase`, `includes`, `starts_with`, `ends_with`\n * - **Other checks**: `property`, `mime_type`, `overwrite`\n *\n * @since 0.4.0\n */\nexport type ZodUnionCheck =\n | $ZodCheckLessThanDef\n | $ZodCheckGreaterThanDef\n | $ZodCheckMultipleOfDef\n | $ZodCheckNumberFormatDef\n | $ZodCheckBigIntFormatDef\n | $ZodCheckMaxSizeDef\n | $ZodCheckMinSizeDef\n | $ZodCheckSizeEqualsDef\n | $ZodCheckMaxLengthDef\n | $ZodCheckMinLengthDef\n | $ZodCheckLengthEqualsDef\n | $ZodCheckStringFormatDef\n | $ZodCheckRegexDef\n | $ZodCheckLowerCaseDef\n | $ZodCheckUpperCaseDef\n | $ZodCheckIncludesDef\n | $ZodCheckStartsWithDef\n | $ZodCheckEndsWithDef\n | $ZodCheckPropertyDef\n | $ZodCheckMimeTypeDef\n | $ZodCheckOverwriteDef;\n\n/**\n * Extracts all validation check definitions from a Zod schema field.\n *\n * This function analyzes a Zod field and returns all check definitions as defined\n * by Zod's internal structure. Returns Zod's raw check definition objects directly,\n * including all properties like `check`, `minimum`, `maximum`, `value`, `inclusive`,\n * `format`, `pattern`, etc.\n *\n * **Unwrapping behavior:** Automatically unwraps optional, nullable, and default layers.\n * For unions, checks only the first option (same as other schema utilities).\n *\n * **Supported check types:** Returns any of the 21 check types defined in {@link ZodUnionCheck},\n * including length, size, numeric range, format validation, string patterns, and more.\n *\n * @template T - The Zod type to extract checks from\n * @param field - The Zod field to analyze\n * @returns Array of Zod check definition objects (see {@link ZodUnionCheck})\n *\n * @example\n * String with length constraints\n * ```typescript\n * const username = z.string().min(3).max(20);\n * const checks = getFieldChecks(username);\n * // [\n * // { check: 'min_length', minimum: 3, when: [Function], ... },\n * // { check: 'max_length', maximum: 20, when: [Function], ... }\n * // ]\n * ```\n *\n * @example\n * Number with range constraints\n * ```typescript\n * const age = z.number().min(18).max(120);\n * const checks = getFieldChecks(age);\n * // [\n * // { check: 'greater_than', value: 18, inclusive: true, when: [Function], ... },\n * // { check: 'less_than', value: 120, inclusive: true, when: [Function], ... }\n * // ]\n * ```\n *\n * @example\n * Array with item count constraints\n * ```typescript\n * const tags = z.array(z.string()).min(1).max(5);\n * const checks = getFieldChecks(tags);\n * // [\n * // { check: 'min_length', minimum: 1, ... },\n * // { check: 'max_length', maximum: 5, ... }\n * // ]\n * ```\n *\n * @example\n * String with format validation\n * ```typescript\n * const email = z.string().email();\n * const checks = getFieldChecks(email);\n * // [\n * // { check: 'string_format', format: 'email', ... }\n * // ]\n * ```\n *\n * @example\n * Unwrapping optional/nullable/default layers\n * ```typescript\n * const bio = z.string().min(10).max(500).optional();\n * const checks = getFieldChecks(bio);\n * // [\n * // { check: 'min_length', minimum: 10, ... },\n * // { check: 'max_length', maximum: 500, ... }\n * // ]\n * ```\n *\n * @see {@link ZodUnionCheck} for all supported check types\n * @since 0.4.0\n */\nexport function getFieldChecks<T extends z.ZodTypeAny>(\n field: T,\n): Array<ZodUnionCheck> {\n const primitiveType = getPrimitiveType(field);\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return (primitiveType.def.checks?.map((check) => check._zod.def) ||\n []) as Array<ZodUnionCheck>;\n}\n\n/**\n * Recursively extracts the exact schema type from a discriminated union based on the discriminator value.\n *\n * This advanced TypeScript utility type walks through a union's options tuple at compile-time,\n * checking each schema against the discriminator field and value, and returns the exact matching\n * schema type (not a union of all options).\n *\n * **How it works:**\n * 1. Extracts the options tuple from the union using `infer Options`\n * 2. Destructure into head (`First`) and tail (`Rest`) using tuple pattern matching\n * 3. Checks if `First` is a ZodObject with the matching discriminator field and value\n * 4. If match found, returns `First` (the exact schema type)\n * 5. If no match, recursively processes `Rest` until a match is found or list is exhausted\n *\n * **Type narrowing magic:**\n * - Input: `z.discriminatedUnion('type', [SchemaA, SchemaB, SchemaC])`\n * - Discriminator value: `'a'` (matches SchemaA)\n * - Output: `SchemaA` (exact type, not `SchemaA | SchemaB | SchemaC`)\n *\n * @template TSchema - The ZodUnion or ZodDiscriminatedUnion type\n * @template TDiscriminatorKey - The discriminator field name (e.g., \"type\", \"mode\")\n * @template TDiscriminatorValue - The specific discriminator value (e.g., \"create\", \"edit\")\n * @returns The exact matching schema type, or `never` if no match found\n *\n * @example\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string() }),\n * z.object({ mode: z.literal('edit'), id: z.number() }),\n * ]);\n *\n * // Exact type: z.object({ mode: z.literal('create'), name: z.string() })\n * type CreateSchema = ExtractZodUnionMember<typeof schema, 'mode', 'create'>;\n * ```\n */\ntype ExtractZodUnionMember<\n TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.input<TSchema> & string,\n TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] &\n util.Literal,\n> = TSchema extends z.ZodUnion<infer Options>\n ? Options extends readonly [\n infer First extends z.ZodTypeAny,\n ...infer Rest extends z.ZodTypeAny[],\n ]\n ? First extends z.ZodObject<infer Shape>\n ? TDiscriminatorKey extends keyof Shape\n ? Shape[TDiscriminatorKey] extends z.ZodLiteral<TDiscriminatorValue>\n ? First\n : Rest extends []\n ? never\n : TDiscriminatorValue extends $InferUnionInput<\n Rest[number]\n >[TDiscriminatorKey]\n ? ExtractZodUnionMember<\n z.ZodUnion<Rest>,\n TDiscriminatorKey,\n TDiscriminatorValue\n >\n : never\n : Rest extends []\n ? never\n : TDiscriminatorValue extends $InferUnionInput<\n Rest[number]\n >[TDiscriminatorKey]\n ? ExtractZodUnionMember<\n z.ZodUnion<Rest>,\n TDiscriminatorKey,\n TDiscriminatorValue\n >\n : never\n : never\n : never\n : never;\n\n/**\n * Extracts a specific schema option from a discriminated union based on the discriminator field value.\n *\n * This function finds and returns the **exact matching schema** from a `ZodDiscriminatedUnion` by\n * comparing the discriminator field value. It's used internally by {@link getSchemaDefaults} to\n * extract defaults from the correct schema variant in a discriminated union.\n *\n * **Key feature:** Returns the **exact schema type**, not a union of all options, thanks to the\n * {@link ExtractZodUnionMember} recursive type utility. This enables precise type narrowing at\n * compile-time based on the discriminator value.\n *\n * **How it works:**\n * 1. Iterates through all options in the discriminated union at runtime\n * 2. For each option, validates it's a ZodObject and checks if the discriminator field matches\n * 3. Returns the first matching schema with its exact type narrowed at compile-time\n * 4. Returns `undefined` if no match found or if option is not a ZodObject\n *\n * @template TSchema - The ZodUnion or ZodDiscriminatedUnion schema type\n * @template TDiscriminatorKey - The discriminator field name (string key of the inferred union type)\n * @template TDiscriminatorValue - The specific discriminator value to match (literal type)\n * @param params - Parameters object\n * @param params.schema - The discriminated union schema to search\n * @param params.discriminatorKey - The discriminator field name (e.g., \"mode\", \"type\")\n * @param params.discriminatorValue - The discriminator value to match (e.g., \"create\", \"edit\")\n * @returns The exact matching schema option (with precise type), or `undefined` if not found\n *\n * @example\n * Basic discriminated union - create/edit mode\n * ```typescript\n * const userSchema = z.discriminatedUnion('mode', [\n * z.object({\n * mode: z.literal('create'),\n * name: z.string(),\n * age: z.number().optional(),\n * }),\n * z.object({\n * mode: z.literal('edit'),\n * id: z.number(),\n * name: z.string().optional(),\n * }),\n * ]);\n *\n * // Extract the \"create\" schema\n * const createSchema = extractDiscriminatedSchema({\n * schema: userSchema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'create',\n * });\n * // Result: z.object({ mode: z.literal('create'), name: z.string(), age: z.number().optional() })\n *\n * // Extract the \"edit\" schema\n * const editSchema = extractDiscriminatedSchema({\n * schema: userSchema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'edit',\n * });\n * // Result: z.object({ mode: z.literal('edit'), id: z.number(), name: z.string().optional() })\n * ```\n *\n * @example\n * Type-based discrimination\n * ```typescript\n * const eventSchema = z.discriminatedUnion('type', [\n * z.object({ type: z.literal('click'), x: z.number(), y: z.number() }),\n * z.object({ type: z.literal('keypress'), key: z.string() }),\n * ]);\n *\n * const clickSchema = extractDiscriminatedSchema({\n * schema: eventSchema,\n * discriminatorKey: 'type',\n * discriminatorValue: 'click',\n * });\n * // Result: z.object({ type: z.literal('click'), x: z.number(), y: z.number() })\n * ```\n *\n * @example\n * Invalid discriminator value\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string() }),\n * ]);\n *\n * const result = extractDiscriminatedSchema({\n * schema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'invalid', // doesn't match any option\n * });\n * // Result: undefined\n * ```\n *\n * @example\n * Type narrowing demonstration\n * ```typescript\n * const schema = z.discriminatedUnion('mode', [\n * z.object({ mode: z.literal('create'), name: z.string(), age: z.number() }),\n * z.object({ mode: z.literal('edit'), id: z.number(), bio: z.string() }),\n * ]);\n *\n * const createSchema = extractDiscriminatedSchema({\n * schema,\n * discriminatorKey: 'mode',\n * discriminatorValue: 'create',\n * });\n *\n * // Type is EXACTLY: z.object({ mode: z.literal('create'), name: z.string(), age: z.number() })\n * // NOT: z.object({ mode: ..., ... }) | z.object({ mode: ..., ... }) | undefined\n *\n * if (createSchema) {\n * createSchema.shape.age; // ✅ TypeScript knows 'age' exists\n * createSchema.shape.name; // ✅ TypeScript knows 'name' exists\n * // createSchema.shape.id; // ❌ TypeScript error: 'id' doesn't exist on 'create' schema\n * }\n * ```\n *\n * @see {@link getSchemaDefaults} for usage with discriminated unions\n * @see {@link ExtractZodUnionMember} for the type-level extraction logic\n * @since 0.6.0\n */\nexport const extractDiscriminatedSchema = <\n TSchema extends z.ZodUnion | z.ZodDiscriminatedUnion,\n TDiscriminatorKey extends keyof z.input<TSchema> & string,\n TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>({\n schema,\n key,\n value,\n}: {\n schema: TSchema;\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n}) => {\n return schema.options.find(\n (\n option,\n ): option is ExtractZodUnionMember<\n TSchema,\n TDiscriminatorKey,\n TDiscriminatorValue\n > => {\n if (option instanceof z.ZodObject) {\n const targetField = option.shape[String(key)];\n if (!targetField) return false;\n\n const parseResult = targetField.safeParse(value);\n return parseResult.success;\n }\n return false;\n },\n );\n};\n","import type { util } from 'zod';\nimport * as z from 'zod';\nimport {\n canUnwrap,\n extractDiscriminatedSchema,\n getPrimitiveType,\n tryStripNullishOnly,\n} from './schema';\nimport type { Simplify } from './types';\n\n/**\n * Extracts the default value from a Zod field, recursively unwrapping optional, nullable, and union layers.\n *\n * This function traverses through wrapper types (like `ZodOptional`, `ZodNullable`, `ZodUnion`) to find\n * the underlying `ZodDefault` and returns its default value. If no default is found, returns `undefined`.\n *\n * **Union handling:** For union types, strips nullish types (null/undefined) first. If only one type\n * remains after stripping, extracts the default from that type. If multiple non-nullish types remain,\n * returns `undefined` (does not extract from any option).\n *\n * @template T - The Zod type to extract default from\n * @param field - The Zod field to extract default from\n * @returns The default value if present, undefined otherwise\n *\n * @example\n * Basic usage with default value\n * ```typescript\n * const field = z.string().default('hello');\n * const defaultValue = extractDefaultValue(field);\n * // Result: 'hello'\n * ```\n *\n * @example\n * Unwrapping optional/nullable layers\n * ```typescript\n * const field = z.string().default('world').optional();\n * const defaultValue = extractDefaultValue(field);\n * // Result: 'world' (unwraps optional to find default)\n * ```\n *\n * @example\n * Union with only nullish types stripped to single type\n * ```typescript\n * const field = z.union([z.string().default('hello'), z.null()]);\n * const defaultValue = extractDefaultValue(field);\n * // Result: 'hello' (null stripped, leaving only string)\n * ```\n *\n * @example\n * Union with multiple non-nullish types\n * ```typescript\n * const field = z.union([z.string().default('hello'), z.number()]);\n * const defaultValue = extractDefaultValue(field);\n * // Result: undefined (multiple non-nullish types - no default extracted)\n * ```\n *\n * @example\n * Field without default\n * ```typescript\n * const field = z.string().optional();\n * const defaultValue = extractDefaultValue(field);\n * // Result: undefined\n * ```\n *\n * @see {@link getSchemaDefaults} for extracting defaults from entire schemas\n * @see {@link tryStripNullishOnly} for union nullish stripping logic\n * @since 0.1.0\n */\nexport function extractDefaultValue<T extends z.ZodType>(\n field: T,\n): z.input<T> | undefined {\n if (field instanceof z.ZodDefault) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return field.def.defaultValue as z.input<T>;\n }\n\n if (canUnwrap(field)) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefaultValue(field.unwrap()) as z.input<T>;\n }\n\n if (field instanceof z.ZodUnion) {\n const unwrapped = tryStripNullishOnly(field);\n if (unwrapped !== false) {\n // Successfully unwrapped to single type\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefaultValue(unwrapped) as z.input<T>;\n }\n\n // Multiple non-nullish types or all nullish - no default\n return undefined;\n }\n\n if (field instanceof z.ZodPipe && field.def.in instanceof z.ZodType) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return extractDefaultValue(field.def.in) as z.input<T>;\n }\n\n return undefined;\n}\n\n/**\n * Extracts default values from a Zod object schema, returning only fields with explicit `.default()`.\n *\n * This function traverses the schema and collects fields that have explicit default values.\n * Fields without defaults are excluded from the result.\n *\n * **Important:** Nested defaults are NOT extracted unless the parent object also has\n * an explicit `.default()`. This is by design to match Zod's default value behavior.\n *\n * **Component handling:** For form inputs without explicit defaults (like `z.string()` or `z.number()`),\n * use the `?? ''` pattern in your components: `<Input value={field.value ?? ''} />`\n *\n * @template TSchema - The Zod object schema type\n * @param targetSchema - The Zod object schema to extract defaults from\n * @returns A partial object containing only fields with explicit default values\n *\n * @example\n * Basic usage - only explicit defaults\n * ```typescript\n * const schema = z.object({\n * name: z.string(), // no default → NOT included\n * age: z.number(), // no default → NOT included\n * role: z.string().default('user'), // explicit default → included\n * count: z.number().default(0), // explicit default → included\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { role: 'user', count: 0 }\n * ```\n *\n * @example\n * Nested objects with defaults\n * ```typescript\n * const schema = z.object({\n * user: z.object({\n * name: z.string().default('Guest')\n * }).default({ name: 'Guest' }), // ✅ Extracted because parent has .default()\n *\n * settings: z.object({\n * theme: z.string().default('light')\n * }), // ❌ NOT extracted - parent has no .default()\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { user: { name: 'Guest' } }\n * ```\n *\n * @example\n * Unwrapping optional/nullable fields\n * ```typescript\n * const schema = z.object({\n * title: z.string().default('Untitled').optional(),\n * count: z.number().default(0).nullable(),\n * name: z.string().optional(), // no default → NOT included\n * age: z.number().optional(), // no default → NOT included\n * });\n *\n * const defaults = getSchemaDefaults(schema);\n * // Result: { title: 'Untitled', count: 0 }\n * ```\n *\n * @example\n * Component usage for fields without defaults\n * ```typescript\n * // For string/number fields without defaults, handle in components:\n * <Input value={field.value ?? ''} />\n * <Input type=\"number\" value={field.value ?? ''} />\n * ```\n *\n * @see {@link extractDefaultValue} for extracting defaults from individual fields\n * @since 0.1.0\n */\nexport function getSchemaDefaults<\n TSchema extends z.ZodType,\n TDiscriminatorKey extends keyof z.input<TSchema> & string,\n TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>(\n schema: TSchema,\n options?: {\n discriminator?: {\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n };\n },\n): Simplify<Partial<z.input<TSchema>>> {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const primitiveSchema = getPrimitiveType(schema) as TSchema;\n\n let targetSchema: z.ZodObject | undefined;\n if (primitiveSchema instanceof z.ZodDiscriminatedUnion) {\n if (options?.discriminator) {\n targetSchema = extractDiscriminatedSchema({\n schema: primitiveSchema,\n ...options.discriminator,\n });\n }\n } else if (primitiveSchema instanceof z.ZodObject) {\n targetSchema = primitiveSchema;\n }\n\n const defaults: Record<string, unknown> = {};\n\n if (targetSchema) {\n for (const key in targetSchema.shape) {\n const field = targetSchema.shape[key];\n if (!field) continue;\n\n const defaultValue = extractDefaultValue(field);\n if (defaultValue !== undefined) {\n defaults[key] = defaultValue;\n }\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return defaults as Partial<z.input<TSchema>>;\n}\n","import { type util, z } from 'zod';\nimport { extractDiscriminatedSchema, getPrimitiveType } from './schema';\n\nexport function extractFieldFromSchema<\n TSchema extends z.ZodType,\n TName extends keyof Extract<\n Required<z.input<TSchema>>,\n Record<TDiscriminatorKey, TDiscriminatorValue>\n >,\n TDiscriminatorKey extends keyof z.input<TSchema> & string,\n TDiscriminatorValue extends z.input<TSchema>[TDiscriminatorKey] &\n util.Literal,\n>({\n schema,\n fieldName,\n discriminator,\n}: {\n schema: TSchema;\n fieldName: TName;\n discriminator?: {\n key: TDiscriminatorKey;\n value: TDiscriminatorValue;\n };\n}) {\n let targetSchema: z.ZodObject | undefined;\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const primitiveSchema = getPrimitiveType(schema) as TSchema;\n\n if (primitiveSchema instanceof z.ZodDiscriminatedUnion) {\n if (discriminator) {\n targetSchema = extractDiscriminatedSchema({\n schema: primitiveSchema,\n ...discriminator,\n });\n }\n } else if (primitiveSchema instanceof z.ZodObject) {\n targetSchema = primitiveSchema;\n }\n\n if (!targetSchema) return undefined;\n\n const field: z.ZodType = targetSchema.shape[String(fieldName)];\n\n return field;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zod-utils/core",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Pure TypeScript utilities for Zod schema manipulation and default extraction",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",