Skip to content

Conversation

@RobinTail
Copy link
Owner

@RobinTail RobinTail commented May 28, 2025

AI led me to realization that I have to much any in the generated client types.
I'd like to fix it to prevent possible issues with such a broad type.

Summary by CodeRabbit

  • New Features
    • Added support for Zod types never, void, and unknown, which now map to their respective TypeScript types.
  • Bug Fixes
    • Improved fallback typing behavior to better distinguish between response and non-response contexts.
  • Tests
    • Enhanced test coverage for primitive schema handling and error scenarios in schema processing.

@RobinTail RobinTail added breaking Backward incompatible changes prevention labels May 28, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 28, 2025

Walkthrough

A helper function was added to determine fallback TypeScript types based on a response flag, and new primitive producers for Zod's never, void, and unknown types were introduced. The test suite was updated to parameterize primitive schema tests by response context and to verify error handling in preprocessors within the schema pipeline.

Changes

File(s) Change Summary
express-zod-api/src/zts.ts Added getFallback helper for fallback type selection; added producers for Zod never, void, unknown types; updated fallback logic in producers and handlers.
express-zod-api/tests/zts.spec.ts Parameterized primitive schema tests by isResponse; renamed effect block to pipe; added test for preprocess error handling.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite
    participant zodToTs
    participant getFallback
    participant producers

    TestSuite->>zodToTs: Call with schema and context (isResponse)
    zodToTs->>producers: Lookup Zod type producer
    alt Producer exists
        producers-->>zodToTs: Return TypeScript type node
    else Producer missing
        zodToTs->>getFallback: Call with isResponse flag
        getFallback-->>zodToTs: Return fallback type node (unknown/any)
    end
    zodToTs-->>TestSuite: Return TypeScript type node
Loading

Poem

In the warren of types, a new helper appears,
Deciding if "unknown" or "any" calms our fears.
Now "never", "void", and "unknown" hop in too,
With tests that check what preprocessors do.
The code grows stronger, as rabbits rejoice—
Type safety and clarity, our favorite choice!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 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.

@RobinTail RobinTail added this to the v24 milestone May 28, 2025
@coveralls-official
Copy link

coveralls-official bot commented May 28, 2025

Coverage Status

coverage: 100.0%. remained the same
when pulling 9e95ba8 on minimize-any-in-client-types
into 0781730 on make-v24.

@RobinTail RobinTail marked this pull request as ready for review May 28, 2025 07:34
@RobinTail
Copy link
Owner Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 28, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@RobinTail RobinTail added enhancement New feature or request and removed breaking Backward incompatible changes labels May 28, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (1)
express-zod-api/src/zts.ts (1)

250-250: Address the static analysis hint while maintaining correct functionality.

The static analysis tool flagged the empty object pattern, but this is actually valid destructuring syntax when you don't need any properties from the first parameter. However, for better code clarity, consider using an underscore parameter name.

-    onMissing: ({}, { isResponse }) => getFallback(isResponse),
+    onMissing: (_, { isResponse }) => getFallback(isResponse),
🧰 Tools
🪛 Biome (1.9.4)

[error] 250-250: Unexpected empty object pattern.

(lint/correctness/noEmptyPattern)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0781730 and 9e95ba8.

⛔ Files ignored due to path filters (1)
  • express-zod-api/tests/__snapshots__/zts.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (2)
  • express-zod-api/src/zts.ts (4 hunks)
  • express-zod-api/tests/zts.spec.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
express-zod-api/src/zts.ts (1)
express-zod-api/src/typescript-api.ts (1)
  • ensureTypeNode (120-128)
🪛 Biome (1.9.4)
express-zod-api/src/zts.ts

[error] 250-250: Unexpected empty object pattern.

(lint/correctness/noEmptyPattern)

🔇 Additional comments (6)
express-zod-api/src/zts.ts (3)

163-166: Excellent abstraction for context-aware fallback types!

The getFallback function is a great addition that centralizes the logic for choosing between unknown (for responses) and any (for requests). This approach significantly improves type safety for response types while maintaining compatibility for request types.


188-188: Good usage of the new fallback function.

Replacing the hardcoded fallback with getFallback(isResponse) makes the pipeline handling more consistent with the overall type safety strategy.


215-217: Essential primitive type additions for comprehensive Zod support.

Adding producers for never, void, and unknown types ensures complete coverage of Zod's primitive types and improves the overall robustness of the type transformation system.

express-zod-api/tests/zts.spec.ts (3)

331-352: Excellent test coverage improvement with parameterized testing.

Converting the primitive schema test to use describe.each with both isResponse values ensures comprehensive testing of the new fallback logic. This directly validates that the getFallback function behaves correctly in both response and request contexts.


379-379: Good terminology update reflecting current Zod API.

The rename from "z.effect()" to "z.pipe()" aligns with the current Zod v4 terminology and improves code clarity.


398-403: Important edge case coverage for error handling.

Adding a test for preprocess errors in request context ensures the fallback logic works correctly even when preprocessing throws exceptions. This improves the robustness of the error handling path.

Copy link
Owner Author

@RobinTail RobinTail left a comment

Choose a reason for hiding this comment

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

ok

@RobinTail RobinTail changed the title Minimizing any in client types Minimizing any in response types May 28, 2025
@RobinTail RobinTail changed the title Minimizing any in response types Minimizing any in client types May 28, 2025
@RobinTail RobinTail merged commit cba3933 into make-v24 May 28, 2025
15 checks passed
@RobinTail RobinTail deleted the minimize-any-in-client-types branch May 28, 2025 07:40
RobinTail added a commit that referenced this pull request May 28, 2025
Related to #2550

## Dedication


![image](https://github.com/user-attachments/assets/0bf05104-d126-4e4b-aa6f-354292ff8dd5)

Ashley Burton was a 37 years young black transgender woman, a
hairstylist and a makeup artist in Atlanta.
She was shot to death at her apartment complex April 11th 2023. 
Her body was found shortly after 4:30 a.m. in the breezeway of her
building.

> She ran out of the house, hollering and screaming, beating on doors.
> This got to be personal. You shot her in her house, then you followed
her outside and shot her.

— _her cousin Ivory Carter told Atlanta TV station WXIA_.

Burton and Carter grew up together in South Carolina.

> She was a sweetheart, she wasn’t nasty. She wasn’t disrespectful. She
just wanted to live her life.
> I’m tired of all these incidents with transgender women just being
pushed up under the rug. We are human beings.

— _Carter said_.

Patrick Burton, the victim’s brother, told Atlanta station WAGA that
“Ashley was very loved all the way across the board, like from South
Carolina to Atlanta.”

Darius Mills, 31, was arrested in June in connection with the crime. He
faces charges of murder, armed robbery, possession of a firearm by a
convicted felon, and possession of a firearm during the commission of a
felony.

https://www.advocate.com/crime/ashley-burton-trans-woman-death

Transgender women suffer [too
frequently](https://www.congress.gov/118/meeting/house/117016/documents/HMKP-118-JU00-20240321-SD015.pdf)
from transphobic violence and cruelty, being the less protected social
group. I'd like to raise an awareness of this problem. Humans should be
creators — not killers. But most importantly, I want every transgender
girl to have an opportunity to create applications quickly and, in
general, learn to write code easily in order to receive job offers and
leave dangerously transphobic territories for more favorable and
civilized ones, and live happily there. Protect transgender women.

## Modern impact


![image](https://github.com/user-attachments/assets/e8f1854d-8581-45f6-8825-9d8f329e8320)

The Trump administration's policies have significantly impacted
transgender individuals, particularly those who are most vulnerable, by
dismantling protections and fostering environments that increase the
risk of discrimination and violence. Here's an overview of how these
policies have affected the transgender community:

### 1. Executive Order 14168: Erasure of Transgender Recognition

On January 20, 2025, President Trump signed Executive Order 14168,
titled "Defending Women from Gender Ideology Extremism and Restoring
Biological Truth to the Federal Government." This order mandates federal
agencies to recognize only two sexes, male and female, determined at
birth, effectively erasing federal recognition of transgender
identities. It also prohibits the use of gender identity in federal
documentation and policies, impacting areas such as passports, housing,
and healthcare. ([Executive Order
14168](https://en.wikipedia.org/wiki/Executive_Order_14168?utm_source=chatgpt.com),
[Trump Administration Moves to Reject Transgender Identity, Rights |
Human Rights
Watch](https://www.hrw.org/news/2025/01/23/trump-administration-moves-reject-transgender-identity-rights?utm_source=chatgpt.com))

### 2. Healthcare Discrimination and Denial of Gender-Affirming Care

The administration rolled back protections under the Affordable Care Act
that previously prohibited discrimination based on gender identity. This
change allows healthcare providers and insurers to deny gender-affirming
treatments, such as hormone therapy and surgeries, which are vital for
the well-being of transgender individuals. ([Trump administration
reverses health protections for transgender people | Trump
administration | The
Guardian](https://www.theguardian.com/us-news/2020/jun/12/trump-transgender-lgbt-healthcare-protections?utm_source=chatgpt.com))

### 3. Restrictions on Access to Shelters

The Department of Housing and Urban Development (HUD) proposed revisions
to the Equal Access Rule, permitting federally funded shelters to deny
access to transgender individuals based on their sex assigned at birth.
This policy change increases the risk of homelessness and exposure to
violence for transgender people seeking safe shelter. ([The Dire
Consequences of the Trump Administration’s Attack on Transgender
People’s Access to Shelters - Center for American
Progress](https://www.americanprogress.org/article/dire-consequences-trump-administrations-attack-transgender-peoples-access-shelters/?utm_source=chatgpt.com))

### 4. Transgender Individuals in the Prison System

Under Executive Order 14168, the Bureau of Prisons is required to house
incarcerated individuals based on their sex assigned at birth, not their
gender identity. This policy has led to transgender women being placed
in men's prisons, where they face heightened risks of sexual assault and
abuse. Additionally, access to gender-affirming healthcare in prisons
has been curtailed. ([Executive Order
14168](https://en.wikipedia.org/wiki/Executive_Order_14168?utm_source=chatgpt.com),
[Trump Administration Moves to Reject Transgender Identity, Rights |
Human Rights
Watch](https://www.hrw.org/news/2025/01/23/trump-administration-moves-reject-transgender-identity-rights?utm_source=chatgpt.com))

### 5. Defunding of LGBTQ+ Support Services

The administration proposed terminating federal funding for specialized
services of the 988 Suicide & Crisis Lifeline that cater to LGBTQ+
youth. These services have been crucial in providing crisis support to
over 1.2 million individuals, and their removal could exacerbate mental
health challenges within the community. ([RFK Jr. Reportedly Wants to
Defund the National Suicide Hotline for LGBTQ+
Youth](https://www.them.us/story/rfk-jr-hhs-suicide-hotline-lgbtq-youth-rfk-jr-trump-administration?utm_source=chatgpt.com))

### 6. Increased Violence Against Transgender Individuals

The rollback of protections and the promotion of policies that
invalidate transgender identities have coincided with a rise in violence
against transgender people. In 2023, at least 29 transgender and
nonbinary individuals were reported killed in the U.S., with many cases
involving women of color. Advocacy groups suggest that the actual number
may be higher due to underreporting and misidentification. ([Trump
Administration Doubles Down on Trans Discrimination | Human Rights
Watch](https://www.hrw.org/news/2020/06/25/trump-administration-doubles-down-trans-discrimination?utm_source=chatgpt.com))

In summary, the Trump administration's policies have systematically
undermined the rights and safety of transgender individuals, leading to
increased discrimination, denial of essential services, and a rise in
violence against the community.

## Summary

Version 24 introduces initial support for Zod 4, requiring at least
version `3.25.1`, but due to the special versioning strategy of Zod all
imports must be changed to `zod/v4`. The framework simplifies the
`IOSchema` type to explicitly require schemas that resolve to objects.
`Documentation` generation now uses Zod 4’s native `toJSONSchema()`
method, with custom overrides to align with OpenAPI 3.1, and the
`numericRange` option has been removed. The `Depicter` type changed its
signature, and `brandHandling` is now implemented as a postprocessing
step. The `optionalPropStyle` option was removed from the `Integration`
constructor. Using the Zod's internal storage for examples: method
`.example()` changed its argument from `z.input<>` to `z.output<>` which
is breaking for transforming schemas, so that examples of its input side
must be set before the transformation. The `getExamples()` helper
removed in favour of `.meta()?.examples`.

### Contains

- #2537 
  - #2549 
  - #2560 
    - #2561
  - #2573 
  - #2574 - decided to split and rethink
  - #2575 
  - #2578
  - #2579
  - #2580 
  - #2584
  - #2589
  - #2600 
  - #2604 
    - #2607 
- #2547 
  - #2553 
  - #2557 
    - #2593
  - #2559 
  - #2556 
  - #2572 
  - #2581 
  - #2582
  - #2583 
- Chores on registries:
  - #2562 
- need to start over keeping immutability in mind and preserving all
meta when adding new ones
  - #2563 - postponed
  - #2566 - idea rejected
  - #2564 
  - #2565 
  - #2567 
  - #2643
  - #2632 
  - #2644
- Chores on migration:
  - #2585 
  - #2586 
- #2595 
  - #2598
  - #2599 
- #2631
- #2633 
- #2637
- #2651 
- #2649 
  - #2652 
- #2656
- #2664 
  - 57d08c9
- #2665 
- #2666 
- #2668 
- #2670 

### External bugs

![bug on
buggy](https://github.com/user-attachments/assets/e4eefacc-2bb6-4db7-9e6a-2641c582f13a)

- colinhacks/zod#4234
- colinhacks/zod#4228
- colinhacks/zod#4159
- colinhacks/zod#4152
- colinhacks/zod#4224
- colinhacks/zod#4274
- colinhacks/zod#4275 — This one especially
freaks me out
- colinhacks/zod#4267
- colinhacks/zod#4309 - important
- colinhacks/zod#4317
- colinhacks/zod#4318
- colinhacks/zod#4320
- colinhacks/zod#4322

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Introduced `ez.buffer()` schema for Node.js Buffer validation,
replacing `ez.file()`.
- Enhanced OpenAPI documentation generation using Zod 4’s native
`toJSONSchema()` with improved depiction helpers.
- Added JSON Schema flattening utilities for improved schema processing.
- Improved endpoint result handling with discriminated result types and
integrated output example registration.

- **Breaking Changes**
- Removed simultaneous support for Zod 3 and 4; all imports now use
`zod/v4`.
- Deprecated `ez.file()` schema removed; replaced by `z.string()`,
`z.base64()`, or `ez.buffer()`.
  - Simplified `IOSchema` to accept only object schemas.
- `.example()` now aliases `.meta({ examples })` with updated semantics
and example placement.
- Removed `numericRange` and `optionalPropStyle` options from
constructors.
- Branding refactored to use internal Zod checks instead of metadata
cloning.
- Endpoint request type detection updated to use brand-based schema
identification.
  - Refined type signatures and removed deprecated helpers and types.

- **Bug Fixes**
- Improved error handling and diagnostics for schema validation,
including cycle detection.
  - Fixed example metadata immutability and accumulation.
- Enhanced output example extraction and registration via Zod global
registry.

- **Documentation**
- Updated README and CHANGELOG with new features and migration guidance.
- Clarified and improved code samples, especially for date handling and
non-JSON responses.
- Strengthened OpenAPI schema generation with stricter validation,
examples, and additional properties control.

- **Style**
- Migrated all code and tests to use `zod/v4` imports and updated schema
definitions.
- Simplified schema walking and depiction using Zod v4 JSON schema
output and overrides.
  - Consolidated and cleaned middleware and factory type constraints.
- Refactored branding, metadata, and example handling for better
maintainability.

- **Tests**
- Added tests for buffer schema, deep schema checks, JSON schema
helpers, migration rules, and environment validations.
- Removed tests for deprecated features and schemas such as `ez.file()`.
- Enhanced coverage for error classes, diagnostics, branding
persistence, and example extraction.
- Updated snapshots and assertions to align with Zod v4 internals and
behaviors.

- **Chores**
- Updated CI workflows to target new branches and remove legacy
triggers.
  - Added `pretest` script for type checking before tests.
  - Updated security policy to support version 24.x.x.
  - Rewrote migration ESLint rule for v24 API and schema changes.
- Improved Vitest serializers for Zod errors and schemas with brand
metadata.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request prevention

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants