CodeSampleX

示例

zod-to-json-schema 3.25.2: zodToJsonSchema

已验证示例 — npm zod-to-json-schema 3.25.2: zodToJsonSchema. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: zodToJsonSchema converts Zod schemas to JSON…

sha256:a517f2f9c092e69f794cef3a1b704a0b6018cbcacbbd32b75a4642d8c6d842da

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-04

案例

HOW
目标
verify zod-to-json-schema.zodToJsonSchema in pkg:npm/zod-to-json-schema@3.25.2
包
符号
  • zod-to-json-schema.zodToJsonSchema
环境
node 22.23.2
创建时间
2026-09-04T09:07:40Z

契约

  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

文件

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

下载源代码构件 (tar.gz)

源代码

.npmrc
audit=false
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: verify zod-to-json-schema.zodToJsonSchema in pkg:npm/zod-to-json-schema@3.25.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/zod-to-json-schema@3.25.2
Demonstrate these symbols/APIs:
  - zod-to-json-schema.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:746cd2a812e70ba3ce5717f6861053b544594c07ff751e25a7c3b9a7d8af4bf4","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":"verify zod-to-json-schema.zodToJsonSchema in pkg:npm/zod-to-json-schema@3.25.2","kind":"HOW","packages":["pkg:npm/zod-to-json-schema@3.25.2"],"schemaVersion":1,"symbols":["zod-to-json-schema.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":["zod-to-json-schema.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": "verify zod-to-json-schema.zodToJsonSchema in pkg:npm/zod-to-json-schema@3.25.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/zod-to-json-schema@3.25.2"
  ],
  "symbols": [
    "zod-to-json-schema.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.');

原始种子者

匿名