UNPKG

bguard

Version:

**bguard** is a powerful, flexible, and type-safe validation library for TypeScript. It allows developers to define validation schemas for their data structures and ensures that data conforms to the expected types and constraints.

201 lines (198 loc) 9.29 kB
import { BaseType, TranslationErrorMap, ValidationErrorData, MetaContext, TransformCallback, WithNull, WithUndefined } from './commonTypes.mjs'; import { InferType } from './InferType.mjs'; import { ctxSymbol } from './helpers/constants.mjs'; declare class ExceptionContext { readonly initialReceived: unknown; readonly t: TranslationErrorMap; readonly pathToError: string; readonly errors?: ValidationErrorData[] | undefined; readonly meta?: MetaContext | undefined; constructor(initialReceived: unknown, t: TranslationErrorMap, pathToError: string, errors?: ValidationErrorData[] | undefined, meta?: MetaContext | undefined); createChild(childPathToError: string, childMeta?: MetaContext): ExceptionContext; ref(path: string): unknown; addIssue(expected: unknown, received: unknown, messageKey: string): never | void; } type RequiredValidation = (received: any, ctx: ExceptionContext) => void; type ObjectShapeSchemaType = Record<string, CommonSchema>; interface ValidatorContext { type: BaseType[]; isNullable?: boolean; isOptional?: boolean; requiredValidations: RequiredValidation[]; array?: CommonSchema; object?: ObjectShapeSchemaType; allowUnrecognizedObjectProps?: boolean; strictType?: boolean; strictTypeValue?: unknown; date?: boolean; defaultValue?: unknown; meta?: MetaContext; transformListBefore?: TransformCallback<any, any>[]; } declare class CommonSchema { [ctxSymbol]: ValidatorContext; constructor(ctx: ValidatorContext); /** * @param validators - One or more custom validation functions. * @returns {this} The schema instance with the added custom validation. */ custom(...validators: RequiredValidation[]): this; /** * Marks the schema as nullable, allowing the value to be `null`. * * @returns {WithNull<this>} The schema instance marked as nullable. */ nullable(): WithNull<this>; /** * Marks the schema as optional, allowing the value to be `undefined`. * * @returns {WithUndefined<this>} The schema instance marked as optional. */ optional(): WithUndefined<this>; /** * Marks the schema as optional, allowing the value to be `undefined`. * * @returns {this} The schema instance. This method should be used as a last one because it does the check of previous methods and */ default(defaultValue: InferType<this>): this; /** * Applies a transformation to the input value before any validation occurs. * The transformation should return a value of the same type as the inferred type of the schema, * ensuring that the overall type is not altered. * * @template In - The type of the input value before transformation (defaults to `unknown`). * @param {TransformCallback<In, InferType<this>>} cb - The callback function that performs the transformation. * @returns {this} The updated schema with the applied transformation. * * @example * const schema = string() * .nullable() * .transformBeforeValidation((val) => val + '') // Ensure the value is a string * .transformBeforeValidation((val: string) => (val === '' ? null : val)); // Convert empty strings to null * * // Parse 'test' will pass as 'test' is a valid string longer than 3 characters. * parseOrFail(schema, 'test'); * * // Parsing '' will be transformed to null and will pass due to .nullable(). * parseOrFail(schema, ''); */ transformBeforeValidation<In>(cb: TransformCallback<In, InferType<this>>): this; /** * Assigns a unique identifier to the schema. * This ID can be used to track or map validation errors back to specific fields * in a form or other structures. * * @param {string} value - The unique identifier for the schema. * @returns {this} The updated schema with the assigned ID. * * @example * const schema = string().id('username'); */ id(value: string): this; /** * Provides a description for the schema, offering additional context or information. * The description can be used when displaying validation errors or for documentation purposes. * * @param {string} value - The description for the schema. * @returns {this} The updated schema with the added description. * * @example * const schema = string().description('The username of the account holder.'); */ description(value: string): this; private meta; protected defaultValueCheck(): void; } /** * Parses and validates a value against the provided schema, returning a type-safe result. * * This function will throw a `ValidationError` if the value does not conform to the schema. * The inferred TypeScript type of the returned value will match the structure defined by the schema. * * @template T * @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value. * @param {unknown} receivedValue - The value to be validated and parsed according to the schema. * @param {ParseOptions} options - Options * @param {ParseOptions.lng} options.lng - Set language keyword to map Error message * @returns {InferType<T>} The validated value, with its TypeScript type inferred from the schema. * * @throws {ValidationError} If the received value does not match the schema, a `ValidationError` will be thrown. * @throws {Error} If an unexpected error occurs during validation, an error will be thrown with a generic message. * * @example * const schema = object({ * name: string(), * age: number(), * }); * * const result = parseOrFail(schema, { name: 'Alice', age: 30 }); * // result will be inferred as { name: string; age: number } * * parseOrFail(schema, { name: 'Alice', age: '30' }); * // Throws ValidationError because 'age' should be a number, not a string. */ declare function parseOrFail<T extends CommonSchema>(schema: T, receivedValue: unknown, options?: ParseOptions): InferType<T>; interface ParseOptions { /** * Set language keyword to map error messages. * @default 'default' * @example 'sr' or 'Serbia' or any string to identify language */ lng?: string; } interface ParseOptions { /** * Set language keyword to map error messages. * @default 'default' * @example 'sr' or 'Serbia' or any string to identify language */ lng?: string; /** * If true, collects all validation errors and returns them. * If false or undefined, returns the first validation error it can find and stops looking, * which provides a small runtime optimization. * @default undefined */ getAllErrors?: boolean; } /** * Parses and validates a value against the provided schema, returning a type-safe parsedValue. * * This function will throw a `ValidationError` if the value does not conform to the schema. * The inferred TypeScript type of the returned value will match the structure defined by the schema. * * @template T * @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value. * @param {unknown} receivedValue - The value to be validated and parsed according to the schema. * @param {ParseOptions} options - Options * @param {ParseOptions.lng} options.lng - Set language keyword to map Error messages * @param {ParseOptions.lng} options.getAllErrors - If `false` or `undefined` - returns the first validation error it can find and stops looking, which provides a small runtime optimization. * @returns {[undefined, InferType<T>]} A tuple of [undefined, InferType<T>] if parsing is successful. * @returns {[ValidationErrorData[], undefined]} A tuple of [ValidationErrorData[], undefined]] if errors occur. * * @example * const schema = object({ * name: string(), * age: number(), * }); * * const [errors, parsedValue] = parse(schema, { name: 'Alice', age: 30 }); * // parsedValue will be inferred as { name: string; age: number } * * * const [errors, parsedValue] = parse(schema, { name: 'Alice', age: '30' }); * // First element in array "errors" will have an error because 'age' should be a number, not a string. * // Array 'errors' returns only one element. * * * const [errors, parsedValue] = parse(schema, { name: true, age: '30' }, { getAllErrors: true}); * // Returns array "errors" with multiple errors because 'age' should be a number and 'name' a string. * // With provided options { getAllErrors: true}, we can expecte more than one error in 'errors' array. * * * const [errors, parsedValue] = parse(schema, { name: true, age: '30' }, { lng: 'SR'}); * // First element in array "errors" will have an error because 'age' should be a number, not a string. * // With provided options { lng: 'SR'}, errors will be translated to a language mapped with keyword 'SR' */ declare function parse<T extends CommonSchema>(schema: T, receivedValue: unknown, options?: ParseOptions): [ValidationErrorData[], undefined] | [undefined, InferType<T>]; export { CommonSchema, ExceptionContext, type ObjectShapeSchemaType, type RequiredValidation, type ValidatorContext, parse, parseOrFail };