Documentation menuMenu da documentação

$ cat docs/recipes/validators.md

Recipe: Zod and ValibotReceita: Zod e Valibot

Use Zod or Valibot schemas as they are, classify the personal fields and turn the schemas into JSON Schema for OpenAPI and response shaping.Use schemas Zod ou Valibot como estão, classifique os campos pessoais e transforme os schemas em JSON Schema para o OpenAPI e o corte da resposta.

Any Standard SchemaQualquer Standard Schema

Zod, Valibot and ArkType implement Standard Schema v1, so they go straight into schema: { body, query, params, headers, response }. ctx.body gets the output type of the schema. Without a params schema, ctx.params is a Record<string, string>.

Zod, Valibot e ArkType implementam Standard Schema v1, então entram direto em schema: { body, query, params, headers, response }. O ctx.body recebe o tipo de saída do schema. Sem schema de params, ctx.params é um Record<string, string>.

Classify the fieldsClassificar os campos

classify(schema, { email: 'pii', diagnosis: 'health' }) records the classes on the schema itself and returns the same schema. Paths are typed from the schema output and use dots ('address.street'). The classes travel to the logger, the audit, OpenAPI (x-data-class) and MCP. Fields marked secret never leave in a response.

classify(schema, { email: 'pii', diagnosis: 'health' }) grava as classes no próprio schema e devolve o mesmo schema. Os caminhos são tipados pela saída do schema e usam ponto ('address.street'). As classes chegam ao logger, à auditoria, ao OpenAPI (x-data-class) e ao MCP. Campos marcados como secret nunca saem numa resposta.

JSON SchemaJSON Schema

Response shaping (response: 'strip', the default) needs the field list of the response schema. Tupik first reads the JSON Schema the schema exposes itself (a jsonSchema property or Standard JSON Schema in ~standard.jsonSchema, which Zod 4 has), then createApp({ schemaConverter }). For a schema with neither, pass classify(schema, classes, { fields: [...] }).

O corte da resposta (response: 'strip', o padrão) precisa da lista de campos do schema de resposta. O Tupik lê primeiro o JSON Schema que o próprio schema expõe (uma propriedade jsonSchema ou Standard JSON Schema em ~standard.jsonSchema, que o Zod 4 tem) e depois o createApp({ schemaConverter }). Para um schema sem nenhum dos dois, passe classify(schema, classes, { fields: [...] }).

generateOpenApiDocument uses its schemaConverter first and the schema's own JSON Schema otherwise. Without either it throws (onMissingConverter: 'warn' emits {} instead). When you mix libraries, pick the converter by ~standard.vendor, as below.

O generateOpenApiDocument usa primeiro o seu schemaConverter e, sem ele, o JSON Schema do próprio schema. Sem nenhum dos dois ele lança erro (onMissingConverter: 'warn' emite {}). Quando misturar bibliotecas, escolha o conversor pelo ~standard.vendor, como abaixo.

patients.ts
import { classify, createApp, createModule, type StandardSchemaV1 } from '@tupik/core';
import { generateOpenApiDocument } from '@tupik/openapi';
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
import { z } from 'zod';

// Zod 4 schema with classified fields
const Patient = classify(
  z.object({ id: z.string(), name: z.string(), email: z.string().email(), diagnosis: z.string() }),
  { email: 'pii', diagnosis: 'health' },
);

// Valibot: same idea, any Standard Schema works
const NewPatient = classify(
  v.object({ name: v.pipe(v.string(), v.minLength(1)), email: v.pipe(v.string(), v.email()) }),
  { email: 'pii' },
);

// one converter per vendor; a converter wins over the schema's own JSON Schema
const schemaConverter = (schema: StandardSchemaV1) =>
  schema['~standard'].vendor === 'valibot' ? toJsonSchema(schema as v.GenericSchema) : z.toJSONSchema(schema as z.ZodType);

const patients = createModule('/patients')
  .access('authenticated')
  .get('/:id', {
    schema: { params: z.object({ id: z.string() }), response: { 200: Patient } },
    // passwordHash is not declared: the response drops it
    handler: (ctx) => db.patient(ctx.params.id),
  })
  .post('/', {
    schema: { body: NewPatient },
    handler: async (ctx) => ctx.status(201).json(await db.create(ctx.body)),
  });

export const app = createApp({ authenticate, schemaConverter }).register(patients);
export const document = generateOpenApiDocument(app, { info: { title: 'Clinic', version: '1.0.0' }, schemaConverter });
import { classify, createApp, createModule, type StandardSchemaV1 } from '@tupik/core';
import { generateOpenApiDocument } from '@tupik/openapi';
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
import { z } from 'zod';

// schema Zod 4 com campos classificados
const Patient = classify(
  z.object({ id: z.string(), name: z.string(), email: z.string().email(), diagnosis: z.string() }),
  { email: 'pii', diagnosis: 'health' },
);

// Valibot: mesma ideia, qualquer Standard Schema serve
const NewPatient = classify(
  v.object({ name: v.pipe(v.string(), v.minLength(1)), email: v.pipe(v.string(), v.email()) }),
  { email: 'pii' },
);

// um conversor por fornecedor; o conversor vence o JSON Schema do próprio schema
const schemaConverter = (schema: StandardSchemaV1) =>
  schema['~standard'].vendor === 'valibot' ? toJsonSchema(schema as v.GenericSchema) : z.toJSONSchema(schema as z.ZodType);

const patients = createModule('/patients')
  .access('authenticated')
  .get('/:id', {
    schema: { params: z.object({ id: z.string() }), response: { 200: Patient } },
    // passwordHash não está declarado: a resposta o corta
    handler: (ctx) => db.patient(ctx.params.id),
  })
  .post('/', {
    schema: { body: NewPatient },
    handler: async (ctx) => ctx.status(201).json(await db.create(ctx.body)),
  });

export const app = createApp({ authenticate, schemaConverter }).register(patients);
export const document = generateOpenApiDocument(app, { info: { title: 'Clinic', version: '1.0.0' }, schemaConverter });

What can go wrongO que pode dar errado

  • Zod 3 has no z.toJSONSchema and no Standard JSON Schema. Use zod-to-json-schema as the converter, or move to Zod 4.
  • An open object (additionalProperties allowed, or .passthrough()) cannot be stripped: Tupik keeps it whole. Close response objects.
  • Async refinements make validation asynchronous and cost an await per request. Keep request schemas synchronous where you can (see Performance).
  • O Zod 3 não tem z.toJSONSchema nem Standard JSON Schema. Use o zod-to-json-schema como conversor, ou passe para o Zod 4.
  • Um objeto aberto (com additionalProperties, ou .passthrough()) não pode ser cortado: o Tupik o mantém inteiro. Feche os objetos de resposta.
  • Refinamentos assíncronos tornam a validação assíncrona e custam um await por requisição. Mantenha os schemas de entrada síncronos quando puder (veja Desempenho).