Skip to content

Commit 2abc9e0

Browse files
authored
docs: note that the JSON Schema emitter reads static optin (#6417)
* docs: note that the JSON Schema emitter reads static optin `objectProcessor` is the one consumer of `optin` that has to read the static declaration rather than the runtime flag, because `io: "input"` describes the declared input type. Nothing near the emitter said so, and #6409 and #6133 landed seven minutes apart taking opposite lines on the two halves of that question: #6409 stripped an output-typed catch value from the input schema while explicitly leaving requiredness on the runtime flag, and #6133 then had to rewrite the snapshot #6409 had just added. Add the emitter to the consumer table in wiki/optionality.md, with a section covering the split and both halves of it, and point at that section from inputOptin(). Also drop the stale in-flight branch reference in the header and the "each with a single consumer" claim, which the optin row already contradicted. * docs: scope the uniqueness claim and correct the #6409 description Two corrections from review. `objectProcessor` is not the only emitter consumer of `optin`. `tupleProcessor` reads it in the same input branch to shrink `minItems`, and it reads the runtime value with no resolution past transform or catch. That is a live divergence, not just a wording gap: z.toJSONSchema(z.tuple([z.string(), z.preprocess(v => v, z.string())]), { io: "input" }) // minItems: 1, but z.input<> is [string, string] and .safeParse(["a"]) rejects Record it rather than assert consistency the emitter does not have. Left unfixed here to keep this docs-only β€” the fix touches core/ and needs its own tuple minItems snapshots. The #6409 sentence also generalized too far. A plain catch keeps its `default` under io: "input"; #6409 added catch to isTransforming's recursion, so only a catch over a transforming schema loses it. * docs: point the inputOptin comment at the section that documents it The cross-reference named "Static/runtime divergence", which covers the parser-level catch/transform/preprocess split and never mentions the emitter. The section that documents this comment is the one added here.
1 parent 578e1cd commit 2abc9e0

2 files changed

Lines changed: 33 additions & 3 deletions

File tree

β€Žpackages/zod/src/v4/core/json-schema-processors.tsβ€Ž

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,9 @@ export const arrayProcessor: Processor<schemas.$ZodArray> = (schema, ctx, _json,
266266
// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an
267267
// absent key, but their declared input type stays required. An input JSON Schema describes the
268268
// declared type, so resolve past them to the schema that actually carries the optionality.
269+
// `tupleProcessor` reads `optin` in the same input branch but has not been given this treatment,
270+
// so its `minItems` still tracks the runtime flag; see wiki/optionality.md, "The JSON Schema
271+
// emitter reads the *static* value".
269272
function inputOptin(schema: schemas.$ZodType): "optional" | undefined {
270273
const def = schema._zod.def;
271274
if (def.type === "pipe" && (def as schemas.$ZodPipeDef).in._zod.traits.has("$ZodTransform")) {

β€Žwiki/optionality.mdβ€Ž

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
# Optionality in Zod v4
22

3-
Internal reference for how Zod's parsing handles "missing" / "undefined" input. Reflects the current state of `main` plus the in-flight branch `fix-fallback-flag-and-preprocess`.
3+
Internal reference for how Zod's parsing handles "missing" / "undefined" input. Reflects the current state of `main`.
44

55
The system has accumulated a few orthogonal mechanisms. This doc names them, says which schema sets what, and walks through the gnarly interactions.
66

77
## TL;DR
88

9-
Three runtime signals, each with a single consumer:
9+
Three runtime signals:
1010

1111
| Signal | Set by | Consumed by | Means |
1212
|---|---|---|---|
13-
| `_zod.optin === "optional"` | catch, default, prefault, optional, transform | `$ZodObject`, `$ZodTuple`, `$ZodOptional` | "I accept absent input" |
13+
| `_zod.optin === "optional"` | catch, default, prefault, optional, transform | `$ZodObject`, `$ZodTuple`, `$ZodOptional`; also the JSON Schema emitter, where `objectProcessor` reads the **static** value but `tupleProcessor` still reads the runtime one β€” see below | "I accept absent input" |
1414
| `_zod.optout === "optional"` | optional, exact-optional, default-on-output cases | `$ZodObject`, `$ZodTuple` | "My output may legitimately be `undefined`; treat that as absent for length-shortening / key-omission" |
1515
| `payload.fallback === true` | catch (when `catchValue` substitutes), transform | `$ZodOptional` (in `handleOptionalResult`) | "This value is provisional; an outer wrapper may override it on undefined input" |
1616

@@ -113,6 +113,33 @@ inst._zod.parse = (payload, ctx) => {
113113

114114
So `optional` *invokes* its inner whenever inner says "I handle absence." It only short-circuits when inner is silent on the question.
115115

116+
### The JSON Schema emitter reads the *static* value
117+
118+
The JSON Schema emitter consumes `optin` too, in two places. `io: "input"` describes the declared input type, so the three schemas above that diverge have to be resolved past to whatever actually carries the optionality. `objectProcessor` in `json-schema-processors.ts` does this:
119+
120+
```ts
121+
function inputOptin(schema: $ZodType): "optional" | undefined {
122+
const def = schema._zod.def;
123+
if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) return inputOptin(def.out);
124+
if (def.type === "catch") return inputOptin(def.innerType);
125+
return schema._zod.optin;
126+
}
127+
```
128+
129+
Reading `_zod.optin` directly here builds a `required` list that matches runtime parse behavior instead of the declared type, dropping a preprocessed or caught key even though `z.input<>` shows it as required. #5003 settled the policy β€” the input JSON Schema describes what you *should* pass, not everything you *can* pass β€” and #6133 restored it after #5939 and #5941 set the runtime flags.
130+
131+
**`tupleProcessor` has not been brought in line.** Its `minItems` tail scan reads `_zod[optKey]` directly, so the same divergence is still live for tuples:
132+
133+
```ts
134+
z.toJSONSchema(z.tuple([z.string(), z.preprocess((v) => v, z.string())]), { io: "input" });
135+
// minItems: 1 β€” but z.input<> is [string, string], and .safeParse(["a"]) rejects
136+
// the object equivalent emits required: ["a", "b"]
137+
```
138+
139+
For `catch` that output at least tracks the parser (`.safeParse(["a"])` succeeds); for `preprocess` it matches neither the declared type nor the parser. Nothing pins either direction in the tuple `minItems` tests, so this is unsettled rather than deliberate.
140+
141+
The same split applies to emitted *values*, not just requiredness: `isTransforming` now recurses through `catch` (#6409), so a catch no longer hides an inner transform from its ancestors and the output-typed `default` is stripped under `io: "input"`. A catch over a non-transforming inner keeps its `default`. Both halves answer the same question, and they have to answer it the same way.
142+
116143
## `optout`
117144

118145
> "Can my output be `undefined` even when input was present, and should the parent treat that as 'absent' for length-shortening / key-omission?"

0 commit comments

Comments
Β (0)