Skip to content

fix: apply description and default metadata to enum, const, and not schemas in fromJSONSchema#5758

Open
mibragimov wants to merge 1 commit intocolinhacks:mainfrom
mibragimov:fix/from-json-schema-metadata
Open

fix: apply description and default metadata to enum, const, and not schemas in fromJSONSchema#5758
mibragimov wants to merge 1 commit intocolinhacks:mainfrom
mibragimov:fix/from-json-schema-metadata

Conversation

@mibragimov
Copy link

Problem

z.fromJSONSchema() ignores description and default fields when the JSON Schema uses enum, const, or not: {} (never). This happens because these paths use early returns in convertBaseSchema() before reaching the metadata application block at the bottom of the function.

Minimal reproduction:

const schema = z.fromJSONSchema({
  enum: ["red", "green", "blue"],
  description: "A color value",
  default: "red",
});

schema.description; // undefined ❌ (expected "A color value")
schema.parse(undefined); // throws ❌ (expected "red")

Fixes #5732

Solution

Extract the metadata application (description + default) into a helper function applyBaseMetadata() and call it from each of the affected early-return paths:

  • not: {}z.never()
  • enumz.enum() / z.literal() / z.union()
  • constz.literal()

Tests

Added five new tests covering:

  • description on enum schema
  • description on const schema
  • description on not: {} (never) schema
  • default on enum schema
  • default on const schema

… fromJSONSchema

Fixes colinhacks#5732

Early returns for enum, const, and not: {} (never) schemas in
convertBaseSchema() bypassed the metadata application block at the end
of the function.

Extract metadata application into a helper function applyBaseMetadata()
and call it from each of the affected early-return paths so that
description and default are consistently honored across all schema types.
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.

z.fromJSONSchema() does not support metadata for enums, literals and not/never

1 participant