CodeSampleX

Sample

zod 3.25.76

Verified sample for npm zod 3.25.76. The contract ran on node 22 · linux alpine/x64 · docker and passed: z.object and primitive schemas validate structured…

sha256:96dcacf3a83e327416fc9943129042c928b8c2cdc477ed1f369927507c5d4914

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19

Case

HOW
Goal
verify pkg:npm/zod@3.25.76
Packages
Environment
node 22.23.2
Created
2026-08-19T18:34:48Z

Contract

  1. z.object and primitive schemas validate structured data and parse conforming inputs with default values
  2. z.discriminatedUnion and schema transformations validate tagged variants and transform parsed payloads
  3. safeParse and ZodError formatting provide field-level error messages and structured error flattening

Files

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

Download the source artifact (tar.gz)

Source

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 pkg:npm/zod@3.25.76
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/zod@3.25.76
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:76048640fd8506b47d6ab3c54eeb8bccea8df4b484fe53a4fe28afbb095882da","constraints":{"executionContext":"node"},"contract":["z.object and primitive schemas validate structured data and parse conforming inputs with default values","z.discriminatedUnion and schema transformations validate tagged variants and transform parsed payloads","safeParse and ZodError formatting provide field-level error messages and structured error flattening"],"goal":"verify pkg:npm/zod@3.25.76","kind":"HOW","packages":["pkg:npm/zod@3.25.76"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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@3.25.76"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "zod-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "zod-sample",
      "version": "1.0.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": "zod-sample",
  "version": "1.0.0",
  "dependencies": {
    "zod": "3.25.76"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/zod@3.25.76",
  "kind": "HOW",
  "packages": [
    "pkg:npm/zod@3.25.76"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { z } = require('zod');

/**
 * Creates a schema for validating structured user records.
 *
 * @returns {import('zod').ZodObject}
 */
function createUserSchema() {
  return z.object({
    id: z.string().min(1),
    username: z.string().min(3).max(20),
    email: z.string().email(),
    age: z.number().int().min(0).max(120).optional(),
    roles: z.array(z.enum(['admin', 'member', 'guest'])).default(['member']),
    isActive: z.boolean().default(true),
  });
}

/**
 * Validates and parses user data against the user schema.
 *
 * @param {import('zod').ZodSchema} schema
 * @param {unknown} data
 * @returns {object}
 */
function parseUserData(schema, data) {
  return schema.parse(data);
}

/**
 * Creates a discriminated union schema for handling tagged event variants.
 *
 * @returns {import('zod').ZodDiscriminatedUnion}
 */
function createEventSchema() {
  return z.discriminatedUnion('type', [
    z.object({
      type: z.literal('message'),
      content: z.string().min(1),
      timestamp: z.number().int().positive(),
    }),
    z.object({
      type: z.literal('notification'),
      level: z.enum(['info', 'warning', 'error']),
      message: z.string().min(1),
    }),
    z.object({
      type: z.literal('metric'),
      name: z.string().min(1),
      value: z.number(),
    }),
  ]);
}

/**
 * Creates a schema that validates a list of records and transforms them.
 *
 * @returns {import('zod').ZodEffects}
 */
function createBatchTransformSchema() {
  const itemSchema = z.object({
    key: z.string().trim().toLowerCase(),
    score: z.number().min(0).max(100),
  });

  return z.array(itemSchema).transform((items) => {
    const totalScore = items.reduce((acc, item) => acc + item.score, 0);
    return {
      count: items.length,
      averageScore: items.length > 0 ? totalScore / items.length : 0,
      keys: items.map((item) => item.key),
    };
  });
}

/**
 * Performs safe parsing on input data and returns structured error formatting on failure.
 *
 * @param {import('zod').ZodSchema} schema
 * @param {unknown} data
 * @returns {{ success: true, data: any } | { success: false, issues: import('zod').ZodIssue[], formatted: object, flattened: object }}
 */
function safeValidate(schema, data) {
  const result = schema.safeParse(data);
  if (result.success) {
    return {
      success: true,
      data: result.data,
    };
  }

  return {
    success: false,
    issues: result.error.issues,
    formatted: result.error.format(),
    flattened: result.error.flatten(),
  };
}

module.exports = {
  z,
  createUserSchema,
  parseUserData,
  createEventSchema,
  createBatchTransformSchema,
  safeValidate,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  createUserSchema,
  parseUserData,
  createEventSchema,
  createBatchTransformSchema,
  safeValidate,
} = require('../src/index.js');

// Contract 1: z.object and primitive schemas validate structured data and parse conforming inputs with default values
{
  const schema = createUserSchema();

  const validData = {
    id: 'user-101',
    username: 'alexdev',
    email: 'alex@example.com',
    age: 28,
  };

  const parsed = parseUserData(schema, validData);
  assert.strictEqual(parsed.id, 'user-101', 'id should match input');
  assert.strictEqual(parsed.username, 'alexdev', 'username should match input');
  assert.strictEqual(parsed.email, 'alex@example.com', 'email should match input');
  assert.strictEqual(parsed.age, 28, 'age should match input');
  assert.deepStrictEqual(parsed.roles, ['member'], 'default role should be [member]');
  assert.strictEqual(parsed.isActive, true, 'default isActive should be true');

  // Throws error for invalid input
  assert.throws(
    () => parseUserData(schema, { id: 'user-102', username: 'al', email: 'invalid-email' }),
    (err) => {
      assert.strictEqual(err.name, 'ZodError');
      return true;
    },
    'Should throw ZodError on invalid username and email'
  );
}

// Contract 2: z.discriminatedUnion and schema transformations validate tagged variants and transform parsed payloads
{
  const eventSchema = createEventSchema();

  const msgEvent = eventSchema.parse({
    type: 'message',
    content: 'hello world',
    timestamp: 1700000000,
  });
  assert.strictEqual(msgEvent.type, 'message');
  assert.strictEqual(msgEvent.content, 'hello world');

  const notifEvent = eventSchema.parse({
    type: 'notification',
    level: 'warning',
    message: 'storage nearly full',
  });
  assert.strictEqual(notifEvent.type, 'notification');
  assert.strictEqual(notifEvent.level, 'warning');

  // Batch transform schema tests
  const batchSchema = createBatchTransformSchema();
  const rawBatch = [
    { key: '  ItemA  ', score: 80 },
    { key: 'ItemB', score: 90 },
  ];
  const transformed = batchSchema.parse(rawBatch);
  assert.strictEqual(transformed.count, 2, 'Count should be 2');
  assert.strictEqual(transformed.averageScore, 85, 'Average score should be (80+90)/2 = 85');
  assert.deepStrictEqual(transformed.keys, ['itema', 'itemb'], 'Keys should be trimmed and lowercased');
}

// Contract 3: safeParse and ZodError formatting provide field-level error messages and structured error flattening
{
  const userSchema = createUserSchema();

  const invalidInput = {
    id: '',
    username: 'x',
    email: 'not-an-email',
    age: -5,
  };

  const validationResult = safeValidate(userSchema, invalidInput);
  assert.strictEqual(validationResult.success, false, 'safeValidate should return success: false for invalid data');
  assert.ok(Array.isArray(validationResult.issues), 'issues should be an array');
  assert.ok(validationResult.issues.length >= 4, 'Should contain issues for id, username, email, and age');

  // Verify flattened error structure
  const { fieldErrors } = validationResult.flattened;
  assert.ok(Array.isArray(fieldErrors.id), 'fieldErrors.id should be an array');
  assert.ok(Array.isArray(fieldErrors.username), 'fieldErrors.username should be an array');
  assert.ok(Array.isArray(fieldErrors.email), 'fieldErrors.email should be an array');
  assert.ok(Array.isArray(fieldErrors.age), 'fieldErrors.age should be an array');

  // Verify formatted error structure
  assert.ok(validationResult.formatted.email._errors.length > 0, 'formatted error should contain email errors');

  // Test successful safe validation
  const validResult = safeValidate(userSchema, {
    id: 'user-ok',
    username: 'validuser',
    email: 'user@example.com',
  });
  assert.strictEqual(validResult.success, true, 'safeValidate should return success: true for valid input');
  assert.strictEqual(validResult.data.username, 'validuser');
}

console.log('All pkg:npm/zod@3.25.76 contracts passed successfully.');

Origin Seeder

anonymous