CodeSampleX

サンプル

zod 4.4.3: ZodType

検証済みサンプル — npm zod 4.4.3: ZodType. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: zod.ZodType is the base schema constructor and primitive and…

sha256:24d673f2829f1090af8e812b00bdccb7aed79089930e9cdba105f3dd781702a3

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
2
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 npm

検証実行環境

環境 コントラクト ステージ 実行日
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
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 SKIPPED compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

ケース

HOW
ゴール
verify zod.ZodType in pkg:npm/zod@4.4.3
パッケージ
シンボル
  • zod.ZodType
作成日
2026-08-23T05:43:15Z

コントラクト

  1. zod.ZodType is the base schema constructor and primitive and composite schemas are instances of ZodType
  2. ZodType parse method synchronously validates valid input and throws ZodError on invalid input
  3. ZodType safeParse method returns success result object with parsed data or failure object with error issues
  4. ZodType optional, nullable, and default combinator methods produce schema instances handling undefined and null values
  5. ZodType refine and transform methods create validation pipeline stages for custom assertions and data transformation
  6. ZodType pipe and or combinators compose sequential schema validation and type unions

ファイル

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

ソースアーティファクトをダウンロード (tar.gz)

ソース

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.ZodType in pkg:npm/zod@4.4.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/zod@4.4.3
Demonstrate these symbols/APIs:
  - zod.ZodType

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:39a2e49f54f14189cca418a6dbfc7d450eff0254c63904a77f24f76252a8f70e","contract":["zod.ZodType is the base schema constructor and primitive and composite schemas are instances of ZodType","ZodType parse method synchronously validates valid input and throws ZodError on invalid input","ZodType safeParse method returns success result object with parsed data or failure object with error issues","ZodType optional, nullable, and default combinator methods produce schema instances handling undefined and null values","ZodType refine and transform methods create validation pipeline stages for custom assertions and data transformation","ZodType pipe and or combinators compose sequential schema validation and type unions"],"goal":"verify zod.ZodType in pkg:npm/zod@4.4.3","kind":"HOW","packages":["pkg:npm/zod@4.4.3"],"schemaVersion":1,"symbols":["zod.ZodType"]},"contractCommand":["node","test/contract.mjs"],"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@4.4.3"],"schemaVersion":1,"subject":"pkg:npm/zod@4.4.3","symbols":["zod.ZodType"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-zod-zodtype",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-zod-zodtype",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "zod": "4.4.3"
      }
    },
    "node_modules/zod": {
      "version": "4.4.3",
      "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",
      "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",
      "license": "MIT",
      "funding": {
        "url": "https://github.com/sponsors/colinhacks"
      }
    }
  }
}
package.json
{
  "name": "sample-zod-zodtype",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of zod.ZodType in zod@4.4.3",
  "main": "src/index.mjs",
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "zod": "4.4.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify zod.ZodType in pkg:npm/zod@4.4.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/zod@4.4.3"
  ],
  "symbols": [
    "zod.ZodType"
  ]
}
src/index.mjs
import { z, ZodType, ZodError } from "zod";

/**
 * Checks whether the given schema is an instance of ZodType.
 *
 * @param {unknown} schema - Candidate schema to inspect.
 * @returns {boolean} True if schema is a ZodType instance.
 */
export function isZodType(schema) {
  return schema instanceof ZodType;
}

/**
 * Validates data against a ZodType schema and returns a safe result object.
 *
 * @template T
 * @param {ZodType<T>} schema - Zod schema to validate with.
 * @param {unknown} data - Data to parse.
 * @returns {{ success: true; data: T } | { success: false; error: ZodError }} SafeParse result.
 */
export function safeValidate(schema, data) {
  if (!(schema instanceof ZodType)) {
    throw new TypeError("Expected an instance of ZodType");
  }
  return schema.safeParse(data);
}

/**
 * Validates data against a ZodType schema, throwing ZodError on failure.
 *
 * @template T
 * @param {ZodType<T>} schema - Zod schema to validate with.
 * @param {unknown} data - Data to parse.
 * @returns {T} Parsed and validated data.
 */
export function validateData(schema, data) {
  if (!(schema instanceof ZodType)) {
    throw new TypeError("Expected an instance of ZodType");
  }
  return schema.parse(data);
}

/**
 * Wraps a ZodType schema to provide a default value when input is undefined.
 *
 * @template T
 * @param {ZodType<T>} schema - Base schema.
 * @param {T} defaultValue - Fallback value.
 * @returns {ZodType<T>} Schema with default value.
 */
export function withDefault(schema, defaultValue) {
  if (!(schema instanceof ZodType)) {
    throw new TypeError("Expected an instance of ZodType");
  }
  return schema.default(defaultValue);
}

/**
 * Combines two ZodType schemas into a union.
 *
 * @template A, B
 * @param {ZodType<A>} first - First schema.
 * @param {ZodType<B>} second - Second schema.
 * @returns {ZodType<A | B>} Union schema.
 */
export function combineUnion(first, second) {
  if (!(first instanceof ZodType) || !(second instanceof ZodType)) {
    throw new TypeError("Expected instances of ZodType");
  }
  return first.or(second);
}

export { z, ZodType, ZodError };
export default z;
test/contract.mjs
import assert from "node:assert/strict";
import { z, ZodType, ZodError } from "zod";
import {
  isZodType,
  safeValidate,
  validateData,
  withDefault,
  combineUnion,
} from "../src/index.mjs";

// 1. zod.ZodType is the base schema constructor and primitive and composite schemas are instances of ZodType
assert.strictEqual(typeof ZodType, "function", "ZodType must be a constructor function");

const stringSchema = z.string();
const numberSchema = z.number();
const booleanSchema = z.boolean();
const objectSchema = z.object({ id: z.string(), count: z.number() });
const arraySchema = z.array(z.string());

assert.ok(stringSchema instanceof ZodType, "z.string() must be an instance of ZodType");
assert.ok(numberSchema instanceof ZodType, "z.number() must be an instance of ZodType");
assert.ok(booleanSchema instanceof ZodType, "z.boolean() must be an instance of ZodType");
assert.ok(objectSchema instanceof ZodType, "z.object() must be an instance of ZodType");
assert.ok(arraySchema instanceof ZodType, "z.array() must be an instance of ZodType");

assert.strictEqual(isZodType(stringSchema), true, "isZodType helper must return true for ZodType instance");
assert.strictEqual(isZodType({}), false, "isZodType helper must return false for plain object");

// 2. ZodType parse method synchronously validates valid input and throws ZodError on invalid input
assert.strictEqual(stringSchema.parse("valid-string"), "valid-string");
assert.strictEqual(numberSchema.parse(42), 42);
assert.deepStrictEqual(
  objectSchema.parse({ id: "item-101", count: 7 }),
  { id: "item-101", count: 7 }
);

assert.strictEqual(validateData(stringSchema, "hello"), "hello");

assert.throws(
  () => stringSchema.parse(999),
  (err) => {
    assert.ok(err instanceof ZodError, "Thrown error must be instance of ZodError");
    assert.ok(Array.isArray(err.issues), "ZodError issues must be an array");
    assert.strictEqual(err.issues.length, 1);
    assert.strictEqual(err.issues[0].expected, "string");
    return true;
  }
);

assert.throws(
  () => objectSchema.parse({ id: "item-1" }),
  (err) => {
    assert.ok(err instanceof ZodError);
    assert.deepStrictEqual(err.issues[0].path, ["count"]);
    return true;
  }
);

// 3. ZodType safeParse method returns success result object with parsed data or failure object with error issues
const validResult = objectSchema.safeParse({ id: "item-202", count: 12 });
assert.strictEqual(validResult.success, true);
assert.deepStrictEqual(validResult.data, { id: "item-202", count: 12 });

const safeHelperResult = safeValidate(objectSchema, { id: "item-202", count: 12 });
assert.strictEqual(safeHelperResult.success, true);
assert.deepStrictEqual(safeHelperResult.data, { id: "item-202", count: 12 });

const invalidResult = objectSchema.safeParse({ id: 123, count: "invalid" });
assert.strictEqual(invalidResult.success, false);
assert.ok(invalidResult.error instanceof ZodError);
assert.strictEqual(invalidResult.error.issues.length, 2);

// 4. ZodType optional, nullable, and default combinator methods produce schema instances handling undefined and null values
const optionalSchema = z.string().optional();
assert.ok(optionalSchema instanceof ZodType);
assert.strictEqual(optionalSchema.parse(undefined), undefined);
assert.strictEqual(optionalSchema.parse("defined"), "defined");

const nullableSchema = z.number().nullable();
assert.ok(nullableSchema instanceof ZodType);
assert.strictEqual(nullableSchema.parse(null), null);
assert.strictEqual(nullableSchema.parse(25), 25);

const defaultSchema = withDefault(z.string(), "fallback-value");
assert.ok(defaultSchema instanceof ZodType);
assert.strictEqual(defaultSchema.parse(undefined), "fallback-value");
assert.strictEqual(defaultSchema.parse("custom-value"), "custom-value");

// 5. ZodType refine and transform methods create validation pipeline stages for custom assertions and data transformation
const refinedSchema = z.string().refine((val) => val.startsWith("CSX_"), {
  message: "String must start with CSX_",
});
assert.ok(refinedSchema instanceof ZodType);
assert.strictEqual(refinedSchema.parse("CSX_ALPHA"), "CSX_ALPHA");
assert.throws(
  () => refinedSchema.parse("INVALID_PREFIX"),
  (err) => {
    assert.ok(err instanceof ZodError);
    assert.strictEqual(err.issues[0].message, "String must start with CSX_");
    return true;
  }
);

const transformedSchema = z.string().transform((val) => val.trim().toUpperCase());
assert.ok(transformedSchema instanceof ZodType);
assert.strictEqual(transformedSchema.parse("  hello world  "), "HELLO WORLD");

// 6. ZodType pipe and or combinators compose sequential schema validation and type unions
const pipedSchema = z.string().pipe(z.string().min(5));
assert.ok(pipedSchema instanceof ZodType);
assert.strictEqual(pipedSchema.parse("abcdef"), "abcdef");
assert.throws(() => pipedSchema.parse("abc"));

const unionSchema = combineUnion(z.string(), z.number());
assert.ok(unionSchema instanceof ZodType);
assert.strictEqual(unionSchema.parse("union-text"), "union-text");
assert.strictEqual(unionSchema.parse(100), 100);
assert.throws(() => unionSchema.parse(false));

console.log("All zod.ZodType contract assertions passed successfully.");

オリジンシーダー

匿名