import { Faker } from '@faker-js/faker'; import { LocaleDefinition } from '@faker-js/faker'; import { Randomizer } from '@faker-js/faker'; /** * A factory function for the added-fields overload of {@link Factory.extend}. * It produces only the fields being added; base factory fields are preserved * and merged automatically, giving `Factory`. * * @template T - The base type the factory extends * @template Added - The fields being added */ export declare type AddedFieldsFunction = (factory: Factory, iteration: number, kwargs?: Partial) => FactorySchema | Promise>; export declare type AfterBuildHook = (obj: T) => Promise | T; /** * Abstract base class for generators that produce infinite sequences from finite iterables. * Converts iterables to arrays for efficient random access and validates non-empty input. * * @template T - The type of values to generate */ export declare abstract class BaseGenerator { protected values: T[]; constructor(iterable: Iterable); abstract generate(): Generator; } export declare type BeforeBuildHook = (params: Partial) => Partial | Promise>; export declare class CircularReferenceError extends Error { constructor(message?: string); } export declare class ConfigurationError extends Error { constructor(message: string); } /** * Error thrown when a constraint helper cannot produce a conforming value. * * @property field - The field the constraint applies to, when provided * @property constraint - The constraint name that was violated * @property attempts - How many generation attempts were made, when applicable */ export declare class ConstraintError extends Error { readonly attempts?: number; readonly constraint: string; readonly field?: string; constructor(options: { attempts?: number; constraint: string; field?: string; }); } export declare interface ConstraintOptions { /** * Maximum generation attempts before a `ConstraintError` is thrown. * Defaults to {@link DEFAULT_CONSTRAINT_ATTEMPTS}. */ attempts?: number; } /** * Sync constraint helpers for core factories (Zod/JSON Schema factories have * their own validation layers). Every helper produces a runtime reference * (Ref), just like `use()`, so the constrained value regenerates on every * build/batch and can be defined once and reused. * * Uniqueness is factory-local: each factory instance exposes its own * `constraints` object and therefore its own uniqueness tracking. * * @example * ```typescript * const UserFactory = new Factory((faker) => ({ * age: factory.use(() => ...), * email: factory.constraints.unique('email', () => faker.internet.email()), * })); * ``` */ export declare class Constraints { #private; /** * Produces a number constrained to at least `minValue` by clamping * the generated value (clamping keeps results deterministic and total). */ min(minValue: number, generate: Generate): number; /** * Produces a number constrained to at most `maxValue` by clamping * the generated value. */ max(maxValue: number, generate: Generate): number; /** * Produces a number constrained to the inclusive `[minValue, maxValue]` * range by clamping the generated value. */ between(minValue: number, maxValue: number, generate: Generate): number; /** * Produces a string matching `pattern`, regenerating until a match or * the attempt limit is reached (then a `ConstraintError` is thrown). */ pattern(pattern: Pattern, generate: Generate, options?: ConstraintOptions): string; /** * Produces a value the caller-defined `accepts` predicate approves, * regenerating until the predicate passes or the attempt limit is * reached (then a `ConstraintError` is thrown). */ custom(field: string, accepts: (value: R) => boolean, generate: Generate, options?: ConstraintOptions): R; /** * Produces a value not seen before for `field` on this factory * (factory-local uniqueness). Uniqueness is tracked across builds and * batch items on the factory's `constraints` object. */ unique(field: string, generate: Generate, options?: ConstraintOptions): R; } export declare interface CreateManyOptions { adapter?: PersistenceAdapter; presets?: string[]; } export declare interface CreateOptions { adapter?: PersistenceAdapter; } export declare function createSequenceFactory(): SequenceFactory; /** * Generates values by cycling through an array in sequential order. * When the end is reached, it starts over from the beginning, creating an infinite sequence. * Useful for predictable, repeating patterns in test data. * * @template T - The type of values to cycle through */ export declare class CycleGenerator extends BaseGenerator { generate(): Generator; } /** * Generates dates by stepping from a fixed start date. */ export declare class DateSequenceGenerator { #private; constructor({ start, step, unit }: DateSequenceOptions); generate(): Generator; } export declare interface DateSequenceOptions { start: Date | number | string; step?: number; unit?: 'day' | 'hour' | 'minute'; } /** * Default number of generation attempts for retry-based constraints * (`unique`, `pattern`, `custom`) before a `ConstraintError` is thrown. */ export declare const DEFAULT_CONSTRAINT_ATTEMPTS = 5; /** * A factory class for generating type-safe mock data by extending Faker.js functionality. * Provides methods for creating single instances, batches, and complex object compositions * with support for circular references through depth control and persistence. * * @template T - The type of objects this factory generates * @template O - The type of factory options */ export declare class Factory | PartialFactoryFunction = FactoryFunction> extends Faker { #private; readonly options?: { maxDepth: number; } & Omit; protected afterBuildHooks: AfterBuildHook[]; protected beforeBuildHooks: BeforeBuildHook[]; protected readonly factory: F; private defaultAdapter?; readonly sequence: SequenceFactory; /** * Constraint helpers bound to this factory instance. Uniqueness tracking * through {@link Constraints.unique} is factory-local. */ readonly constraints: Constraints; constructor(factory: F, { locale, randomizer, ...rest }?: Partial); /** * Adds a hook that will be executed after building the instance. * Hooks are executed in the order they were added and can be either synchronous or asynchronous. * This method returns the factory instance for method chaining. * * @param hook Function that receives the built instance and returns the modified instance * @returns The current Factory instance for method chaining */ afterBuild(hook: AfterBuildHook): this; /** * Generates an array of instances using the factory's schema. * Supports both uniform overrides (same for all instances) and individual overrides per instance. * * @param size Number of instances to generate (must be non-negative integer) * @param kwargs Either a single partial object (applied to all) or an array of partials (one per instance) * @returns Array of generated instances * @throws {Error} If size is negative or not an integer */ batch: (size: number, kwargs?: Partial | Partial[], options?: Partial) => T[]; /** * Creates multiple instances asynchronously, allowing use of async factory functions. * This method supports both synchronous and asynchronous factory functions and hooks. * * @param size Number of instances to generate (must be non-negative integer) * @param kwargs Either a single partial object (applied to all) or an array of partials (one per instance) * @returns Promise that resolves to an array of generated instances * @throws {Error} If size is negative or not an integer * * @example * ```typescript * const UserFactory = new Factory(async (factory) => ({ * id: factory.string.uuid(), * email: factory.internet.email(), * apiKey: await generateApiKey() // async operation * })); * * const users = await UserFactory.batchAsync(5); * ``` */ batchAsync(size: number, kwargs?: Partial | Partial[], options?: Partial): Promise ? T[] : Partial[]>; /** * Adds a hook that will be executed before building the instance. * Hooks receive the partial parameters (kwargs) and can modify them before the instance is built. * Multiple hooks are executed in the order they were added. * * @param hook Function that receives partial parameters and returns modified parameters * @returns The current Factory instance for method chaining */ beforeBuild(hook: BeforeBuildHook): this; /** * Generates a single instance of type T using the factory's schema. * Properties can be overridden by passing a partial object. * Synchronous hooks are automatically applied if registered. * If async hooks are registered, a ConfigurationError is thrown. * * @param kwargs Properties to override in the generated instance * @param options Factory options including fixture generation * @returns A new instance with factory-generated values merged with any overrides * @throws {ConfigurationError} If async hooks are registered * @throws {FixtureError} If fixture operations fail * @throws {FixtureValidationError} If fixture validation fails */ build: (kwargs?: Partial, options?: Partial) => F extends FactoryFunction ? T : Partial; /** * Builds an instance asynchronously with all registered hooks applied in sequence. * This method supports both synchronous and asynchronous hooks. * Hooks are executed in the order they were registered. * * @param kwargs Optional properties to override in the generated instance * @param options Factory options including fixture generation * @returns A promise that resolves to the built and processed instance * @throws {Error} If any hook throws an error during execution * @throws {FixtureError} If fixture operations fail * @throws {FixtureValidationError} If fixture validation fails */ buildAsync(kwargs?: Partial, options?: Partial): Promise ? T : Partial>; /** * Creates a new factory by merging this factory's schema with additional properties. * Composed properties can be static values or other factory instances. * * @template U The composed type (must extend the base type T) * @param composition Object mapping property names to values or factories * @returns A new factory that generates objects with combined properties */ compose(composition: FactoryComposition): Factory; /** * Creates and persists a single instance using the factory's schema. * Uses the configured persistence adapter if available. * * @param kwargs Optional properties to override in the generated instance * @param options Options including an optional persistence adapter * @returns Promise that resolves with the persisted instance * @throws {ConfigurationError} If no persistence adapter is configured * * @example * ```typescript * // With default adapter * const userFactory = new Factory((faker) => ({ * email: faker.internet.email(), * name: faker.person.fullName() * })).withAdapter(mongooseAdapter); * * const user = await userFactory.create({ name: 'John' }); * * // With adapter in options * const user2 = await userFactory.create( * { name: 'Jane' }, * { adapter: prismaAdapter } * ); * ``` */ create(kwargs?: Partial, options?: CreateOptions): Promise; /** * Creates and persists multiple instances in a batch operation. * Uses the configured persistence adapter if available. * * @param size Number of instances to create and persist * @param kwargs Optional overrides for the instances * @param options Options including an optional persistence adapter * @returns Promise that resolves with the persisted instances * @throws {ConfigurationError} If no persistence adapter is configured * * @example * ```typescript * // Create 5 users with default adapter * const users = await userFactory.createMany(5); * * // With individual overrides * const users2 = await userFactory.createMany(3, [ * { role: 'admin' }, * { role: 'user' }, * { role: 'guest' } * ]); * * // With adapter in options * const users3 = await userFactory.createMany( * 10, * undefined, * { adapter: typeormAdapter } * ); * ``` */ createMany(size: number, kwargs?: Partial | Partial[], options?: CreateManyOptions): Promise; /** * Creates a new factory that inherits from this factory's schema with modifications. * Unlike compose(), extend() provides access to the factory instance for dynamic property generation. * * Two overloads are available: * - Full override: the factory function returns the complete extended type, as before. * - Added fields: the factory function returns only the fields being added and the * base fields are preserved automatically. * * @template U The extended type (must extend the base type T) or {@link AddedFieldsFunction} usage * @param factoryFn Function that returns properties to merge with the base schema * @returns A new factory with inherited and extended properties */ extend(factoryFn: FactoryFunction): Factory; extend(factoryFn: AddedFieldsFunction): Factory; /** * Creates a generator that yields values from an iterable in sequential, cyclic order. * Values must be explicitly requested via the generator's next() method. When all values * have been yielded, the generator starts over from the beginning. * * @template T The type of elements in the iterable * @param iterable An iterable containing values to cycle through (must not be empty) * @returns A generator that yields values in order, restarting after the last element * @throws {Error} If the iterable is empty */ iterate(iterable: Iterable): Generator; /** * Creates a new factory where all properties are optional (Partial). * This is useful for creating test data where only specific fields need to be set. * * @returns A new factory that produces Partial objects */ partial(): Factory>; /** * Creates a generator that yields random values from an iterable without consecutive duplicates. * Each value is randomly selected with replacement, but the generator ensures the same value * is never returned twice in a row (unless the iterable contains only one element). * * @template T The type of elements in the iterable * @param iterable An iterable containing values to sample from (must not be empty) * @returns A generator that yields random values without consecutive repetition * @throws {Error} If the iterable is empty */ sample(iterable: Iterable): Generator; /** * Registers a named preset with a set of partial overrides for this factory. * Presets are applied during build/batch through the `presets` option: * presets listed later override values from earlier presets, and explicit * build kwargs override all preset values. * * @param name Unique preset name on this factory * @param values Partial values to merge when the preset is applied * @returns The current Factory instance for method chaining * * @example * ```typescript * const userFactory = new Factory((faker) => ({ * name: faker.person.fullName(), * role: 'user', * })) * .preset('admin', { role: 'admin' }) * .preset('banned', { isActive: false }); * * userFactory.build(undefined, { presets: ['admin'] }); * userFactory.build({ role: 'guest' }, { presets: ['admin', 'banned'] }); * ``` */ preset(name: string, values: Partial): this; /** * Creates a reference to a function call for lazy evaluation within factory definitions. * The function and its arguments are stored but not executed until the factory builds an object. * Essential for creating relationships between factories without causing infinite recursion. * * Async handlers are supported with {@link Factory.buildAsync} and {@link Factory.batchAsync}. * Values from `use(async () => ...)` await resolution during async builds and fail clearly * if used with the synchronous `build()`. * * @template C The function type * @param handler The function to call during object generation (may be async) * @param args Arguments to pass to the function when called * @returns A reference that will execute the function during build */ use(handler: (...args: A) => R, ...args: A): R; /** * Sets the default persistence adapter for this factory instance. * * @param adapter The persistence adapter to use as default * @returns The current Factory instance for method chaining * * @example * ```typescript * import { MongooseAdapter } from './adapters/mongoose-adapter'; * * const userFactory = new Factory((faker) => ({ * id: faker.string.uuid(), * email: faker.internet.email(), * name: faker.person.fullName() * })); * * // Set default adapter * const factoryWithDb = userFactory.withAdapter( * new MongooseAdapter(UserModel) * ); * * // Now all create/createMany calls will use this adapter * const user = await factoryWithDb.create(); * const users = await factoryWithDb.createMany(5); * ``` */ withAdapter(adapter: PersistenceAdapter): this; protected assertSyncFactory(): void; protected assertSyncHooks(): void; protected buildWithFixture(filePath: string, kwargs: Partial | undefined, _options: FactoryOptions & O): F extends FactoryFunction ? T : Partial; protected buildWithFixtureAsync(filePath: string, kwargs: Partial | undefined, _options: FactoryOptions & O): Promise ? T : Partial>; protected calculateSignature(config: Required): string; /* Excluded from this release type: createDepthLimitedProxy */ protected getDefaultFixturePath(): string; protected getFixtureConfig(): Required; /* Excluded from this release type: isDepthExceeded */ protected parseFixturePath(filePath: string, config: Required): { fixturesDir: string; fullPath: string; }; protected readFixture(fullPath: string): FixtureMetadata | null; protected validateFixture(metadata: FixtureMetadata, config: Required): void; protected writeFixture(parsedPath: { fixturesDir: string; fullPath: string; }, data: unknown, config: Required): void; } export declare type FactoryComposition = { [K in keyof T]?: Factory | T[K]; }; export declare type FactoryFunction = (factory: Factory, iteration: number, kwargs?: Partial) => FactorySchema | Promise>; export declare interface FactoryOptions { /** * Fixture configuration for caching generated data */ fixtures?: FixtureConfiguration; /** * Enable fixture generation/loading for this build. * - true: Use default fixture path based on call stack * - string: Use as fixture file path */ generateFixture?: boolean | string; locale?: LocaleDefinition | LocaleDefinition[]; maxDepth?: number; /** * Named presets registered with {@link Factory.preset} to apply during * build/batch, in order. Later presets override earlier ones and explicit * kwargs override preset values. */ presets?: string[]; randomizer?: Randomizer; } /** * Extracts the output type of a factory: the full generated type when the * factory holds a complete factory function, otherwise its partial output * (e.g. through {@link Factory.partial}). * * @template F - A Factory type */ export declare type FactoryOutput = F extends Factory ? FF extends FactoryFunction ? T : Partial : F extends Factory ? Partial : never; export declare type FactorySchema = { [K in keyof T]: Generator | Ref T[K]> | T[K]; }; export declare interface FixtureConfiguration { /** * Base directory for storing fixtures. Defaults to process.cwd() */ basePath?: string; /** * Custom directory name for fixtures. Defaults to '__fixtures__' * Set to empty string to store fixtures in the same directory as the file path */ directory?: string; /** * Whether to include the factory function source in signature calculation. Defaults to true */ includeSource?: boolean; /** * Whether to use subdirectories for fixtures. Defaults to true * When true: fixtures are stored in a subdirectory (e.g., /path/__fixtures__/file.json) * When false: fixtures are stored directly in the path (e.g., /path/file.json) */ useSubdirectory?: boolean; /** * Whether to validate factory signature changes. Defaults to true */ validateSignature?: boolean; } export declare class FixtureError extends Error { constructor(message: string); } export declare interface FixtureMetadata { /** * ISO 8601 timestamp when the fixture was created */ createdAt: string; /** * The actual fixture data */ data: unknown; /** * SHA-256 hash of the factory configuration */ signature: string; /** * Fixture version for future compatibility */ version: number; } export declare class FixtureValidationError extends FixtureError { constructor(message: string); } declare type Generate = () => R; /** * Generates an infinite numeric sequence. */ export declare class IncrementSequenceGenerator { #private; constructor({ start, step }?: IncrementSequenceOptions); generate(): Generator; } export declare interface IncrementSequenceOptions { start?: number; step?: number; } export declare type PartialFactoryFunction = (factory: Factory, iteration: number) => Partial> | Promise>>; export declare type Pattern = string | RegExp; /** * Interface for a persistence adapter. * Adapters are responsible for interacting with the underlying data store * (e.g., database, API) to save generated objects. */ export declare interface PersistenceAdapter { /** * Persists a single generated object to the data store. * * @param data The object to persist. * @returns A promise that resolves with the persisted object, * including any properties assigned by the database (e.g., auto-generated IDs). */ create(data: T): Promise; /** * Persists multiple generated objects to the data store in a batch. * * @param data An array of objects to persist. * @returns A promise that resolves with an array of the persisted objects, * including any properties assigned by the database. */ createMany(data: T[]): Promise; } /** * Encapsulates a function and its arguments for deferred execution within factories. * This enables lazy evaluation of nested factory calls, preventing infinite recursion * and allowing complex object relationships to be defined declaratively. * * @template T - The return type of the encapsulated function * @template C - The function type that returns T */ export declare class Ref T> { private readonly args; private readonly handler; constructor({ args, handler }: { args: Parameters; handler: C; }); callHandler(): T; } /** * Generates random values from an array while preventing consecutive duplicates. * Each value is randomly selected, but the same value will never appear twice in a row * unless the array contains only one element. Useful for creating varied but not * repetitive test data. * * @template T - The type of values to sample from */ export declare class SampleGenerator extends BaseGenerator { generate(): Generator; } export declare interface SequenceFactory { date(options: DateSequenceOptions): Generator; increment(options?: IncrementSequenceOptions): Generator; template(pattern: string, options?: TemplateSequenceOptions): Generator; } /** * Generates strings by replacing numeric placeholders in a template. */ export declare class TemplateSequenceGenerator { #private; constructor(pattern: string, { start }?: TemplateSequenceOptions); generate(): Generator; } export declare interface TemplateSequenceOptions { start?: number; } export declare class ValidationError extends Error { constructor(message: string); } export { }