CodeSampleX

Beispiel

zod 3.25.76: Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod

Verifiziertes Beispiel für npm zod 3.25.76: Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod. Der Vertrag lief auf…

sha256:8481cecd353d1aa53e78f3fe731486c75549aa16aeeab769d5ff48b918566655

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 npm

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
Validate recursive tree structures and dynamic key records using z.lazy and z.record in Zod
Pakete
Symbole
  • zod.z.lazy
Erstellt
2026-08-23T06:52:13Z

Contract

  1. z.lazy allows defining recursive self-referential schemas for tree nodes with nested child nodes
  2. z.lazy validates deeply nested hierarchical structures without infinite recursion
  3. z.lazy rejects invalid child nodes deep within the tree structure reporting exact error paths
  4. z.record validates dynamic key-value dictionaries with typed string keys and schema-validated values
  5. z.lazy combined with z.record validates nested recursive JSON-like tree hierarchies with property maps
  6. safeParse on recursive schemas returns detailed issue path for malformed deep leaves

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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: 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.
csx.json
{"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"}
index.js
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,
};
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "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"
  }
}
spec.json
{
  "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"
  ]
}
test/contract.js
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();

Ursprungs-Seeder

anonym