Documentation

API Reference

generate

generate<TSchema>(schema: TSchema, options?: GenerateOptions<output<TSchema>>): output<TSchema>

Zero-config entry point. Generates a value from any Zod schema without any world setup. Internally creates a temporary world and discards it.

Parameters

schema

TSchema

Any Zod schema to generate a value from.

options

GenerateOptions<output<TSchema>>· optional

Per-call GenerateOptions (`seed`, `overrides`, …).

overrides
DeepPartial<T>· optional

Partial values deep-merged onto the generated result, overriding any field. An array override sets the array element count: the result has exactly `override.length` elements, and `overrides[i]` deep-merges onto the i-th generated base element (un-overridden siblings preserved; a sparse hole / `undefined` slot leaves that element fully generated). The override length wins even over an explicit `.length(N)`; schema bounds (`.length()` / `.min()` / `.max()`) and `defaultArrayLength` govern only the no-override count.

transform
{ … }· optional

Post-processor applied to the generated value before it is returned/stored.

store
boolean· optional

When `false`, suppress the registry write for this `world.generate` call — useful for ephemeral generation (search-bucket envelopes, paginated responses, one-off fixtures). Propagates through nested generation so inner registered schemas are also not stored. Ignored by `world.get` (its create path must always store) and by `world.populate` (its purpose is to populate the registry). Default `true`.

unique
boolean· optional

When `false`, bypass the derived-schema upsert keyed by `(schema, source)`: generate a fresh record even if a derived record already exists for this source. Has no effect on schemas without `from:`. Default `true` (upsert).

seed
number· optional

Seed for this call's PRNG; same seed + schema yields the same value.

optionalProbability
number· optional

Probability (0–1) that an optional field is present.

defaultArrayLength
readonly [number, number]· optional

Default `[min, max]` length for unconstrained arrays.

recursionLimit
number· optional

Maximum recursion depth for self-referential / nested schemas.

locale
LocaleData· optional

Locale supplying names, words, and other locale-specific data.

Example

import { generate } from "zod4-mock";

const user = generate(UserSchema);
const admin = generate(UserSchema, { overrides: { role: "admin" }, seed: 42 });

createWorld

createWorld(options?: WorldOptions): World

Create a World — the central, deterministic generation session. Chain `.withSchema` / `.withGenerators` / `.withKeyMap` to configure it, then `.generate` / `.populate` to produce data. One world = one seed = one dataset.

Parameters

options

WorldOptions· optional

World-wide settings (WorldOptions); the `seed` fixes determinism.

generators
Record<string, KeyGenerator<unknown>>· optional

Custom field-name generators, matched case-insensitively by field name.

trace
boolean· optional

Opt in to provenance capture for World.trace. When omitted (or `false`), `world.trace()` still returns the registry projection — one TraceNode per stored record — but no per-field or relation-edge provenance is captured. (At the current stub the flag is plumbing only: field and edge capture land in later cards, so an enabled trace returns the same shape as a default one.)

seed
number· optional

Seed for this call's PRNG; same seed + schema yields the same value.

optionalProbability
number· optional

Probability (0–1) that an optional field is present.

defaultArrayLength
readonly [number, number]· optional

Default `[min, max]` length for unconstrained arrays.

recursionLimit
number· optional

Maximum recursion depth for self-referential / nested schemas.

locale
LocaleData· optional

Locale supplying names, words, and other locale-specific data.

Example

import { createWorld } from "zod4-mock";

const world = createWorld({ seed: 1 });
world.withSchema(UserSchema);
const user = world.generate(UserSchema);

createPrng

createPrng(seed: number): Prng

Create a seeded PRNG.

Parameters

seed

number

Any 32-bit integer. The same seed always produces the same sequence.

World

interface World

One deterministic generation session, built fluently from `createWorld`. Register schemas (`withSchema`), wire generators (`withGenerators`, `withKeyMap`), produce data (`generate`, `get`, `populate`, `populateFrom`), and introspect resolution (`explain`) or provenance (`trace`); all records live in its `registry`.

withSchema

withSchema<TSchema, TSource, TRelations>(schema: TSchema, opts?: SchemaOpts<TSchema, TSource, TRelations>): this

Register a schema with optional matchers, relations, or a source binding. Primary (no from:): world.withSchema(PersonSchema, { matchers: { email: (ctx) => ... } }) Relational (with relations:): world.withSchema(FileSchema, { relations: { owner: PersonSchema }, matchers: { ownerId: (ctx) => ctx.related("owner").personId }, }) Derived (with from:): world.withSchema(SummarySchema, { from: PersonSchema, matchers: { id: (ctx) => ctx.source.personId }, }) The same output schema can be registered multiple times, each with a different `from:` binding, to represent multiple source types.

withGenerators

withGenerators(map: Record<string, KeyGenerator>): this

Register additional key-based generators. Calls are additive. Keys are matched case-insensitively against field names.

withKeyMap

withKeyMap<T>(schema: T, map: SchemaKeyMap<T>): this

Bind field generators to a specific schema (legacy API, kept for compat).

generate

generate<TSchema>(schema: TSchema, options?: GenerateOptions<output<TSchema>>): output<TSchema>

Generate a value from a Zod schema. - Object schema → single generated object - z.array(schema) → array respecting min/max/length constraints - Registered derived schemas → one record per source

get

get<TSchema>(schema: TSchema, predicate?: Partial<input<TSchema>>): output<TSchema>

Find an existing stored record matching `predicate`, or generate one. Search the registry for the first stored record (insertion order) for which every key in `predicate` matches the record's value — shallow keys by value, nested-object values by deep equality. If one is found it is returned by reference. Otherwise a new record is generated via the `generate` overrides path with `predicate` supplied as `overrides` (so the predicate wins over matchers), stored in the registry for `schema`, and returned. An absent or empty predicate matches everything: returns the first stored record if any exist, else generates-and-stores one. Deterministic for a given seed and idempotent for a repeated predicate.

populate

populate<TSchema>(schema: TSchema, count: number, factory?: {}): this

Pre-generate `count` instances of the schema and store them in the registry. Returns `this` for fluent chaining. An optional per-record `factory` may be supplied. When given, it is invoked once per record with the 0-based index and must return `GenerateOptions` (`overrides`, `transform`, etc.) for that record. The returned options flow through the normal generate pipeline.

populateFrom

populateFrom<TDerived, TSource>(derivedSchema: TDerived, sourceSchema: TSource, predicate?: {}, factory?: {}): this

Iterate the source bucket and call `world.generate(derivedSchema, { source })` once per source record (filtered by `predicate` if supplied). The optional `factory` receives the source record itself (`z.infer<TSource>`, contrast `populate`'s index-based factory) and returns `GenerateOptions<TDerived>` that flow through the delegated `generate` call. Idempotence comes from the per-`(derivedSchema, identity(source))` upsert: re-running `populateFrom` with the same arguments leaves the derived bucket unchanged. The source bucket is snapshotted at call start — mid-loop inserts to it are visible only to the next `populateFrom` call. Always writes (like `populate`): a factory return containing `store: false` is silently stripped. Returns `this` for fluent chaining.

explain

explain<TSchema>(schema: TSchema): ExplainResult<TSchema>

Read-only debug helper: for each top-level field of `schema`, report which step of the resolution pipeline (matcher → withKeyMap → withGenerators → exact-key → key-pattern → schema-based) would resolve the field, and a short reason. Returns a structured `ExplainResult` with a `toString()` formatter for human-readable output. PRNG-neutral and registry-neutral — calling `explain` does not consume the world PRNG, does not write to the registry, and does not advance any generation counter.

trace

trace(): WorldTrace

Return the provenance structure for everything generated so far in this world's lifetime — a plain, JSON-serializable WorldTrace. Emits one TraceNode per stored registry record (in registration order), each carrying the record's stable id, its value, and its registration polarity (`node<regId>` for primary, `derived<regId>` for derived, with `derivedFrom` set on derived nodes). `seed` echoes the world's root seed. Provenance capture is opt-in via `createWorld({ trace: true })`. At the current stub every node's `fields` and the trace's `edges` are empty (field and relation-edge capture land in later cards), so an enabled trace returns the same shape as a default one.

Registry

interface Registry

In-memory store of every record generated within one world, keyed by Zod schema reference. Matchers reach across schemas through it (`pick`, `all`, `find`) to keep generated data mutually consistent.

store

store<T>(schema: T, item: input<T>): void

all

all<T>(schema: T): output<T>[]

pick

pick<T>(schema: T): output<T>

filter

filter<T>(schema: T, predicate: {}): output<T>[]

find

find<T>(schema: T, predicate: {}): output<T> | undefined

count

count(schema: ZodType): number

GeneratorContext

interface GeneratorContext

The per-field context handed to every generator and matcher. Carries the field-seeded `prng`, the bound `gen` namespace, registry access, the relation resolver, accumulated sibling values (`current`), and the active locale for one field of one record.

generate

generate<S>(schema: S, options?: GenerateOptions<output<S>>): output<S>

Generates a value using the full world engine (honoring matchers and registry).

GenerationDefaults

interface GenerationDefaults

World-wide generation defaults shared by `WorldOptions` (set once) and `GenerateOptions` (override per call).

seed

number· optional

Seed for this call's PRNG; same seed + schema yields the same value.

optionalProbability

number· optional

Probability (0–1) that an optional field is present.

defaultArrayLength

readonly [number, number]· optional

Default `[min, max]` length for unconstrained arrays.

recursionLimit

number· optional

Maximum recursion depth for self-referential / nested schemas.

locale

LocaleData· optional

Locale supplying names, words, and other locale-specific data.

GenerateOptions

interface GenerateOptions

Per-call options for `generate` / `world.generate`: `overrides` (deep-merged onto the result), a `transform` post-processor, the `seed`, and tuning knobs for optional probability, array length, recursion, and registry writes.

overrides

DeepPartial<T>· optional

Partial values deep-merged onto the generated result, overriding any field. An array override sets the array element count: the result has exactly `override.length` elements, and `overrides[i]` deep-merges onto the i-th generated base element (un-overridden siblings preserved; a sparse hole / `undefined` slot leaves that element fully generated). The override length wins even over an explicit `.length(N)`; schema bounds (`.length()` / `.min()` / `.max()`) and `defaultArrayLength` govern only the no-override count.

transform

{ … }· optional

Post-processor applied to the generated value before it is returned/stored.

store

boolean· optional

When `false`, suppress the registry write for this `world.generate` call — useful for ephemeral generation (search-bucket envelopes, paginated responses, one-off fixtures). Propagates through nested generation so inner registered schemas are also not stored. Ignored by `world.get` (its create path must always store) and by `world.populate` (its purpose is to populate the registry). Default `true`.

unique

boolean· optional

When `false`, bypass the derived-schema upsert keyed by `(schema, source)`: generate a fresh record even if a derived record already exists for this source. Has no effect on schemas without `from:`. Default `true` (upsert).

Inherited from GenerationDefaults: seed·optionalProbability·defaultArrayLength·recursionLimit·locale

WorldOptions

interface WorldOptions

Options passed to `createWorld`. Sets the master `seed` and world-wide defaults — optional-field probability, unconstrained-array length, custom key generators, recursion limit, and the active locale.

generators

Record<string, KeyGenerator<unknown>>· optional

Custom field-name generators, matched case-insensitively by field name.

trace

boolean· optional

Opt in to provenance capture for World.trace. When omitted (or `false`), `world.trace()` still returns the registry projection — one TraceNode per stored record — but no per-field or relation-edge provenance is captured. (At the current stub the flag is plumbing only: field and edge capture land in later cards, so an enabled trace returns the same shape as a default one.)

Inherited from GenerationDefaults: seed·optionalProbability·defaultArrayLength·recursionLimit·locale

SchemaOpts

interface SchemaOpts

Options for withSchema. - If `from` is provided, the schema is "derived" and matchers receive `ctx.source`. - If `from` is omitted, the schema is "primary" and `ctx.source` is undefined.

from

TSource· optional

sourceKey

conditional· optional

Identity field on the source record used to key the per-pair derived-schema upsert. When omitted, identity falls back to reference equality on `source`. Declared at registration only — not overridable per `generate` call.

relations

mapped· optional

matchers

mapped· optional

ExplainResult

interface ExplainResult

Structured introspection result for `world.explain(schema)`. The `fields` map is keyed by top-level field name in schema-shape order; the `relations` map is keyed by relation name (empty `{}` when none). The `toString()` method produces a human-readable aligned table.

toString

toString(): string

Currency

interface Currency

An ISO 4217 currency record drawn by money generators: alphabetic `code`, display `name`, `symbol`, and the ISO `numeric` code.

code

string

name

string

symbol

string

numeric

string

FieldExplanation

interface FieldExplanation

Per-field resolution record returned by `world.explain(schema)`. `generator` is a stable identifier (e.g. `'person.firstName'`, `'matcher:<key>'`, `'schema-based'`); `reason` is a short human-readable explanation of which step of the pipeline picked it.

generator

string

reason

string

LastNamePrefix

interface LastNamePrefix

A surname prefix (tussenvoegsel) with its relative sampling weight.

prefix

string

weight

number

LocaleData

interface LocaleData

The full set of locale-specific word lists and formatting callbacks a world draws from. Bundled locales (`en`, `nl`) implement it; pass a custom one via `WorldOptions.locale` or compose one with `extend` (from `@zod4-mock/locale-en` / `@zod4-mock/locale-nl`).

id

string

frequencyExponent

number· optional

Locale-level Zipf exponent applied at open-corpus `pickZipf` call sites when no per-corpus override is present. Resolved at the data-generator call site as `overrides[corpusName] ?? frequencyExponent ?? 1.0`, so locales authored without this field continue to behave unchanged.

frequencyExponentOverrides

Readonly<Partial<Record<string, number>>>· optional

Per-corpus Zipf exponent overrides (keyed by data-generator corpus name, e.g. `lastNames`, `firstNamesMale`). Wins over `frequencyExponent` for the matching corpus; closed/enumerable lists ignore this map entirely.

person

{ … }

address

{ … }

commerce

{ … }

company

{ … }

word

{ … }

finance

{ … }

date

{ … }

color

{ … }

phone

{ … }

internet

{ … }· optional

Prng

interface Prng

Seeded pseudo-random number generator. Implemented in the main `zod4-mock` package.

random

random(): number

int

int(min: number, max: number): number

pick

pick<T>(items: readonly [T, T]): T

pickZipf

pickZipf<T>(items: readonly T[], s: number): T

Zipf-distributed pick from a freq-sorted array via a closed-form inverse-CDF draw — one `random()`, no rejection loop. `s = 0` reproduces `pick`; `s = 1` is classic Zipf. See B51 report §3 for the formula.

logUniform

logUniform(min: number, max: number): number

Closed-form log-uniform draw on `[min, max]` — one `random()`, no rejection. Formula: `min * Math.pow(max / min, u)` for `u = random()`. Caller MUST ensure `min > 0`; cross-zero handling lives in the per-key generators. See B54 research report §5 / B57 R8.

geometric

geometric(p: number): number

Truncated-geometric draw with parameter `p ∈ (0, 1)` — one `random()`, no rejection. Returns a non-negative integer offset from 0: `Math.floor(Math.log(1 - u) / Math.log(1 - p))`. Callers add `min` if desired. See B54 research report §3 / B57 R8.

shuffle

shuffle<T>(items: readonly T[]): T[]

sample

sample<T>(items: readonly T[], count: number): T[]

fork

fork(key: string): Prng

bytes

bytes(n: number): Uint8Array

RelationExplanation

interface RelationExplanation

Per-relation record on `ExplainResult.relations`. `schema` is the leaf `def.type` of the related schema (e.g. `'object'`, `'lazy'`); `where` reports whether the relation entry was the object form `{ schema, where }` with a predicate.

schema

string

where

"present" | "none"

TraceEdge

interface TraceEdge

One relation pick in a WorldTrace: the `from` node's `fromField` referenced the `to` node via the named `relation`, a one-to-one (`"one"`) or one-to-many (`"many"`) pick drawn from a pool of `poolSize` candidates at `pickedIndex`.

from

string

fromField

string

to

string

relation

string

kind

"one" | "many"

poolSize

number

pickedIndex

number

TraceField

interface TraceField

Per-field provenance entry on a TraceNode. Extends `FieldExplanation` so `world.trace()` and `world.explain()` speak one provenance language: `generator` (a stable generator-id string, e.g. `'person.firstName'`, `'matcher:<key>'`, `'schema-based'`) and `reason` (a short human-readable explanation) carry the identical meaning in both. Adds the trace-only fields: the field `path`, the produced `value`, the resolving `resolution` rung, the PRNG `forkKey`, whether an override won (`overridden`), and the relation/field `dependsOn` keys consulted.

path

string

Dotted field path within the record (e.g. `"user.email"`).

value

unknown

The value produced for this field. JSON-serializable.

resolution

TraceResolution

Which pipeline rung resolved the value.

forkKey

string

The PRNG fork key used to seed this field.

overridden

boolean

Whether an `options.overrides` entry won over the pipeline value.

dependsOn

string[]

Sibling field / relation keys this field's value depended on.

Inherited from FieldExplanation: generator·reason

TraceNode

interface TraceNode

One generated record in a WorldTrace. `id` is the stable, human-friendly `` `${typeName}#${index}` `` id (e.g. `"person#1"`, `"order#5"`) — a binding public contract: the `typeName` is the registration's display name (the Zod schema's `.description`, else the stable `` `schema${id}` `` fallback), and the `<index>` is **1-based** (the first record of a type is `#1`). When two registrations of the same polarity resolve to the same display name, the id auto-disambiguates by registration order (`user`, `user-2`, `user-3`, …) rather than throwing. `type` is that same resolved `typeName`. `index` is the record's **0-based** position within its registration. `value` is the stored record; `store` reflects whether the record was written to the registry. `derivedFrom` is present only for derived records and holds the source node's friendly id (e.g. `"person#1"`). `fields` is the per-field provenance.

id

string

Friendly `` `${typeName}#${index}` `` id (1-based index), e.g. `"person#1"`.

type

string

index

number

value

unknown

derivedFrom

string· optional

For derived records, the friendly id of the source node (e.g. `"person#1"`).

store

boolean

fields

TraceField[]

WorldTrace

interface WorldTrace

The full provenance structure returned by World.trace: the world's root `seed`, one TraceNode per stored record, and one TraceEdge per relation pick. Fully JSON-serializable.

seed

number

nodes

TraceNode[]

edges

TraceEdge[]