CodeSampleX

Exemplo

zod 4.4.3: Restore .catch() fallback and preprocess evaluation for absent keys in z.object schemas fixed in zod 4.4.3

Amostra verificada para npm zod 4.4.3: Restore .catch() fallback and preprocess evaluation for absent keys in z.object schemas fixed in zod 4.4.3. O contrato…

sha256:30dbed125fd6944057a2d3d053851104df423c6580f301a14ce9d4143dcf07d1

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
3
Chaves de assinatura que o compilaram
3
Ambiente declarado node linux x64 node node npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-07

Caso

HOW
Objetivo
Restore .catch() fallback and preprocess evaluation for absent keys in z.object schemas fixed in zod 4.4.3
Pacotes
Símbolos
  • z.object
  • z.ZodType.catch
  • z.preprocess
Ambiente
node
Criado
2026-08-16T04:51:32Z

Contrato

  1. assert z.object with .catch() fallback on an enum field successfully returns the catch value when key is absent in input object
  2. assert z.object with .catch() fallback on a string and a number field returns both catch values when input object is empty
  3. assert z.object with .catch() fallback on a number field returns the catch value when string field is explicitly provided
  4. assert z.object with z.preprocess() receives undefined for absent keys and resolves the default fallback value

Arquivos

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/schemas.mjs
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# Notes on Zod 4.4.3 Bugfix: Absent Object Keys in `.catch()` and `z.preprocess()`

## Known Solution Search Result
`search_known_solution` returned `MATCH: COMPATIBLE` pointing to existing samples:
- `sha256:b1df332fb06be1ad1dddffd68c8ee86edefa3d3c5d234d6ebb92ca96fad55572` (basic object schema validation and error shapes)
- `sha256:d3a9cc5fa6af1de9c4bd13813f2a670ad60d7afe148dadb0bcc4dc95133a9eb4` (constructor coercion traps in `z.coerce` and `.refine()` return value discarding)

Neither sample proves the regression where absent keys in object schemas were prematurely rejected before `.catch()` or `z.preprocess()` could execute.

## Real Release and Origin
- **Release**: `zod@4.4.3` (patch release)
- **Commits & PRs**:
  - Commit `1cab69383fcdeae2a366d5e2a2fc4d8fc765d168`: `fix(v4): restore catch handling for absent object keys (#5937) (#5939)`
  - Commit `c2be4f819064eed62c7c350a2d399b5faecd15f8`: `fix(v4): generalize optin/fallback to transform; restore preprocess on absent keys (#5941)`

## What the Behaviour Was Before (zod 4.4.0 – 4.4.2)
When `zod` 4.4.0 tightened object parsing to reject absent keys whose schema was not explicitly marked with `optin === "optional"`, fields wrapped in `.catch(...)` or `z.preprocess(...)` were incorrectly blocked during object validation.

Instead of passing `undefined` to the inner `.catch()` handler or `preprocess` callback:
- `z.object({ mode: z.enum(['development', 'production']).catch('development') }).parse({})` threw `ZodError: Invalid input: expected nonoptional, received undefined` at path `['mode']`.
- `z.object({ region: z.preprocess((v) => v ?? 'default-region', z.string()) }).parse({})` threw `ZodError: Invalid input: expected nonoptional, received undefined` at path `['region']`.

## What It Is Now (zod 4.4.3)
In Zod 4.4.3, absent keys in `z.object` are properly routed to `.catch()` and `z.preprocess()`:
- `ConfigSchema.parse({})` evaluates to `{ mode: 'development' }`.
- `UserSettingsSchema.parse({})` evaluates to `{ username: 'anonymous', timeoutSec: 5 }`.
- `PreprocessedPayloadSchema.parse({})` evaluates to `{ region: 'default-region' }`.

## How the Broken Version Fails
Loudly with a thrown `ZodError` (`invalid_type`, `expected: "nonoptional"`, `received: "undefined"`).
csx.json
{"case":{"caseId":"case:sha256:0174b3972420e464827395ec6b61a24a9022800c38108e60250d7295886b37e3","contract":["assert z.object with .catch() fallback on an enum field successfully returns the catch value when key is absent in input object","assert z.object with .catch() fallback on a string and a number field returns both catch values when input object is empty","assert z.object with .catch() fallback on a number field returns the catch value when string field is explicitly provided","assert z.object with z.preprocess() receives undefined for absent keys and resolves the default fallback value"],"goal":"Restore .catch() fallback and preprocess evaluation for absent keys in z.object schemas fixed in zod 4.4.3","kind":"HOW","packages":["pkg:npm/zod@4.4.3"],"schemaVersion":1,"symbols":["z.object","z.ZodType.catch","z.preprocess"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/zod@4.4.3"],"schemaVersion":1,"symbols":["z.object","z.ZodType.catch","z.preprocess"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-zod-absent-keys-bugfix",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-zod-absent-keys-bugfix",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "zod": "4.4.3"
      }
    },
    "node_modules/zod": {
      "version": "4.4.3",
      "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
      "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
      "license": "MIT",
      "funding": {
        "url": "https://github.com/sponsors/colinhacks"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-zod-absent-keys-bugfix",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "zod": "4.4.3"
  }
}
src/schemas.mjs
import { z } from 'zod';

/**
 * Schemas exercising .catch() fallback and z.preprocess() on absent object keys.
 * In Zod 4.4.0 through 4.4.2, absent keys in z.object were rejected immediately
 * with `invalid_type` before inner .catch() or preprocess handlers could execute.
 * Zod 4.4.3 restored evaluating absent keys against catch fallbacks and preprocessors.
 */

// 1. Enum property with .catch() fallback for absent key
export const ConfigSchema = z.object({
  mode: z.enum(['development', 'production', 'staging']).catch('development'),
});

// 2. Multiple properties (string and number) with .catch() fallbacks for absent keys
export const UserSettingsSchema = z.object({
  username: z.string().catch('anonymous'),
  timeoutSec: z.number().int().min(1).catch(5),
});

// 3. Preprocessed property that defaults an absent key
export const PreprocessedPayloadSchema = z.object({
  region: z.preprocess((v) => v ?? 'default-region', z.string()),
});
test/contract.mjs
import { strict as assert } from 'node:assert';
import {
  ConfigSchema,
  UserSettingsSchema,
  PreprocessedPayloadSchema,
} from '../src/schemas.mjs';

// 1. Enum property with .catch() fallback resolves when key is absent in input object
assert.deepEqual(
  ConfigSchema.parse({}),
  { mode: 'development' },
  'z.object must apply .catch() fallback when enum key is absent in input object'
);

// 2. Multiple .catch() fallbacks resolve when all keys are absent in input object
assert.deepEqual(
  UserSettingsSchema.parse({}),
  { username: 'anonymous', timeoutSec: 5 },
  'z.object must apply .catch() fallbacks for all absent keys in input object'
);

// 3. Partially specified object resolves .catch() fallback for the remaining absent key
assert.deepEqual(
  UserSettingsSchema.parse({ username: 'alice' }),
  { username: 'alice', timeoutSec: 5 },
  'z.object must apply .catch() fallback for an absent key alongside an explicit valid key'
);

// 4. z.preprocess() receives undefined and supplies fallback when key is absent in input object
assert.deepEqual(
  PreprocessedPayloadSchema.parse({}),
  { region: 'default-region' },
  'z.object must pass absent keys to z.preprocess() to evaluate default fallback'
);

console.log('CONTRACT PASS: zod 4.4.3 absent object key catch and preprocess handling verified');

Seeder de origem

anonymous