Exemple
zod 3.25.76: Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod
Échantillon vérifié pour npm zod 3.25.76: Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod. Le contrat s'est…
sha256:8481cecd353d1aa53e78f3fe731486c75549aa16aeeab769d5ff48b918566655
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 1
- Clés de signature qui l’ont compilé
- 1
Environnement déclaré
linux 24 · ubuntu · glibc 2.39 x64 npm
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| 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-23 |
Cas
HOW- Objectif
- Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod
- Paquets
- Symboles
-
- zod.z.lazy
- Créé
- 2026-08-23T06:52:13Z
Contrat
- z.lazy allows defining recursive self-referential schemas for tree nodes with nested child nodes
- z.lazy validates deeply nested hierarchical structures without infinite recursion
- z.lazy rejects invalid child nodes deep within the tree structure reporting exact error paths
- z.record validates dynamic key-value dictionaries with typed string keys and schema-validated values
- z.lazy combined with z.record validates nested recursive JSON-like tree hierarchies with property maps
- safeParse on recursive schemas returns detailed issue path for malformed deep leaves
Fichiers
- PROMPT.md
- csx.json
- index.js
- package-lock.json
- package.json
- spec.json
- test/contract.js
Code source
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: Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/zod@3.25.76
Demonstrate these symbols/APIs:
- zod.z.lazy
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:717b2a9fc68a6b8e731ce7d98675ae0d7b1ca4be59d604593d5eeae014df6ba2","contract":["z.lazy allows defining recursive self-referential schemas for tree nodes with nested child nodes","z.lazy validates deeply nested hierarchical structures without infinite recursion","z.lazy rejects invalid child nodes deep within the tree structure reporting exact error paths","z.record validates dynamic key-value dictionaries with typed string keys and schema-validated values","z.lazy combined with z.record validates nested recursive JSON-like tree hierarchies with property maps","safeParse on recursive schemas returns detailed issue path for malformed deep leaves"],"goal":"Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod","kind":"HOW","packages":["pkg:npm/zod@3.25.76"],"schemaVersion":1,"symbols":["zod.z.lazy"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/zod@3.25.76"],"schemaVersion":1,"subject":"pkg:npm/zod@3.25.76","symbols":["zod.z.lazy"],"verifierAdapter":"node-typescript@1"}
const { z } = require('zod');
// Recursive tree node schema using z.lazy
const treeNodeSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
value: z.number().optional(),
attributes: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),
children: z.array(z.lazy(() => treeNodeSchema)).default([]),
});
// Recursive JSON value schema using z.lazy and z.record
const jsonValueSchema = z.lazy(() =>
z.union([
z.string(),
z.number(),
z.boolean(),
z.null(),
z.array(jsonValueSchema),
z.record(z.string(), jsonValueSchema),
])
);
// Dynamic key-value dictionary schema using z.record
const configMapSchema = z.record(
z.string().min(1),
z.object({
enabled: z.boolean(),
timeoutMs: z.number().int().positive().default(5000),
metadata: z.record(z.string(), z.string()).default({}),
})
);
function parseTreeNode(input) {
return treeNodeSchema.parse(input);
}
function safeParseTreeNode(input) {
return treeNodeSchema.safeParse(input);
}
function parseJsonValue(input) {
return jsonValueSchema.parse(input);
}
function safeParseJsonValue(input) {
return jsonValueSchema.safeParse(input);
}
function parseConfigMap(input) {
return configMapSchema.parse(input);
}
function safeParseConfigMap(input) {
return configMapSchema.safeParse(input);
}
module.exports = {
z,
treeNodeSchema,
jsonValueSchema,
configMapSchema,
parseTreeNode,
safeParseTreeNode,
parseJsonValue,
safeParseJsonValue,
parseConfigMap,
safeParseConfigMap,
};
{
"name": "sample-zod-lazy",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-zod-lazy",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"zod": "3.25.76"
}
},
"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"
}
}
}
}
{
"name": "sample-zod-lazy",
"version": "1.0.0",
"private": true,
"description": "Clean-room verification sample for zod.z.lazy and z.record in zod",
"main": "index.js",
"scripts": {
"test": "node test/contract.js"
},
"license": "MIT-0",
"dependencies": {
"zod": "3.25.76"
}
}
{
"schemaVersion": 1,
"goal": "Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod",
"kind": "HOW",
"packages": [
"pkg:npm/zod@3.25.76"
],
"symbols": [
"zod.z.lazy"
]
}
const assert = require('assert');
const {
z,
treeNodeSchema,
jsonValueSchema,
configMapSchema,
parseTreeNode,
safeParseTreeNode,
parseJsonValue,
safeParseJsonValue,
parseConfigMap,
safeParseConfigMap,
} = require('../index.js');
function runTests() {
// 1. z.lazy allows defining recursive self-referential schemas for tree nodes with nested child nodes
{
const rootNode = {
id: 'root',
name: 'Root Node',
attributes: { priority: 1, isRoot: true },
children: [
{
id: 'child-1',
name: 'First Child',
attributes: { tag: 'leaf' },
children: [],
},
{
id: 'child-2',
name: 'Second Child',
children: [
{
id: 'grandchild-1',
name: 'Deep Child',
},
],
},
],
};
const parsed = parseTreeNode(rootNode);
assert.strictEqual(parsed.id, 'root');
assert.strictEqual(parsed.children.length, 2);
assert.strictEqual(parsed.children[0].name, 'First Child');
assert.deepStrictEqual(parsed.children[0].children, []);
assert.strictEqual(parsed.children[1].children.length, 1);
assert.strictEqual(parsed.children[1].children[0].id, 'grandchild-1');
assert.deepStrictEqual(parsed.children[1].children[0].attributes, {});
assert.deepStrictEqual(parsed.children[1].children[0].children, []);
}
// 2. z.lazy validates deeply nested hierarchical structures without infinite recursion
{
let deepNode = { id: 'leaf-10', name: 'Level 10 Node', children: [] };
for (let i = 9; i >= 1; i--) {
deepNode = {
id: `node-${i}`,
name: `Level ${i} Node`,
value: i * 100,
children: [deepNode],
};
}
const parsed = parseTreeNode(deepNode);
assert.strictEqual(parsed.id, 'node-1');
assert.strictEqual(parsed.value, 100);
let current = parsed;
for (let i = 1; i <= 9; i++) {
assert.strictEqual(current.id, `node-${i}`);
assert.strictEqual(current.children.length, 1);
current = current.children[0];
}
assert.strictEqual(current.id, 'leaf-10');
assert.deepStrictEqual(current.children, []);
}
// 3. z.lazy rejects invalid child nodes deep within the tree structure reporting exact error paths
{
const invalidTree = {
id: 'root',
name: 'Root',
children: [
{
id: 'valid-branch',
name: 'Branch',
children: [
{
id: '', // Invalid empty id
name: 'Invalid Leaf',
},
],
},
],
};
const res = safeParseTreeNode(invalidTree);
assert.strictEqual(res.success, false);
const issue = res.error.issues.find((iss) =>
iss.path.join('.').includes('children.0.children.0.id')
);
assert.ok(issue, 'reports error at exact nested path children.0.children.0.id');
assert.strictEqual(issue.code, 'too_small');
}
// 4. z.record validates dynamic key-value dictionaries with typed string keys and schema-validated values
{
const validConfig = {
database: { enabled: true, timeoutMs: 3000, metadata: { region: 'us-east' } },
cache: { enabled: false },
};
const parsed = parseConfigMap(validConfig);
assert.strictEqual(parsed.database.enabled, true);
assert.strictEqual(parsed.database.timeoutMs, 3000);
assert.strictEqual(parsed.database.metadata.region, 'us-east');
assert.strictEqual(parsed.cache.enabled, false);
assert.strictEqual(parsed.cache.timeoutMs, 5000, 'applies default timeout');
assert.deepStrictEqual(parsed.cache.metadata, {});
const invalidConfig = {
serviceA: { enabled: 'not-a-boolean' },
};
const invalidRes = safeParseConfigMap(invalidConfig);
assert.strictEqual(invalidRes.success, false);
assert.ok(
invalidRes.error.issues.some(
(iss) => iss.path.join('.') === 'serviceA.enabled' && iss.code === 'invalid_type'
),
'reports invalid type on dictionary value property'
);
}
// 5. z.lazy combined with z.record validates nested recursive JSON-like tree hierarchies with property maps
{
const complexJson = {
title: 'Config Tree',
version: 1,
nested: {
active: true,
tags: ['alpha', 'beta', null, 42],
subRecord: {
innerKey: {
deepList: [{ flag: false }],
},
},
},
};
const parsed = parseJsonValue(complexJson);
assert.strictEqual(parsed.title, 'Config Tree');
assert.strictEqual(parsed.version, 1);
assert.strictEqual(parsed.nested.active, true);
assert.deepStrictEqual(parsed.nested.tags, ['alpha', 'beta', null, 42]);
assert.strictEqual(parsed.nested.subRecord.innerKey.deepList[0].flag, false);
const invalidValue = safeParseJsonValue(undefined);
assert.strictEqual(invalidValue.success, false, 'rejects undefined');
const invalidFunc = safeParseJsonValue({ fn: () => {} });
assert.strictEqual(invalidFunc.success, false, 'rejects functions');
}
// 6. safeParse on recursive schemas returns detailed issue path for malformed deep leaves
{
const malformedPayload = {
menu: {
header: 'Main',
items: [
{ name: 'Home' },
{ name: 'Settings', sub: { invalidKey: Symbol('cannot serialize') } },
],
},
};
const result = safeParseJsonValue(malformedPayload);
assert.strictEqual(result.success, false);
assert.ok(result.error.issues.length > 0);
}
// 7. Verify z.lazy export and function signature
{
assert.strictEqual(typeof z.lazy, 'function');
assert.strictEqual(typeof z.record, 'function');
}
console.log('Contract tests passed successfully.');
}
runTests();
Seeder d'origine
anonyme