Skip to content

New zod@4 defaultObjectBySchema - #93

Merged
alessandrobellesia merged 1 commit into
developfrom
feature/defaultObjectBySchema
Jul 31, 2025
Merged

alessandrobellesia merged 1 commit into
developfrom
feature/defaultObjectBySchema

Conversation

@alessandrobellesia

@alessandrobellesia alessandrobellesia commented Jul 31, 2025 •

Copy link
Copy Markdown
Member

fix: remove JSON Schema conversion for zod@4 defaultObjectBySchema

Summary by CodeRabbit

  • New Features

    • Added comprehensive support for Zod v4 schema types, including default value generation and type detection.
    • Enhanced handling of nested and complex Zod v4 schemas, such as objects, arrays, records, optionals, nullables, pipes, and transforms.
  • Refactor

    • Improved logic for generating default objects from schemas by directly inspecting Zod v4 schemas, replacing previous JSON schema conversion methods.

fix: remove JSON Schema conversion for zod@4 `defaultObjectBySchema`
@coderabbitai

coderabbitai Bot commented Jul 31, 2025 •

Copy link
Copy Markdown

Walkthrough

The update enhances Zod v4 schema support by adding new type guard and helper functions, enabling direct introspection and default value generation for Zod v4 schemas. The logic for handling Zod v3 remains largely unchanged, while Zod v4 processing now avoids JSON schema conversion, relying on recursive schema inspection and new helper utilities.

Changes

Cohort / File(s) Change Summary
Zod v4 Type Guards & Helpers
src/utils.ts
Added type guard functions for Zod v4 schema variants (object, default, nullable, record, array, optional, pipe, transform). Introduced helpers for extracting inner types and checking optionality for Zod v4. Added internal helpers for value type detection and compatibility checks.
Default Value Construction
src/utils.ts
Refactored defaultObjectBySchema to directly introspect Zod v4 schemas, recursively generating default values without JSON schema conversion. Updated logic for handling nested objects, arrays, records, optionals, nullables, and unknown keys.
Zod v3 Alignment
src/utils.ts
Retained and minimally refactored Zod v3 helpers for consistency with new Zod v4 approach.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Utils
    participant ZodV4Schema

    Caller->>Utils: defaultObjectBySchema(zodV4Schema, original)
    Utils->>ZodV4Schema: Inspect shape, catchall, and properties
    Utils->>Utils: Recursively process fields (optional, default, nullable, array, record)
    Utils->>Caller: Return constructed default object
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

In the warren of code, new helpers appear,
Zod v4 now hops with logic so clear!
No more JSON schema, we peek right inside—
Arrays, records, and objects, all handled with pride.
With every new carrot of type guard in tow,
The rabbit reviews, then leaps—ready to go! 🥕

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/defaultObjectBySchema

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sonarqubecloud

Copy link
Copy Markdown

@alessandrobellesia
alessandrobellesia merged commit 763cd1e into develop Jul 31, 2025
@alessandrobellesia
alessandrobellesia deleted the feature/defaultObjectBySchema branch July 31, 2025 10:04

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/utils.ts (3)

90-90: Fix typo in comment

-// replace of effercts
+// replacement for effects

157-177: Consider refactoring to eliminate code duplication

The pipe unwrapping logic is duplicated from getZod4SchemaInnerType. Consider refactoring to reuse that function.

 export const isZod4SchemaOptional = <Type extends z4.$ZodType>(
     schema:
         | Type
         | z4.$ZodPipe<Type>
         | z4.$ZodPipe<any, Type>
         | z4.$ZodOptional<Type>,
 ) => {
-    let toReturn = schema
-    while (isZod4Pipe(toReturn)) {
-        if (isZod4Transform(toReturn._zod.def.out)) {
-            toReturn = toReturn._zod.def.in
-        }
-        else {
-            toReturn = toReturn._zod.def.out as Type
-        }
-    }
-    if (isZod4Optional(toReturn)) {
-        return true
-    }
-    return false
+    const innerType = getZod4SchemaInnerType(schema)
+    return isZod4Optional(innerType)
 }

321-324: Add type assertion for record value access

When accessing originalValue[recordKey], TypeScript may not infer the correct type.

 return [key, Object.keys(originalValue).reduce((acc: Record<string, unknown>, recordKey: string) => {
-    acc[recordKey] = defaultObjectBySchema(valueType, originalValue[recordKey])
+    acc[recordKey] = defaultObjectBySchema(valueType, (originalValue as Record<string, unknown>)[recordKey])
     return acc
 }, {})]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 01b94cb and 6111223.

📒 Files selected for processing (1)
  • src/utils.ts (6 hunks)
🔇 Additional comments (6)
src/utils.ts (6)

14-36: Helper functions are well-implemented

The internal helper functions _getValueType and _isValueCompatibleWithSchema correctly handle type determination and compatibility checking, including the special case for integer values in JSON Schema.


42-98: Zod v4 type guards are correctly implemented

The new type guards properly check the internal structure of Zod v4 types using _zod.def.type, mirroring the pattern used for Zod v3 guards.


117-137: Inner type extraction logic is sound

The getZod4SchemaInnerType function correctly unwraps nested pipes, transforms, and optionals, with appropriate handling for transform types that returns the input schema rather than the transformed output.


185-185: Good refactoring to use helper function

Using the _isValueCompatibleWithSchema helper improves code maintainability by centralizing the compatibility logic.


266-266: Verify the unknown keys logic

The current logic appears inverted. Unknown keys should typically be preserved when a catchall is defined (and not of type 'never'). The double negation makes this confusing.

Consider clarifying this logic:

-const unknownKeys = !(!innerType._zod.def.catchall || innerType._zod.def.catchall?._zod.def.type === 'never')
+const unknownKeys = innerType._zod.def.catchall && innerType._zod.def.catchall._zod.def.type !== 'never'

262-343: Zod v4 implementation successfully removes JSON Schema dependency

The direct schema introspection approach is well-implemented and maintains feature parity with the Zod v3 handling. The implementation correctly handles all schema types including defaults, nullable, optional, arrays, records, and nested objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant