/** * Determines if an iterable collection of {@link Result | Result} were all successful. * @param results - The collection of {@link Result | Result} to be tested. * @param successValue - The value to be returned if results are successful. * @param aggregatedErrors - Optional string array to which any returned error messages will be * appended. Each error is appended as an individual string. * @returns Returns {@link Success} with `successValue` if all {@link Result | results} are successful. * If any are unsuccessful, returns {@link Failure} with a concatenated summary of the error * messages from all failed elements. * @public */ export declare function allSucceed(results: Iterable>, successValue: T, aggregatedErrors?: IMessageAggregator): Result; /** * A helper function to create a {@link Converter | Converter} which converts `unknown` to an array of ``. * @remarks * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored. * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used to convert each * item in the array. * @param ignoreErrors - Specifies treatment of unconvertible elements. * @returns A {@link Converter | Converter} which returns an array of ``. * @public */ declare function arrayOf(converter: Converter | Validator, onError?: OnError): Converter; /** * Helper function to create a {@link Validation.Classes.ArrayValidator | ArrayValidator} which * validates an array in place. * @param validateElement - A {@link Validation.Validator | validator} which validates each element. * @returns A new {@link Validation.Classes.ArrayValidator | ArrayValidator } which validates the desired * array in place. * @public */ declare function arrayOf_2(validateElement: Validator, params?: Omit, 'validateElement'>): ArrayValidator; /** * An in-place {@link Validator | Validator} for arrays of validated * values or objects. * @public */ declare class ArrayValidator extends ValidatorBase { /** * {@link Validation.ValidatorOptions | Options} which apply to this * validator. */ readonly options: ValidatorOptions; protected readonly _validateElement: Validator; /** * Constructs a new {@link Validation.Classes.ArrayValidator | ArrayValidator}. * @param params - Optional {@link Validation.Classes.ArrayValidatorConstructorParams | init params} for the * new {@link Validation.Classes.ArrayValidator | ArrayValidator}. */ constructor(params: ArrayValidatorConstructorParams); /** * Static method which validates that a supplied `unknown` value is a `array` * and that every element of the array can be validated by the supplied array * validator. * @param from - The `unknown` value to be tested. * @param context - Optional validation context will be propagated to element validator. * @param self - Optional self-reference for recursive validation. * @returns Returns `true` if `from` is an `array` of valid elements, or * {@link Failure} with an error message if not. */ protected _validate(from: unknown, context?: TC, self?: Validator): boolean | Failure; } /** * Parameters used to construct a {@link Validation.Classes.ArrayValidator | ArrayValidator}. * @public */ declare interface ArrayValidatorConstructorParams extends ValidatorBaseConstructorParams { validateElement: Validator; } declare namespace Base { export { GenericValidatorConstructorParams, GenericValidator } } /** * Base templated wrapper to simplify creation of new {@link Converter}s. * @public */ declare class BaseConverter implements Converter { /** * @internal */ protected readonly _defaultContext?: TC; /** * @internal */ protected _isOptional: boolean; /** * @internal */ protected _brand?: string; private readonly _converter; /** * Constructs a new {@link Converter} which uses the supplied function to perform the conversion. * @param converter - The conversion function to be applied. * @param defaultContext - Optional conversion context to be used by default. * @param traits - Optional {@link Conversion.ConverterTraits | traits} to be assigned to the resulting * converter. */ constructor(converter: ConverterFunc, defaultContext?: TC, traits?: ConverterTraits); /** * {@inheritdoc Converter.isOptional} */ get isOptional(): boolean; /** * {@inheritdoc Converter.brand} */ get brand(): string | undefined; /** * {@inheritdoc Converter.convert} */ convert(from: unknown, context?: TC): Result; /** * {@inheritdoc Converter.convertOptional} */ convertOptional(from: unknown, context?: TC, onError?: OnError): Result; /** * {@inheritdoc Converter.optional} */ optional(onError?: OnError): Converter; /** * {@inheritdoc Converter.map} */ map(mapper: (from: T, context?: TC) => Result): Converter; /** * {@inheritdoc Converter.mapConvert} */ mapConvert(mapConverter: Converter): Converter; /** * {@inheritdoc Converter.mapItems} */ mapItems(mapper: (from: unknown, context?: TC) => Result): Converter; /** * {@inheritdoc Converter.mapConvertItems} */ mapConvertItems(mapConverter: Converter): Converter; /** * {@inheritdoc Converter.withAction} */ withAction(action: (result: Result, context?: TC) => Result): Converter; /** * {@inheritdoc Converter.withTypeGuard} */ withTypeGuard(guard: (from: unknown, context?: TC) => from is TI, message?: string): Converter; /** * {@inheritdoc Converter.withItemTypeGuard} */ withItemTypeGuard(guard: (from: unknown, context?: TC) => from is TI, message?: string): Converter; /** * {@inheritdoc Converter.withConstraint} */ withConstraint(constraint: (val: T, context?: TC) => boolean | Result, options?: ConstraintOptions): Converter; /** * {@inheritdoc Converter.withBrand} */ withBrand(brand: B): Converter, TC>; /** * {@inheritdoc Converter.withDefault} */ withDefault(defaultValue: TD): DefaultingConverter; /** * @internal */ protected _context(supplied?: TC): TC | undefined; /** * {@inheritdoc Converter.withFormattedError} */ withFormattedError(formatter: ConversionErrorFormatter): Converter; /** * @internal */ protected _traits(traits?: Partial): ConverterTraits; /** * @internal */ protected _with(traits: Partial): this; } /** * A {@link Converter | Converter} which converts `unknown` to `boolean`. * @remarks * Boolean values or the case-insensitive strings `'true'` and `'false'` succeed. * Anything else fails. * @public */ declare const boolean: Converter; /** * A {@link Validation.Classes.BooleanValidator | BooleanValidator} which validates a boolean in place. * @public */ declare const boolean_2: Validator; /** * An in-place {@link Validation.Validator | Validator} for `boolean` values. * @public */ declare class BooleanValidator extends GenericValidator { /** * Constructs a new {@link Validation.Classes.BooleanValidator | BooleanValidator}. * @param params - Optional {@link Validation.Classes.BooleanValidatorConstructorParams | init params} for the * new {@link Validation.Classes.BooleanValidator | BooleanValidator}. */ constructor(params?: BooleanValidatorConstructorParams); /** * Static method which validates that a supplied `unknown` value is a `boolean`. * @param from - The `unknown` value to be tested. * @returns Returns `true` if `from` is a `boolean`, or {@link Failure} with an error * message if not. */ static validateBoolean(from: unknown): boolean | Failure; } /** * Parameters used to construct a {@link Validation.Classes.BooleanValidator | BooleanValidator}. * @public */ declare type BooleanValidatorConstructorParams = GenericValidatorConstructorParams; /** * Helper type to brand a simple type to prevent inappropriate use * @public */ export declare type Brand = T & { __brand: B; }; /** * Wraps a function which might throw to convert exception results * to {@link Failure}. * @param func - The function to be captured. * @returns Returns {@link Success} with a value of type `` on * success , or {@link Failure} with the thrown error message if * `func` throws an `Error`. * @public */ export declare function captureResult(func: () => T): Result; declare namespace Classes { export { ArrayValidator, ArrayValidatorConstructorParams, BooleanValidator, BooleanValidatorConstructorParams, NumberValidator, NumberValidatorConstructorParams, FieldValidators, ObjectValidator, ObjectValidatorConstructorParams, ObjectValidatorOptions, OneOfValidator, OneOfValidatorConstructorParams, StringValidator, StringValidatorConstructorParams, TypeGuardValidator, TypeGuardValidatorConstructorParams } } /** * Simple implementation of {@link Collections.ICollectible | ICollectible} which does not allow the index to be * changed once set. * @public */ declare class Collectible implements ICollectible { /** * {@link Collections.ICollectible.key} */ readonly key: TKEY; /** * {@link Collections.ICollectible.index} */ get index(): TINDEX | undefined; protected _index: TINDEX | undefined; protected readonly _indexConverter?: Validator | Converter; /** * Constructs a new {@link Collections.Collectible | Collectible} instance * with a defined, strongly-typed index. * @param params - {@link Collections.ICollectibleConstructorParamsWithIndex | Parameters} for constructing * the collectible. */ constructor(params: ICollectibleConstructorParamsWithIndex); /** * Constructs a new {@link Collections.Collectible | Collectible} instance with * an undefined index and an index converter to validate te index when it is set. * @param params - {@link Collections.ICollectibleConstructorParamsWithConverter | Parameters} for constructing * the collectible. */ constructor(params: ICollectibleConstructorParamsWithConverter); /** * Constructs a new {@link Collections.Collectible | Collectible} instance. * @param params - {@link Collections.ICollectibleConstructorParams | Parameters} for constructing * the collectible. */ constructor(params: ICollectibleConstructorParams); /** * Creates a new {@link Collections.Collectible | Collectible} instance with a defined, strongly-typed index. * @param params - {@link Collections.ICollectibleConstructorParamsWithIndex | Parameters} for constructing * the collectible. * @returns {@link Success} with the new collectible if successful, {@link Failure} otherwise. */ static createCollectible(params: ICollectibleConstructorParamsWithIndex): Result>; /** * Creates a new {@link Collections.Collectible | Collectible} instance with an undefined index and an index * converter to validate the index when it is set. * @param params - {@link Collections.ICollectibleConstructorParamsWithConverter | Parameters} for constructing * the collectible. * @returns {@link Success} with the new collectible if successful, {@link Failure} otherwise. */ static createCollectible(params: ICollectibleConstructorParamsWithConverter): Result>; /** * Creates a new {@link Collections.Collectible | Collectible} instance. * @param params - {@link Collections.ICollectibleConstructorParams | Parameters} for constructing * the collectible. * @returns {@link Success} with the new collectible if successful, {@link Failure} otherwise * @public */ static createCollectible(params: ICollectibleConstructorParams): Result>; /** * {@link Collections.ICollectible.setIndex} */ setIndex(index: number): Result; } /** * Factory function for creating a new {@link Collections.ICollectible | ICollectible} instance given a key, an index and a source representation * of the item to be added. * @public */ declare type CollectibleFactory, TSRC> = (key: CollectibleKey, index: number, item: TSRC) => Result; /** * Factory function for creating a new {@link Collections.ICollectible | ICollectible} instance given a key and an index. * @public */ declare type CollectibleFactoryCallback> = (key: CollectibleKey, index: number) => Result; /** * Infer the index type from an {@link Collections.ICollectible | ICollectible} type. * @public */ declare type CollectibleIndex = TITEM extends ICollectible ? TINDEX : never; /** * Infer the key type from an {@link Collections.ICollectible | ICollectible} type. * @public */ declare type CollectibleKey = TITEM extends ICollectible ? TKEY : never; declare namespace Collections { export { Utils, ICollectible, CollectibleKey, CollectibleIndex, CollectibleFactory, CollectibleFactoryCallback, ICollectibleConstructorParamsWithIndex, ICollectibleConstructorParamsWithConverter, ICollectibleConstructorParams, Collectible, IConvertingCollectorConstructorParams, ConvertingCollector, CollectorResultDetail, IReadOnlyCollector, ICollectorConstructorParams, Collector, IReadOnlyCollectorValidator, ICollectorValidatorCreateParams, CollectorValidator, IConvertingCollectorValidatorCreateParams, ConvertingCollectorValidator, IValidatingConvertingCollectorConstructorParams, ValidatingConvertingCollector, KeyValueEntry, IKeyValueConverterConstructorParams, KeyValueConverters, ResultMapResultDetail, ResultMapForEachCb, IReadOnlyResultMap, IResultMapConstructorParams, ResultMapValueFactory, ResultMap, IReadOnlyResultMapValidator, IResultMapValidatorCreateParams, ResultMapValidator, IReadOnlyValidatingCollector, IValidatingCollectorConstructorParams, ValidatingCollector, IReadOnlyValidatingResultMap, IValidatingResultMapConstructorParams, ValidatingResultMap } } export { Collections } /** * A {@link Collections.Collector | Collector} that is a specialized collection * which contains items of type {@link Collections.ICollectible | ICollectible}, * which have a unique key and a write-once index. * * Items are assigned an index sequentially as they are added to the collection. * Once added, items are immutable - they cannot be removed or replaced. * @public */ export declare class Collector> implements IReadOnlyCollector { private readonly _byKey; private readonly _byIndex; /** * {@inheritdoc Collections.ResultMap.size} */ get size(): number; /** * Constructs a new {@link Collections.Collector | Collector}. * @param params - Optional {@link Collections.ICollectorConstructorParams | initialization parameters} used * to construct the collector. */ constructor(params?: ICollectorConstructorParams); /** * Creates a new {@link Collections.Collector | Collector} instance. * @param params - Optional {@link Collections.ICollectorConstructorParams | initialization parameters} used * to create the collector. * @returns Returns {@link Success | Success} with the new collector if it was created successfully, * or {@link Failure | Failure} with an error if the collector could not be created. */ static createCollector>(params?: ICollectorConstructorParams): Result>; /** * Adds an item to the collection, failing if a different item with the same key already exists. Note * that adding an object that is already in the collection again will succeed without updating the collection. * @param item - The item to add. * @returns Returns {@link DetailedSuccess | Success} with the item and detail `added` if it was added * or detail `exists` if the item was already in the map. Returns {@link DetailedFailure | Failure} with * an error message and appropriate detail if the item could not be added. */ add(item: TITEM): DetailedResult; /** * {@inheritdoc Collections.ResultMap.entries} */ entries(): IterableIterator, TITEM>>; /** * {@inheritdoc Collections.ResultMap.forEach} */ forEach(callback: ResultMapForEachCb, TITEM>, arg?: unknown): void; /** * {@inheritdoc Collections.ResultMap.get} */ get(key: CollectibleKey): DetailedResult; /** * {@inheritdoc Collections.IReadOnlyCollector.getAt} */ getAt(index: number): Result; /** * Gets an existing item with a key matching that of a supplied item, or adds the supplied * item to the collector if no item with that key exists. * @param item - The item to get or add. * @returns Returns {@link DetailedSuccess | Success} with the item stored in the collector - * detail `exists` indicates that an existing item return and detail `added` indicates that the * item was added. Returns {@link DetailedFailure | Failure} with an error and appropriate * detail if the item could not be added. */ getOrAdd(item: TITEM): DetailedResult; /** * Gets an existing item with a key matching the supplied key, or adds a new item to the collector * using a factory callback if no item with that key exists. * @param key - The key of the item to add. * @param callback - The factory callback to create the item. * @returns Returns {@link DetailedSuccess | Success} with the item stored in the collector - * detail `exists` indicates that an existing item return and detail `added` indicates that the * item was added. Returns {@link DetailedFailure | Failure} with an error and appropriate * detail if the item could not be added. */ getOrAdd(key: CollectibleKey, factory: CollectibleFactoryCallback): DetailedResult; /** * {@inheritdoc Collections.ResultMap.has} */ has(key: CollectibleKey): boolean; /** * {@inheritdoc Collections.ResultMap.keys} */ keys(): IterableIterator>; /** * {@inheritdoc Collections.ResultMap.values} */ values(): IterableIterator; /** * {@inheritdoc Collections.IReadOnlyCollector.valuesByIndex} */ valuesByIndex(): ReadonlyArray; /** * Gets a read-only version of this collector. */ toReadOnly(): IReadOnlyCollector; /** * Gets an iterator over the map entries. * @returns An iterator over the map entries. */ [Symbol.iterator](): IterableIterator, TITEM>>; protected _isItem(keyOrItem: CollectibleKey | TITEM): keyOrItem is TITEM; } /** * Additional success or failure details for mutating collector calls. * @public */ declare type CollectorResultDetail = ResultMapResultDetail | 'invalid-index'; /** * A {@link Collections.Collector | Collector} wrapper which validates weakly-typed keys * and values before calling the wrapped collector. * @public */ declare class CollectorValidator> implements IReadOnlyCollectorValidator { readonly converters: KeyValueConverters, TITEM>; get map(): IReadOnlyResultMap, TITEM>; protected _collector: Collector; /** * Constructs a new {@link Collections.ConvertingCollectorValidator | ConvertingCollectorValidator}. * @param params - Required parameters for constructing the collector validator. */ constructor(params: ICollectorValidatorCreateParams); /** * {@inheritdoc Collections.Collector.add} */ add(item: unknown): DetailedResult; /** * {@inheritdoc Collections.Collector.get} */ get(key: string): DetailedResult; /** * {@inheritdoc Collections.Collector.(getOrAdd:2)} */ getOrAdd(key: string, factory: ResultMapValueFactory, TITEM>): DetailedResult; /** * {@inheritdoc Collections.Collector.(getOrAdd:1)} * @param item - The item to add to the collector. */ getOrAdd(item: unknown): DetailedResult; /** * {@inheritdoc Collections.ResultMap.has} */ has(key: string): boolean; /** * {@inheritdoc Collections.Collector.toReadOnly} */ toReadOnly(): IReadOnlyCollectorValidator; /** * Helper to convert a value, returning a {@link DetailedResult | DetailedResult} * and formatting the error message. * @param value - The value to convert. * @returns {@link DetailedSuccess | DetailedSuccess} with the converted value * and detail `success` if conversion is successful, or * {@link DetailedFailure | DetailedFailure} with the error message and detail `invalid-value` * if conversion fails. */ protected _convertValue(value: unknown): DetailedResult; } /** * A console logger that outputs messages to the console. * @public */ declare class ConsoleLogger extends LoggerBase { /** * Creates a new console logger. * @param logLevel - The level of logging to be used. */ constructor(logLevel?: ReporterLogLevel); /** * {@inheritDoc Logging.LoggerBase._log} * @internal */ protected _log(message: string, level: MessageLogLevel): Success; } /** * A {@link Validation.Constraint | Constraint} function returns * `true` if the supplied value meets the constraint. Can return * {@link Failure} with an error message or simply return `false` * for a default message. * @public */ declare type Constraint = (val: T) => boolean | Failure; /** * Options for {@link Converter.withConstraint}. * @public */ declare interface ConstraintOptions { /** * Optional description for error messages when constraint * function returns false. */ readonly description: string; } /** * Union of all supported constraint traits. * @public */ declare type ConstraintTrait = FunctionConstraintTrait; declare namespace Conversion { export { Converters, Infer, ConvertedToType, ConverterFunc, BaseConverter, OnError, ConverterTraits, ConversionErrorFormatter, ConstraintOptions, Converter, DefaultingConverter, GenericDefaultingConverter, ObjectConverterOptions, FieldConverters, ObjectConverter, StringMatchOptions, StringConverter } } export { Conversion } /** * Formats an incoming error message and value that failed validation. * @param val - The value that failed validation. * @param message - The default error message, if any. * @param context - Optional validation context. * @returns The formatted error message. * @public */ declare type ConversionErrorFormatter = (val: unknown, message?: string, context?: TC) => string; /** * Deprecated name for Infer retained for compatibility * @deprecated use @see Infer instead * @internal */ declare type ConvertedToType = Infer; /** * Generic converter to convert unknown to a templated type ``, using * intrinsic rules or as modified by an optional conversion context * of optional templated type `` (default `undefined`). * @public */ export declare interface Converter extends ConverterTraits { /** * Indicates whether this element is explicitly optional. */ readonly isOptional: boolean; /** * Returns the brand for a branded type. */ readonly brand?: string; /** * Converts from `unknown` to ``. For objects and arrays, is guaranteed * to return a new entity, with any unrecognized properties removed. * @param from - The `unknown` to be converted * @param context - An optional conversion context of type `` to be used in * the conversion. * @returns A {@link Result} with a {@link Success} and a value on success or an * {@link Failure} with a a message on failure. */ convert(from: unknown, context?: TC): Result; /** * Converts from `unknown` to `` or `undefined`, as appropriate. * * @remarks * If `onError` is `failOnError`, the converter succeeds for * `undefined` or any convertible value, but reports an error * if it encounters a value that cannot be converted. * * If `onError` is `ignoreErrors` (default) then values that * cannot be converted result in a successful return of `undefined`. * @param from - The `unknown` to be converted * @param context - An optional conversion context of type `` to be used in * the conversion. * @param onError - Specifies handling of values that cannot be converted (default `ignoreErrors`). * @returns A {@link Result} with a {@link Success} and a value on success or an * {@link Failure} with a a message on failure. */ convertOptional(from: unknown, context?: TC, onError?: OnError): Result; /** * Creates a {@link Converter} for an optional value. * * @remarks * If `onError` is `failOnError`, the resulting converter will accept `undefined` * or a convertible value, but report an error if it encounters a value that cannot be * converted. * * If `onError` is `ignoreErrors` (default) then values that cannot be converted will * result in a successful return of `undefined`. * * @param onError - Specifies handling of values that cannot be converted (default `ignoreErrors`). * @returns A new {@link Converter} returning ``. * */ optional(onError?: OnError): Converter; /** * Creates a {@link Converter} which applies a (possibly) mapping conversion to * the converted value of this {@link Converter}. * @param mapper - A function which maps from the the result type `` of this * converter to a new result type ``. * @returns A new {@link Converter} returning ``. */ map(mapper: (from: T, context?: TC) => Result): Converter; /** * Creates a {@link Converter} which applies an additional supplied * converter to the result of this converter. * * @param mapConverter - The {@link Converter} to be applied to the * converted result from this {@link Converter}. * @returns A new {@link Converter} returning ``. */ mapConvert(mapConverter: Converter): Converter; /** * Creates a {@link Converter} which maps the individual items of a collection * resulting from this {@link Converter} using the supplied map function. * * @remarks * Fails if `from` is not an array. * * @param mapper - The map function to be applied to each element of the * result of this {@link Converter}. * @returns A new {@link Converter} returning ``. */ mapItems(mapper: (from: unknown, context?: TC) => Result): Converter; /** * Creates a {@link Converter} which maps the individual items of a collection * resulting from this {@link Converter} using the supplied {@link Converter}. * * @remarks * Fails if `from` is not an array. * * @param mapConverter - The {@link Converter} to be applied to each element of the * result of this {@link Converter}. * @returns A new {@link Converter} returning ``. */ mapConvertItems(mapConverter: Converter): Converter; /** * Creates a {@link Converter | Converter} which applies a supplied action after * conversion. The supplied action is always called regardless of success or failure * of the base conversion and is allowed to mutate the return type. * @param action - The action to be applied. */ withAction(action: (result: Result, context?: TC) => Result): Converter; /** * Creates a {@link Converter} which applies a supplied type guard to the conversion * result. * @param guard - The type guard function to apply. * @param message - Optional message to be reported if the type guard fails. * @returns A new {@link Converter} returning ``. */ withTypeGuard(guard: (from: unknown, context?: TC) => from is TI, message?: string): Converter; /** * Creates a {@link Converter} which applies a supplied type guard to each member of * the conversion result from this converter. * * @remarks * Fails if the conversion result is not an array or if any member fails the * type guard. * @param guard - The type guard function to apply to each element. * @param message - Optional message to be reported if the type guard fails. * @returns A new {@link Converter} returning ``. */ withItemTypeGuard(guard: (from: unknown, context?: TC) => from is TI, message?: string): Converter; /** * Creates a {@link Converter} which applies an optional constraint to the result * of this conversion. If this {@link Converter} (the base converter) succeeds, the new * converter calls a supplied constraint evaluation function with the conversion, which * fails the entire conversion if the constraint function returns either `false` or * {@link Failure | Failure}. * * @param constraint - Constraint evaluation function. * @param options - {@link Conversion.ConstraintOptions | Options} for constraint evaluation. * @returns A new {@link Converter} returning ``. */ withConstraint(constraint: (val: T, context?: TC) => boolean | Result, options?: ConstraintOptions): Converter; /** * Creates a new {@link Converter} which is derived from this one but which returns an * error message formatted by the supplied formatter if the conversion fails. * @param formatter - The formatter to be applied. * @returns A new {@link Converter} returning ``. */ withFormattedError(formatter: ConversionErrorFormatter): Converter; /** * returns a converter which adds a brand to the type to prevent mismatched usage * of simple types. * @param brand - The brand to be applied to the result value. * @returns A {@link Converter} returning `Brand`. */ withBrand(brand: B): Converter, TC>; /** * Returns a Converter which always succeeds with a default value rather than failing. */ withDefault(dflt: TD): DefaultingConverter; } /** * Function signature for a converter function. * @public */ declare type ConverterFunc = (from: unknown, self: Converter, context?: TC) => Result; declare namespace Converters { export { enumeratedValue, mappedEnumeratedValue, literal, delimitedString, validated, generic, isA, oneOf, arrayOf, recordOf, mapOf, validateWith, element, optionalElement, field, optionalField, object, strictObject, discriminatedObject, transform, transformObject, OnError, string, value, number, boolean, optionalString, optionalNumber, optionalBoolean, stringArray, numberArray, KeyedConverterOptions, StrictObjectConverterOptions, DiscriminatedObjectConverters, FieldTransformers, TransformObjectOptions } } export { Converters } /** * Converter traits. * @public */ declare interface ConverterTraits { readonly isOptional: boolean; readonly brand?: string; } /** * A {@link Collector | collector} that collects {@link Collections.ICollectible | ICollectible} items, * optionally converting them from a source representation to the target representation using a factory * supplied at default or at the time of collection. * @public */ export declare class ConvertingCollector, TSRC = TITEM> extends Collector { private _factory; /** * Constructs a new {@link Collections.ConvertingCollector | ConvertingCollector}. * @param params - Parameters for constructing the collector. */ constructor(params: IConvertingCollectorConstructorParams); /** * Creates a new {@link Collections.ConvertingCollector | ConvertingCollector}. * @param params - Required parameters for constructing the collector. * @returns Returns {@link Success | Success} with the new collector if it is created, or {@link Failure | Failure} * with an error if the collector cannot be created. */ static createConvertingCollector, TSRC = TITEM>(params: IConvertingCollectorConstructorParams): Result>; /** * {@inheritdoc Collections.Collector.add} */ add(item: TITEM): DetailedResult; /** * Adds an item to the collector using the default {@link Collections.CollectibleFactory | factory} * at a specified key, failing if an item with that key already exists. * @param key - The key of the item to add. * @param item - The source representation of the item to be added. * @returns Returns {@link Success | Success} with the item if it is added, or {@link Failure | Failure} with * an error if the item cannot be created and indexed. * @public */ add(key: CollectibleKey, item: TSRC): DetailedResult; /** * Adds an item to the collector using a supplied {@link Collections.CollectibleFactoryCallback | factory callback} * at a specified key, failing if an item with that key already exists or if the created item is invalid. * @param key - The key of the item to add. * @param callback - The factory callback to create the item. * @returns Returns {@link Success | Success} with the item if it is added, or {@link Failure | Failure} with * an error if the item cannot be created and indexed. */ add(key: CollectibleKey, cb: CollectibleFactoryCallback): DetailedResult; /** * {@inheritdoc Collections.Collector.(getOrAdd:1)} */ getOrAdd(item: TITEM): DetailedResult; /** * {@inheritdoc Collections.Collector.(getOrAdd:2)} */ getOrAdd(key: CollectibleKey, callback: CollectibleFactoryCallback): DetailedResult; /** * Gets an item by key if it exists, or creates a new item and adds it using the default {@link Collections.CollectibleFactory | factory} if not. * @param key - The key of the item to retrieve. * @param item - The source representation of the item to be added if it does not exist. * @returns Returns {@link Success | Success} with the item if it exists or could be created, or {@link Failure | Failure} with an error if the * item cannot be created and indexed. */ getOrAdd(key: CollectibleKey, item: TSRC): DetailedResult; /** * Helper method for derived classes to determine if a supplied * itemOrCb parameter is a factory callback. * @param itemOrCb - Overloaded parameter is either `CollectibleKey` or * a {@link Collections.CollectibleFactoryCallback | factory callback}. * @returns Returns `true` if the parameter is a factory callback, `false` otherwise. * @public */ protected _isFactoryCB(itemOrCb: TSRC | CollectibleFactoryCallback): itemOrCb is CollectibleFactoryCallback; /** * Helper method for derived classes to determine if a supplied * keyOrItem parameter is an item. * @param keyOrItem - Overloaded parameter is either `CollectibleKey` or `TITEM`. * @param itemOrCb - Overloaded parameter is either `TSRC`, a {@link Collections.CollectibleFactoryCallback | factory callback} * or `undefined`. * @returns Returns `true` if the parameter is an item, `false` otherwise. * @public */ protected _overloadIsItem(keyOrItem: CollectibleKey | TITEM, itemOrCb?: TSRC | CollectibleFactoryCallback): keyOrItem is TITEM; /** * Helper method for derived classes to build an item from a key and a source representation using * a default or supplied factory. * @param key - The key of the item to build. * @param itemOrCb - The source representation of the item to build, or a factory callback to create it. * @returns Returns {@link Success | Success} with the item if it is built, or {@link Failure | Failure} * with an error if the item cannot be built. * @public */ protected _buildItem(key: CollectibleKey, itemOrCb: TSRC | CollectibleFactoryCallback): Result; } /** * A {@link Collections.ConvertingCollector | ConvertingCollector} wrapper which validates weakly-typed keys * and values before calling the wrapped collector. Unlike the basic {@link Collections.CollectorValidator | CollectorValidator}, * the converting collector expects the items to be in the source type of the converting collector, not the target type. * @public */ declare class ConvertingCollectorValidator, TSRC = TITEM> implements IReadOnlyCollectorValidator { readonly converters: KeyValueConverters, TSRC>; get map(): IReadOnlyResultMap, TITEM>; protected _collector: ConvertingCollector; /** * Constructs a new {@link Collections.ConvertingCollectorValidator | ConvertingCollectorValidator}. * @param params - Required parameters for constructing the collector validator. */ constructor(params: IConvertingCollectorValidatorCreateParams); /** * {@inheritdoc Collections.ConvertingCollector.(add:1)} */ add(key: string, value: unknown): DetailedResult; /** * {@inheritdoc Collections.ConvertingCollector.(add:2)} */ add(key: string, factory: ResultMapValueFactory, TITEM>): DetailedResult; /** * {@inheritdoc Collections.Collector.get} */ get(key: string): DetailedResult; /** * {@inheritdoc Collections.ConvertingCollector.(getOrAdd:3)} */ getOrAdd(key: string, value: unknown): DetailedResult; /** * {@inheritdoc Collections.Collector.(getOrAdd:2)} */ getOrAdd(key: string, factory: ResultMapValueFactory, TITEM>): DetailedResult; /** * {@inheritdoc Collections.ResultMap.has} */ has(key: string): boolean; /** * {@inheritdoc Collections.Collector.toReadOnly} */ toReadOnly(): IReadOnlyCollectorValidator; /** * Determines if a value is a {@link Collections.CollectibleFactoryCallback | CollectibleFactoryCallback}. * @param value - The value to check. * @returns `true` if the value is a {@link Collections.CollectibleFactoryCallback | CollectibleFactoryCallback}, * `false` otherwise. * @public */ protected _isCollectibleFactoryCallback(value: unknown | CollectibleFactoryCallback): value is CollectibleFactoryCallback; } /** * A {@link Hash.HashingNormalizer | hashing normalizer} which computes object * hash using the CRC32 algorithm. * @public */ declare class Crc32Normalizer extends HashingNormalizer { constructor(); static crc32Hash(parts: string[]): string; } /** * @public */ declare interface DefaultingConverter extends Converter { /** * Default value to use if the conversion fails. */ readonly defaultValue: TD; /** * Convert the supplied `unknown` to `Success` or to the `Success` with the default value * if conversion is not possible. * @param from - the value to be converted. * @param ctx - optional context for the conversion. */ convert(from: unknown, ctx?: TC): Success; } /** * Default {@link Validation.ValidatorTraitValues | validation traits}. * @public */ declare const defaultValidatorTraits: ValidatorTraitValues; /** * Represents a deferred result that will be evaluated if needed. * @public */ export declare type DeferredResult = () => Result; /** * Helper function to create a {@link Converter | Converter} which converts any `string` into an * array of `string`, by separating at a supplied delimiter. * @remarks * Delimiter may also be supplied as context at conversion time. * @param delimiter - The delimiter at which to split. * @returns A new {@link Converter | Converter} returning `string[]`. * @public */ declare function delimitedString(delimiter: string, options?: 'filtered' | 'all'): Converter; /** * A {@link DetailedFailure | DetailedFailure} extends {@link Failure | Failure} to report optional * failure details in addition to the error message. * @public */ export declare class DetailedFailure extends Failure { /** * @internal */ protected _detail?: TD; /** * Constructs a new {@link DetailedFailure | DetailedFailure} with the supplied * message and detail. * @param message - The message to be returned. * @param detail - The error detail to be returned. */ constructor(message: string, detail?: TD); /** * The error detail associated with this {@link DetailedFailure}. */ get detail(): TD | undefined; /** * Reports that this {@link DetailedFailure} is a failure. * @remarks * Always true for {@link DetailedFailure} but can be used as type guard * to discriminate {@link DetailedSuccess} from {@link DetailedFailure} in * a {@link DetailedResult}. * @returns `true` */ isFailure(): this is DetailedFailure; /** * Propagates the error message and detail from this result. * @remarks * Mutates the success type as the success callback would have, but does not * call the success callback. * @param _cb - {@link DetailedSuccessContinuation | Success callback} to be called * on a {@link DetailedResult} in case of success (ignored). * @returns A new {@link DetailedFailure | DetailedFailure} which contains * the error message and detail from this one. */ onSuccess(__cb: DetailedSuccessContinuation): DetailedResult; /** * Invokes the supplied {@link DetailedFailureContinuation | failure callback} and propagates * its returned {@link DetailedResult | DetailedResult}. * @param cb - The {@link DetailedFailureContinuation | failure callback} to be invoked. * @returns The {@link DetailedResult | DetailedResult} returned by the failure callback. */ onFailure(cb: DetailedFailureContinuation): DetailedResult; /** * {@inheritdoc IResult.withErrorFormat} */ withErrorFormat(cb: ErrorFormatter): DetailedResult; /** * {@inheritdoc IResult.aggregateError} */ aggregateError(errors: IMessageAggregator, formatter?: ErrorFormatter): this; /** * {@inheritdoc IResult.report} */ report(reporter?: IResultReporter, options?: IResultReportOptions): DetailedFailure; orThrow(logOrFormat?: IResultLogger | ErrorFormatter): never; orThrow(cb: ErrorFormatter): never; /** * Returns this {@link DetailedFailure} as a {@link Result}. */ get asResult(): Result; /** * Creates a {@link DetailedFailure | DetailedFailure} with the supplied error message * and optional detail. * @param message - The error message to be returned. * @param detail - The error detail to be returned. * @returns The resulting {@link DetailedFailure | DetailedFailure} with the supplied * error message and detail. * @public */ static with(message: string, detail?: TD): DetailedFailure; } /** * Callback to be called when a {@link DetailedResult | DetailedResult} encounters a failure. * @remarks * A failure callback can change {@link DetailedFailure | DetailedFailure} to * {@link DetailedSuccess | DetailedSuccess} (e.g. by returning a default value) * or it can change or embellish the error message, but it cannot change the success return type. * @public */ export declare type DetailedFailureContinuation = (message: string, detail?: TD) => DetailedResult; /** * Type inference to determine the result type `T` of a {@link DetailedResult | DetailedResult}. * @beta */ export declare type DetailedResult = DetailedSuccess | DetailedFailure; /** * A {@link DetailedSuccess | DetailedSuccess} extends {@link Success | Success} to report optional success * details in addition to the error message. * @public */ export declare class DetailedSuccess extends Success { /** * @internal */ protected _detail?: TD; /** * Constructs a new {@link DetailedSuccess | DetailedSuccess} with the supplied * value and detail. * @param value - The value to be returned. * @param detail - An optional successful detail to be returned. If omitted, detail * will be `undefined`. */ constructor(value: T, detail?: TD); /** * The success detail associated with this {@link DetailedSuccess}, or `undefined` if * no detail was supplied. */ get detail(): TD | undefined; /** * Reports that this {@link DetailedSuccess} is a success. * @remarks * Always true for {@link DetailedSuccess} but can be used as type guard * to discriminate {@link DetailedSuccess} from {@link DetailedFailure} in * a {@link DetailedResult}. * @returns `true` */ isSuccess(): this is DetailedSuccess; /** * Invokes the supplied {@link DetailedSuccessContinuation | success callback} and propagates * its returned {@link DetailedResult | DetailedResult}. * @remarks * The success callback mutates the return type from `` to ``. * @param cb - The {@link DetailedSuccessContinuation | success callback} to be invoked. * @returns The {@link DetailedResult | DetailedResult} returned by the success callback. */ onSuccess(cb: DetailedSuccessContinuation): DetailedResult; /** * Propagates this {@link DetailedSuccess}. * @remarks * Failure does not mutate return type so we can return this event directly. * @param _cb - {@link DetailedFailureContinuation | Failure callback} to be called * on a {@link DetailedResult} in case of failure (ignored). * @returns `this` */ onFailure(__cb: DetailedFailureContinuation): DetailedResult; /** * {@inheritdoc Success.withErrorFormat} */ withErrorFormat(cb: ErrorFormatter): DetailedResult; /** * {@inheritdoc IResult.report} */ report(reporter?: IResultReporter, options?: IResultReportOptions): DetailedSuccess; /** * Creates a {@link DetailedSuccess | DetailedSuccess} with the supplied value and * optional detail. */ static with(value: T, detail?: TD): DetailedSuccess; /** * Returns this {@link DetailedSuccess} as a {@link Result}. */ get asResult(): Result; } /** * Callback to be called when a {@link DetailedResult | DetailedResult} encounters success. * @remarks * A success callback can return a different result type than it receives, allowing * success results to chain through intermediate result types. * @public */ export declare type DetailedSuccessContinuation = (value: T, detail?: TD) => DetailedResult; /** * Helper to create a {@link Converter | Converter} which converts a discriminated object without changing shape. * @remarks * Takes the name of the discriminator property and a * {@link Converters.DiscriminatedObjectConverters | string-keyed Record of converters and validators}. During conversion, * the resulting {@link Converter | Converter} invokes the converter from `converters` that corresponds to the value of * the discriminator property in the source object. * * If the source is not an object, the discriminator property is missing, or the discriminator has * a value not present in the converters, conversion fails and returns {@link Failure | Failure} with more information. * @param discriminatorProp - Name of the property used to discriminate types. * @param converters - {@link Converters.DiscriminatedObjectConverters | String-keyed record of converters and validators} * to invoke, where each key corresponds to a value of the discriminator property. * @returns A {@link Converter | Converter} which converts the corresponding discriminated object. * @public */ declare function discriminatedObject(discriminatorProp: string, converters: DiscriminatedObjectConverters): Converter; /** * A string-keyed `Record` which maps specific {@link Converter | converters} or * {@link Validator | Validators} to the value of a discriminator property. * @public */ declare type DiscriminatedObjectConverters = Record | Validator>; /** * A helper function to create a {@link Converter | Converter} which extracts and converts an element from an array. * @remarks * The returned {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists * in the supplied array and can be converted. Returns {@link Failure | Failure} with an error message otherwise. * @param index - The index of the element to be extracted. * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} for the extracted element. * @returns A {@link Converter | Converter} which extracts the specified element from an array. * @public */ declare function element(index: number, converter: Converter | Validator): Converter; /** * @internal */ declare type Entry = [string | number | symbol, T]; /** * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied * enumerated values. Anything else fails. * * @remarks * Allowed enumerated values can also be supplied as context at conversion time. * @param values - Array of allowed values. * @returns A new {@link Converter | Converter} returning ``. * @public */ declare function enumeratedValue(values: ReadonlyArray): Converter>; /** * Helper function to create a {@link Validation.Validator} which validates an enumerated * value in place. * @public */ declare function enumeratedValue_2(values: ReadonlyArray): Validator>; /** * Formats an error message. * @param message - The error message to be formatted. * @param detail - An optional detail to be included in the formatted message. * @public */ export declare type ErrorFormatter = (message: string, detail?: TD) => string; /** * Returns {@link Failure | Failure} with the supplied error message. * @param message - Error message to be returned. * @remarks * A `fails` alias was added in release 5.0 due to * issues with the name `fail` being used test frameworks and libraries. * @public */ declare function fail_2(message: string): Failure; export { fail_2 as fail } /** * {@inheritdoc fail} * @public */ export declare function fails(message: string): Failure; /** * {@inheritdoc failWithDetail} * @public */ export declare function failsWithDetail(message: string, detail?: TD): DetailedFailure; /** * Reports a failed {@link IResult | result} from some operation, with an error message. * @public */ export declare class Failure implements IResult { /** * {@inheritdoc IResult.success} */ readonly success: false; /** * Failed operation always returns undefined for value. */ readonly value: undefined; /** * @internal */ protected readonly _message: string; /** * Constructs a {@link Failure} with the supplied message. * @param message - Error message to be reported. */ constructor(message: string); /** * Gets the error message associated with this error. */ get message(): string; /** * {@inheritdoc IResult.isSuccess} */ isSuccess(): this is Success; /** * {@inheritdoc IResult.isFailure} */ isFailure(): this is Failure; /** * {@inheritdoc IResult.(orThrow:1)} */ orThrow(logger?: IResultLogger): never; /** * {@inheritdoc IResult.(orThrow:2)} */ orThrow(cb: ErrorFormatter): never; /** * {@inheritdoc IResult.(orDefault:1)} */ orDefault(dflt: T): T; /** * {@inheritdoc IResult.(orDefault:2)} */ orDefault(): T | undefined; /** * {@inheritdoc IResult.getValueOrThrow} * @deprecated Use {@link Failure.(orThrow:1) | orThrow(logger)} or {@link Failure.(orThrow:2) | orThrow(formatter)} instead. */ getValueOrThrow(logger?: IResultLogger): never; /** * {@inheritdoc IResult.getValueOrDefault} * @deprecated Use {@link Failure.(orDefault:1) | orDefault(T)} or {@link Failure.(orDefault:2) | orDefault()} instead. */ getValueOrDefault(dflt?: T): T | undefined; /** * {@inheritdoc IResult.onSuccess} */ onSuccess(__: SuccessContinuation): Result; /** * {@inheritdoc IResult.onFailure} */ onFailure(cb: FailureContinuation): Result; /** * {@inheritdoc IResult.withErrorFormat} */ withErrorFormat(cb: ErrorFormatter): Result; /** * {@inheritdoc IResult.withFailureDetail} */ withFailureDetail(detail: TD): DetailedResult; /** * {@inheritdoc IResult.withDetail} */ withDetail(detail: TD, __successDetail?: TD): DetailedResult; /** * {@inheritdoc IResult.aggregateError} */ aggregateError(errors: IMessageAggregator, formatter?: ErrorFormatter): this; /** * {@inheritdoc IResult.report} */ report(reporter?: IResultReporter, options?: IResultReportOptions): Failure; /** * Get a 'friendly' string representation of this object. * @remarks * The string representation of a {@link Failure} value is the error message. * @returns A string representing this object. */ toString(): string; /** * Creates a {@link Failure | Failure} with the supplied error message. * @param message - The error message to be returned. * @returns The resulting {@link Failure | Failure} with the supplied error message. */ static with(message: string): Failure; } /** * Continuation callback to be called in the event that an * {@link Result} fails. * @public */ export declare type FailureContinuation = (message: string) => Result; /** * Returns {@link DetailedFailure | DetailedFailure} with a supplied error message and detail. * @param message - The error message to be returned. * @param detail - The event detail to be returned. * @returns An {@link DetailedFailure | DetailedFailure} with the supplied error * message and detail. * @remarks * The `failsWithDetail` alias was added in release 5.0 for naming consistency * with {@link fails | fails}, which was added to avoid conflicts with test frameworks and libraries. * @public */ export declare function failWithDetail(message: string, detail?: TD): DetailedFailure; /** * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified * by name from an object. * @remarks * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of the corresponding * object property if the field exists and can be converted. Returns {@link Failure | Failure} with an error message * otherwise. * @param name - The name of the field to be extracted. * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted * field. * @public */ declare function field(name: string, converter: Converter | Validator): Converter; /** * Per-property converters or validators for each of the properties in type T. * @remarks * Used to construct a {@link Conversion.ObjectConverter | ObjectConverter} * @public */ declare type FieldConverters = { [key in keyof T]: Converter | Validator; }; /** * String-keyed record of initialization functions to be passed to {@link (populateObject:1)} * or {@link (populateObject:2)}. * @public */ export declare type FieldInitializers = { [key in keyof T]: (state: Partial) => Result; }; /** * Per-property converters and configuration for each field in the destination object of * a {@link Converters.transformObject} call. * @public */ declare type FieldTransformers = { [key in keyof TDEST]: { /** * The name of the property in the source object to be converted. */ from: keyof TSRC; /** * The converter or validator used to convert the property. */ converter: Converter | Validator; /** * If `true` then a missing source property is ignored. If `false` or omitted * then a missing source property causes an error. */ optional?: boolean; }; }; /** * Per-property {@link Validation.Validator | validators} for each of the properties in ``. * @public */ declare type FieldValidators = { [key in keyof T]: Validator; }; /** * Returns the first successful result from a collection of {@link Result | Result} or {@link DeferredResult | DeferredResult}. * @param results - The collection of {@link Result | Result} or {@link DeferredResult | DeferredResult} to be tested. * @returns The first successful result, or {@link Failure} with a concatenated summary of all error messages. * @public */ export declare function firstSuccess(results: Iterable | DeferredResult>): Result; /** * A {@link Validation.ConstraintTrait | ConstraintTrait} indicating that * a {@link Validation.Constraint | Constraint} function provides an * additional constraint implementation. * @public */ declare interface FunctionConstraintTrait { type: 'function'; } /** * Helper function to create a {@link Converter | Converter} from a supplied {@link Conversion.ConverterFunc | ConverterFunc}. * @param convert - the function to be wrapped * @returns A {@link Converter | Converter} which uses the supplied function. * @public */ declare function generic(convert: ConverterFunc): Converter; /** * Helper function to create a {@link Validation.Validator | Validator} using a * supplied {@link Validation.ValidatorFunc | validator function}. * @param validator - A {@link Validation.ValidatorFunc | validator function} that a * supplied unknown value matches some condition. * @returns A new {@link Validation.Validator | Validator} which validates the desired * value using the supplied function. * @public */ declare function generic_2(validator: ValidatorFunc): Validator; /** * Generic {@link Conversion.DefaultingConverter | DefaultingConverter}, which wraps another converter * to substitute a supplied default value for any errors returned by the inner converter. * @public */ declare class GenericDefaultingConverter implements DefaultingConverter { private _converter; /** * {@inheritdoc Conversion.DefaultingConverter.defaultValue} */ defaultValue: TD; /** * {@inheritdoc Converter.isOptional} */ get isOptional(): boolean; /** * {@inheritdoc Converter.isOptional} */ get brand(): string | undefined; /** * Constructs a new {@link Conversion.GenericDefaultingConverter | generic defaulting converter}. * @param converter - inner {@link Converter | Converter} used for the base conversion. * @param defaultValue - default value to be supplied if the inner conversion fails. */ constructor(converter: Converter, defaultValue: TD); /** * {@inheritdoc Converter.convert} */ convert(from: unknown, ctx?: TC | undefined): Success; /** * {@inheritdoc Converter.convertOptional} */ convertOptional(from: unknown, context?: TC | undefined, onError?: ('failOnError' | 'ignoreErrors') | undefined): Result; /** * {@inheritdoc Converter.optional} */ optional(onError?: ('failOnError' | 'ignoreErrors') | undefined): Converter; /** * {@inheritdoc Converter.map} */ map(mapper: (from: T | TD) => Result): Converter; /** * {@inheritdoc Converter.mapConvert} */ mapConvert(mapConverter: Converter): Converter; /** * {@inheritdoc Converter.mapItems} */ mapItems(mapper: (from: unknown) => Result): Converter; /** * {@inheritdoc Converter.mapConvertItems} */ mapConvertItems(mapConverter: Converter): Converter; /** * {@inheritdoc Converter.withAction} */ withAction(action: (result: Result) => Result): Converter; /** * {@inheritdoc Converter.withTypeGuard} */ withTypeGuard(guard: (from: unknown) => from is TI, message?: string | undefined): Converter; /** * {@inheritdoc Converter.withItemTypeGuard} */ withItemTypeGuard(guard: (from: unknown) => from is TI, message?: string | undefined): Converter; /** * {@inheritdoc Converter.withConstraint} */ withConstraint(constraint: (val: T | TD) => boolean | Result, options?: ConstraintOptions | undefined): Converter; /** * {@inheritdoc Converter.withBrand} */ withBrand(brand: B): Converter, TC>; /** * {@inheritdoc Converter.withFormattedError} */ withFormattedError(formatter: ConversionErrorFormatter): Converter; /** * Returns a Converter which always succeeds with the supplied default value rather * than failing. * * Note that the supplied default value *overrides* the default value of this * {@link Conversion.DefaultingConverter | DefaultingConverter}. */ withDefault(dflt: TD2): DefaultingConverter; private _applyDefault; } /** * Generic base implementation for an in-place {@link Validation.Validator | Validator}. * @public */ declare class GenericValidator implements Validator { /** * {@inheritdoc Validation.Validator.traits} */ readonly traits: ValidatorTraits; /** * @internal */ protected readonly _validator: ValidatorFunc; /** * @internal */ protected readonly _options: ValidatorOptions; /** * Constructs a new {@link Validation.Base.GenericValidator | GenericValidator}. * @param params - The {@link Validation.Base.GenericValidatorConstructorParams | constructor params} * used to configure validation. */ constructor(params: Partial>); /** * {@inheritdoc Validation.Validator.isOptional} */ get isOptional(): boolean; /** * {@inheritdoc Validation.Validator.brand} */ get brand(): string | undefined; /** * {@inheritdoc Validation.Validator.validate} */ validate(from: unknown, context?: TC): Result; /** * {@inheritdoc Validation.Validator.convert} */ convert(from: unknown, context?: TC): Result; /** * {@inheritdoc Validation.Validator.validateOptional} */ validateOptional(from: unknown, context?: TC): Result; /** * {@inheritdoc Validation.Validator.guard} */ guard(from: unknown, context?: TC): from is T; /** * {@inheritdoc Validation.Validator.optional} */ optional(): Validator; /** * {@inheritdoc Validation.Validator.withConstraint} */ withConstraint(constraint: Constraint, trait?: ConstraintTrait): Validator; /** * {@inheritdoc Validation.Validator.brand} */ withBrand(brand: B): Validator, TC>; /** * {@inheritdoc Validation.Validator.withFormattedError} */ withFormattedError(formatter: ValidationErrorFormatter): Validator; /** * Gets a default or explicit context. * @param explicitContext - Optional explicit context. * @returns The appropriate context to use. * @internal */ protected _context(explicitContext?: TC): TC | undefined; } /** * Options used to initialize a {@link Validation.Base.GenericValidator | GenericValidator}. * @public */ declare interface GenericValidatorConstructorParams { options?: ValidatorOptions; traits?: Partial; validator?: ValidatorFunc; } /** * Gets the type of a property specified by key from an arbitrary object. * @param key - The key specifying the property to be tested. * @param item - The object from which the property is to be tested. * @returns The type of the requested property, or `undefined` if the * property does not exist. * @example * Returns `'undefined'` (a string) if the property exists but has the value * undefined but `undefined` (the literal) if the property does not exist. * @public */ export declare function getTypeOfProperty(key: string | number | symbol, item: T): 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'undefined' | 'object' | 'function' | undefined; /** * Gets the value of a property specified by key from an arbitrary object, * or a default value if the property does not exist. * @param key - The key specifying the property to be retrieved. * @param item - The object from which the property is to be retrieved. * @param defaultValue - An optional default value to be returned if the property * is not present (default `undefined`). * @returns The value of the requested property, or the default value if the * requested property does not exist. * @public */ export declare function getValueOfPropertyOrDefault(key: string | number | symbol, item: T, defaultValue?: unknown): unknown | undefined; declare namespace Hash { export { Crc32Normalizer, HashFunction, HashingNormalizer } } export { Hash } /** * Function to compute a hash from a pre-normalized array of strings. * @public */ declare type HashFunction = (parts: string[]) => string; /** * Normalizes an arbitrary JSON object * @public */ declare class HashingNormalizer extends Normalizer { private _hash; constructor(hash: HashFunction); computeHash(from: unknown): Result; /** * Constructs a normalized string representation of some literal value. * @param from - The literal value to be normalized. * @returns A normalized string representation of the literal. * @internal */ protected _normalizeLiteralToString(from: string | number | bigint | boolean | symbol | undefined | Date | RegExp | null): Result; } /** * An item that can be collected by some {@link ConvertingCollector | Collector}. * @public */ export declare interface ICollectible { readonly key: TKEY; readonly index: TINDEX | undefined; setIndex(index: number): Result; } /** * Parameters for constructing a new {@link Collections.ICollectible | ICollectible} instance. * @public */ declare type ICollectibleConstructorParams = ICollectibleConstructorParamsWithIndex | ICollectibleConstructorParamsWithConverter; /** * Parameters for constructing a new {@link Collections.ICollectible | ICollectible} instance with an * index converter. * @public */ declare interface ICollectibleConstructorParamsWithConverter { key: TKEY; index?: number; indexConverter: Validator | Converter | ConverterFunc; } /** * Parameters for constructing a new {@link Collections.ICollectible | ICollectible} instance with * a defined, strongly-typed index. * @public */ declare interface ICollectibleConstructorParamsWithIndex { key: TKEY; index: TINDEX; } /** * Parameters for constructing a {@link Collections.Collector | ICollector}. * @public */ declare interface ICollectorConstructorParams> { items?: TITEM[]; } /** * Parameters for constructing a {@link Collections.CollectorValidator | CollectorValidator}. * @public */ declare interface ICollectorValidatorCreateParams> { readonly collector: Collector; readonly converters: KeyValueConverters, TITEM>; } /** * Parameters for constructing a {@link Collections.ConvertingCollector | ConvertingCollector}. * @public */ declare interface IConvertingCollectorConstructorParams, TSRC = TITEM> { /** * The default {@link Collections.CollectibleFactory | factory} to create items. */ factory: CollectibleFactory; /** * An optional array of entries to add to the collector. */ entries?: KeyValueEntry, TSRC>[]; } /** * Parameters for constructing a {@link Collections.ConvertingCollectorValidator | ConvertingCollectorValidator}. * @public */ declare interface IConvertingCollectorValidatorCreateParams, TSRC = TITEM> { collector: ConvertingCollector; converters: KeyValueConverters, TSRC>; } /** * Parameters for constructing a {@link Collections.KeyValueConverters | KeyValueConverters} instance. * @public */ declare interface IKeyValueConverterConstructorParams { /** * Required key {@link Validator | validator}, {@link Converter | converter}, * or {@link Conversion.ConverterFunc | converter function}. */ key: Validator | Converter | ConverterFunc; /** * Required value {@link Validator | validator}, {@link Converter | converter}, * or {@link Conversion.ConverterFunc | converter function}. */ value: Validator | Converter | ConverterFunc; } /** * Generic Result-aware logger interface with multiple levels of logging. * @public */ declare interface ILogger { /** * The level of logging to be used. */ readonly logLevel: ReporterLogLevel; /** * Logs a message at the given level. * @param level - The level of the message. * @param message - The message to log. * @param parameters - The parameters to log. * @returns `Success` with the logged message if the level is enabled, or * `Success` with `undefined` if the message is suppressed. */ log(level: MessageLogLevel, message?: unknown, ...parameters: unknown[]): Success; /** * Logs a detail message. * @param message - The message to log. * @param parameters - The parameters to log. * @returns `Success` with the logged message if the level is enabled, or * `Success` with `undefined` if the message is suppressed. */ detail(message?: unknown, ...parameters: unknown[]): Success; /** * Logs an info message. * @param message - The message to log. * @param parameters - The parameters to log. * @returns `Success` with the logged message if the level is enabled, or * `Success` with `undefined` if the message is suppressed. */ info(message?: unknown, ...parameters: unknown[]): Success; /** * Logs a warning message. * @param message - The message to log. * @param parameters - The parameters to log. * @returns `Success` with the logged message if the level is enabled, or * `Success` with `undefined` if the message is suppressed. */ warn(message?: unknown, ...parameters: unknown[]): Success; /** * Logs an error message. * @param message - The message to log. * @param parameters - The parameters to log. * @returns `Success` with the logged message if the level is enabled, or * `Success` with `undefined` if the message is suppressed. */ error(message?: unknown, ...parameters: unknown[]): Success; } /** * Parameters for creating a {@link Logging.LogReporter | LogReporter}. * @public */ declare interface ILogReporterCreateParams { logger?: ILogger; valueFormatter?: LogValueFormatter; messageFormatter?: LogMessageFormatter; } /** * Simple error aggregator to simplify collecting all errors in * a flow. * @public */ export declare interface IMessageAggregator { /** * Indicates whether any messages have been aggregated. */ readonly hasMessages: boolean; /** * The number of messages aggregated. */ readonly numMessages: number; /** * The aggregated messages. */ readonly messages: ReadonlyArray; /** * Adds a message to the aggregator, if defined. * @param message - The message to add - pass `undefined` * or the empty string to continue without adding a message. */ addMessage(message: string | undefined): this; /** * Adds multiple messages to the aggregator. * @param messages - the messages to add. */ addMessages(messages: string[] | undefined): this; /** * Returns all messages as a single string joined * using the optionally-supplied `separator`, or * newline if no separator is specified. * @param separator - The optional separator used * to join strings. */ toString(separator?: string): string; } /** * Details for reporting a message. * @public */ export declare interface IMessageReportDetail { level?: MessageLogLevel; message?: ErrorFormatter; detail?: TD; } /** * Infers the type that will be returned by an instantiated converter. Works * for complex as well as simple types. * @example `Infer` is `Map` * @beta */ declare type Infer = TCONV extends Converter ? InnerInferredType : never; /** * An in-memory logger that stores logged and suppressed messages. * @public */ declare class InMemoryLogger extends LoggerBase { /** * The messages that have been logged. * @internal */ private _logged; /** * The messages that have been suppressed. * @internal */ private _suppressed; /** * Creates a new in-memory logger. * @param logLevel - The level of logging to be used. */ constructor(logLevel?: ReporterLogLevel); /** * The messages that have been logged. */ get logged(): string[]; /** * The messages that have been suppressed. */ get suppressed(): string[]; /** * Clears the logged and suppressed messages. */ clear(): void; /** * {@inheritDoc Logging.LoggerBase._log} * @internal */ protected _log(message: string, __level: MessageLogLevel): Success; /** * {@inheritDoc Logging.LoggerBase._suppressLog} * @param level - The level of the message. * @param message - The message to suppress. * @param parameters - The parameters to suppress. * @returns `Success` with `undefined` if the message is suppressed. * @internal */ protected _suppressLog(level: MessageLogLevel, message?: unknown, ...parameters: unknown[]): Success; } /** * internal */ declare type InnerInferredType = TCONV extends Converter ? TTO extends Array ? InnerInferredType[] : TTO : TCONV extends Array ? InnerInferredType[] : TCONV; /** * A read-only interface exposing only the non-mutating methods of a {@link Collections.Collector | ICollector}. * @public */ declare interface IReadOnlyCollector> extends IReadOnlyResultMap, TITEM> { /** * Gets the item at a specified index. * @param index - The index of the item to retrieve. * @returns Returns {@link Success | Success} with the item if it exists, or {@link Failure | Failure} * with an error if the index is out of range. */ getAt(index: number): Result; /** * Gets all items in the collection, ordered by index. * @returns An array of items in the collection, ordered by index. */ valuesByIndex(): ReadonlyArray; } /** * A read-only interface exposing non-mutating methods of a * {@link Collections.CollectorValidator | CollectorValidator}. * @public */ declare interface IReadOnlyCollectorValidator> extends IReadOnlyResultMapValidator, TITEM> { /** * {@inheritdoc Collections.ConvertingCollectorValidator.map} */ readonly map: IReadOnlyResultMap, TITEM>; /** * {@inheritdoc Collections.Collector.get} */ get(key: string): DetailedResult; /** * {@inheritdoc Collections.ResultMap.has} */ has(key: string): boolean; /** * {@inheritdoc Collections.Collector.(getOrAdd:2)} */ getOrAdd(key: string, factory: ResultMapValueFactory, TITEM>): DetailedResult; } /** * A readonly `ReadonlyMap`-like object which reports success or failure * with additional details using the * {@link https://github.com/ErikFortune/fgv/tree/main/libraries/ts-utils#the-result-pattern | result pattern}. * @public */ export declare interface IReadOnlyResultMap { /** * {@inheritdoc Collections.ResultMap.size} */ readonly size: number; /** * {@inheritdoc Collections.ResultMap.entries} */ entries(): IterableIterator>; /** * {@inheritdoc Collections.ResultMap.forEach} */ forEach(cb: ResultMapForEachCb, arg?: unknown): void; /** * {@inheritdoc Collections.ResultMap.get} */ get(key: TK): DetailedResult; /** * {@inheritdoc Collections.ResultMap.has} */ has(key: TK): boolean; /** * {@inheritdoc Collections.ResultMap.keys} */ keys(): IterableIterator; /** * {@inheritdoc Collections.ResultMap.values} */ values(): IterableIterator; /** * Gets an iterator over the map entries. * @returns An iterator over the map entries. */ [Symbol.iterator](): IterableIterator>; } /** * A read-only interface exposing non-mutating methods of a {@link Collections.ResultMapValidator | ResultMapValidator}. * @public */ declare interface IReadOnlyResultMapValidator { /** * {@inheritdoc Collections.ResultMapValidator.map} */ readonly map: IReadOnlyResultMap; /** * {@inheritdoc Collections.ResultMap.get} */ get(key: string): DetailedResult; /** * {@inheritdoc Collections.ResultMap.has} */ has(key: string): boolean; } /** * A read-only interface exposing non-mutating methods of a * {@link Collections.ValidatingCollector | ValidatingCollector}. * @public */ declare interface IReadOnlyValidatingCollector> extends IReadOnlyValidatingResultMap, TITEM> { /** * {@inheritdoc Collections.ValidatingCollector.validating} */ readonly validating: IReadOnlyCollectorValidator; /** * {@inheritdoc Collections.IReadOnlyValidatingCollector.getAt} */ getAt(index: number): Result; /** * {@inheritdoc Collections.IReadOnlyCollector.valuesByIndex} */ valuesByIndex(): ReadonlyArray; } /** * A read-only interface exposing non-mutating methods of a {@link Collections.ValidatingResultMap | ValidatingResultMap}. * @public */ declare interface IReadOnlyValidatingResultMap extends IReadOnlyResultMap { /** * {@inheritdoc Collections.ValidatingResultMap.validating} */ readonly validating: IReadOnlyResultMapValidator; } /** * Options for {@link Validators.recordOf} helper function. * @public */ declare interface IRecordOfValidatorOptions { /** * If `onError` is `'fail'` (default), then the entire validation fails if any key or element * cannot be validated. If `onError` is `'ignore'`, failing elements are silently ignored. */ onError?: 'fail' | 'ignore'; /** * If present, `keyValidator` is used to validate the source object property names. * @remarks * Can be used to validate key names to supported values and/or strong types. */ keyValidator?: Validator; } /** * Represents the result of some operation of sequence of operations. * @remarks * This common contract enables commingled discriminated usage of {@link Success | Success} * and {@link Failure | Failure}. * @public */ export declare interface IResult { /** * Indicates whether the operation was successful. */ readonly success: boolean; /** * Value returned by a successful operation, undefined * for a failed operation. */ readonly value: T | undefined; /** * Error message returned by a failed operation, undefined * for a successful operation. */ readonly message: string | undefined; /** * Indicates whether this operation was successful. Functions * as a type guard for {@link Success | Success}. */ isSuccess(): this is Success; /** * Indicates whether this operation failed. Functions * as a type guard for {@link Failure | Failure}. */ isFailure(): this is Failure; /** * Gets the value associated with a successful {@link IResult | result}, * or throws the error message if the corresponding operation failed. * * Note that `getValueOrThrow` is being superseded by `orThrow` and * will eventually be deprecated. Please use orDefault instead. * * @param logger - An optional {@link IResultLogger | logger} to which the * error will also be reported. * @returns The return value, if the operation was successful. * @throws The error message if the operation failed. * @deprecated Use {@link IResult.(orThrow:1) | orThrow(logger)} or {@link IResult.(orThrow:2) | orThrow(formatter)} instead. */ getValueOrThrow(logger?: IResultLogger): T; /** * Gets the value associated with a successful {@link IResult | result}, * or a default value if the corresponding operation failed. * @param dflt - The value to be returned if the operation failed (default is * `undefined`). * * Note that `getValueOrDefault` is being superseded by `orDefault` and * will eventually be deprecated. Please use orDefault instead. * * @returns The return value, if the operation was successful. Returns * the supplied default value or `undefined` if no default is supplied. * @deprecated Use {@link IResult.(orDefault:1) | orDefault(T)} or {@link IResult.(orDefault:2) | orDefault()} instead. */ getValueOrDefault(dflt?: T): T | undefined; /** * Gets the value associated with a successful {@link IResult | result}, * or throws the error message if the corresponding operation failed. * @param logger - An optional {@link IResultLogger | logger} to which the * error will also be reported. * @returns The return value, if the operation was successful. * @throws The error message if the operation failed. * {@label logger} */ orThrow(logger?: IResultLogger): T; /** * Gets the value associated with a successful {@link IResult | result}, * or throws the error message if the corresponding operation failed. * @param cb - The {@link ErrorFormatter | error formatter} to be called in the event of failure. * @returns The return value, if the operation was successful. * @throws The error message if the operation failed. * {@label formatter} */ orThrow(cb: ErrorFormatter): T; /** * Gets the value associated with a successful {@link IResult | result}, * or a default value if the corresponding operation failed. * @param dflt - The value to be returned if the operation failed. * @returns The return value, if the operation was successful. Returns * the supplied default if an error occurred. * {@label SUPPLIED} */ orDefault(dflt: T): T; /** * Gets the value associated with a successful {@link IResult | result}, * or a default value if the corresponding operation failed. * @returns The return value, if the operation was successful, or * `undefined` if an error occurs. * {@label MISSING} */ orDefault(): T | undefined; /** * Calls a supplied {@link SuccessContinuation | success continuation} if * the operation was a success. * @remarks * The {@link SuccessContinuation | success continuation} might return a * different result type than {@link IResult} on which it is invoked. This * enables chaining of operations with heterogenous return types. * * @param cb - The {@link SuccessContinuation | success continuation} to * be called in the event of success. * @returns If this operation was successful, returns the value returned * by the {@link SuccessContinuation | success continuation}. If this result * failed, propagates the error message from this failure. */ onSuccess(cb: SuccessContinuation): Result; /** * Calls a supplied {@link FailureContinuation | failed continuation} if * the operation failed. * @param cb - The {@link FailureContinuation | failure continuation} to * be called in the event of failure. * @returns If this operation failed, returns the value returned by the * {@link FailureContinuation | failure continuation}. If this result * was successful, propagates the result value from the successful event. */ onFailure(cb: FailureContinuation): Result; /** * Calls a supplied {@link ErrorFormatter | error formatter} if * the operation failed. * @param cb - The {@link ErrorFormatter | error formatter} to * be called in the event of failure. * @returns If this operation failed, returns the returns {@link Failure | Failure} * with the message returned by the formatter. If this result * was successful, propagates the result value from the successful event. */ withErrorFormat(cb: ErrorFormatter): Result; /** * Converts a {@link IResult | IResult} to a {@link DetailedResult | DetailedResult}, * adding a supplied detail if the operation failed. * @param detail - The detail to be added if this operation failed. * @returns A new {@link DetailedResult | DetailedResult} with either * the success result or the error message from this {@link IResult}, with * the supplied detail (if this event failed) or detail `undefined` (if * this result succeeded). */ withFailureDetail(detail: TD): DetailedResult; /** * Converts a {@link IResult | IResult} to a {@link DetailedResult | DetailedResult}, * adding supplied details. * @param detail - The default detail to be added to the new {@link DetailedResult}. * @param successDetail - An optional detail to be added if this result was successful. * @returns A new {@link DetailedResult | DetailedResult} with either * the success result or the error message from this {@link IResult} and the * appropriate added detail. */ withDetail(detail: TD, successDetail?: TD): DetailedResult; /** * Propagates interior result, appending any error message to the * supplied errors array. * @param errors - {@link IMessageAggregator | Error aggregator} in which * errors will be aggregated. * @param formatter - An optional {@link ErrorFormatter | error formatter} to be used to format the error message. */ aggregateError(errors: IMessageAggregator, formatter?: ErrorFormatter): this; /** * Reports the result to the supplied reporter * @param reporter - The {@link IResultReporter | reporter} to which the result will be reported. * @param options - The {@link IResultReportOptions | options} for reporting the result. */ report(reporter?: IResultReporter, options?: IResultReportOptions): Result; } /** * Simple logger interface used by {@link IResult.(orThrow:1) | orThrow(logger)} and {@link IResult.(orThrow:2) | orThrow(formatter)}. * @public */ export declare interface IResultLogger { /** * Log an error message. * @param message - The message to be logged. */ error(message: string, detail?: TD): void; } /** * Parameters for constructing a {@link Collections.ResultMap | ResultMap}. * @public */ declare interface IResultMapConstructorParams { entries?: Iterable>; } /** * Parameters for constructing a {@link Collections.ResultMapValidator | ResultMapValidator}. * @public */ declare interface IResultMapValidatorCreateParams { map: ResultMap; converters: KeyValueConverters; } /** * Interface for reporting a result. * @public */ export declare interface IResultReporter { reportSuccess(level: MessageLogLevel, value: T, detail?: TD, message?: ErrorFormatter): void; reportFailure(level: MessageLogLevel, message: string, detail?: TD): void; } /** * Options for reporting a result. * @public */ export declare interface IResultReportOptions { /** * The level of reporting to be used for failure results. Default is 'error'. */ failure?: MessageLogLevel | IMessageReportDetail; /** * The level of reporting to be used for success results. Default is 'quiet'. */ success?: MessageLogLevel | IMessageReportDetail; } /** * Helper function to create a {@link Converter | Converter} from a supplied type guard function. * @param description - a description of the thing to be validated for use in error messages * @param guard - a {@link Validation.TypeGuardWithContext} which performs the validation. * @returns A new {@link Converter | Converter} which validates the values using the supplied type guard * and returns them in place. * @public */ declare function isA(description: string, guard: TypeGuardWithContext): Converter; /** * Helper function to create a {@link Validation.Classes.TypeGuardValidator | TypeGuardValidator} which * validates a value or object in place. * @param description - a description of the thing to be validated for use in error messages * @param guard - a {@link Validation.TypeGuardWithContext} which performs the validation. * @returns A new {@link Validation.Classes.TypeGuardValidator | TypeGuardValidator } which validates * the values using the supplied type guard. * @public */ declare function isA_2(description: string, guard: TypeGuardWithContext, params?: Omit, 'description' | 'guard'>): TypeGuardValidator; /** * Checks if a result is a deferred result. * @param result - The result to check. * @returns `true` if the result is a deferred result, `false` otherwise. * @public */ export declare function isDeferredResult(result: Result | DeferredResult): result is DeferredResult; /** * Determines if a supplied value is an iterable object or some other type. * @param value - The value to be tested. * @returns `true` if the value is an iterable object, `false` otherwise. * @public */ declare function isIterable = Iterable, TO = unknown>(value: TI | TO): value is TI; /** * Helper type-guard function to report whether a specified key is present in * a supplied object. * @param key - The key to be tested. * @param item - The object to be tested. * @returns Returns `true` if the key is present, `false` otherwise. * @public */ export declare function isKeyOf(key: string | number | symbol, item: T): key is keyof T; /** * Parameters for constructing a {@link Collections.ValidatingCollector | ValidatingCollector}. * @public */ declare interface IValidatingCollectorConstructorParams> { /** * {@inheritdoc Collections.ICollectorValidatorCreateParams.converters} */ converters: KeyValueConverters, TITEM>; /** * {@inheritdoc Collections.ICollectorConstructorParams.items} */ items?: unknown[]; } /** * Parameters for constructing a {@link Collections.ValidatingConvertingCollector | ValidatingConvertingCollector}. * @public */ declare interface IValidatingConvertingCollectorConstructorParams, TSRC = TITEM> { /** * {@inheritdoc Collections.IConvertingCollectorConstructorParams.factory} */ factory: CollectibleFactory; /** * {@inheritdoc Collections.IConvertingCollectorValidatorCreateParams.converters} */ converters: KeyValueConverters, TSRC>; /** * {@inheritdoc Collections.IConvertingCollectorConstructorParams.entries} */ entries?: KeyValueEntry, TSRC>[]; } /** * Parameters for constructing a {@link Collections.ResultMap | ResultMap}. * @public */ declare interface IValidatingResultMapConstructorParams { entries?: Iterable>; converters: KeyValueConverters; } /** * Options for {@link Converters.(recordOf:3) | Converters.recordOf} and * {@link Converters.(mapOf:3) | Converters.mapOf} * helper functions. * @public */ declare interface KeyedConverterOptions { /** * if `onError` is `'fail'` (default), then the entire conversion fails if any key or element * cannot be converted. If `onError` is `'ignore'`, failing elements are silently ignored. */ onError?: 'fail' | 'ignore'; /** * If present, `keyConverter` is used to convert the source object property names to * keys in the resulting map or record. * @remarks * Can be used to coerce key names to supported values and/or strong types. */ keyConverter?: Converter | Validator; } /** * Type for factory methods which convert a key-value pair to a new unique value. * @public */ declare type KeyedThingFactory = (key: TK, thing: TS) => Result; /** * Helper class for converting strongly-typed keys, values, or entries * from unknown values. * @public */ declare class KeyValueConverters { /** * Required key {@link Validator | validator} or {@link Converter | converter}. */ readonly key: Validator | Converter; /** * Required value {@link Validator | validator} or {@link Converter | converter}. */ readonly value: Validator | Converter; /** * Constructs a new key-value validator. * @param key - Required key {@link Validator | validator}, {@link Converter | converter}, * or {@link Conversion.ConverterFunc | converter function}. * @param value - Required value {@link Validator | validator}, {@link Converter | converter}, * or {@link Conversion.ConverterFunc | converter function}. */ constructor({ key, value }: IKeyValueConverterConstructorParams); /** * Converts a supplied unknown to a valid key value of type ``. * @param key - The unknown to be converted. * @returns `Success` with the converted key value and 'success' detail if the key is valid, * or `Failure` with an error message and 'invalid-key' detail if the key is invalid. */ convertKey(key: unknown): DetailedResult; /** * Converts a supplied unknown to a valid value of type ``. * @param key - The unknown to be converted. * @returns `Success` with the converted value and 'success' detail if the value is valid, * or `Failure` with an error message and 'invalid-value' detail if the value is invalid. */ convertValue(key: unknown): DetailedResult; /** * Converts a supplied unknown to a valid entry of type `[, ]`. * @param entry - The unknown to be converted. * @returns `Success` with the converted entry and 'success' detail if the entry * is valid, or `Failure` with an error message and 'invalid-key' or 'invalid-value' detail if * the entry is invalid */ convertEntry(entry: unknown): DetailedResult, ResultMapResultDetail>; /** * Converts a supplied iterable of unknowns to valid key-value pairs. * @param entries - The iterable of unknowns to be converted. * @returns `Success` with an array of converted key-value pairs if all entries are valid, * or `Failure` with an error message if any entry is invalid. */ convertEntries(entries: Iterable): Result[]>; } /** * Generic key-value entry. * @public */ declare type KeyValueEntry = [TK, TV]; /** * Helper function to create a {@link Converter | Converter} which converts `unknown` to some supplied literal value. Succeeds with * the supplied value if an identity comparison succeeds, fails otherwise. * @param value - The value to be compared. * @returns A {@link Converter | Converter} which returns the supplied value on success. * @public */ declare function literal(value: T): Converter; /** * Helper function to create a {@link Validation.Validator} which validates a literal value. * @param value - the literal value to be validated * @public */ declare function literal_2(value: T): Validator; /** * Abstract base class which implements {@link Logging.ILogger | ILogger}. * @public */ declare abstract class LoggerBase implements ILogger { /** * {@inheritDoc Logging.ILogger.logLevel} */ logLevel: ReporterLogLevel; protected constructor(logLevel?: ReporterLogLevel); /** * {@inheritDoc Logging.ILogger.detail} */ detail(message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc Logging.ILogger.info} */ info(message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc Logging.ILogger.warn} */ warn(message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc Logging.ILogger.error} */ error(message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc Logging.ILogger.log} */ log(level: MessageLogLevel, message?: unknown, ...parameters: unknown[]): Success; /** * Formats a message and parameters into a string. * @param message - The message to format. * @param parameters - The parameters to format. * @returns The formatted message. * @public */ protected _format(message?: unknown, ...parameters: unknown[]): string; /** * Inner method called for suppressed log messages. * @public */ protected _suppressLog(__level: MessageLogLevel, __message?: unknown, ...__parameters: unknown[]): Success; /** * Inner method called for logged messages. Should be implemented by derived classes. * @param message - The message to log. * @param level - The {@link MessageLogLevel | level} of the message. * @returns `Success` with the logged message, or `Success` with `undefined` if the message is suppressed. * @public */ protected abstract _log(message: string, level: MessageLogLevel): Success; } declare namespace Logging { export { shouldLog, stringifyLogValue, ReporterLogLevel, ILogger, LoggerBase, InMemoryLogger, ConsoleLogger, NoOpLogger, LogValueFormatter, LogMessageFormatter, ILogReporterCreateParams, LogReporter } } export { Logging } /** * A function that formats a message for logging. * @public */ declare type LogMessageFormatter = (message: string, detail?: TD) => string; /** * Abstract base class which wraps an existing {@link Logging.ILogger | ILogger} to implement * both {@link Logging.ILogger | ILogger} and {@link IResultReporter | IResultReporter}. * @public */ declare class LogReporter implements ILogger, IResultReporter { /** * Base logger used to by this reporter. * @public */ readonly logger: ILogger; /** * The formatter to use for values. * @internal */ protected readonly _valueFormatter: LogValueFormatter; /** * The formatter to use for messages. * @internal */ protected readonly _messageFormatter: LogMessageFormatter; /** * Creates a new {@link Logging.LogReporter | LogReporter}. * @param params - The parameters for creating the {@link Logging.LogReporter | LogReporter}. */ constructor(params?: ILogReporterCreateParams); /** * {@inheritDoc Logging.ILogger.logLevel} */ get logLevel(): ReporterLogLevel; /** * {@inheritDoc Logging.ILogger.detail} */ detail(message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc Logging.ILogger.info} */ info(message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc Logging.ILogger.warn} */ warn(message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc Logging.ILogger.error} */ error(message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc Logging.ILogger.log} */ log(level: MessageLogLevel, message?: unknown, ...parameters: unknown[]): Success; /** * {@inheritDoc IResultReporter.reportSuccess} */ reportSuccess(level: MessageLogLevel, value: T, detail?: TD, message?: ErrorFormatter): void; /** * {@inheritDoc IResultReporter.reportFailure} */ reportFailure(level: MessageLogLevel, message: string, detail?: TD): void; /** * Creates a new {@link Logging.LogReporter | LogReporter} with the same logger but a different value formatter. * @param valueFormatter - The value formatter to use. * @returns A new {@link Logging.LogReporter | LogReporter} with the same logger but a different value formatter. */ withValueFormatter(valueFormatter: LogValueFormatter): LogReporter; /** * Generic method to try to format an object for logging. * @param value - The value to format. * @param detail - The detail to format. * @returns */ static tryFormatObject(value: T, detail?: TD): string; } /** * A function that formats a value for logging. * @public */ declare type LogValueFormatter = (value: T, detail?: TD) => string; /** * Aggregates successful results from a collection of {@link DetailedResult | DetailedResult}, * optionally ignoring certain error details. * @param results - The collection of {@link DetailedResult | DetailedResult} to be mapped. * @param ignore - An array of error detail values (of type ``) that should be ignored. * @param aggregatedErrors - Optional string array to which any non-ignorable error messages will be * appended. Each error is appended as an individual string. * @returns {@link Success} with an array containing all successful results if all results either * succeeded or returned error details listed in `ignore`. If any results failed with details * that cannot be ignored, returns {@link Failure} with an concatenated summary of all non-ignorable * error messages. * @public */ export declare function mapDetailedResults(results: Iterable>, ignore: TD[], aggregatedErrors?: IMessageAggregator): Result; /** * Aggregates error messages from a collection of {@link Result | Result}. * @param results - An iterable collection of {@link Result | Result} for which * error messages are aggregated. * @param aggregatedErrors - Optional string array to which any returned error messages will be * appended. Each error is appended as an individual string. * @returns An array of strings consisting of all error messages returned by * {@link Result | results} in the source collection. Ignores {@link Success} * results and returns an empty array if there were no errors. * @public */ export declare function mapFailures(results: Iterable>, aggregatedErrors?: IMessageAggregator): string[]; /** * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed properties * using a supplied {@link Converter | Converter} or {@link Validator | Validator} to produce a * `Map`. * @remarks * The resulting converter fails conversion if any element cannot be converted. * @param converter - {@link Converter | Converter} | {@link Validator | Validator} used for each item in * the source object. * @returns A {@link Converter | Converter} which returns `Map`. * {@label WITH_DEFAULT} * @public */ declare function mapOf(converter: Converter | Validator): Converter, TC>; /** * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed properties * using a supplied {@link Converter | Converter} or {@link Validator | Validator} to produce a * `Map` and specified handling of elements that cannot be converted. * @remarks * if `onError` is `'fail'` (default), then the entire conversion fails if any key or element * cannot be converted. If `onError` is `'ignore'`, failing elements are silently ignored. * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used for * each item in the source object. * @returns A {@link Converter | Converter} which returns `Map`. * {@label WITH_ON_ERROR} * @public */ declare function mapOf(converter: Converter | Validator, onError: 'fail' | 'ignore'): Converter, TC>; /** * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed properties * using a supplied {@link Converter | Converter} or {@link Validator | Validator} to produce * a `Map`. * @remarks * If present, the supplied {@link Converters.KeyedConverterOptions | options} can provide a strongly-typed * converter for keys and/or control the handling of elements that fail conversion. * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used for each item * in the source object. * @param options - Optional {@link Converters.KeyedConverterOptions | KeyedConverterOptions} which * supplies a key converter and/or error-handling options. * @returns A {@link Converter | Converter} which returns `Map`. * {@label WITH_OPTIONS} * @public */ declare function mapOf(converter: Converter | Validator, options: KeyedConverterOptions): Converter, TC>; /** * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied enumerated * values, mapping any of multiple supplied values to the enumeration. * @remarks * Enables mapping of multiple input values to a consistent internal representation (so e.g. `'y'`, `'yes'`, * `'true'`, `1` and `true` can all map to boolean `true`) * @param map - An array of tuples describing the mapping. The first element of each tuple is the result * value, the second is the set of values that map to the result. Tuples are evaluated in the order * supplied and are not checked for duplicates. * @param message - An optional error message. * @returns A {@link Converter | Converter} which applies the mapping and yields `` on success. * @public */ declare function mappedEnumeratedValue(map: ReadonlyArray<[T, ReadonlyArray]>, message?: string): Converter>; /** * Aggregates successful result values from a collection of {@link Result | Result}. * @param results - The collection of {@link Result | Result} to be mapped. * @param aggregatedErrors - Optional string array to which any error messages will be * appended. Each error is appended as an individual string. * @returns If all {@link Result | results} are successful, returns {@link Success} with an * array containing all returned values. If any {@link Result | results} failed, returns * {@link Failure} with a concatenated summary of all error messages. * @public */ export declare function mapResults(results: Iterable>, aggregatedErrors?: IMessageAggregator): Result; /** * Aggregates successful results from a a collection of {@link Result | Result}. * @param results - An `Iterable` of {@link Result | Result} from which success * results are to be aggregated. * @param aggregatedErrors - Optional string array to which any returned error messages will be * appended. Each error is appended as an individual string. * @returns {@link Success} with an array of `` if any results were successful. If * all {@link Result | results} failed, returns {@link Failure} with a concatenated * summary of all error messages. * @public */ export declare function mapSuccess(results: Iterable>, aggregatedErrors?: IMessageAggregator): Result; /** * Applies a factory method to convert a `ReadonlyMap` into a `Record`. * @param src - The `Map` object to be converted. * @param factory - The factory method used to convert elements. * @returns {@link Success} with the resulting `Record` if conversion succeeds, or * {@link Failure} with an error message if an error occurs. * @public */ export declare function mapToRecord(src: ReadonlyMap, factory: KeyedThingFactory): Result>; /** * A simple error aggregator to simplify collecting and reporting all errors in * a flow. * @public */ export declare class MessageAggregator implements IMessageAggregator { private readonly _messages; /** * Constructs a new {@link MessageAggregator | ErrorAggregator} with an * optionally specified initial set of error messages. * @param errors - optional array of errors to be included * in the aggregation. */ constructor(errors?: string[]); /** * {@inheritdoc IMessageAggregator.hasMessages} */ get hasMessages(): boolean; /** * {@inheritdoc IMessageAggregator.numMessages} */ get numMessages(): number; /** * {@inheritdoc IMessageAggregator.messages} */ get messages(): string[]; /** * {@inheritdoc IMessageAggregator.addMessage} */ addMessage(message: string | undefined): this; /** * {@inheritdoc IMessageAggregator.addMessages} */ addMessages(messages: string[] | undefined): this; /** * {@inheritdoc IMessageAggregator.toString} */ toString(separator?: string): string; /** * If any error messages have been aggregated, returns * {@link Failure | Failure} with the aggregated * messages concatenated using the optionally-supplied * separator, or newline. If the supplied {@link Result | Result} * contains an error message that has not already been aggregated, * it will be included in the aggregated messages. * * If no error messages have been aggregated, returns * the supplied {@link Result | Result}. * @param result - The {@link Result | Result} to be returned * if no messages have been aggregated. * @param separator - Optional string separator used to construct * the error message. * @returns {@link Failure | Failure} with an aggregated message * if any error messages were collected, the supplied * {@link Result | Result} otherwise. */ returnOrReport(result: Result, separator?: string): Result; } /** * The severity level at which a message should be logged. * @public */ export declare type MessageLogLevel = 'quiet' | 'detail' | 'info' | 'warning' | 'error'; /** * A no-op {@link Logging.LoggerBase | LoggerBase} that does not log anything. * @public */ declare class NoOpLogger extends LoggerBase { /** * Creates a new no-op logger. * @param logLevel - The level of logging to be used. */ constructor(logLevel?: ReporterLogLevel); /** * {@inheritDoc Logging.LoggerBase._log} * @internal */ protected _log(message: string, __level: MessageLogLevel): Success; } /** * Normalizes an arbitrary JSON object * @public */ export declare class Normalizer { /** * Normalizes the supplied value * * @param from - The value to be normalized * @returns A normalized version of the value */ normalize(from: T): Result; /** * Compares two property names from some object being normalized. * @param k1 - First key to be compared. * @param k2 - Second key to be compared. * @returns `1` if `k1` is greater, `-1` if `k2` is greater and * `0` if they are equal. * @internal */ protected _compareKeys(k1: unknown, k2: unknown): number; /** * Normalizes an array of object property entries (e.g. as returned by `Object.entries()`). * @remarks * Converts property names (entry key) to string and then sorts as string. * @param entries - The entries to be normalized. * @returns A normalized sorted array of entries. */ normalizeEntries(entries: Iterable>): Entry[]; protected _normalizeArray(from: unknown[]): Result; /** * Normalizes the supplied literal value * @param from - The literal value to be normalized. * @returns A normalized value for the literal. */ normalizeLiteral(from: T): Result; } /** * A {@link Converter | Converter} which converts `unknown` to a `number`. * @remarks * Numbers and strings with a numeric format succeed. Anything else fails. * @public */ declare const number: Converter; /** * A {@link Validation.Classes.NumberValidator | NumberValidator} which validates a number in place. * @public */ declare const number_2: Validator; /** * {@link Converter | Converter} to convert an `unknown` to an array of `number`. * @remarks * Returns {@link Success | Success} with the the supplied value if it as an array * of numbers, returns {@link Failure | Failure} with an error message otherwise. * @public */ declare const numberArray: Converter; /** * An in-place {@link Validation.Validator | Validator} for `number` values. * @public */ declare class NumberValidator extends GenericValidator { /** * Constructs a new {@link Validation.Classes.NumberValidator | NumberValidator}. * @param params - Optional {@link Validation.Classes.NumberValidatorConstructorParams | init params} for the * new {@link Validation.Classes.NumberValidator | NumberValidator}. */ constructor(params?: NumberValidatorConstructorParams); /** * Static method which validates that a supplied `unknown` value is a `number`. * @param from - The `unknown` value to be tested. * @returns Returns `true` if `from` is a `number`, or {@link Failure} with an error * message if not. */ static validateNumber(from: unknown): boolean | Failure; } /** * Parameters used to construct a {@link Validation.Classes.NumberValidator | NumberValidator}. * @public */ declare type NumberValidatorConstructorParams = GenericValidatorConstructorParams; /** * Helper function to create a {@link Conversion.ObjectConverter | ObjectConverter} which converts an object * without changing shape, given a {@link Conversion.FieldConverters | FieldConverters} and an optional * {@link Conversion.ObjectConverterOptions | ObjectConverterOptions} to further refine conversion behavior. * @remarks * By default, if all of the requested fields exist and can be converted, returns {@link Success | Success} * with a new object that contains the converted values under the original key names. If any required properties * do not exist or cannot be converted, the entire conversion fails, returning {@link Failure | Failure} with additional * error information. * * Fields that succeed but convert to undefined are omitted from the result object but do not * fail the conversion. * @param properties - An {@link Conversion.FieldConverters | FieldConverters} defining the shape of the * source object and {@link Converter | converters} to be applied to each properties. * @param options - An {@link Conversion.ObjectConverterOptions | ObjectConverterOptions} containing options * for the object converter. * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} which applies the specified conversions. * {@label WITH_OPTIONS} * @public */ declare function object(properties: FieldConverters, options?: ObjectConverterOptions): ObjectConverter; /** * Helper function to create a {@link Conversion.ObjectConverter | ObjectConverter} which converts an object * without changing shape, given a {@link Conversion.FieldConverters | FieldConverters} and a set of * optional properties. * @remarks * By default, if all of the requested fields exist and can be converted, returns {@link Success | Success} * with a new object that contains the converted values under the original key names. If any required properties * do not exist or cannot be converted, the entire conversion fails, returning {@link Failure | Failure} with additional * error information. * * Fields that succeed but convert to undefined are omitted from the result object but do not * fail the conversion. * @param properties - An {@link Conversion.FieldConverters | FieldConverters} defining the shape of the * source object and {@link Converter | converters} to be applied to each properties. * @param optional - An array of `(keyof T)` listing the keys to be considered optional. * {@label WITH_KEYS} * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} which applies the specified conversions. * @public * @deprecated Use {@link Converters.(object:1) | Converters.object(fields, options)} instead. */ declare function object(properties: FieldConverters, optional: (keyof T)[]): ObjectConverter; /** * Helper function to create a {@link Validation.Classes.ObjectValidator | ObjectValidator} which validates * an object in place. * @param fields - A {@link Validation.Classes.FieldValidators | field validator definition} * describing the validations to be applied. * @param params - Optional {@link Validation.Classes.ObjectValidatorConstructorParams | parameters} * to refine the behavior of the resulting {@link Validation.Validator | validator}. * @returns A new {@link Validation.Validator | Validator} which validates the desired * object in place. * @public */ declare function object_2(fields: FieldValidators, params?: Omit, 'fields'>): ObjectValidator; /** * A {@link Converter | Converter} which converts an object of type `` without changing shape, given * a {@link Conversion.FieldConverters | FieldConverters} for the fields in the object. * @remarks * By default, if all of the required fields exist and can be converted, returns a new object with * the converted values under the original key names. If any required fields do not exist or cannot * be converted, the entire conversion fails. See {@link Conversion.ObjectConverterOptions | ObjectConverterOptions} * for other conversion options. * @public */ export declare class ObjectConverter extends BaseConverter { /** * Fields converted by this {@link Conversion.ObjectConverter | ObjectConverter}. */ readonly fields: FieldConverters; /** * Options used to initialize this {@link Conversion.ObjectConverter | ObjectConverter}. */ readonly options: ObjectConverterOptions; /** * Constructs a new {@link Conversion.ObjectConverter | ObjectConverter} using options * supplied in a {@link Conversion.ObjectConverterOptions | ObjectConverterOptions}. * @param fields - A {@link Conversion.FieldConverters | FieldConverters} containing * a {@link Converter} for each field * @param options - An optional @see ObjectConverterOptions to configure the conversion * {@label WITH_OPTIONS} */ constructor(fields: FieldConverters, options?: ObjectConverterOptions); /** * Constructs a new {@link Conversion.ObjectConverter | ObjectConverter} with optional * properties specified as an array of `keyof T`. * @param fields - A {@link Conversion.FieldConverters | FieldConverters} containing * a {@link Converter} for each field. * @param optional - An array of `keyof T` listing fields that are not required. * {@label WITH_KEYS} * @deprecated Use {@link Conversion.Converter.optional | .optional()} on the individual * fields, or pass {@link Conversion.ObjectConverterOptions | ObjectConverterOptions} to the constructor. */ constructor(fields: FieldConverters, optional?: (keyof T)[]); /** * Converts the supplied object using the {@link Conversion.ObjectConverter | ObjectConverter} * with all fields optional. * @param from - The object to be converted. * @param context - An optional context object passed to the field converters. * @returns A {@link Result} containing the converted object or an error message. */ convertPartial(from: unknown, context?: TC): Result>; /** * Converts the supplied object using the {@link Conversion.ObjectConverter | ObjectConverter} * with all fields required. * @param from - The object to be converted. * @param context - An optional context object passed to the field converters. * @returns A {@link Result} containing the converted object or an error message. */ convertRequired(from: unknown, context?: TC): Result>; /** * Creates a new {@link Conversion.ObjectConverter | ObjectConverter} derived from this one but with * all properties optional. * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} with the additional optional source properties. * {@label WITHOUT_OPTIONS} */ partial(): ObjectConverter, TC>; /** * Creates a new {@link Conversion.ObjectConverter | ObjectConverter} derived from this one but with * new optional properties as specified by a supplied {@link Conversion.ObjectConverterOptions | ObjectConverterOptions}. * @param options - The {@link Conversion.ObjectConverterOptions | options} to be applied to the new * converter. * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} with the additional optional source properties. * {@label WITH_OPTIONS} * @deprecated Pass just the keys to be made optional. */ partial(options: ObjectConverterOptions): ObjectConverter, TC>; /** * Creates a new {@link Conversion.ObjectConverter | ObjectConverter} derived from this one but with * new optional properties as specified by a supplied array of `keyof T`. * @param optional - The keys of the source object properties to be made optional. * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} with the additional optional source * properties. * {@label WITH_KEYS} */ partial(optional: (keyof T)[]): ObjectConverter, TC>; /** * Creates a new {@link Conversion.ObjectConverter | ObjectConverter} derived from this one but with * new optional properties as specified by a supplied array of `keyof T`. * @param addOptionalProperties - The keys to be made optional. * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} with the additional optional source * properties. */ addPartial(addOptionalProperties: (keyof T)[]): ObjectConverter, TC>; /** * Creates a new {@link Conversion.ObjectConverter | ObjectConverter} derived from this one but with * all properties required. * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} with the additional required source properties. */ required(): ObjectConverter, TC>; private static _convert; } /** * Options for an {@link Conversion.ObjectConverter | ObjectConverter}. * @public */ declare interface ObjectConverterOptions { /** * If present, lists optional fields. Missing non-optional fields cause an error. */ optionalFields?: (keyof T)[]; /** * If true, unrecognized fields yield an error. If false or undefined (default), * unrecognized fields are ignored. */ strict?: boolean; /** * Optional description to be included in error messages. */ description?: string; /** * Optional modifier to apply to the converter. */ modifier?: 'partial' | 'required'; } /** * In-place {@link Validation.Validator | Validator} for an object of type ``. * @remarks * By default, succeeds if all of the required fields exist and are validate, and fails if * any required fields do not exist or are invalid. See {@link Validation.Classes.ObjectValidatorOptions} * for other validation options. * @public */ declare class ObjectValidator extends ValidatorBase { /** * A {@link Validation.Classes.FieldValidators | FieldValidators} object specifying a * {@link Validation.Validator | Validator} for each of the expected properties */ readonly fields: FieldValidators; /** * {@link Validation.Classes.ObjectValidatorOptions | Options} which apply to this * validator. */ readonly options: ObjectValidatorOptions; /** * @internal */ protected readonly _innerValidators: FieldValidators; /** * @internal */ protected readonly _allowedFields?: Set; /** * Constructs a new {@link Validation.Classes.ObjectValidator | ObjectValidator}. * @param fields - A {@link Validation.Classes.FieldValidators | FieldValidators} containing * a {@link Validation.Validator | Validator} for each field. * @param options - An optional {@link Validation.Classes.ObjectValidatorOptions} to configure * validation. */ constructor(params: ObjectValidatorConstructorParams); /** * Creates the actual {@link Validation.Classes.FieldValidators | FieldValidators} to be * used by this converter by applying any options or traits defined in the options * to the field converters passed to the constructor. * @param fields - The base {@link Validation.Classes.FieldValidators | FieldValidators} passed * in to the constructor. * @param options - The {@link Validation.Classes.ObjectValidatorOptions | object validator options} * passed in to the constructor. * @returns A new {@link Validation.Classes.FieldValidators | FieldValidators} with the fully-configured * individual {@link Validation.Validator | field validators} to be applied. * @internal */ protected static _resolveValidators(fields: FieldValidators, options?: ObjectValidatorOptions): FieldValidators; /** * Creates a new {@link Validation.Classes.ObjectValidator | ObjectValidator} derived from this one but with * new optional properties as specified by a supplied * {@link Validation.Classes.ObjectValidatorOptions | ObjectValidatorOptions}. * @param options - The {@link Validation.Classes.ObjectValidatorOptions | options} to be applied to the new * {@link Validation.Classes.ObjectValidator | validator}. * @returns A new {@link Validation.Classes.ObjectValidator | ObjectValidator} with the additional optional * source properties. */ partial(options?: ObjectValidatorOptions): ObjectValidator, TC>; /** * Creates a new {@link Validation.Classes.ObjectValidator | ObjectValidator} derived from this one but with * new optional properties as specified by a supplied array of `keyof T`. * @param addOptionalProperties - The keys to be made optional. * @returns A new {@link Validation.Classes.ObjectValidator | ObjectValidator} with the additional optional * source properties. */ addPartial(addOptionalFields: (keyof T)[]): ObjectValidator, TC>; /** * {@inheritdoc Validation.ValidatorBase._validate} * @internal */ protected _validate(from: unknown, context?: TC, self?: Validator): boolean | Failure; } /** * Options for the {@link Validation.Classes.ObjectValidator | ObjectValidator} constructor. * @public */ declare interface ObjectValidatorConstructorParams extends ValidatorBaseConstructorParams { /** * A {@link Validation.Classes.FieldValidators | FieldValidators} object specifying a * {@link Validation.Validator | Validator} for each of the expected properties * of a result object. */ fields: FieldValidators; /** * Optional additional {@link Validation.Classes.ObjectValidatorOptions | ValidatorOptions} to * configure validation. */ options?: ObjectValidatorOptions; } /** * Options for an {@link Validation.Classes.ObjectValidator | ObjectValidator}. * @public */ declare interface ObjectValidatorOptions extends ValidatorOptions { /** * If present, lists optional fields. Missing non-optional fields cause an error. */ optionalFields?: (keyof T)[]; /** * If true, unrecognized fields yield an error. If false or undefined (default), * unrecognized fields are ignored. */ strict?: boolean; } /** * Simple implicit omit function, which picks all of the properties from a supplied * object except those specified for exclusion. * @param from - The object from which keys are to be picked. * @param exclude - The keys of the properties to be excluded from the returned object. * @returns A new object containing all of the properties from `from` that were not * explicitly excluded. * @public */ export declare function omit(from: T, exclude: K[]): Omit; /** * A helper function to create a {@link Converter | Converter} for polymorphic values. * Returns a converter which invokes the wrapped converters in sequence, returning the * first successful result. Returns an error if none of the supplied converters can * convert the value. * @remarks * If `onError` is `ignoreErrors` (default), then errors from any of the * converters are ignored provided that some converter succeeds. If * onError is `failOnError`, then an error from any converter fails the entire * conversion. * * @param converters - An ordered list of {@link Converter | converters} or {@link Validator | validators} * to be considered. * @param onError - Specifies treatment of unconvertible elements. * @returns A new {@link Converter | Converter} which yields a value from the union of the types returned * by the wrapped converters. * @public */ declare function oneOf(converters: Array | Validator>, onError?: OnError): Converter; /** * Helper function to create a {@link Validation.Validator | Validator} which validates one * of several possible validated values. * @param validators - the {@link Validation.Validator | validators} to be considered. * @param params - Optional {@link Validation.Classes.OneOfValidatorConstructorParams | params} used to construct the validator. * @returns A new {@link Validator | Validator} which validates values that match any of * the supplied validators. * @public */ declare function oneOf_2(validators: Array>, params?: Omit, 'validators'>): OneOfValidator; /** * An in-place {@link Validator | Validator} which validates that a supplied * value matches one of several other validators. * @public */ declare class OneOfValidator extends ValidatorBase { /** * {@link Validation.ValidatorOptions | Options} which apply to this * validator. */ readonly options: ValidatorOptions; protected readonly _validators: Validator[]; /** * Constructs a new {@link Validation.Classes.OneOfValidator | OneOfValidator}. * @param params - Optional {@link Validation.Classes.OneOfValidatorConstructorParams | init params} for the * new {@link Validation.Classes.OneOfValidator | OneOfValidator}. */ constructor(params: OneOfValidatorConstructorParams); /** * Static method which validates that a supplied `unknown` value matches at least one * of the configured validators. * @param from - The `unknown` value to be tested. * @param context - Optional validation context will be propagated to element validator. * @param self - Optional self-reference for recursive validation. * @returns Returns `true` if `from` is an `array` of valid elements, or * {@link Failure} with an error message if not. */ protected _validate(from: unknown, context?: TC, self?: Validator): boolean | Failure; } /** * Parameters used to construct a {@link Validation.Classes.OneOfValidator | OneOfValidator}. * @public */ declare interface OneOfValidatorConstructorParams extends ValidatorBaseConstructorParams { validators: Validator[]; } /** * Action to take on conversion failures. * @public */ declare type OnError = 'failOnError' | 'ignoreErrors'; /** * A {@link Converter | Converter} to convert an optional `boolean` value. * @remarks * Values of type `boolean` or strings that match (case-insensitive) `'true'` * or `'false'` are converted and returned. Anything else returns {@link Success | Success} * with value `undefined`. * @public */ declare const optionalBoolean: Converter; /** * A helper function to create a {@link Converter | Converter} which extracts and converts an optional element from an array. * @remarks * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists * in the supplied array and can be converted. Returns {@link Success | Success} with value `undefined` if the parameter * is an array but the index is out of range. Returns {@link Failure | Failure} with a message if the supplied parameter * is not an array, if the requested index is negative, or if the element cannot be converted. * @param index - The index of the element to be extracted. * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} used for the extracted element. * @returns A {@link Converter | Converter} which extracts the specified element from an array. * @public */ declare function optionalElement(index: number, converter: Converter | Validator): Converter; /** * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified * by name from an object. * @remarks * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of * the corresponding object property if the field exists and can be converted. Returns {@link Success | Success} * with `undefined` if the supplied parameter is an object but the named field is not present. * Returns {@link Failure | Failure} with an error message otherwise. * @param name - The name of the field to be extracted. * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted field. * @public */ declare function optionalField(name: string, converter: Converter | Validator): Converter; /** * Applies a factory method to convert an optional `ReadonlyMap` into a `Record` * @param src - The `ReadonlyMap` object to be converted, or `undefined`. * @param factory - The factory method used to convert elements. * @returns {@link Success} with the resulting record (empty if `src` is `undefined`) if conversion succeeds. * Returns {@link Failure} with a message if an error occurs. * @public */ export declare function optionalMapToPossiblyEmptyRecord(src: ReadonlyMap | undefined, factory: KeyedThingFactory): Result>; /** * Applies a factory method to convert an optional `ReadonlyMap` into a `Record` or `undefined`. * @param src - The `Map` object to be converted, or `undefined`. * @param factory - The factory method used to convert elements. * @returns {@link Success} with the resulting record if conversion succeeds, or {@link Success} with `undefined` if * `src` is `undefined`. Returns {@link Failure} with a message if an error occurs. * @public */ export declare function optionalMapToRecord(src: ReadonlyMap | undefined, factory: KeyedThingFactory): Result | undefined>; /** * A {@link Converter | Converter} which converts an optional `number` value. * @remarks * Values of type `number` or numeric strings are converted and returned. * Anything else returns {@link Success | Success} with value `undefined`. * @public */ declare const optionalNumber: Converter; /** * Applies a factory method to convert an optional `Record` into a `Map`, or `undefined`. * @param src - The `Record` to be converted, or undefined. * @param factory - The factory method used to convert elements. * @returns {@link Success} with the resulting map if conversion succeeds, or {@link Success} with `undefined` * if `src` is `undefined`. Returns {@link Failure} with a message if an error occurs. * @public */ export declare function optionalRecordToMap(src: Record | undefined, factory: KeyedThingFactory): Result | undefined>; /** * Applies a factory method to convert an optional `Record` into a `Map` * @param src - The `Record` to be converted, or `undefined`. * @param factory - The factory method used to convert elements. * @returns {@link Success} with the resulting map (empty if `src` is `undefined`) if conversion succeeds. * Returns {@link Failure} with a message if an error occurs. * @public */ export declare function optionalRecordToPossiblyEmptyMap(src: Record | undefined, factory: KeyedThingFactory): Result>; /** * A {@link Converter | Converter} which converts an optional `string` value. Values of type * `string` are returned. Anything else returns {@link Success | Success} with value `undefined`. * @public */ declare const optionalString: Converter; /** * Simple implicit pick function, which picks a set of properties from a supplied * object. Ignores picked properties that do not exist regardless of type signature. * @param from - The object from which keys are to be picked. * @param include - The keys of the properties to be picked from `from`. * @returns A new object containing the requested properties from `from`, where present. * @public */ export declare function pick(from: T, include: K[]): Pick; /** * Populates an an object based on a prototype full of field initializers that return {@link Result | Result}. * Returns {@link Success} with the populated object if all initializers succeed, or {@link Failure} with a * concatenated list of all error messages. * @param initializers - An object with the shape of the target but with initializer functions for * each property. * @param options - An optional {@link PopulateObjectOptions | set of options} which * modify the behavior of this call. * @param aggregatedErrors - Optional string array to which any returned error messages will be * appended. Each error is appended as an individual string. * {@label WITH_OPTIONS} * @public */ export declare function populateObject(initializers: FieldInitializers, options?: PopulateObjectOptions, aggregatedErrors?: IMessageAggregator): Result; /** * Populates an an object based on a prototype full of field initializers that return {@link Result | Result}. * Returns {@link Success} with the populated object if all initializers succeed, or {@link Failure} with a * concatenated list of all error messages. * @param initializers - An object with the shape of the target but with initializer functions for * each property. * @param order - Optional order in which keys should be written. * @param aggregatedErrors - Optional string array to which any returned error messages will be * appended. Each error is appended as an individual string. * @public * {@label WITH_ORDER} * @deprecated Pass {@link PopulateObjectOptions} instead. */ export declare function populateObject(initializers: FieldInitializers, order: (keyof T)[] | undefined, aggregatedErrors?: IMessageAggregator): Result; /** * Options for the {@link (populateObject:1)} function. * @public */ export declare interface PopulateObjectOptions { /** * If present, specifies the order in which property values should * be evaluated. Any keys not listed are evaluated after all listed * keys in indeterminate order. If 'order' is not present, keys * are evaluated in indeterminate order. */ order?: (keyof T)[]; /** * Specify handling of `undefined` values. By default, successful * `undefined` results are written to the result object. If this value * is `true` then `undefined` results are suppressed for all properties. * If this value is an array of property keys then `undefined` results * are suppressed for those properties only. */ suppressUndefined?: boolean | (keyof T)[]; } /** * Propagates a {@link Success} or {@link Failure} {@link Result}, adding supplied * event details as appropriate. * @param result - The {@link Result} to be propagated. * @param detail - The event detail (type ``) to be added to the {@link Result | result}. * @param successDetail - An optional distinct event detail to be added to {@link Success} results. If `successDetail` * is omitted or `undefined`, then `detail` will be applied to {@link Success} results. * @returns A new {@link DetailedResult | DetailedResult} with the success value or error * message from the original `result` but with the specified detail added. * @public */ export declare function propagateWithDetail(result: Result, detail: TD, successDetail?: TD): DetailedResult; /** * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed * properties using a supplied {@link Converter | Converter} or {@link Validator | Validator} to * produce a `Record`. * @remarks * The resulting converter fails conversion if any element cannot be converted. * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used for each * item in the source object. * @returns A {@link Converter | Converter} which returns `Record`. * {@label WITH_DEFAULT} * @public */ declare function recordOf(converter: Converter | Validator): Converter, TC>; /** * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed properties * using a supplied {@link Converter | Converter} or {@link Validator | Validator} to produce a * `Record` and optionally specified handling of elements that cannot be converted. * @remarks * if `onError` is `'fail'` (default), then the entire conversion fails if any key or element * cannot be converted. If `onError` is `'ignore'`, failing elements are silently ignored. * @param converter - {@link Converter | Converter} or {@link Validator | Validator} for each item in * the source object. * @returns A {@link Converter | Converter} which returns `Record`. * {@label WITH_ON_ERROR} * @public */ declare function recordOf(converter: Converter | Validator, onError: 'fail' | 'ignore'): Converter, TC>; /** * A helper function to create a {@link Converter | Converter} or which converts the `string`-keyed properties * using a supplied {@link Converter | Converter} or {@link Validator | Validator} to produce a * `Record`. * @remarks * If present, the supplied {@link Converters.KeyedConverterOptions | options} can provide a strongly-typed * converter for keys and/or control the handling of elements that fail conversion. * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used for each item in the source object. * @param options - Optional {@link Converters.KeyedConverterOptions | KeyedConverterOptions} which * supplies a key converter and/or error-handling options. * @returns A {@link Converter | Converter} which returns `Record`. * {@label WITH_OPTIONS} * @public */ declare function recordOf(converter: Converter | Validator, options: KeyedConverterOptions): Converter, TC>; /** * A helper function to create a {@link Validation.Validator | Validator} which validates the `string`-keyed properties * using a supplied {@link Validation.Validator | Validator} to produce a `Record`. * @remarks * If present, the supplied {@link Validators.IRecordOfValidatorOptions | options} can provide a strongly-typed * validator for keys and/or control the handling of elements that fail validation. * @param validator - {@link Validation.Validator | Validator} used for each item in the source object. * @param options - Optional {@link Validators.IRecordOfValidatorOptions | IRecordOfValidatorOptions} which * supplies a key validator and/or error-handling options. * @returns A {@link Validation.Validator | Validator} which validates `Record`. * @public */ declare function recordOf_2(validator: Validator, options?: IRecordOfValidatorOptions): Validator, TC>; /** * Applies a factory method to convert a `Record` into a `Map`. * @param src - The `Record` to be converted. * @param factory - The factory method used to convert elements. * @returns {@link Success} with the resulting map on success, or {@link Failure} with a * message if an error occurs. * @public */ export declare function recordToMap(src: Record, factory: KeyedThingFactory): Result>; /** * The level of logging to be used. * @public */ declare type ReporterLogLevel = 'all' | 'detail' | 'info' | 'warning' | 'error' | 'silent'; /** * Represents the {@link IResult | result} of some operation or sequence of operations. * @remarks * {@link Success | Success} and {@link Failure | Failure} share the common * contract {@link IResult}, enabling commingled discriminated usage. * @public */ export declare type Result = Success | Failure; /** * Type inference to determine the detail type `TD` of a {@link DetailedResult | DetailedResult}. * @beta */ export declare type ResultDetailType = T extends DetailedResult ? TD : never; /** * A {@link Collections.ResultMap | ResultMap} class as a `Map`-like object which * reports success or failure with additional details using the * {@link https://github.com/ErikFortune/fgv/tree/main/libraries/ts-utils#the-result-pattern | result pattern}. * @public */ export declare class ResultMap implements IReadOnlyResultMap { /** * Protected raw access to the inner `Map` object. * @public */ protected readonly _inner: Map; /** * Constructs a new {@link Collections.ResultMap | ResultMap}. * @param iterable - An iterable to initialize the map. */ constructor(iterable?: Iterable>); /** * Constructs a new {@link Collections.ResultMap | ResultMap}. * @param params - An optional set of parameters to configure the map. */ constructor(params: IResultMapConstructorParams); /** * Creates a new {@link Collections.ResultMap | ResultMap}. * @param elements - An optional iterable to initialize the map. * @returns `Success` with the new map, or `Failure` with error details * if an error occurred. * @public */ static create(elements: Iterable>): Result>; /** * Creates a new {@link Collections.ResultMap | ResultMap}. * @param params - An optional set of parameters to configure the map. * @returns `Success` with the new map, or `Failure` with error details * if an error occurred. * @public */ static create(params?: IResultMapConstructorParams): Result>; /** * Sets a key/value pair in the map if the key does not already exist. * @param key - The key to set. * @param value - The value to set. * @returns `Success` with the value and detail `added` if the key was added, * `Failure` with detail `exists` if the key already exists. Fails with detail * 'invalid-key' or 'invalid-value' and an error message if either is invalid. */ add(key: TK, value: TV): DetailedResult; /** * Clears the map. */ clear(): void; /** * Deletes a key from the map. * @param key - The key to delete. * @returns `Success` with the previous value and the detail 'deleted' * if the key was found and deleted, `Failure` with detail 'not-found' * if the key was not found, or with detail 'invalid-key' if the key is invalid. */ delete(key: TK): DetailedResult; /** * Returns an iterator over the map entries. * @returns An iterator over the map entries. */ entries(): IterableIterator>; /** * Calls a function for each entry in the map. * @param cb - The function to call for each entry. * @param arg - An optional argument to pass to the callback. */ forEach(cb: ResultMapForEachCb, arg?: unknown): void; /** * Gets a value from the map. * @param key - The key to retrieve. * @returns `Success` with the value and detail `exists` if the key was found, * `Failure` with detail `not-found` if the key was not found or with detail * `invalid-key` if the key is invalid. */ get(key: TK): DetailedResult; /** * Gets a value from the map, or adds a supplied value it if it does not exist. * @param key - The key to be retrieved or created. * @param value - The value to add if the key does not exist. * @returns `Success` with the value and detail `exists` if the key was found, * `Success` with the value and detail `added` if the key was not found and added. * Fails with detail 'invalid-key' or 'invalid-value' and an error message if either * is invalid. * {@label WITH_VALUE} */ getOrAdd(key: TK, value: TV): DetailedResult; /** * Gets a value from the map, or adds a value created by a factory function if it does not exist. * @param key - The key of the element to be retrieved or created. * @param factory - A {@link Collections.ResultMapValueFactory | factory function} to create the value if * the key does not exist. * @returns `Success` with the value and detail `exists` if the key was found, `Success` with * the value and detail `added` if the key was not found and added. Fails with detail 'invalid-key' * or 'invalid-value' and an error message if either is invalid. * {@label WITH_FACTORY} */ getOrAdd(key: TK, factory: ResultMapValueFactory): DetailedResult; /** * Returns `true` if the map contains a key. * @param key - The key to check. * @returns `true` if the key exists, `false` otherwise. */ has(key: TK): boolean; /** * Returns an iterator over the map keys. * @returns An iterator over the map keys. */ keys(): IterableIterator; /** * Sets a key/value pair in the map. * @param key - The key to set. * @param value - The value to set. * @returns `Success` with the new value and the detail `updated` if the * key was found and updated, `Success` with the new value and detail * `added` if the key was not found and added. Fails with detail * 'invalid-key' or 'invalid-value' and an error message if either is invalid. */ set(key: TK, value: TV): DetailedResult; /** * Returns the number of entries in the map. */ get size(): number; /** * Updates an existing key in the map - the map is not updated if the key does * not exist. * @param key - The key to update. * @param value - The value to set. * @returns `Success` with the value and detail 'exists' if the key was found * and the value updated, `Failure` an error message and with detail `not-found` * if the key was not found, or with detail 'invalid-key' or 'invalid-value' * if either is invalid. */ update(key: TK, value: TV): DetailedResult; /** * Returns an iterator over the map values. * @returns An iterator over the map values. */ values(): IterableIterator; /** * Gets an iterator over the map entries. * @returns An iterator over the map entries. */ [Symbol.iterator](): IterableIterator>; /** * Gets a readonly version of this map. * @returns A readonly version of this map. */ toReadOnly(): IReadOnlyResultMap; /** * Determines if a value is a {@link Collections.ResultMapValueFactory | ResultMapValueFactory}. * @param value - The value to check. * @returns `true` if the value is a {@link Collections.ResultMapValueFactory | ResultMapValueFactory}, * `false` otherwise. * @public */ protected _isResultMapValueFactory(value: TV | ResultMapValueFactory): value is ResultMapValueFactory; } /** * Callback for {@link Collections.ResultMap | ResultMap} `forEach` method. * @public */ declare type ResultMapForEachCb = (value: TE, key: TK, map: IReadOnlyResultMap, thisArg?: unknown) => void; /** * Additional success or failure details for {@link Collections.ResultMap | ResultMap} calls. * @public */ declare type ResultMapResultDetail = 'added' | 'deleted' | 'exists' | 'failure' | 'invalid-key' | 'invalid-value' | 'not-found' | 'success' | 'updated'; /** * A {@link Collections.ResultMap | ResultMap} wrapper which validates weakly-typed keys * before calling the wrapped result map. * @public */ declare class ResultMapValidator implements IReadOnlyResultMapValidator { readonly converters: KeyValueConverters; get map(): IReadOnlyResultMap; protected _map: ResultMap; /** * Constructs a new {@link Collections.ResultMapValidator | ResultMapValidator}. * @param params - Required parameters for constructing the result map validator. */ constructor(params: IResultMapValidatorCreateParams); /** * {@inheritdoc Collections.ResultMap.add} */ add(key: string, value: unknown): DetailedResult; /** * {@inheritdoc Collections.ResultMap.delete} */ delete(key: string): DetailedResult; /** * {@inheritdoc Collections.ResultMap.get} */ get(key: string): DetailedResult; /** * {@inheritdoc Collections.ResultMap.(getOrAdd:1)} */ getOrAdd(key: string, value: unknown): DetailedResult; /** * {@inheritdoc Collections.ResultMap.(getOrAdd:2)} */ getOrAdd(key: string, factory: ResultMapValueFactory): DetailedResult; /** * {@inheritdoc Collections.ResultMap.has} */ has(key: string): boolean; /** * {@inheritdoc Collections.ResultMap.set} */ set(key: string, value: unknown): DetailedResult; /** * {@inheritdoc Collections.ResultMap.update} */ update(key: string, value: unknown): DetailedResult; /** * Gets a read-only version of this validator. */ toReadOnly(): IReadOnlyResultMapValidator; /** * Determines if a value is a {@link Collections.ResultMapValueFactory | ResultMapValueFactory}. * @param value - The value to check. * @returns `true` if the value is a {@link Collections.ResultMapValueFactory | ResultMapValueFactory}, * `false` otherwise. * @public */ protected _isResultMapValueFactory(value: TV | ResultMapValueFactory): value is ResultMapValueFactory; } /** * Deferred constructor for the {@link Collections.ResultMap.(getOrAdd:2) | getOrAdd} method. * @public */ declare type ResultMapValueFactory = (key: TK) => Result; /** * Type inference to determine the result type of an {@link Result}. * @beta */ export declare type ResultValueType = T extends Result ? TV : never; /** * Compares two log levels. * @param message - The first log level. * @param reporter - The second log level. * @returns `true` if the message should be logged, `false` if it should be suppressed. * @public */ declare function shouldLog(message: MessageLogLevel, reporter: ReporterLogLevel): boolean; /** * Helper function to create a {@link Conversion.ObjectConverter | ObjectConverter} which converts an object * without changing shape, a {@link Conversion.FieldConverters | FieldConverters} and an optional * {@link Converters.StrictObjectConverterOptions | StrictObjectConverterOptions} to further refine * conversion behavior. * * @remarks * Fields that succeed but convert to undefined are omitted from the result object but do not * fail the conversion. * * The conversion fails if any unexpected fields are encountered. * * @param properties - An object containing defining the shape and converters to be applied. * @param options - An optional @see StrictObjectConverterOptions containing options for the object converter. * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} which applies the specified conversions. * {@label WITH_OPTIONS} * @public */ declare function strictObject(properties: FieldConverters, options?: StrictObjectConverterOptions): ObjectConverter; /** * Helper function to create a {@link Conversion.ObjectConverter | ObjectConverter} which converts an object * without changing shape, a {@link Conversion.FieldConverters | FieldConverters} and an optional * {@link Converters.StrictObjectConverterOptions | StrictObjectConverterOptions} to further refine * conversion behavior. * * @remarks * Fields that succeed but convert to undefined are omitted from the result object but do not * fail the conversion. * * The conversion fails if any unexpected fields are encountered. * * @param properties - An object containing defining the shape and converters to be applied. * @param optional - An array of `keyof T` containing keys to be considered optional. * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} which applies the specified conversions. * {@label WITH_KEYS} * @deprecated Use {@link Converters.(strictObject:1) | Converters.strictObject(options)} instead. * @public */ declare function strictObject(properties: FieldConverters, optional: (keyof T)[]): ObjectConverter; /** * Options for the {@link Converters.(strictObject:1)} helper function. * @public */ declare type StrictObjectConverterOptions = Omit, 'strict'>; /** * A converter to convert unknown to string. Values of type * string succeed. Anything else fails. * @public */ declare const string: StringConverter; /** * A {@link Validation.Classes.StringValidator | StringValidator} which validates a string in place. * @public */ declare const string_2: Validator; /** * {@link Converter | Converter} to convert an `unknown` to an array of `string`. * @remarks * Returns {@link Success | Success} with the the supplied value if it as an array * of strings, returns {@link Failure | Failure} with an error message otherwise. * @public */ declare const stringArray: Converter; /** * The {@link Conversion.StringConverter | StringConverter} class extends * {@link Conversion.BaseConverter | BaseConverter} to provide string-specific * helper methods. * @public */ export declare class StringConverter extends BaseConverter { /** * Construct a new {@link Conversion.StringConverter | StringConverter}. * @param defaultContext - Optional context used by the conversion. * @param traits - Optional traits to be applied to the conversion. * @param converter - Optional conversion function to be used for the conversion. */ constructor(defaultContext?: TC, traits?: ConverterTraits, converter?: (from: unknown, self: Converter, context?: TC) => Result); /** * @internal */ protected static _convert(from: unknown): Result; /** * @internal */ protected static _wrap(wrapped: StringConverter, converter: (from: T) => Result, traits?: ConverterTraits): StringConverter; /** * Returns a {@link Conversion.StringConverter | StringConverter} which constrains the result to match * a supplied string. * @param match - The string to be matched * @param options - Optional {@link Conversion.StringMatchOptions} for this conversion. * @returns {@link Success} with a matching string or {@link Failure} with an informative * error if the string does not match. * {@label WITH_STRING} */ matching(match: string, options?: Partial): StringConverter; /** * Returns a {@link Conversion.StringConverter | StringConverter} which constrains the result to match * one of a supplied array of strings. * @param match - The array of allowed strings. * @param options - Optional {@link Conversion.StringMatchOptions} for this conversion. * @returns {@link Success} with a matching string or {@link Failure} with an informative * error if the string does not match. * {@label WITH_ARRAY} */ matching(match: string[], options?: Partial): StringConverter; /** * Returns a {@link Conversion.StringConverter | StringConverter} which constrains the result to match * one of a supplied `Set` of strings. * @param match - The `Set` of allowed strings. * @param options - Optional {@link Conversion.StringMatchOptions} for this conversion. * @returns {@link Success} with a matching string or {@link Failure} with an informative * error if the string does not match. * {@label WITH_SET} */ matching(match: Set, options?: Partial): StringConverter; /** * Returns a {@link Conversion.StringConverter | StringConverter} which constrains the result to match * a supplied regular expression. * @param match - The regular expression to be used as a constraint. * @param options - Optional {@link Conversion.StringMatchOptions} for this conversion * @returns {@link Success} with a matching string or {@link Failure} with an informative * error if the string does not match. * {@label WITH_REGEXP} */ matching(match: RegExp, options?: Partial): StringConverter; } /** * Stringifies an arbitrary value for logging. * @param value - The value to stringify. * @returns The stringified value. * @param maxLength - The maximum length of the stringified value. * @public */ declare function stringifyLogValue(value: unknown, maxLength?: number): string; /** * Options for {@link Conversion.StringConverter | StringConverter} * matching method * @public */ declare interface StringMatchOptions { /** * An optional message to be displayed if a non-matching string * is encountered. */ message?: string; } /** * An in-place {@link Validation.Validator | Validator} for `string` values. * @public */ declare class StringValidator extends GenericValidator { /** * Constructs a new {@link Validation.Classes.StringValidator | StringValidator}. * @param params - Optional {@link Validation.Classes.StringValidatorConstructorParams | init params} * for the new {@link Validation.Classes.StringValidator | StringValidator}. */ constructor(params?: StringValidatorConstructorParams); /** * Static method which validates that a supplied `unknown` value is a `string`. * @param from - The `unknown` value to be tested. * @returns Returns `true` if `from` is a `string`, or {@link Failure} with an error * message if not. */ static validateString(from: unknown): boolean | Failure; } /** * Parameters used to construct a {@link Validation.Classes.StringValidator | StringValidator}. * @public */ declare type StringValidatorConstructorParams = GenericValidatorConstructorParams; /** * Returns {@link Success | Success} with the supplied result value. * @param value - The successful result value to be returned * @remarks * A `succeeds` alias was added in release 5.0 for * naming consistency with {@link fails | fails}, which was added * to avoid conflicts with test frameworks and libraries. * @public */ export declare function succeed(value: T): Success; /** * {@inheritdoc succeed} * @public */ export declare function succeeds(value: T): Success; /** * {@inheritdoc succeedWithDetail} * @public */ export declare function succeedsWithDetail(value: T, detail?: TD): DetailedSuccess; /** * Returns {@link DetailedSuccess | DetailedSuccess} with a supplied value and optional * detail. * @param value - The value of type `` to be returned. * @param detail - An optional detail of type `` to be returned. * @returns A {@link DetailedSuccess | DetailedSuccess} with the supplied value * and detail, if supplied. * @remarks * The `succeedsWithDetail` alias was added in release 5.0 for * naming consistency with {@link fails | fails}, which was added to avoid conflicts * with test frameworks and libraries. * @public */ export declare function succeedWithDetail(value: T, detail?: TD): DetailedSuccess; /** * Reports a successful {@link IResult | result} from some operation and the * corresponding value. * @public */ export declare class Success implements IResult { /** * {@inheritdoc IResult.success} */ readonly success: true; /** * For a successful operation, the error message is always `undefined`. */ readonly message: undefined; /** * @internal */ protected readonly _value: T; /** * Constructs a {@link Success} with the supplied value. * @param value - The value to be returned. */ constructor(value: T); /** * The result value returned by the successful operation. */ get value(): T; /** * {@inheritdoc IResult.isSuccess} */ isSuccess(): this is Success; /** * {@inheritdoc IResult.isFailure} */ isFailure(): this is Failure; /** * {@inheritdoc IResult.(orThrow:1)} */ orThrow(logger?: IResultLogger): T; /** * {@inheritdoc IResult.(orThrow:2)} */ orThrow(cb: ErrorFormatter): T; /** * {@inheritdoc IResult.(orDefault:1)} */ orDefault(dflt: T): T; /** * {@inheritdoc IResult.(orDefault:2)} */ orDefault(): T | undefined; /** * {@inheritdoc IResult.getValueOrThrow} * @deprecated Use {@link Success.(orThrow:1) | orThrow(logger)} or {@link Success.(orThrow:2) | orThrow(formatter)} instead. */ getValueOrThrow(__logger?: IResultLogger): T; /** * {@inheritdoc IResult.getValueOrDefault} * @deprecated Use {@link Success.(orDefault:1) | orDefault(T)} or {@link Success.(orDefault:2) | orDefault()} instead. */ getValueOrDefault(dflt?: T): T | undefined; /** * {@inheritdoc IResult.onSuccess} */ onSuccess(cb: SuccessContinuation): Result; /** * {@inheritdoc IResult.onFailure} */ onFailure(__: FailureContinuation): Result; /** * {@inheritdoc IResult.withErrorFormat} */ withErrorFormat(__cb: ErrorFormatter): Result; /** * {@inheritdoc IResult.withFailureDetail} */ withFailureDetail(__detail: TD): DetailedResult; /** * {@inheritdoc IResult.withDetail} */ withDetail(detail: TD, successDetail?: TD): DetailedResult; /** * {@inheritdoc IResult.aggregateError} */ aggregateError(__errors: IMessageAggregator, __formatter?: ErrorFormatter): this; /** * {@inheritdoc IResult.report} */ report(reporter?: IResultReporter, options?: IResultReportOptions): Success; /** * Creates a {@link Success | Success} with the supplied value. * @param value - The value to be returned. * @returns The resulting {@link Success | Success} with the supplied value. * @public */ static with(value: T): Success; } /** * Continuation callback to be called in the event that an * {@link Result} is successful. * @public */ export declare type SuccessContinuation = (value: T) => Result; /** * Helper to create a {@link Converter | Converter} which converts a source object to a new object with a * different shape. * * @remarks * On successful conversion, the resulting {@link Converter | Converter} returns {@link Success | Success} with a new * object, which contains the converted values under the key names specified at initialization time. * It returns {@link Failure | Failure} with an error message if any fields to be extracted do not exist * or cannot be converted. * * Fields that succeed but convert to undefined are omitted from the result object but do not * fail the conversion. * * @param properties - An object with key names that correspond to the target object and an * appropriate {@link Conversion.FieldConverters | FieldConverter} which extracts and converts * a single filed from the source object. * @returns A {@link Converter | Converter} with the specified conversion behavior. * @public */ declare function transform(properties: FieldConverters): Converter; /** * Helper to create a strongly-typed {@link Converter | Converter} which converts a source object to a * new object with a different shape. * * @remarks * On successful conversion, the resulting {@link Converter | Converter} returns {@link Success | Success} with a new * object, which contains the converted values under the key names specified at initialization time. * * It returns {@link Failure | Failure} with an error message if any fields to be extracted do not exist * or cannot be converted. * * @param destinationFields - An object with key names that correspond to the target object and an * appropriate {@link Converters.FieldTransformers | FieldTransformers} which specifies the name * of the corresponding property in the source object, the converter or validator used for each source * property and any other configuration to guide the conversion. * @param options - Options which affect the transformation. * * @returns A {@link Converter | Converter} with the specified conversion behavior. * @public */ declare function transformObject(destinationFields: FieldTransformers, options?: TransformObjectOptions): Converter; /** * Options for a {@link Converters.transformObject} call. * @public */ declare interface TransformObjectOptions { /** * If `strict` is `true` then unused properties in the source object cause * an error, otherwise they are ignored. */ strict: true; /** * An optional list of source properties to be ignored when strict mode * is enabled. */ ignore?: (keyof TSRC)[]; /** * An optional description of this transform to be used for error messages. */ description?: string; } /** * An in-place {@link Validation.Validator | Validator} that can be instantiated using a type guard * function. * @public */ declare class TypeGuardValidator extends ValidatorBase { /** * {@link Validation.ValidatorOptions | Options} which apply to this * validator. */ readonly options: ValidatorOptions; readonly description: string; protected readonly _guard: TypeGuardWithContext; /** * Constructs a new {@link Validation.Classes.TypeGuardValidator | TypeGuardValidator}. * @param params - Optional {@link Validation.Classes.TypeGuardValidatorConstructorParams | init params} for the * new {@link Validation.Classes.TypeGuardValidator | TypeGuardValidator}. */ constructor(params: TypeGuardValidatorConstructorParams); /** * Static method which validates that a supplied `unknown` value matches the supplied * type guard, returning a `Failure` containing more information about a failure. * @param from - Value to be converted. * @param context - Optional validation context. * @param self - Optional self-reference for recursive validation. * @returns `true` if `from` is valid, {@link Failure | Failure} * with an error message if `from` is invalid. * @internal */ protected _validate(from: unknown, context?: TC, self?: Validator): boolean | Failure; } /** * Parameters used to construct a {@link Validation.Classes.TypeGuardValidator}. * @public */ declare interface TypeGuardValidatorConstructorParams extends ValidatorBaseConstructorParams { guard: TypeGuardWithContext; description: string; } /** * A type guard function which validates a specific type, with an optional context * that can be used to shape the validation. * @public */ declare type TypeGuardWithContext = (from: unknown, context?: TC) => from is T; /** * Uses a value or calls a supplied initializer if the supplied value is undefined. * @param value - the value * @param initializer - a function that initializes the value if it is undefined * @returns `Success` with the value if it is defined, or the result of calling the initializer function. * @public */ export declare function useOrInitialize(value: T | undefined, initializer: () => Result): Result; declare namespace Utils { export { isIterable } } /** * Helper function to create a {@link Converter | Converter} from any {@link Validation.Validator} * @param validator - the validator to be wrapped * @returns A {@link Converter | Converter} which uses the supplied validator. * @public */ declare function validated(validator: Validator): Converter; /** * Helper function to create a {@link Converter | Converter} which validates that a supplied value is * of a type validated by a supplied validator function and returns it. * @remarks * If `validator` succeeds, this {@link Converter | Converter} returns {@link Success | Success} with the supplied * value of `from` coerced to type ``. Returns a {@link Failure | Failure} with additional * information otherwise. * @param validator - A validator function to determine if the converted value is valid. * @param description - A description of the validated type for use in error messages. * @returns A new {@link Converter | Converter} which applies the supplied validation. * @public */ declare function validateWith(validator: (from: unknown) => from is T, description?: string): Converter; /** * A {@link Collections.Collector | Collector} with a {@link Collections.CollectorValidator | CollectorValidator} * property that enables validated use of the underlying map with weakly-typed keys and values. * @public */ export declare class ValidatingCollector> extends Collector { /** * A {@link Collections.CollectorValidator | CollectorValidator} which validates keys and values * before inserting them into this collector. */ readonly validating: CollectorValidator; protected readonly _converters: KeyValueConverters, TITEM>; /** * Constructs a new {@link Collections.ValidatingCollector | ValidatingConvertingCollector} * from the supplied {@link Collections.IValidatingCollectorConstructorParams | parameters}. * @param params - Required parameters for constructing the collector. */ constructor(params: IValidatingCollectorConstructorParams); /** * Creates a new {@link Collections.ValidatingCollector | ValidatingCollector} instance from * the supplied {@link Collections.IValidatingCollectorConstructorParams | parameters}. * @param params - Required parameters for constructing the collector. * @returns {@link Success} with the new collector if successful, {@link Failure} otherwise. */ static createValidatingCollector>(params: IValidatingCollectorConstructorParams): Result>; /** * Gets a read-only version of this collector as a * {@link Collections.IReadOnlyValidatingResultMap | read-only map}. * @returns */ toReadOnly(): IReadOnlyValidatingCollector; } /** * A {@link Collections.ConvertingCollector | ConvertingCollector} with a * {@link Collections.ConvertingCollectorValidator | ConvertingCollectorValidator} * property that enables validated use of the underlying map with weakly-typed keys and values. * @public */ export declare class ValidatingConvertingCollector, TSRC = TITEM> extends ConvertingCollector { /** * A {@link Collections.ConvertingCollectorValidator | ConvertingCollectorValidator} which validates keys and values * before inserting them into this collector. */ readonly validating: ConvertingCollectorValidator; protected readonly _converters: KeyValueConverters, TSRC>; /** * Constructs a new {@link Collections.ValidatingConvertingCollector | ValidatingConvertingCollector} * from the supplied {@link Collections.IValidatingConvertingCollectorConstructorParams | parameters}. * @param params - Required parameters for constructing the collector. */ constructor(params: IValidatingConvertingCollectorConstructorParams); /** * Creates a new {@link Collections.ValidatingConvertingCollector | ValidatingConvertingCollector} instance from * the supplied {@link Collections.IValidatingConvertingCollectorConstructorParams | parameters}. * @param params - Required parameters for constructing the collector. * @returns {@link Success} with the new collector if successful, {@link Failure} otherwise. */ static createValidatingCollector, TSRC = TITEM>(params: IValidatingConvertingCollectorConstructorParams): Result>; /** * Gets a read-only version of this collector as a * {@link Collections.IReadOnlyValidatingResultMap | read-only map}. * @returns */ toReadOnly(): IReadOnlyValidatingCollector; } /** * A {@link Collections.ResultMap | ResultMap} with a {@link Collections.ResultMapValidator | validator} * property that enables validated use of the underlying map with weakly-typed keys and values. * @public */ export declare class ValidatingResultMap extends ResultMap implements IReadOnlyValidatingResultMap { /** * A {@link Collections.ResultMapValidator | ResultMapValidator} which validates keys and values * before inserting them into this collection. */ readonly validating: ResultMapValidator; /** * Constructs a new {@link Collections.ValidatingResultMap | ValidatingResultMap}. * @param params - Required parameters for constructing the map. */ constructor(params: IValidatingResultMapConstructorParams); /** * Creates a new {@link Collections.ValidatingResultMap | ValidatingResultMap} instance. * @param params - Required parameters for constructing the map. * @returns `Success` with the new map if successful, `Failure` otherwise. * @public */ static createValidatingResultMap(params: IValidatingResultMapConstructorParams): Result>; /** * Gets a read-only version of this map. */ toReadOnly(): IReadOnlyValidatingResultMap; } declare namespace Validation { export { Base, Classes, Validators, TypeGuardWithContext, FunctionConstraintTrait, ConstraintTrait, ValidatorTraitValues, defaultValidatorTraits, ValidatorTraits, ValidatorFunc, ValidatorOptions, Constraint, ValidationErrorFormatter, Validator } } export { Validation } /** * Formats an incoming error message and value that failed validation. * @param val - The value that failed validation. * @param message - The default error message, if any. * @param context - Optional validation context. * @returns The formatted error message. * @public */ declare type ValidationErrorFormatter = (val: unknown, message?: string, context?: TC) => string; /** * In-place validation that a supplied unknown matches some * required characteristics (type, values, etc). * @public */ export declare interface Validator { /** * {@link Validation.ValidatorTraits | Traits} describing this validation. */ readonly traits: ValidatorTraits; /** * Indicates whether this element is explicitly optional. */ readonly isOptional: boolean; /** * The brand for a branded type. */ readonly brand: string | undefined; /** * Tests to see if a supplied `unknown` value matches this validation. All * validate calls are guaranteed to return the entity passed in on Success. * @param from - The `unknown` value to be tested. * @param context - Optional validation context. * @returns {@link Success} with the typed, validated value, * or {@link Failure} with an error message if validation fails. */ validate(from: unknown, context?: TC): Result; /** * Tests to see if a supplied 'unknown' value matches this validation. In * contrast to {@link Validator.validate | validate}, makes no guarantees * about the identity of the returned value. * @param from - The `unknown` value to be tested. * @param context - Optional validation context. * @returns {@link Success} with the typed, conversion value, * or {@link Failure} with an error message if conversion fails. */ convert(from: unknown, context?: TC): Result; /** * Tests to see if a supplied `unknown` value matches this * validation. Accepts `undefined`. * @param from - The `unknown` value to be tested. * @param context - Optional validation context. * @returns {@link Success} with the typed, validated value, * or {@link Failure} with an error message if validation fails. */ validateOptional(from: unknown, context?: TC): Result; /** * Non-throwing type guard * @param from - The value to be tested. * @param context - Optional validation context. */ guard(from: unknown, context?: TC): from is T; /** * Creates an {@link Validation.Validator | in-place validator} * which is derived from this one but which also matches `undefined`. */ optional(): Validator; /** * Creates an {@link Validation.Validator | in-place validator} * which is derived from this one but which applies additional constraints. * @param constraint - the constraint to be applied * @param trait - As optional {@link Validation.ConstraintTrait | ConstraintTrait} * to be applied to the resulting {@link Validation.Validator | Validator}. * @returns A new {@link Validation.Validator | Validator}. */ withConstraint(constraint: Constraint, trait?: ConstraintTrait): Validator; /** * Creates a new {@link Validation.Validator | in-place validator} which * is derived from this one but which matches a branded result. * @param brand - The brand to be applied. */ withBrand(brand: B): Validator, TC>; /** * Creates a new {@link Validation.Validator | in-place validator} which * is derived from this one but which returns an error message supplied * by the provided formatter if an error occurs. * @param formatter - The error message formatter to be applied. * @returns A new {@link Validation.Validator | Validator}. */ withFormattedError(formatter: ValidationErrorFormatter): Validator; } /** * Abstract base helper class for specific validator implementations * @internal */ declare abstract class ValidatorBase extends GenericValidator { /** * Inner constructor * @param params - Initialization params. * @internal */ protected constructor(params: Partial>); /** * Abstract validation method to me implemented by derived classes. * @param from - Value to be converted. * @param context - Optional validation context. * @param self - Optional self-reference for recursive validation. * @returns `true` if `from` is valid, {@link Failure | Failure} * with an error message if `from` is invalid. * @internal */ protected abstract _validate(from: unknown, context?: TC, self?: Validator): boolean | Failure; } /** * @internal */ declare type ValidatorBaseConstructorParams = Omit, 'validator'>; /** * Type for a validation function, which validates that a supplied `unknown` * value is a valid value of type ``, possibly as influenced by * an optionally-supplied validation context of type ``. * @public */ declare type ValidatorFunc = (from: unknown, context?: TC, self?: Validator) => boolean | Failure; /** * Options that apply to any {@link Validation.Validator | Validator}. * @public */ declare interface ValidatorOptions { defaultContext?: TC; } declare namespace Validators { export { object_2 as object, arrayOf_2 as arrayOf, recordOf_2 as recordOf, enumeratedValue_2 as enumeratedValue, literal_2 as literal, oneOf_2 as oneOf, isA_2 as isA, generic_2 as generic, string_2 as string, number_2 as number, boolean_2 as boolean, IRecordOfValidatorOptions } } export { Validators } /** * Generic implementation of {@link Validation.ValidatorTraitValues | ValidatorTraitValues}. * @public */ declare class ValidatorTraits implements ValidatorTraitValues { /** * {@inheritdoc Validation.ValidatorTraitValues.isOptional} */ readonly isOptional: boolean; /** * {@inheritdoc Validation.ValidatorTraitValues.brand} */ readonly brand?: string; /** * {@inheritdoc Validation.ValidatorTraitValues.constraints} */ readonly constraints: ConstraintTrait[]; /** * Constructs a new {@link Validation.ValidatorTraits | ValidatorTraits} optionally * initialized with the supplied base and initial values. * @remarks * Initial values take priority over base values, which fall back to the global default values. * @param init - Partial initial values to be set in the resulting {@link Validation.Validator | Validator}. * @param base - Base values to be used when no initial values are present. */ constructor(init?: Partial, base?: ValidatorTraitValues); } /** * Interface describing the supported validator traits. * @public */ declare interface ValidatorTraitValues { /** * Indicates whether the validator accepts `undefined` as * a valid value. */ readonly isOptional: boolean; /** * If present, indicates that the result will be branded * with the corresponding brand. */ readonly brand?: string; /** * Zero or more additional {@link Validation.ConstraintTrait | ConstraintTrait}s * describing additional constraints applied by this {@link Validation.Validator | Validator}. */ readonly constraints: ConstraintTrait[]; } /** * Deprecated alias for @see literal * @param value - The value to be compared. * @deprecated Use {@link Converters.literal} instead. * @internal */ declare const value: typeof literal; export { }