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
TSchemaAny Zod schema to generate a value from.
Per-call GenerateOptions (`seed`, `overrides`, …).
Example
import { generate } from "zod4-mock";
const user = generate(UserSchema);
const admin = generate(UserSchema, { overrides: { role: "admin" }, seed: 42 });createWorld
createWorld(options?: WorldOptions): WorldCreate 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
World-wide settings (WorldOptions); the `seed` fixes determinism.
Example
import { createWorld } from "zod4-mock";
const world = createWorld({ seed: 1 });
world.withSchema(UserSchema);
const user = world.generate(UserSchema);createPrng
createPrng(seed: number): PrngCreate a seeded PRNG.
Parameters
seed
numberAny 32-bit integer. The same seed always produces the same sequence.
World
interface WorldOne 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>): thisRegister 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>): thisRegister additional key-based generators. Calls are additive. Keys are matched case-insensitively against field names.
withKeyMap
withKeyMap<T>(schema: T, map: SchemaKeyMap<T>): thisBind 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?: { … }): thisPre-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?: { … }): thisIterate 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(): WorldTraceReturn 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 RegistryIn-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>): voidall
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> | undefinedcount
count(schema: ZodType): numberGeneratorContext
interface GeneratorContextThe 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 GenerationDefaultsWorld-wide generation defaults shared by `WorldOptions` (set once) and `GenerateOptions` (override per call).
seed
number· optionalSeed for this call's PRNG; same seed + schema yields the same value.
optionalProbability
number· optionalProbability (0–1) that an optional field is present.
defaultArrayLength
readonly [number, number]· optionalDefault `[min, max]` length for unconstrained arrays.
recursionLimit
number· optionalMaximum recursion depth for self-referential / nested schemas.
Locale supplying names, words, and other locale-specific data.
GenerateOptions
interface GenerateOptionsPer-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>· optionalPartial 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
{ … }· optionalPost-processor applied to the generated value before it is returned/stored.
store
boolean· optionalWhen `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· optionalWhen `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 WorldOptionsOptions 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>>· optionalCustom field-name generators, matched case-insensitively by field name.
trace
boolean· optionalOpt 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 SchemaOptsOptions 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· optionalsourceKey
conditional· optionalIdentity 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· optionalmatchers
mapped· optionalExplainResult
interface ExplainResultStructured 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(): stringCurrency
interface CurrencyAn ISO 4217 currency record drawn by money generators: alphabetic `code`, display `name`, `symbol`, and the ISO `numeric` code.
code
stringname
stringsymbol
stringnumeric
stringFieldExplanation
interface FieldExplanationPer-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
stringreason
stringLastNamePrefix
interface LastNamePrefixA surname prefix (tussenvoegsel) with its relative sampling weight.
prefix
stringweight
numberLocaleData
interface LocaleDataThe 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
stringfrequencyExponent
number· optionalLocale-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>>>· optionalPer-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
{ … }· optionalPrng
interface PrngSeeded pseudo-random number generator. Implemented in the main `zod4-mock` package.
random
random(): numberint
int(min: number, max: number): numberpick
pick<T>(items: readonly [T, T]): TpickZipf
pickZipf<T>(items: readonly T[], s: number): TZipf-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): numberClosed-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): numberTruncated-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): Prngbytes
bytes(n: number): Uint8ArrayRelationExplanation
interface RelationExplanationPer-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
stringwhere
"present" | "none"TraceEdge
interface TraceEdgeOne 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
stringfromField
stringto
stringrelation
stringkind
"one" | "many"poolSize
numberpickedIndex
numberTraceField
interface TraceFieldPer-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
stringDotted field path within the record (e.g. `"user.email"`).
value
unknownThe value produced for this field. JSON-serializable.
resolution
TraceResolutionWhich pipeline rung resolved the value.
forkKey
stringThe PRNG fork key used to seed this field.
overridden
booleanWhether 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 TraceNodeOne 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
stringFriendly `` `${typeName}#${index}` `` id (1-based index), e.g. `"person#1"`.
type
stringindex
numbervalue
unknownderivedFrom
string· optionalFor derived records, the friendly id of the source node (e.g. `"person#1"`).
store
booleanfields
TraceField[]WorldTrace
interface WorldTraceThe 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.