CodeSampleX

Пример

zod-to-json-schema 3.25.2: convert zod schema to json schema with zodToJsonSchema

Проверенный пример — npm zod-to-json-schema 3.25.2: convert zod schema to json schema with zodToJsonSchema. Контракт выполнен на node 22 · linux alpine/x64 …

sha256:54ced0265bbe26a1ef44c001d2806647901deec191338cffab49d1bd8491fe1b

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-08-27

Кейс

HOW
Цель
convert zod schema to json schema with zodToJsonSchema
Пакеты
Символы
  • zodToJsonSchema
Окружение
node 22.23.2
Создан
2026-08-27T21:50:03Z

Контракт

  1. zodToJsonSchema converts Zod schemas to JSON Schema Draft-07 objects by default
  2. zodToJsonSchema generates $ref and definitions when provided a schema name
  3. zodToJsonSchema supports openApi3 target configuration with nullable properties
  4. zodToJsonSchema maps string constraints, number bounds, enums, and optional fields
  5. zodToJsonSchema preserves field descriptions and default values defined in Zod schemas
  6. zodToJsonSchema correctly translates nested objects, array schemas, and union types

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: convert zod schema to json schema with zodToJsonSchema
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/zod-to-json-schema@3.25.2
Demonstrate these symbols/APIs:
  - zodToJsonSchema
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:df36a408065d0647a947995fdc587b6831d199402980d9aee208598f5fea3220","constraints":{"executionContext":"node"},"contract":["zodToJsonSchema converts Zod schemas to JSON Schema Draft-07 objects by default","zodToJsonSchema generates $ref and definitions when provided a schema name","zodToJsonSchema supports openApi3 target configuration with nullable properties","zodToJsonSchema maps string constraints, number bounds, enums, and optional fields","zodToJsonSchema preserves field descriptions and default values defined in Zod schemas","zodToJsonSchema correctly translates nested objects, array schemas, and union types"],"goal":"convert zod schema to json schema with zodToJsonSchema","kind":"HOW","packages":["pkg:npm/zod-to-json-schema@3.25.2"],"schemaVersion":1,"symbols":["zodToJsonSchema"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/zod-to-json-schema@3.25.2"],"schemaVersion":1,"subject":"pkg:npm/zod-to-json-schema@3.25.2","symbols":["zodToJsonSchema"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-zod-to-json-schema",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-zod-to-json-schema",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "zod": "3.25.76",
        "zod-to-json-schema": "3.25.2"
      }
    },
    "node_modules/zod": {
      "version": "3.25.76",
      "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
      "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
      "license": "MIT",
      "funding": {
        "url": "https://github.com/sponsors/colinhacks"
      }
    },
    "node_modules/zod-to-json-schema": {
      "version": "3.25.2",
      "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
      "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
      "license": "ISC",
      "peerDependencies": {
        "zod": "^3.25.28 || ^4"
      }
    }
  }
}
package.json
{
  "name": "sample-zod-to-json-schema",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.js",
  "dependencies": {
    "zod": "3.25.76",
    "zod-to-json-schema": "3.25.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "convert zod schema to json schema with zodToJsonSchema",
  "kind": "HOW",
  "packages": [
    "pkg:npm/zod-to-json-schema@3.25.2"
  ],
  "symbols": [
    "zodToJsonSchema"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { zodToJsonSchema } = require('zod-to-json-schema');
const { z } = require('zod');

/**
 * Converts a Zod schema into a JSON Schema object.
 *
 * @param {import('zod').ZodTypeAny} schema - The Zod schema to convert.
 * @param {string|object} [optionsOrName] - Schema name or conversion options object.
 * @returns {object} The converted JSON Schema object.
 */
function convertZodToJsonSchema(schema, optionsOrName) {
  return zodToJsonSchema(schema, optionsOrName);
}

module.exports = {
  zodToJsonSchema,
  convertZodToJsonSchema,
  z
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  zodToJsonSchema,
  convertZodToJsonSchema,
  z
} = require('../src/index.js');
const upstream = require('zod-to-json-schema');

// 1. Verify module exports and helper functions
assert.equal(typeof zodToJsonSchema, 'function', 'zodToJsonSchema must be a function');
assert.strictEqual(zodToJsonSchema, upstream.zodToJsonSchema, 'zodToJsonSchema must match upstream export');
assert.equal(typeof convertZodToJsonSchema, 'function', 'convertZodToJsonSchema helper must be a function');

// 2. zodToJsonSchema converts Zod schemas to JSON Schema Draft-07 objects by default
const simpleSchema = z.object({
  id: z.string().uuid(),
  count: z.number().int().min(1)
});

const defaultResult = zodToJsonSchema(simpleSchema);
assert.equal(defaultResult.$schema, 'http://json-schema.org/draft-07/schema#', 'Default target must be draft-07');
assert.equal(defaultResult.type, 'object', 'Root type must be object');
assert.equal(defaultResult.properties.id.type, 'string', 'id property type must be string');
assert.equal(defaultResult.properties.id.format, 'uuid', 'id property format must be uuid');
assert.equal(defaultResult.properties.count.type, 'integer', 'count property type must be integer');
assert.equal(defaultResult.properties.count.minimum, 1, 'count property minimum must be 1');
assert.deepEqual(defaultResult.required, ['id', 'count'], 'id and count must be required');
assert.equal(defaultResult.additionalProperties, false, 'additionalProperties must be false by default');

// 3. zodToJsonSchema generates $ref and definitions when provided a schema name
const userSchema = z.object({
  username: z.string().min(3),
  role: z.enum(['admin', 'user'])
});

const namedResult = convertZodToJsonSchema(userSchema, 'User');
assert.equal(namedResult.$ref, '#/definitions/User', '$ref must point to definitions/User');
assert.ok(namedResult.definitions && namedResult.definitions.User, 'definitions.User must exist');
assert.equal(namedResult.definitions.User.type, 'object', 'definitions.User type must be object');
assert.deepEqual(namedResult.definitions.User.properties.role.enum, ['admin', 'user'], 'role enum values must match');

// 4. zodToJsonSchema supports openApi3 target configuration with nullable properties
const productSchema = z.object({
  title: z.string(),
  discount: z.number().nullable()
});

const openApiResult = zodToJsonSchema(productSchema, { target: 'openApi3' });
assert.equal(openApiResult.$schema, undefined, 'OpenAPI 3 target must omit $schema keyword');
assert.equal(openApiResult.properties.discount.type, 'number', 'nullable discount type must be number');
assert.equal(openApiResult.properties.discount.nullable, true, 'nullable discount must have nullable flag set to true');

// 5. zodToJsonSchema maps string constraints, number bounds, enums, and optional fields
const profileSchema = z.object({
  bio: z.string().max(200).optional(),
  score: z.number().positive(),
  tag: z.enum(['beta', 'stable'])
});

const profileResult = zodToJsonSchema(profileSchema);
assert.equal(profileResult.properties.bio.maxLength, 200, 'bio maxLength must be 200');
assert.ok(!profileResult.required.includes('bio'), 'optional bio field must not be in required array');
assert.equal(profileResult.properties.score.exclusiveMinimum, 0, 'positive score must set exclusiveMinimum to 0');
assert.deepEqual(profileResult.properties.tag.enum, ['beta', 'stable'], 'tag enum must match');

// 6. zodToJsonSchema preserves field descriptions and default values defined in Zod schemas
const configSchema = z.object({
  timeout: z.number().default(5000).describe('Timeout in milliseconds'),
  retries: z.number().default(3)
});

const configResult = zodToJsonSchema(configSchema);
assert.equal(configResult.properties.timeout.description, 'Timeout in milliseconds', 'description must be preserved');
assert.equal(configResult.properties.timeout.default, 5000, 'default value must be preserved');
assert.equal(configResult.properties.retries.default, 3, 'retries default must be preserved');

// 7. zodToJsonSchema correctly translates nested objects, array schemas, and union types
const taskListSchema = z.object({
  name: z.string(),
  tags: z.array(z.string().min(1)),
  metadata: z.object({
    priority: z.union([z.string(), z.number()])
  })
});

const taskListResult = zodToJsonSchema(taskListSchema);
assert.equal(taskListResult.properties.tags.type, 'array', 'tags property must be array');
assert.equal(taskListResult.properties.tags.items.type, 'string', 'tags items type must be string');
assert.equal(taskListResult.properties.metadata.type, 'object', 'metadata property must be object');
assert.deepEqual(taskListResult.properties.metadata.properties.priority.type, ['string', 'number'], 'union type must map to type array');

console.log('Contract tests passed successfully.');

Исходный сидер

аноним