示例
zod 3.23.8: z.lazy, z.preprocess, z.pipeline
已验证示例 — npm zod 3.23.8: z.lazy, z.preprocess, z.pipeline. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: z.lazy validates recursive self-referential…
sha256:2fc3e0a7c13d4d5aa278c844c1a970cd501f9b94dceb3e0cb9f41a6517cb4f54
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 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 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- 目标
- verify pkg:npm/zod@3.23.8
- 符号
-
- z.lazy
- z.preprocess
- z.pipeline
- parseAsync
- safeParseAsync
- 环境
- node 22.23.2
- 创建时间
- 2026-08-27T20:37:31Z
契约
- z.lazy validates recursive self-referential tree schemas and reports field-level issues with exact nested paths on invalid tree nodes.
- z.preprocess transforms input values prior to validation and handles absent or mismatched types.
- z.pipeline chains schemas sequentially, passing intermediate parsed data to downstream validators.
- Object schemas derived via extend, merge, pick, omit, partial, and required enforce updated shapes without mutating the base schema.
- strict rejects unrecognized keys with unrecognized_keys issues, passthrough preserves them, and strip removes them from parsed output.
- parseAsync and safeParseAsync resolve asynchronous refinements and report async validation failures as structured issues.
文件
- NOTES.md
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
源代码
# Notes on Zod Recursive Schemas, Transformations, Object Derivations, and Async Validations
## Known Solution Search Result
`search_known_solution` returned `NO_SAFE_MATCH` for the target symbols and validation patterns in `pkg:npm/zod@3.23.8`.
## Pinned Release
- `zod@3.23.8`
## Observed Behaviour & Mechanics
1. **Recursive Schemas with `z.lazy`**:
`z.lazy()` delays schema evaluation, allowing self-referential structures such as category/navigation trees. Errors nested multiple levels deep accurately retain the full index/field path hierarchy (e.g. `['subcategories', 0, 'subcategories', 0, 'id']`).
2. **Preprocessing & Type Normalization**:
`z.preprocess()` transforms raw input before validation. Returning unparseable values (such as non-numeric strings or empty strings transformed to undefined) produces structured type errors on the underlying validator.
3. **Pipeline Chaining with `.pipe()`**:
`z.pipeline()` passes validated and transformed outputs from an upstream schema directly into a downstream validator, ensuring end-to-end schema type safety.
4. **Immutability of Object Schema Derivations**:
Methods like `.extend()`, `.merge()`, `.pick()`, `.omit()`, `.partial()`, and `.required()` return newly created schema instances and do not mutate the base schema's shape.
5. **Key Stripping and Strict Modes**:
By default, `z.object()` strips unknown keys. `.strict()` causes validation to fail with `unrecognized_keys`, while `.passthrough()` preserves unrecognized keys in the parsed output.
6. **Asynchronous Validations**:
Async refinements added via `.refine(async ...)` require `parseAsync()` or `safeParseAsync()`. Calling synchronous `.parse()` throws an error indicating that an async refinement was encountered during parse.
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 pkg:npm/zod@3.23.8
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/zod@3.23.8
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.
{"case":{"caseId":"case:sha256:f9a2fda45143ac790d642e405db8da53b38dc4c677ea2b00174075e7e8371f40","constraints":{"executionContext":"node"},"contract":["z.lazy validates recursive self-referential tree schemas and reports field-level issues with exact nested paths on invalid tree nodes.","z.preprocess transforms input values prior to validation and handles absent or mismatched types.","z.pipeline chains schemas sequentially, passing intermediate parsed data to downstream validators.","Object schemas derived via extend, merge, pick, omit, partial, and required enforce updated shapes without mutating the base schema.","strict rejects unrecognized keys with unrecognized_keys issues, passthrough preserves them, and strip removes them from parsed output.","parseAsync and safeParseAsync resolve asynchronous refinements and report async validation failures as structured issues."],"goal":"verify pkg:npm/zod@3.23.8","kind":"HOW","packages":["pkg:npm/zod@3.23.8"],"schemaVersion":1,"symbols":["z.lazy","z.preprocess","z.pipeline","parseAsync","safeParseAsync"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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@3.23.8"],"schemaVersion":1,"subject":"pkg:npm/zod@3.23.8","symbols":["z.lazy","z.preprocess","z.pipeline","parseAsync","safeParseAsync"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-zod-verification",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-zod-verification",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"zod": "3.23.8"
}
},
"node_modules/zod": {
"version": "3.23.8",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz",
"integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}
{
"name": "sample-zod-verification",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"zod": "3.23.8"
}
}
{
"schemaVersion": 1,
"goal": "verify pkg:npm/zod@3.23.8",
"kind": "HOW",
"packages": [
"pkg:npm/zod@3.23.8"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
import { z } from 'zod';
/**
* Creates a recursive category tree schema using z.lazy.
* Demonstrates self-referential schema validation.
*/
export function createCategoryTreeSchema() {
const BaseCategory = z.object({
id: z.string().min(1),
name: z.string().min(1),
});
const CategorySchema = BaseCategory.extend({
subcategories: z.lazy(() => z.array(CategorySchema)).optional(),
});
return CategorySchema;
}
/**
* Creates a schema with z.preprocess for input normalization.
*/
export function createPreprocessedNumberSchema() {
return z.preprocess((val) => {
if (typeof val === 'string') {
const trimmed = val.trim();
if (trimmed === '') return undefined;
const num = Number(trimmed);
return Number.isNaN(num) ? val : num;
}
return val;
}, z.number().int().min(0));
}
/**
* Creates a pipeline schema that chains string parsing into a numeric range schema.
*/
export function createNumericPipelineSchema() {
return z
.string()
.transform((val) => val.trim())
.pipe(z.coerce.number().int().min(1).max(1000));
}
/**
* Demonstrates object schema derivation methods: extend, merge, pick, omit, partial, required.
*/
export function createDerivedSchemas() {
const UserBase = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
role: z.enum(['admin', 'member']),
});
const UserWithTimestamp = UserBase.extend({
createdAt: z.number(),
});
const ExtraProfile = z.object({
bio: z.string(),
});
const UserWithProfile = UserBase.merge(ExtraProfile);
const UserSummary = UserBase.pick({ id: true, name: true });
const UserWithoutRole = UserBase.omit({ role: true });
const PartialUser = UserBase.partial();
const RequiredUser = PartialUser.required();
return {
UserBase,
UserWithTimestamp,
UserWithProfile,
UserSummary,
UserWithoutRole,
PartialUser,
RequiredUser,
};
}
/**
* Demonstrates strict, passthrough, and strip mode on object schemas.
*/
export function createKeyHandlingSchemas() {
const base = z.object({
key: z.string(),
});
return {
strictSchema: base.strict(),
passthroughSchema: base.passthrough(),
stripSchema: base.strip(),
};
}
/**
* Creates an async schema with asynchronous refinement for uniqueness checking.
*
* @param {Set<string>} takenUsernames
*/
export function createAsyncUsernameSchema(takenUsernames) {
return z
.string()
.min(3)
.max(20)
.refine(
async (val) => {
// simulate async lookup
await new Promise((resolve) => setTimeout(resolve, 5));
return !takenUsernames.has(val.toLowerCase());
},
{ message: 'Username is already taken' }
);
}
import { strict as assert } from 'node:assert';
import {
createCategoryTreeSchema,
createPreprocessedNumberSchema,
createNumericPipelineSchema,
createDerivedSchemas,
createKeyHandlingSchemas,
createAsyncUsernameSchema,
} from '../src/index.mjs';
// ---------------------------------------------------------------------------
// 1. z.lazy validates recursive self-referential tree schemas and reports
// field-level issues with exact nested paths on invalid tree nodes.
// ---------------------------------------------------------------------------
const categoryTreeSchema = createCategoryTreeSchema();
const validTree = {
id: 'c1',
name: 'Electronics',
subcategories: [
{
id: 'c1-1',
name: 'Computers',
subcategories: [
{
id: 'c1-1-1',
name: 'Laptops',
},
],
},
{
id: 'c1-2',
name: 'Mobile Phones',
},
],
};
const parsedTree = categoryTreeSchema.parse(validTree);
assert.equal(parsedTree.id, 'c1');
assert.equal(parsedTree.subcategories.length, 2);
assert.equal(parsedTree.subcategories[0].subcategories[0].name, 'Laptops');
const invalidTree = {
id: 'root',
name: 'Root',
subcategories: [
{
id: 'sub1',
name: 'Valid Sub',
subcategories: [
{
id: '', // invalid: min length 1 required
name: 'Invalid SubSub',
},
],
},
],
};
const treeResult = categoryTreeSchema.safeParse(invalidTree);
assert.equal(treeResult.success, false);
assert.equal(treeResult.error.issues.length, 1);
assert.deepEqual(treeResult.error.issues[0].path, ['subcategories', 0, 'subcategories', 0, 'id']);
// ---------------------------------------------------------------------------
// 2. z.preprocess transforms input values prior to validation and handles
// absent or mismatched types.
// ---------------------------------------------------------------------------
const preprocessedSchema = createPreprocessedNumberSchema();
assert.equal(preprocessedSchema.parse(' 42 '), 42);
assert.equal(preprocessedSchema.parse(100), 100);
const blankResult = preprocessedSchema.safeParse(' ');
assert.equal(blankResult.success, false);
assert.equal(blankResult.error.issues[0].code, 'invalid_type');
const nonNumericResult = preprocessedSchema.safeParse('not-a-number');
assert.equal(nonNumericResult.success, false);
assert.equal(nonNumericResult.error.issues[0].code, 'invalid_type');
const negativeResult = preprocessedSchema.safeParse(-5);
assert.equal(negativeResult.success, false);
assert.equal(negativeResult.error.issues[0].code, 'too_small');
// ---------------------------------------------------------------------------
// 3. z.pipeline chains schemas sequentially, passing intermediate parsed
// data to downstream validators.
// ---------------------------------------------------------------------------
const pipelineSchema = createNumericPipelineSchema();
assert.equal(pipelineSchema.parse(' 500 '), 500);
const outOfRangeResult = pipelineSchema.safeParse('1500');
assert.equal(outOfRangeResult.success, false);
assert.equal(outOfRangeResult.error.issues[0].code, 'too_big');
const nonStringResult = pipelineSchema.safeParse(500);
assert.equal(nonStringResult.success, false);
assert.equal(nonStringResult.error.issues[0].code, 'invalid_type');
// ---------------------------------------------------------------------------
// 4. Object schemas derived via extend, merge, pick, omit, partial, and
// required enforce updated shapes without mutating the base schema.
// ---------------------------------------------------------------------------
const {
UserBase,
UserWithTimestamp,
UserWithProfile,
UserSummary,
UserWithoutRole,
PartialUser,
RequiredUser,
} = createDerivedSchemas();
const baseInput = {
id: 'u-1',
name: 'Alice',
email: 'alice@example.com',
role: 'admin',
};
// Base schema validation
const parsedBase = UserBase.parse(baseInput);
assert.equal(parsedBase.name, 'Alice');
// extend: adds createdAt
const extendedInput = { ...baseInput, createdAt: Date.now() };
assert.equal(UserWithTimestamp.parse(extendedInput).createdAt, extendedInput.createdAt);
assert.equal(UserWithTimestamp.safeParse(baseInput).success, false);
// merge: adds bio
const mergedInput = { ...baseInput, bio: 'Software Engineer' };
assert.equal(UserWithProfile.parse(mergedInput).bio, 'Software Engineer');
// pick: only id and name
const pickedResult = UserSummary.parse({ id: 'u-1', name: 'Alice', email: 'ignore@example.com' });
assert.deepEqual(pickedResult, { id: 'u-1', name: 'Alice' });
// omit: role omitted
const omittedResult = UserWithoutRole.parse({ id: 'u-1', name: 'Alice', email: 'alice@example.com' });
assert.equal(omittedResult.role, undefined);
// partial: all optional
const partialResult = PartialUser.parse({ name: 'Bob' });
assert.deepEqual(partialResult, { name: 'Bob' });
// required: all required again
const requiredFail = RequiredUser.safeParse({ name: 'Bob' });
assert.equal(requiredFail.success, false);
// Verify UserBase shape is not mutated
const originalKeys = Object.keys(UserBase.shape);
assert.deepEqual(originalKeys.sort(), ['email', 'id', 'name', 'role'].sort());
// ---------------------------------------------------------------------------
// 5. strict rejects unrecognized keys with unrecognized_keys issues,
// passthrough preserves them, and strip removes them from parsed output.
// ---------------------------------------------------------------------------
const { strictSchema, passthroughSchema, stripSchema } = createKeyHandlingSchemas();
const inputWithExtra = { key: 'valid-key', extraProperty: 'extra-val' };
// strict rejection
const strictResult = strictSchema.safeParse(inputWithExtra);
assert.equal(strictResult.success, false);
assert.equal(strictResult.error.issues[0].code, 'unrecognized_keys');
assert.deepEqual(strictResult.error.issues[0].keys, ['extraProperty']);
// passthrough retains extra keys
const passthroughResult = passthroughSchema.parse(inputWithExtra);
assert.deepEqual(passthroughResult, { key: 'valid-key', extraProperty: 'extra-val' });
// strip removes extra keys
const stripResult = stripSchema.parse(inputWithExtra);
assert.deepEqual(stripResult, { key: 'valid-key' });
// ---------------------------------------------------------------------------
// 6. parseAsync and safeParseAsync resolve asynchronous refinements and
// report async validation failures as structured issues.
// ---------------------------------------------------------------------------
const takenUsers = new Set(['admin', 'root', 'superuser']);
const asyncUsernameSchema = createAsyncUsernameSchema(takenUsers);
// Valid async parse
const validUser = await asyncUsernameSchema.parseAsync('unique_user_42');
assert.equal(validUser, 'unique_user_42');
const validSafe = await asyncUsernameSchema.safeParseAsync('another_user');
assert.equal(validSafe.success, true);
assert.equal(validSafe.data, 'another_user');
// Duplicate async validation failure
const takenResult = await asyncUsernameSchema.safeParseAsync('admin');
assert.equal(takenResult.success, false);
assert.equal(takenResult.error.issues[0].message, 'Username is already taken');
assert.equal(takenResult.error.issues[0].code, 'custom');
// Sync parse on async refinement should reject / throw
let caughtError = null;
try {
asyncUsernameSchema.parse('unique_user_42');
} catch (err) {
caughtError = err;
}
assert.ok(caughtError !== null, 'Synchronous parse() on async refinement must throw');
assert.ok(
caughtError.message.toLowerCase().includes('async refinement'),
`Expected message to contain async refinement, got: ${caughtError?.message}`
);
原始种子者
匿名