/** * @regle/core v1.23.0 * (c) 2026 Victor Garcia * @license MIT */ import { ComputedRef, MaybeRef, MaybeRefOrGetter, Plugin, Raw, Ref, UnwrapNestedRefs, UnwrapRef } from "vue"; import { EmptyObject, Get, IsAny, IsEmptyObject, IsLiteral, IsNever, IsNullable, IsOptional, IsStringLiteral, IsUnion, IsUnknown, Merge, Or, Paths, RequireAtLeastOne, RequireOneOrNone, RequiredDeep, UnionToIntersection, UnionToTuple } from "type-fest"; import { StandardSchemaV1 } from "@standard-schema/spec"; interface GlobalConfigOverrides { /** * Override the default $edited handler. */ isEdited?: isEditedHandlerFn; } type isEditedHandlerFn = (currentValue: MaybeInput, initialValue: MaybeInput, defaultHandlerFn: (currentValue: unknown, initialValue: unknown) => boolean) => boolean; interface RegleBehaviourOptions { /** * Does not run rules until the field is dirty. * @default false */ lazy?: boolean | undefined; /** * Automatically set the dirty state to true when value is changed without the need of calling `$touch`. * @default true * */ autoDirty?: boolean | undefined; /** * Only update error status when calling `$validate` or `$validateSync`. * Will not display errors as you type * @default false * * @default true if rewardEarly is true * */ silent?: boolean | undefined; /** * The fields will turn valid when they are, but not invalid unless calling `r$.$validate()` or `$validateSync` * @default false */ rewardEarly?: boolean | undefined; /** * Define whether the external errors should be cleared when updating a field * * Default to `false` if `$silent` is set to `true` * * @default true */ clearExternalErrorsOnChange?: boolean | undefined; /** * Define whether the external errors should be cleared when calling `$validate` or `$validateSync` * * @default true */ clearExternalErrorsOnValidate?: boolean | undefined; /** * Set the dirty state to true when the form is initialized. * @default false */ immediateDirty?: boolean | undefined; /** * Disable all the computation * @default false */ disabled?: boolean | undefined; } interface LocalRegleBehaviourOptions, TRules extends ReglePartialRuleTree, TValidationGroups extends Record = {}> { /** * A dictionary of external errors to be injected into the field statuses. * * Useful for integrating errors from a backend or other validation sources. * External errors can be assigned using a reactive object or a Ref, and will be merged into the `$externalErrors` and `$errors` properties for each field. * You can also call `r$.$setExternalErrors(...)` directly without providing this option. * Pass this option when the same external errors ref needs to be owned and synchronized outside of Regle. * * More details: https://reglejs.dev/advanced-usage/external-errors */ externalErrors?: Ref> | Record>; /** * Allows you to group fields for custom collective validation logic. * * The `validationGroups` option lets you define logical groupings of fields within your form that should be validated or checked together. * This can be used, for example, to easily determine if a subset of your form (e.g. an "address" group or a set of "contact information" fields) are all valid or share a collective error state. * * The function receives the `$fields` object and must return an object where each key is a group name and the value is an array of RegleStatus or RegleFieldStatus instances representing the grouped fields. * These groups can then be referenced using `$validationGroups.` to access their combined validation state (e.g. `$invalid`, `$error`, `$errors`, etc). * * More details: https://reglejs.dev/core-concepts/modifiers#validationgroups */ validationGroups?: (fields: RegleStatus['$fields']) => TValidationGroups; /** * A unique identifier for the Regle instance in the devtools. * @default undefined */ id?: string | undefined; } type FieldOnlyRegleBehaviourOptions = { /** * Set external errors for the field. */ externalErrors?: Ref; /** * A unique identifier for the Regle instance in the devtools. * @default undefined */ id?: string | undefined; }; type RegleValidationGroupEntry = RegleFieldStatus | undefined; interface RegleValidationGroupOutput { /** Indicates whether any field in the validation group is invalid. */ $invalid: boolean; /** Convenience flag to easily decide if an error message should be displayed. True when any field in the group is dirty, not pending, and invalid. */ $error: boolean; /** Indicates if any async rule in the validation group is currently running. */ $pending: boolean; /** Indicates whether any field in the validation group has been interacted with by the user. */ $dirty: boolean; /** Indicates whether all fields in the validation group pass validation and are dirty. */ $correct: boolean; /** Collection of all error messages from fields in the group where $dirty equals true. */ $errors: string[]; /** Collection of all error messages from fields in the group, regardless of $dirty state. */ $silentErrors: string[]; } type FieldRegleBehaviourOptions = AddDollarToOptions & { /** * Let you declare the number of milliseconds the rule needs to wait before executing. Useful for async or heavy computations. */ $debounce?: number; /** * Override the default `$edited` handler. */ $isEdited?: isEditedHandlerFn; }; type CollectionRegleBehaviourOptions = FieldRegleBehaviourOptions & { /** * Allow deep compare of array children to compute the `$edited` property * * Disabled by default for performance * * @default false * */ $deepCompare?: boolean; }; type ResolvedRegleBehaviourOptions = DeepMaybeRef> & LocalRegleBehaviourOptions, Record, Record>; type ShortcutCommonFn> = { [x: string]: (element: Omit, '~standard'>) => unknown; }; type ShortcutFieldStatus> = RegleFieldStatus & Partial>; type ShortcutNestedStatus> = RegleStatus, ReglePartialRuleTree>>; type ShortcutCollectionStatus> = RegleCollectionStatus & Partial>; type RegleShortcutDefinition = {}> = { /** * Allow you to customize the properties for every field */ fields?: ShortcutCommonFn>; /** * Allow you to customize the properties for every parent of a nested object */ nested?: ShortcutCommonFn>; /** * Allow you to customize the properties for every parent of a collection */ collections?: ShortcutCommonFn>; }; type AddDollarToOptions> = { [K in keyof T as `$${string & K}`]: T[K] }; /** * The main Regle type that represents a complete validation instance. * * @template TState - The shape of the state object being validated * @template TRules - The validation rules tree for the state * @template TValidationGroups - Groups of validation rules that can be run together * @template TShortcuts - Custom shortcut definitions for common validation patterns * @template TAdditionalReturnProperties - Additional properties to extend the return type * */ type Regle = EmptyObject, TRules extends ReglePartialRuleTree = EmptyObject, TValidationGroups extends Record = {}, TShortcuts extends RegleShortcutDefinition = {}, TAdditionalReturnProperties extends Record = {}> = { /** * r$ is a reactive object containing the values, errors, dirty state and all the necessary validations properties you'll need to display information. * * To see the list of properties: {@link https://reglejs.dev/core-concepts/validation-properties} */ r$: Raw>; } & TAdditionalReturnProperties; /** * The type for a single field validation instance. * * @template TState - The type of the state value being validated * @template TRules - The validation rules for the field * @template TShortcuts - Custom shortcut definitions for common validation patterns * @template TAdditionalReturnProperties - Additional properties to extend the return type */ type RegleSingleField = any, TRules extends RegleRuleDecl, CustomRulesDeclarationTree> = EmptyObject, TShortcuts extends RegleShortcutDefinition = {}, TAdditionalReturnProperties extends Record = {}> = { /** * r$ is a reactive object containing the values, errors, dirty state and all the necessary validations properties you'll need to display information. * * To see the list of properties: {@link https://reglejs.dev/core-concepts/validation-properties} */ r$: Raw>; } & TAdditionalReturnProperties; type DeepReactiveState | unknown | undefined> = IsAny extends true ? any : IsUnknown extends true ? never : ExtendOnlyRealRecord extends true ? { [K in keyof T]: InferDeepReactiveState } : never; type InferDeepReactiveState = IsAny extends true ? any : IsUnknown extends true ? MaybeRef : NonNullable extends Array> ? DeepReactiveState : NonNullable extends Date | File ? MaybeRef : NonNullable extends Record ? DeepReactiveState : MaybeRef; type ResetOptions = RequireOneOrNone<{ /** * Reset validation status and reset form state to its initial state. * * Initial state is different than the original state as the initial state can be mutated when using `$reset`. * * This serve as the base comparison state for `$edited` property. * * ⚠️ This doesn't work if the state is a `reactive` object. */ toInitialState?: boolean; /** * Reset validation status and reset form state to its original state. * * Original state is the unmutated state that was passed to the form when it was initialized. */ toOriginalState?: boolean; /** * Reset validation status and reset form state to the given state * Also set the new state as the initial state. */ toState?: TState | (() => TState); /** * Clears the $externalErrors state back to an empty object. * * @default true */ clearExternalErrors?: boolean; /** * Keep the validation state of the form ($dirty, $invalid, $pending etc..) * Only useful if you only want to reset the form state. * * @default false */ keepValidationState?: boolean; }, 'toInitialState' | 'toState'>; type ScopedInstancesRecord = Record> & { '~~global': Record; }; type ScopedInstancesRecordLike = Partial; type PartialFormState> = [unknown] extends [TState] ? {} : Prettify<{ [K in keyof TState as ExtendOnlyRealRecord extends true ? never : TState[K] extends Array ? never : K]?: MaybeOutput } & { [K in keyof TState as ExtendOnlyRealRecord extends true ? K : TState[K] extends Array ? K : never]: NonNullable extends Array> ? PartialFormState[] : PartialFormState }>; type RegleResult | any[] | unknown, TRules extends ReglePartialRuleTree | RegleFormPropertyType> = { /** The result of the validation */valid: false; /** Output data, filter the result by checking the `valid` property */ data: IsUnknown extends true ? unknown : IsAny extends true ? unknown : IsEmptyObject extends true ? isRecordLiteral extends true ? PartialFormState ? Data : {}> : MaybeOutput : HasNamedKeys extends true ? HasNamedKeys extends true ? NonNullable extends Date | File ? MaybeOutput> : NonNullable extends Array> ? PartialFormState[] : NonNullable extends Record ? PartialFormState> : MaybeOutput : isRecordLiteral extends true ? PartialFormState ? Data : {}> : MaybeOutput : unknown; /** * Collection of all the error messages, collected for all children properties and nested forms. * * Only contains errors from properties where $dirty equals true. * */ issues: DataTypeRegleIssues; /** * Collection of all the issues, collected for all children properties and nested forms. * * Only contains issues from properties where $dirty equals true. */ errors: DataTypeRegleErrors; } | { valid: true; data: IsUnknown extends true ? unknown : IsAny extends true ? unknown : IsEmptyObject extends true ? isRecordLiteral extends true ? PartialFormState ? Data : {}> : MaybeOutput : HasNamedKeys extends true ? HasNamedKeys extends true ? NonNullable extends Array> ? DeepSafeFormState ? TRules : {}>[] : NonNullable extends Date | File ? SafeFieldProperty>, TRules extends ReglePartialRuleTree ? TRules : {}> : NonNullable extends Record ? DeepSafeFormState, TRules extends ReglePartialRuleTree ? TRules : {}> : SafeFieldProperty ? TRules : {}> : isRecordLiteral extends true ? PartialFormState ? Data : {}> : MaybeOutput : unknown; issues: EmptyObject; errors: EmptyObject; }; type DataTypeRegleIssues | any[] | unknown, TRules extends ReglePartialRuleTree | RegleFormPropertyType = never> = HasNamedKeys extends true ? NonNullable extends Array ? isRecordLiteral extends true ? RegleFieldIssue[] : RegleCollectionErrors : isRecordLiteral extends true ? RegleIssuesTree : RegleFieldIssue[] : RegleFieldIssue | RegleCollectionErrors | RegleIssuesTree; type DataTypeRegleErrors | any[] | unknown> = HasNamedKeys extends true ? NonNullable extends Array ? isRecordLiteral extends true ? string[] : RegleCollectionErrors : isRecordLiteral extends true ? RegleErrorTree : string[] : string[] | RegleErrorTree | RegleCollectionErrors; type RegleCollectionResult | RegleFormPropertyType> = RegleResult & ({ valid: false; issues: RegleCollectionErrors; errors: RegleCollectionErrors; } | { valid: true; issues: EmptyObject; errors: EmptyObject; }); type RegleFieldResult | RegleFormPropertyType> = RegleResult & ({ valid: false; issues: RegleFieldIssue[]; errors: string[]; } | { valid: true; issues: []; errors: []; }); type $InternalRegleResult = { valid: boolean; data: any; errors: $InternalRegleErrorTree | $InternalRegleCollectionErrors | string[]; issues: $InternalRegleIssuesTree | $InternalRegleCollectionIssues | RegleFieldIssue[]; }; type DeepSafeFormState, TRules extends ReglePartialRuleTree, CustomRulesDeclarationTree> | undefined> = IsUnknown extends true ? {} : IsAny extends true ? unknown : TRules extends undefined ? TState : HasNamedKeys extends true ? TRules extends ReglePartialRuleTree ? Prettify<{ [K in keyof TState as IsPropertyOutputRequired extends false ? K : never]?: SafeProperty extends MaybeInput ? MaybeOutput : SafeProperty } & { [K in keyof TState as IsPropertyOutputRequired extends false ? never : K]-?: IsUnknown> extends true ? unknown : IsAny extends true ? unknown : NonNullable> }> : TState : TState; type FieldHaveRequiredRule | undefined = never> = TRule extends MaybeRefOrComputedRef> ? UnwrapRef extends infer TRuleResolved extends Record ? { [K in keyof TRuleResolved]-?: TRuleResolved[K] extends RegleRuleDefinition ? true : false }[keyof TRuleResolved] extends false ? false : true : false : false; type ObjectHaveAtLeastOneRequiredField, TRules extends ReglePartialRuleTree> = TState extends Maybe ? ({ [K in keyof NonNullable]-?: IsPropertyOutputRequired[K], TRules[K] extends RegleFormPropertyType ? TRules[K] : {}> } & { $self: IsPropertyOutputRequired; })[keyof TState | '$self'] extends false ? false : true : true; type ArrayHaveAtLeastOneRequiredField, TRule extends RegleCollectionRuleDecl> = TState extends Maybe ? FieldHaveRequiredRule extends MaybeRef ? Omit, '$each'> : {}> | ObjectHaveAtLeastOneRequiredField>, ExtractFromGetter extends undefined ? {} : NonNullable>> extends false ? false : true : true; type SafeProperty | undefined> = unknown extends TState ? unknown : [TRule] extends [RegleCollectionRuleDecl] ? TState extends Array> ? DeepSafeFormState>[] : TState : [TRule] extends [ReglePartialRuleTree] ? ExtendOnlyRealRecord extends true ? DeepSafeFormState extends Record ? JoinDiscriminatedUnions> : {}, TRule> : [TRule] extends [MaybeRef>] ? FieldHaveRequiredRule> extends true ? TState : MaybeOutput : TState : TState; type IsPropertyOutputRequired | undefined> = [unknown] extends [TState] ? unknown : NonNullable extends Array ? TRule extends RegleCollectionRuleDecl ? ArrayHaveAtLeastOneRequiredField, TRule> extends false ? false : true : false : TRule extends ReglePartialRuleTree ? ExtendOnlyRealRecord extends true ? ObjectHaveAtLeastOneRequiredField extends Record ? NonNullable : {}, TRule extends ReglePartialRuleTree extends Record ? NonNullable : {}, any> ? TRule : {}> extends false ? false : true : TRule extends MaybeRef> ? FieldHaveRequiredRule> extends false ? false : true : false : false; type SafeFieldProperty | undefined = never> = FieldHaveRequiredRule extends true ? NonNullable : MaybeOutput; /** Types to be augmented by @regle/schemas */ interface NarrowVariantExtracts {} interface NarrowVariantFieldExtracts {} type NarrowVariant | RegleStatus | NarrowVariantExtracts[keyof NarrowVariantExtracts]>> extends { $value: infer V; } ? V : unknown)> = Extract | RegleFieldStatus, any, any> | (IsEmptyObject> extends true ? EmptyObject : NarrowVariantFieldExtracts[keyof NarrowVariantFieldExtracts]) }> & { $fields: Extract | RegleFieldStatus, any, any> | (IsEmptyObject> extends true ? EmptyObject : NarrowVariantFieldExtracts[keyof NarrowVariantFieldExtracts]) }> & { [K in TKey]: TRoot[K] & { $value: TValue; } }; } & { $value: Omit & { [K in TKey]: TValue }; } & { [K in TKey]: TRoot[K] & { $value: TValue; } }; type MaybeVariantStatus | undefined = Record, TRules extends ReglePartialRuleTree> = Record, TShortcuts extends RegleShortcutDefinition = {}, TIsUnionOverride extends boolean = false, /** * Workaround for $each variants, TS generic can't detect if the Rules are an union when type is too nested, to the tuple is passed from parent */ TRulesTuple extends any[] = never> = IsUnion> extends true ? Or> extends true ? (IsNever extends true ? TRules : TRulesTuple[number]) extends infer RulesUnionTuple extends ReglePartialRuleTree> ? ProcessChildrenFields, RulesUnionTuple, TShortcuts> extends infer TChildren ? Omit, RulesUnionTuple, TShortcuts>, '$fields'> & { $fields: TChildren[keyof TChildren]; } & (HasNamedKeys> extends true ? TChildren[keyof TChildren] : {}) : never : RegleStatus>, TRules extends ReglePartialRuleTree>>> ? TRules : EmptyObject, TShortcuts> : RegleStatus>, TRules extends ReglePartialRuleTree>>> ? TRules : EmptyObject, TShortcuts> : RegleStatus; /** Helper type to extract state tuple item at index */ type StateTupleItem = TStateTuple[TIndexInt] extends Record ? TStateTuple[TIndexInt] : never; /** Helper type to extract NonNullable state tuple item */ type NonNullableStateTupleItem = NonNullable>; /** Helper type to find the corresponding variant rule */ type VariantRuleForKey = FindCorrespondingVariant, TRulesTuple> extends [infer U] ? TKey extends keyof U ? U[TKey] : EmptyObject : EmptyObject; type ProcessChildrenFields | undefined, TRules extends ReglePartialRuleTree>, TShortcuts extends RegleShortcutDefinition = {}> = UnionToTuple extends infer TStateTuple extends readonly any[] ? UnionToTuple extends infer TRulesTuple extends readonly any[] ? { [TIndex in keyof TupleToPlainObj]: TIndex extends `${infer TIndexInt extends number}` ? { [TKey in keyof TStateTuple[TIndexInt] as IsEmptyObject> extends true ? TKey extends keyof TState ? TState[TKey] extends NonNullable ? TKey : never : never : TKey]-?: InferRegleStatusType, NonNullableStateTupleItem, TKey, TShortcuts> } & { [TKey in keyof TStateTuple[TIndexInt] as IsEmptyObject> extends true ? TKey extends keyof TState ? TState[TKey] extends NonNullable ? never : TKey : TKey : never]?: InferRegleStatusType, NonNullableStateTupleItem, TKey, TShortcuts> } : {} } : {} : {}; type FindCorrespondingVariant, TRules extends readonly any[]> = TRules extends [infer F, ...infer R] ? F extends ReglePartialRuleTree ? [F] : FindCorrespondingVariant : []; type PossibleLiteralTypes, TKey extends keyof T> = unknown extends T[TKey] ? { [x: string]: { [K in TKey]-?: Omit>, 'literal'> & { literal?: RegleRuleDefinition<'literal', any, [literal: any], false, boolean, any, string | number, true>; } }; } : { [TVal in NonNullable]: { [K in TKey]-?: Omit>, 'literal'> & { literal?: RegleRuleDefinition<'literal', MaybeInput, [literal: TVal], false, boolean, MaybeInput, string | number, true>; } } }; type RequiredForm, TKey extends keyof T> = Omit, TKey> & PossibleLiteralTypes[keyof PossibleLiteralTypes]; type VariantTuple, TKey extends keyof T> = [RequiredForm, ...RequiredForm[]]; declare const RegleStaticSymbol: unique symbol; type RegleStatic = T extends (new (...args: infer Args) => infer U) ? RegleStaticImpl RegleStaticImpl> : RegleStaticImpl; type RegleStaticImpl = Raw; type IsRegleStatic = T extends RegleStaticImpl ? true : false; type UnwrapStatic = IsAny extends true ? any : IsUnknown extends true ? any : NonNullable extends RegleStaticImpl ? Raw : UnwrapStaticSimple; type UnwrapStaticSimple = IsAny extends true ? any : NonNullable extends Array ? Array> : isRecordLiteral> extends true ? { [K in keyof T]: UnwrapStatic } : T; /** * Combine all members of a union type, merging types for each key, and keeping loose types */ type JoinDiscriminatedUnions = IsAny extends true ? any : IsUnknown extends true ? any : HasNamedKeys extends true ? isRecordLiteral extends true ? NonNullable extends infer TNonNull ? NormalizeUnion extends infer TNormalized extends Record ? HasCommonKey, keyof TNormalized> extends true ? ResolveKeys extends infer TResolved extends Record ? DumbJoinDiscriminatedUnions extends infer TDumbJoin ? Omit extends infer TLoose ? Prettify : never : never : never : DumbJoinDiscriminatedUnions : never : never : TUnion : TUnion; type ResolveKeys = NonNullable extends infer TNonNull ? NormalizeUnion extends infer TNormalized extends Record ? Partial, keyof TNormalized>[number]>> & Pick : never : never; /** * Combine all members of a union type on one level and not nested. */ type LazyJoinDiscriminatedUnions = IsAny extends true ? any : IsUnknown extends true ? any : isRecordLiteral extends true ? NonNullable extends infer TNonNull extends Record ? Prettify, keyof TNonNull>[number]>> & Pick> : never : TUnion; type DumbJoinDiscriminatedUnions = IsAny extends true ? any : IsUnknown extends true ? any : isRecordLiteral extends true ? NonNullable extends infer TNonNull extends Record ? Prettify> & Pick> : never : TUnion; type RemoveCommonKey = T extends [infer F, ...infer R] ? [Prettify>, ...RemoveCommonKey] : []; type HasCommonKey = T extends [infer F, ...infer R] ? K extends keyof F ? true : HasCommonKey : false; /** * Transforms a union and apply undefined values to non-present keys to support intersection */ type NormalizeUnion = RetrieveUnionUnknownValues>, RetrieveUnionUnknownKeysOf>>[number]>[number]; /** * Combine all union values to be able to get even the normally "never" values, act as an intersection type */ type RetrieveUnionUnknownValues = T extends [infer F extends Record, ...infer R] ? [{ [K in TKeys as GetMaybeObjectValue extends NonUndefined> ? never : K]?: GetMaybeObjectValue } & { [K in TKeys as GetMaybeObjectValue extends NonUndefined> ? K : never]: GetMaybeObjectValue }, ...RetrieveUnionUnknownValues] : []; /** * Get all possible keys from a union, even the ones present only on one union */ type RetrieveUnionUnknownKeysOf = T extends [infer F, ...infer R] ? [keyof F, ...RetrieveUnionUnknownKeysOf] : []; /** * Get item value from object, otherwise fallback to undefined. Avoid TS to not be able to infer keys not present on all unions */ type GetMaybeObjectValue, K extends string> = K extends keyof O ? O[K] : undefined; type RemoveIndexSignature = { [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: T[K] }; /** * Merge every boolean property into a single boolean. */ type MergePropsIntoRequiredBooleans> = { [K in keyof TObject]-?: TObject[K] extends NonNullable ? true : false }[keyof TObject]; /** * Ensure that if at least one prop is required, the "prop" object will be required too */ type HaveAnyRequiredProps> = [TObject] extends [never] ? false : TObject extends Record ? MergePropsIntoRequiredBooleans extends false ? false : true : false; type EnumType> = T[keyof T]; type EnumLike = { [k: string]: string | number; [nu: number]: string; }; type MaybeRefOrComputedRef = MaybeRef | ComputedRef; type UnwrapMaybeRef | DeepReactiveState> = T extends Ref ? UnwrapRef : UnwrapNestedRefs; type TupleToPlainObj = { [I in keyof T & `${number}`]: T[I] }; type HasNamedKeys = IsAny extends true ? false : IsUnknown extends true ? false : IsUnion extends true ? ProcessHasNamedKeys> : ProcessHasNamedKeys; type ProcessHasNamedKeys = { [K in keyof NonNullable]: K extends string ? (string extends K ? never : K) : never }[keyof NonNullable] extends never ? false : true; /** * Convert a nested object to a deeply nested partial object. */ type DeepPartial = IsAny extends true ? any : IsUnknown extends true ? any : T extends Array ? Array> : T extends Date | File | RegleStaticImpl ? T : T extends Record ? { [K in keyof T]?: DeepPartial | undefined } : T | undefined; type Prettify = T extends infer R ? { [K in keyof R]: R[K] } & {} : never; type Maybe = T | null | undefined; type MaybeInput = T | null | undefined; type MaybeOutput = T | undefined; type MaybeReadonly = T | Readonly; type NonUndefined = Exclude; type isUndefinedOrNull = Or, IsNullable>; type MaybeOrPartial = T extends Record ? Partial : MaybeOutput; type MaybeNullable = Or, IsOptional>; type PromiseReturn = T extends Promise ? U : T; type MaybeGetter = {}, TSelf extends Record = {}> = (T & TSelf) | ((value: Ref, index: number) => T & TAdd & TSelf); type MaybeComputedOrGetter = MaybeRefOrComputedRef | ((...args: any[]) => T); type Unwrap> = T extends Ref ? UnwrapRef : UnwrapNestedRefs; type UnwrapSimple>> = T extends MaybeComputedOrGetter ? U : T extends Ref ? U : T extends ((...args: any[]) => infer U) ? U : T; type ExtractFromGetter> = T extends ((value: Ref, index: number) => infer U extends Record) ? U : T; type ExtendOnlyRealRecord = NonNullable extends File | Date | RegleStatic<{}> | RegleStaticImpl<{}> ? false : NonNullable extends Record ? true : false; type OmitByType, U> = { [K in keyof T as T[K] extends U ? never : K]: T[K] }; type DeepMaybeRef> = { [K in keyof T]: MaybeRefOrGetter }; type ExcludeByType = { [K in keyof T as T[K] extends U ? never : K]: T[K] extends U ? never : T[K] }; type PrimitiveTypes = string | number | boolean | bigint | Date | File; type WidenPrimitiveLiterals = T extends string ? string : T extends number ? number : T extends boolean ? boolean : T extends bigint ? bigint : T; type isRecordLiteral = NonNullable extends Date | File | RegleStatic | RegleStaticImpl ? false : NonNullable extends Record ? true : false; type NoInferLegacy = [A][A extends any ? 0 : never]; /** * Extract the element type from an array. * * @example * ```ts * type Element = ArrayElement<[1, 2, 3]>; // number * ``` */ type ArrayElement = T extends Array ? U : never; /** * Declares a tuple that must have at least one element */ type NonEmptyTuple = [T, ...T[]] | T[]; interface CommonComparisonOptions { /** * Change the behaviour of the rule to check only if the value is equal in addition to be strictly superior or inferior * @default true */ allowEqual?: boolean; } interface CommonAlphaOptions { /** * Allow symbols in alphabetical-like rules (like "_") * @default true */ allowSymbols?: boolean; } interface UrlOptions { /** * Optional regex for validating the URL protocol */ protocol?: RegExp; } type EnumOneOfLike = { readonly [k: string]: TValue; }; type DefaultValidators = { alpha: RegleRuleWithParamsDefinition; alphaNum: RegleRuleWithParamsDefinition; atLeastOne: RegleRuleWithParamsDefinition | object, [keys?: readonly string[] | undefined], false, boolean, false, Record | object>; between: RegleRuleWithParamsDefinition; boolean: RegleRuleDefinition; checked: RegleRuleDefinition; contains: RegleRuleWithParamsDefinition], false, boolean>; containsSpecialCharacter: RegleRuleWithParamsDefinition; containsUppercase: RegleRuleWithParamsDefinition; date: RegleRuleDefinition, unknown>; dateAfter: RegleRuleWithParamsDefinition, options?: CommonComparisonOptions], false, true | { $valid: false; error: 'date-not-after'; } | { $valid: false; error: 'value-or-parameter-not-a-date'; }>; dateBefore: RegleRuleWithParamsDefinition, options?: CommonComparisonOptions], false, true | { $valid: false; error: 'date-not-before'; } | { $valid: false; error: 'value-or-parameter-not-a-date'; }>; dateBetween: RegleRuleWithParamsDefinition, after: MaybeInput, options?: CommonComparisonOptions], false, boolean>; decimal: RegleRuleDefinition; domain: RegleRuleDefinition; email: RegleRuleDefinition; endsWith: RegleRuleWithParamsDefinition], false, boolean>; exactLength: RegleRuleWithParamsDefinition, [count: number], false, boolean>; exactValue: RegleRuleWithParamsDefinition; file: RegleRuleDefinition, unknown>; fileType: RegleRuleWithParamsDefinition; hexadecimal: RegleRuleDefinition; integer: RegleRuleDefinition; ipv4Address: RegleRuleDefinition; literal: RegleRuleDefinition, string | number, true>; macAddress: RegleRuleWithParamsDefinition; maxLength: RegleRuleWithParamsDefinition, [max: number, options?: CommonComparisonOptions], false, boolean>; maxFileSize: RegleRuleWithParamsDefinition, File>; maxValue: RegleRuleWithParamsDefinition; minFileSize: RegleRuleWithParamsDefinition, File>; minLength: RegleRuleWithParamsDefinition, [min: number, options?: CommonComparisonOptions], false, boolean, string | any[] | Record>; minValue: RegleRuleWithParamsDefinition; nativeEnum: RegleRuleDefinition; number: RegleRuleDefinition; numeric: RegleRuleDefinition; oneOf: RegleRuleDefinition], false, boolean, MaybeInput, string | number>; regex: RegleRuleWithParamsDefinition; required: RegleRuleDefinition; sameAs: RegleRuleWithParamsDefinition; string: RegleRuleDefinition; type: RegleRuleDefinition; startsWith: RegleRuleWithParamsDefinition], false, boolean>; url: RegleRuleWithParamsDefinition; }; interface inferRulesFn> { | MaybeInput>, TRules extends ReglePartialRuleTree ? TState : {}>, Partial & TCustomRules>, TDecl extends RegleRuleDecl, Partial & TCustomRules>>(state: Maybe | DeepReactiveState, rulesFactory: Unwrap extends MaybeInput ? TDecl : Unwrap extends Record ? TRules : {}): NonNullable> extends PrimitiveTypes ? TDecl : TRules; } /** * Type helper to provide autocomplete and type-checking for your form rules. * It returns the rules without any processing - useful with computed rules. * * @param state - The state reference * @param rules - Your rule tree * @returns The rules object (passthrough) * * @example * ```ts * import { inferRules, useRegle } from '@regle/core'; * import { required, minLength } from '@regle/rules'; * * const state = ref({ name: '' }); * * // inferRules preserves TypeScript autocompletion * const rules = computed(() => { * return inferRules(state, { * name: { required, minLength: minLength(2) } * }) * }); * * const { r$ } = useRegle(state, rules); * ``` * * @see {@link https://reglejs.dev/core-concepts/#dynamic-rules-object Documentation} */ declare const inferRules: inferRulesFn>; interface GlobalConfigOptions = EmptyObject, TShortcuts extends RegleShortcutDefinition = never> { /** * Declare custom rules to be used globally or override the default rules messages. * * Ex: * ```ts * import { defineRegleConfig } from '@regle/core'; * import { required, withMessage } from '@regle/rules'; * * export const { useRegle, inferRules, useRules } = defineRegleConfig({ * rules: () => ({ * required: withMessage(required, 'This field cannot be empty'), * }), * }); * ``` * @see {@link https://reglejs.dev/advanced-usage/global-config Documentation} */ rules?: () => TCustomRules; /** * Define modifiers to be used globally. * * Ex: * ```ts * import { defineRegleConfig } from '@regle/core'; * * export const { useRegle, inferRules, useRules } = defineRegleConfig({ * modifiers: { * lazy: true, * rewardEarly: true * } * }); * ``` * @see {@link https://reglejs.dev/advanced-usage/global-config#declare-modifiers Documentation} */ modifiers?: RegleBehaviourOptions; /** * Define reusable validation shortcuts to be used globally. * * Ex: * ```ts * import { defineRegleConfig } from '@regle/core'; * * export const { useRegle, inferRules, useRules } = defineRegleConfig({ * shortcuts: { * fields: { * $isRequired: (field) => field.$rules.required?.$active ?? false, * }, * }, * }); * ``` * @see {@link https://reglejs.dev/advanced-usage/extend-properties#extend-properties Documentation} */ shortcuts?: TShortcuts; /** Override default behaviors of Regle processors. */ overrides?: GlobalConfigOverrides; } /** * Define a global Regle configuration to customize the validation behavior across your application. * * Features: * - Customize built-in rules messages * - Add your custom rules with full type inference * - Define global modifiers (lazy, rewardEarly, etc.) * - Define shortcuts for common validation patterns * * @param options - Configuration options * @returns Object containing typed `useRegle`, `inferRules`, and `useRules` functions * * @example * ```ts * import { defineRegleConfig } from '@regle/core'; * import { required, withMessage } from '@regle/rules'; * * export const { useRegle, inferRules, useRules } = defineRegleConfig({ * rules: () => ({ * // Override default required message * required: withMessage(required, 'This field cannot be empty'), * // Add custom rule * myCustomRule: createRule({ * validator: (value) => value === 'valid', * message: 'Invalid value' * }) * }), * modifiers: { * lazy: true, * rewardEarly: true * } * }); * ``` * * @see {@link https://reglejs.dev/advanced-usage/global-config Documentation} */ declare function defineRegleConfig, TCustomRules extends Partial>({ rules, modifiers, shortcuts, overrides }: GlobalConfigOptions): { useRegle: useRegleFn, TShortcuts>; inferRules: inferRulesFn>; useRules: useRulesFn; }; /** * Extend an already created custom `useRegle` configuration with additional rules, modifiers, or shortcuts. * * @param regle - The existing useRegle function to extend * @param options - Additional configuration to merge * @param options.rules - Additional custom rules * @param options.modifiers - Additional modifiers to merge * @param options.shortcuts - Additional shortcuts to merge * @returns Object containing the extended `useRegle` and `inferRules` functions * * @example * ```ts * import { extendRegleConfig } from '@regle/core'; * import { baseUseRegle } from './base-config'; * * export const { useRegle, inferRules } = extendRegleConfig(baseUseRegle, { * rules: () => ({ * additionalRule: myNewRule * }), * modifiers: { * rewardEarly: true * } * }); * ``` * * @see {@link https://reglejs.dev/advanced-usage/global-config Documentation} */ declare function extendRegleConfig, TRootShortcuts extends RegleShortcutDefinition<{}>, TShortcuts extends RegleShortcutDefinition>, TCustomRules extends Partial>(regle: useRegleFn, { rules, modifiers, shortcuts, overrides }: GlobalConfigOptions): { useRegle: useRegleFn, TRootShortcuts & TShortcuts>; inferRules: inferRulesFn>; }; /** * Define a global Regle options to customize the validation behavior across your application. * It's meant to be used with the Regle Vue plugin. * * @param options - Configuration options * @returns The configuration options * * @example * ```ts * import { defineRegleOptions } from '@regle/core'; * * const regleOptions = defineRegleOptions({ * modifiers: { * lazy: true, * rewardEarly: true * } * }); * ``` * * @see {@link https://reglejs.dev/advanced-usage/global-config Documentation} */ declare function defineRegleOptions, RegleShortcutDefinition>>(options: T): T; type useRegleFnOptions | MaybeInput, TRules extends ReglePartialRuleTree>, CustomRulesDeclarationTree>, TAdditionalOptions extends Record, TValidationGroups extends Record> = TState extends Record ? Partial> & LocalRegleBehaviourOptions, TRules, TValidationGroups> & TAdditionalOptions : Partial> & TAdditionalOptions; interface useRegleFn, TShortcuts extends RegleShortcutDefinition = never, TAdditionalReturnProperties extends Record = {}, TAdditionalOptions extends Record = {}> { | MaybeInput>, TRules extends ReglePartialRuleTree>, Partial>>, TDecl extends RegleRuleDecl>>, Partial>, TValidationGroups extends Record>(...params: [state: Maybe | DeepReactiveState, rulesFactory: Unwrap extends MaybeInput ? MaybeRefOrGetter : Unwrap extends Record ? MaybeComputedOrGetter : {}, ...(HaveAnyRequiredProps, TRules, TAdditionalOptions, TValidationGroups>> extends true ? [options: useRegleFnOptions>, TRules, TAdditionalOptions, TValidationGroups>] : [options?: useRegleFnOptions>, TRules, TAdditionalOptions, TValidationGroups>])]): NonNullable> extends PrimitiveTypes ? RegleSingleField>, TDecl, TShortcuts, TAdditionalReturnProperties> : Regle extends Record ? Unwrap : {}, UnwrapSimple extends Record ? UnwrapSimple : {}, TValidationGroups, TShortcuts, TAdditionalReturnProperties>; __config?: GlobalConfigOptions; } /** * `useRegle` serves as the foundation for validation logic. * * It transforms your data and validation rules into a powerful, reactive validation system. * * @param state - Your form data (plain object, ref, reactive object, or structure with nested refs) * @param rules - Validation rules that should align with the structure of your state * @param modifiers - Optional configuration to customize regle behavior * @returns An object containing `r$` - the reactive validation state * * @example * ```ts * import { useRegle } from '@regle/core'; * import { required, email, minLength } from '@regle/rules'; * * const { r$ } = useRegle( * { name: '', email: '' }, * { * name: { required, minLength: minLength(2) }, * email: { required, email } * } * ); * * // Access validation state * r$.$valid // Whether all validations pass * r$.$value // The current form values * r$.name.$errors // Errors for the name field * * // Trigger validation * const result = await r$.$validate(); * ``` * * @see {@link https://reglejs.dev/core-concepts/ Documentation} */ declare const useRegle: useRegleFn, RegleShortcutDefinition, {}, {}>; /** * @internal * This is the internal function that creates the root storage for the Regle instance. * This allows shared logic between all `useRegle` like composables */ declare function useRootStorage({ initialState, originalState, options, scopeRules, state, customRules, shortcuts, schemaErrors, schemaMode, onValidate, overrides }: { scopeRules: Ref<$InternalReglePartialRuleTree>; state: Ref | PrimitiveTypes>; options: ResolvedRegleBehaviourOptions; initialState: Ref | PrimitiveTypes>; originalState: Record | PrimitiveTypes; customRules?: () => CustomRulesDeclarationTree; shortcuts: RegleShortcutDefinition | undefined; schemaErrors?: Ref; schemaMode?: boolean; onValidate?: () => Promise<$InternalRegleResult>; overrides: GlobalConfigOverrides | undefined; }): { regle: Ref<$InternalRegleStatusType | undefined, $InternalRegleStatusType | undefined>; bindToCurrentScope: () => void; }; /** * Converts a nested `$errors` object to a flat array of error strings. * Useful for displaying a complete list of form errors or counting total errors. * * With the `includePath` option, returns errors in Standard Schema Issue format * including the path to each error field. * * @param errors - The `$errors` object from a Regle instance (e.g., `r$.$errors`) * @param options - Configuration options * @param options.includePath - If true, returns Standard Schema Issues with paths * @returns Array of error strings, or Standard Schema Issues if `includePath` is true * * @example * ```ts * import { flatErrors, useRegle } from '@regle/core'; * import { required, email, minLength } from '@regle/rules'; * * const { r$ } = useRegle( * { name: '', email: 'invalid' }, * { name: { required, minLength: minLength(3) }, email: { email } } * ); * * await r$.$validate(); * * // Get flat array of error messages * const errors = flatErrors(r$.$errors); * // ['This field is required', 'Value must be a valid email address'] * * // Get errors with paths (Standard Schema format) * const issues = flatErrors(r$.$errors, { includePath: true }); * // [{ message: 'This field is required', path: ['name'] }, ...] * ``` * * @see {@link https://reglejs.dev/core-concepts/displaying-errors#display-flat-errors Documentation} */ declare function flatErrors(errors: $InternalRegleErrors, options: { includePath: true; }): StandardSchemaV1.Issue[]; declare function flatErrors(errors: $InternalRegleErrors, options?: { includePath?: false; }): string[]; /** * Retrieves error messages for a specific field using a dot-notation path. * Provides type-safe access to nested error arrays in a Regle instance. * * @typeParam TRegle - The Regle instance type (root or status) * @typeParam TPath - The dot-notation path type, validated at compile-time * * @param r$ - The Regle instance (e.g., from `useRegle()`) * @param path - Dot-notation path to the field (e.g., `'user.email'` or `'items.0.name'`) * @returns Array of error strings for the field, or `undefined` if path doesn't exist * * @example * ```ts * import { getErrors, useRegle } from '@regle/core'; * import { required, email } from '@regle/rules'; * * const { r$ } = useRegle( * { user: { email: '' } }, * { user: { email: { required, email } } } * ); * * await r$.$validate(); * * // Type-safe access to nested errors * const emailErrors = getErrors(r$, 'user.email'); * // ['This field is required'] * * // Works with collections too * const itemErrors = getErrors(r$, 'items.0.name'); * ``` * * @see {@link https://reglejs.dev/core-concepts/displaying-errors#get-errors-by-path Documentation} */ declare function getErrors | (string & {})>(r$: MaybeRefOrGetter, path: TPath): IsStringLiteral extends true ? Get : string[] | undefined; /** * Retrieves detailed validation issues for a specific field using a dot-notation path. * Issues contain more information than errors, including the rule name, property, and metadata. * * @typeParam TRegle - The Regle instance type (root or status) * @typeParam TPath - The dot-notation path type, validated at compile-time * * @param r$ - The Regle instance (e.g., from `useRegle()`) * @param path - Dot-notation path to the field (e.g., `'user.email'` or `'items.0.name'`) * @returns Array of `RegleFieldIssue` objects for the field, or `undefined` if path doesn't exist * * @example * ```ts * import { getIssues, useRegle } from '@regle/core'; * import { required, email } from '@regle/rules'; * * const { r$ } = useRegle( * { user: { email: '' } }, * { user: { email: { required, email } } } * ); * * await r$.$validate(); * * // Type-safe access to nested issues with full metadata * const emailIssues = getIssues(r$, 'user.email'); * // [{ * // $message: 'This field is required', * // $property: 'email', * // $rule: 'required' * // }] * * // Works with collections too * const itemIssues = getIssues(r$, 'items.0.name'); * ``` * * @see {@link https://reglejs.dev/core-concepts/displaying-errors#get-issues-by-path Documentation} */ declare function getIssues>(r$: MaybeRefOrGetter, path: TPath | (string & {})): IsStringLiteral extends true ? Get : RegleFieldIssue[] | undefined; type useRulesFnOptions, TState = InferInput> = Partial> & LocalRegleBehaviourOptions ? Unwrap : {}>, TState extends Record ? (TRules extends Record ? TRules : {}) : {}, TValidationGroups>; interface useRulesFn, TShortcuts extends RegleShortcutDefinition = never> { , Partial & TCustomRules>, TValidationGroups extends Record, TState extends Record = InferInput>(rulesFactory: TState extends Record ? MaybeRef | ((...args: any[]) => TRules) : {}, options?: useRulesFnOptions): NonNullable extends PrimitiveTypes ? Raw, TDecl, TShortcuts>> & StandardSchemaV1 : Raw ? Unwrap : {}, TRules extends Record ? TRules : {}, TValidationGroups, TShortcuts>> & StandardSchemaV1; __config?: GlobalConfigOptions; } /** * `useRules` is a variant of `useRegle` that doesn't require you to provide initial state. * It creates an empty state based on your rules structure and implements the Standard Schema spec. * * This is useful when you want to define validation rules first and infer the state type from them. * * @param rules - Your validation rules object * @param modifiers - Optional configuration to customize regle behavior * @returns The reactive validation state (implements StandardSchemaV1) * * @example * ```ts * import { useRules, type InferInput } from '@regle/core'; * import { required, string, email } from '@regle/rules'; * * const r$ = useRules({ * name: { required, string }, * email: { required, email } * }); * * // State is automatically created and typed * r$.$value.name // string | null * r$.$value.email // string | null * * // Can be used with Standard Schema compatible libraries * const result = await r$['~standard'].validate({ name: '', email: '' }); * ``` * * @see {@link https://reglejs.dev/common-usage/standard-schema#userules Documentation} */ declare const useRules: useRulesFn, RegleShortcutDefinition>; /** * Marks a value as static and treats the constructor as a regular raw Field. * @param value - The value to mark as static. * @returns The marked value. * @example * ```ts * const StaticDecimal = markStatic(Decimal); * const StaticBigWrapper = markStatic(BigWrapper); * ``` */ declare function markStatic(value: T): T extends RegleStaticImpl ? T : RegleStatic; /** * Infer type of the `r$` of any function returning a regle instance */ type InferRegleRoot SuperCompatibleRegle> = T extends ((...args: any[]) => infer U) ? U extends SuperCompatibleRegle ? U['r$'] : never : never; /** * Infer custom rules declared in a global configuration */ type InferRegleRules> = T extends useRegleFn ? UnwrapRuleTree> & UnwrapRuleTree> : {}; /** * Infer custom shortcuts declared in a global configuration */ type InferRegleShortcuts> = T extends useRegleFn ? U : {}; /** * Extract a set rules and setting them as required */ type RegleEnforceRequiredRules = Omit, TRules> & { [K in TRules]-?: UnwrapRuleWithParams }; /** * Extract a set of custom rules from a global configuration and setting them as required */ type RegleEnforceCustomRequiredRules, TRules extends keyof InferRegleRules> = Omit, TRules> & { [K in TRules]-?: T extends useRegleFn ? K extends keyof InferRegleRules ? NonNullable[K]>> : never : K extends keyof T ? NonNullable : never }; /** * Extract custom rules and custom shortcuts and apply them to a RegleFieldStatus type */ type RegleCustomFieldStatus, TState extends unknown = any, TRules extends keyof InferRegleRules = never> = RegleFieldStatus> : RegleEnforceCustomRequiredRules, InferRegleShortcuts>; /** * Infer safe output type from a rules object and it's original state type * * ```ts * type FormRequest = InferOutput; * ``` */ type InferOutput, any>> | ((state: any) => ReglePartialRuleTree, any>) | MaybeRef>, TState extends MaybeRef = InferInput> = IsAny extends true ? any : IsUnknown extends true ? any : isRecordLiteral extends true ? TRules extends MaybeRef> ? State : DeepSafeFormState>>, TRules extends MaybeRef, any>> ? UnwrapRef : {}> : TState extends any[] ? TState[] : TState; /** * Infer input type from a rules object * * ```ts * type FormRequest = InferInput; * ``` */ type InferInput, any>> | ((state: any) => ReglePartialRuleTree, any>) | MaybeRef>, TMarkMaybe extends boolean = true> = IsAny extends true ? any : IsUnknown extends true ? any : TRules extends MaybeRef> ? State : UnwrapSimple extends infer TRulesUnwrapped extends Record ? IsUnion extends true ? InferTupleUnionInput>[number] : TMarkMaybe extends true ? Prettify<{ [K in keyof TRulesUnwrapped as [TRulesUnwrapped[K]] extends [MaybeRef>] ? K : never]?: ProcessInputChildren } & { [K in keyof TRulesUnwrapped as [TRulesUnwrapped[K]] extends [MaybeRef>] ? never : K]: ProcessInputChildren }> : Prettify<{ [K in keyof TRulesUnwrapped]: ProcessInputChildren }> : never; type ProcessInputChildren = IsAny extends true ? any : IsUnknown extends true ? any : TRule extends { $each: RegleCollectionEachRules; } ? ExtractFromGetter extends ReglePartialRuleTree ? InferInput, TMarkMaybe>[] : any[] : TRule extends MaybeRef> ? ExtractTypeFromRules> extends infer TRuleInput ? [TRuleInput] extends [never] ? unknown : TRuleInput : unknown : TRule extends ReglePartialRuleTree ? InferInput : string; type ExtractTypeFromRules> = FilterRulesWithInput extends infer TFilteredWithInput extends Record ? TFilteredWithInput extends { type: infer Input; } ? Input : FilterRulesWithSingleType extends infer TFilteredWithSingleType extends Record ? [TFilteredWithSingleType[keyof TFilteredWithSingleType]] extends [never] ? TFilteredWithInput[keyof TFilteredWithInput] : TFilteredWithSingleType[keyof TFilteredWithSingleType] : never : never; type RuleInput = TRule extends RegleRuleDefinition ? Input : unknown; type KnownRuleInput = unknown extends RuleInput ? never : RuleInput; type SingleKnownRuleInput = IsUnion>> extends true ? never : KnownRuleInput; type FilterRulesWithInput> = { [K in keyof TRules as KnownRuleInput extends never ? never : K]: KnownRuleInput }; type FilterRulesWithSingleType> = { [K in keyof TRules as SingleKnownRuleInput extends never ? never : K]: SingleKnownRuleInput }; type InferTupleUnionInput = T extends [infer F extends ReglePartialRuleTree, ...infer R] ? [InferInput, ...InferTupleUnionInput] : []; /** * Infer safe output from any `r$` instance * * ```ts * type FormRequest = InferSafeOutput; * ``` * * @deprecated Use {@link InferValidOutput} instead */ type InferSafeOutput> = IsAny extends true ? any : IsUnknown extends true ? any : UnwrapRef extends Raw, infer TRules, any, any>> ? TRules extends ReglePartialRuleTree, any> ? DeepSafeFormState, TRules> : never : UnwrapRef extends RegleFieldStatus ? SafeFieldProperty : UnwrapRef extends RegleLike> ? TState : never; /** * Infer safe output from any `r$` instance * * ```ts * type FormRequest = InferValidOutput; * ``` */ type InferValidOutput> = InferSafeOutput; /** * Infer complete validation result from any `r$` instance */ type InferRegleValidationResult> = InferRegleSettings extends { state: infer TState; rules: never; } ? ({ valid: true; data: TState; } | { valid: false; data: DeepPartial; }) & { errors: DataTypeRegleErrors; issues: DataTypeRegleIssues; } : InferRegleSettings extends { state: infer TState; rules: infer TRules extends Record; } ? RegleResult : never; /** * Infer State and Rules from any `r$` instance */ type InferRegleSettings> = UnwrapRef extends Raw, infer TRules extends Record, any, any>> ? { state: TState; rules: TRules; } : UnwrapRef extends RegleFieldStatus> ? { state: TState; rules: TRules; } : UnwrapRef extends RegleLike> ? { state: TState; rules: never; } : never; type CreateFn = (...args: T) => any; /** * Transform normal parameters tuple declaration to a rich tuple declaration * * [foo: string, bar?: number] => [foo: MaybeRef | (() => string), bar?: MaybeRef | (() => number) | undefined] */ type RegleUniversalParams> = [T] extends [[]] ? [] : Parameters any) ? (...args: { [K in keyof Args]: MaybeRefOrGetter> }) => any : never>; type UnwrapRegleUniversalParams> = [T] extends [[]] ? [] : Parameters any) ? (...args: { [K in keyof Args]: Args[K] extends MaybeRefOrGetter> ? U : Args[K] }) => any : never>; /** * Transform a tuple of parameters to a tuple of parameters and loose parameters * * [foo: string, bar?: number] => [foo: string, bar?: number, ...unknown[]] * * @param TParams - The tuple of parameters * @param TLoose - The tuple of loose parameters * @returns The tuple of parameters and loose parameters */ type ParamsToLooseParams = TParams extends [] ? [...TLoose] : TParams extends [infer TFirst, ...infer TRest] ? [TFirst, ...TRest, ...TLoose] : [...TParams, ...TLoose]; type HasOptionalParams = T extends [param?: any, ...any[]] ? T[0] extends NonNullable ? false : true : false; /** * Internal definition of the rule, this can be used to reset or patch the rule */ type RegleInternalRuleDefs = Raw<{ _validator: (value: Maybe, ...args: TParams) => TAsync extends false ? TMetadata : Promise; _message: string | string[] | ((metadata: PossibleRegleRuleMetadataConsumer) => string | string[]); _active?: boolean | ((metadata: PossibleRegleRuleMetadataConsumer) => boolean); _tooltip?: string | string[] | ((metadata: PossibleRegleRuleMetadataConsumer) => string | string[]); _type?: string; _message_patched: boolean; _tooltip_patched: boolean; _params?: RegleUniversalParams; _async: TAsync; readonly _brand: symbol; }>; declare const InternalRuleType: { readonly Inline: "__inline"; readonly Async: "__async"; }; type InternalRuleType = EnumType; /** * Returned typed of rules created with `createRule` * */ interface RegleRuleDefinition extends RegleInternalRuleDefs, RegleRuleDefinitionLight { validator: RegleRuleDefinitionProcessor>; message: (metadata: PossibleRegleRuleMetadataConsumer) => string | string[]; active?: (metadata: PossibleRegleRuleMetadataConsumer) => boolean; tooltip?: (metadata: PossibleRegleRuleMetadataConsumer) => string | string[]; type?: TType; _value?: IsLiteral extends true ? TValue : any; exec: (value: Maybe) => TAsync extends false ? TMetaData : Promise; required?: TNonEmpty; } type RegleRuleDefinitionLight = { value: unknown; params: [...TParams]; async: TAsync; metadata: TMetaData; }; /** * Rules with params created with `createRules` are callable while being customizable */ type RegleRuleWithParamsDefinition = RegleRuleCore & RegleInternalRuleDefs & RegleRuleDefinitionLight & { (...params: RegleUniversalParams): RegleRuleDefinition; } & (HasOptionalParams extends true ? { exec: (value: Maybe) => TAsync extends false ? TMetadata : Promise; } : IsAny extends true ? { exec?: (value: Maybe) => TAsync extends false ? TMetadata : Promise; } : {}); type RegleRuleWithParamsDefinitionInput = RegleRuleCoreInput & RegleInternalRuleDefs & { exec: (value: Maybe) => TAsync extends false ? TMetadata : Promise; }; type RegleRuleMetadataExtended = { $valid: boolean; [x: string]: any; }; type UnwrapRuleTree | undefined; }> = { [K in keyof T]: UnwrapRuleWithParams }; type UnwrapRuleWithParams | undefined> = T extends RegleRuleWithParamsDefinition ? HasOptionalParams extends true ? RegleRuleWithParamsDefinition | RegleRuleDefinition : RegleRuleDefinition : T; /** * Define a rule Metadata definition */ type RegleRuleMetadataDefinition = RegleRuleMetadataExtended | boolean; type DefaultMetadataPropertiesCommon = Pick, '$invalid' | '$dirty' | '$pending' | '$correct' | '$error'>; type DefaultMetadataProperties = DefaultMetadataPropertiesCommon & { $rule: Pick<$InternalRegleRuleStatus, '$valid' | '$pending'>; }; /** * Will be used to consume metadata on related helpers and rule status */ type RegleRuleMetadataConsumer = { $value: Maybe; } & DefaultMetadataProperties & (TParams extends never ? {} : { $params: [...TParams]; }) & (Exclude extends RegleRuleMetadataExtended ? TMetadata extends boolean ? Partial, '$valid'>> : Omit, '$valid'> : {}); /** * Will be used to consume metadata on related helpers and rule status */ type PossibleRegleRuleMetadataConsumer = { $value: Maybe; } & DefaultMetadataProperties & { $params?: [...any[]]; }; /** * Generic types for a created RegleRule */ type RegleRuleRaw = RegleRuleDefinition | RegleRuleWithParamsDefinition; type RegleRuleRawInput = Omit | RegleRuleWithParamsDefinition, 'message' | 'tooltip' | 'active'> & { message: any; active?: any; tooltip?: any; }; /** * Process the type of created rule with `createRule`. * For a rule with params it will return a function * Otherwise it will return the rule definition */ type InferRegleRule = [TParams] extends [[]] ? RegleRuleDefinition : RegleRuleWithParamsDefinition; type RegleRuleDefinitionProcessor = (value: Maybe, ...params: TParams) => TReturn; type RegleRuleDefinitionWithMetadataProcessor, TReturn = any> = ((metadata: TMetadata) => TReturn) | TReturn; type RegleCollectionRuleDefinition = Partial> = (RegleRuleDecl, TCustomRules, CollectionRegleBehaviourOptions> & { $each: MaybeGetter>, TCustomRules>, ArrayElement>; }) | ({ $each: MaybeGetter>, TCustomRules>, ArrayElement>; } & CollectionRegleBehaviourOptions); type RegleInitPropertyGetter = TReturn | ((metadata: RegleRuleMetadataConsumer) => TReturn); type RegleInitPropertyGetterInput = TReturn | ((metadata: any) => TReturn); /** * @argument * createRule arguments options */ interface RegleRuleInit = boolean, TMetadata extends RegleRuleMetadataDefinition = RegleRuleMetadataDefinition, TAsync extends boolean = (TReturn extends Promise ? true : false), TNonEmpty extends boolean = false> { validator: (value: Maybe, ...args: TParams) => TReturn; message: RegleInitPropertyGetter; active?: RegleInitPropertyGetter; tooltip?: RegleInitPropertyGetter; type?: TType; async?: TAsync; required?: TNonEmpty; } /** * @argument * Rule core */ interface RegleRuleCore { validator: (value: Maybe, ...args: TParams) => TAsync extends false ? TMetadata : Promise; message: RegleInitPropertyGetter; active?: RegleInitPropertyGetter; tooltip?: RegleInitPropertyGetter; type?: TType; async?: boolean; required?: TNonEmpty; } interface RegleRuleCoreInput { validator: (value: Maybe, ...args: TParams) => TAsync extends false ? TMetadata : Promise; message: RegleInitPropertyGetterInput; active?: RegleInitPropertyGetterInput; tooltip?: RegleInitPropertyGetterInput; type?: TType; async?: boolean; required?: TNonEmpty; } type RegleRuleTypeReturn = { value: TValue; params: [...TParams]; }; type CustomRulesDeclarationTree = { [x: string]: RegleRuleRawInput | undefined; }; type DefaultValidatorsTree = { [K in keyof DefaultValidators]: DefaultValidators[K] extends ((...args: any[]) => infer U) ? U : DefaultValidators[K] }; type DefaultValidatorsTreeOverrides = { [K in keyof DefaultValidators]: DefaultValidators[K] | ((...args: any[]) => DefaultValidators[K]) }; /** * Extend this interface to declare your custom rules */ interface CustomRules {} type ExtendedRulesDeclarations = CustomRulesDeclarationTree & DefaultValidatorsTree & CustomRules; type ExtendedRulesDeclarationsOverrides = CustomRulesDeclarationTree & DefaultValidatorsTreeOverrides & CustomRules; /** @deprecated Use {@link ExtendedRulesDeclarations} instead */ type AllRulesDeclarations = ExtendedRulesDeclarations; /** * Extend this interface to declare your custom field properties */ interface CustomFieldProperties {} /** * Extend this interface to declare your custom nested properties */ interface CustomNestedProperties {} /** * Extend this interface to declare your custom collection properties */ interface CustomCollectionProperties {} /** * @public */ type RegleRoot = {}, TRules extends ReglePartialRuleTree = Record, TValidationGroups extends Record = never, TShortcuts extends RegleShortcutDefinition = {}> = MaybeVariantStatus & ([TValidationGroups] extends [never] ? {} : { /** * Collection of validation groups used declared with the `validationGroups` modifier */ $groups: { readonly [TKey in keyof TValidationGroups]: RegleValidationGroupOutput }; }); type ComputeNestedFieldStatus, TRules extends Record, TKey extends keyof TState, TShortcuts extends RegleShortcutDefinition> = TKey extends string ? IsUnion> extends true ? ExtendOnlyRealRecord extends true ? MaybeVariantStatus[TKey], NonNullable, TShortcuts> : InferRegleStatusType, NonNullable, TKey, TShortcuts> : InferRegleStatusType, NonNullable, TKey, TShortcuts> : never; type ProcessNestedFields | undefined, TRules extends ReglePartialRuleTree>, TShortcuts extends RegleShortcutDefinition = {}, TIsFields extends boolean = false> = Or, TIsFields> extends true ? { readonly [TKey in keyof TState as TRules[TKey] extends NonNullable ? NonNullable extends MaybeRef ? IsEmptyObject extends true ? TKey : never : never : TKey]: ComputeNestedFieldStatus, TRules, TKey, TShortcuts> } & (IsEmptyObject extends true ? { readonly [TKey in keyof TState as TRules[TKey] extends NonNullable ? NonNullable extends MaybeRef ? IsEmptyObject extends true ? never : TKey : TKey : never]: ComputeNestedFieldStatus, TRules, TKey, TShortcuts> | (isUndefinedOrNull extends true ? undefined : never) } : { readonly [TKey in keyof TState as TRules[TKey] extends NonNullable ? NonNullable extends MaybeRef ? IsEmptyObject extends true ? never : TKey : TKey : never]-?: ComputeNestedFieldStatus, TRules, TKey, TShortcuts> }) : {}; /** * @public */ type RegleStatus | undefined = Record, TRules extends ReglePartialRuleTree, Partial> = Record, TShortcuts extends RegleShortcutDefinition = {}, _TFields = ProcessNestedFields> = RegleCommonStatus & { /** Represents all the children of your object. You can access any nested child at any depth to get the relevant data you need for your form. */readonly $fields: _TFields; /** * Collection of all the issues, collected for all children properties and nested forms. * * Only contains issues from properties where $dirty equals true. */ readonly $issues: RegleIssuesTree; /** * Collection of all the error messages, collected for all children properties and nested forms. * * Only contains errors from properties where $dirty equals true. * */ readonly $errors: RegleErrorTree; /** Collection of all the error messages, collected for all children properties. */ readonly $silentErrors: RegleErrorTree; /** Sets the external errors for the field. */ $setExternalErrors(errors: RegleExternalErrorTree): void; /** Will return a copy of your state with only the fields that are dirty. By default it will filter out nullish values or objects, but you can override it with the first parameter $extractDirtyFields(false). */ $extractDirtyFields: (filterNullishValues?: boolean) => DeepPartial; /** Sets all properties as dirty, triggering all rules. It returns a promise that will either resolve to false or a type safe copy of your form state. Values that had the required rule will be transformed into a non-nullable value (type only). */ $validate: (forceValues?: JoinDiscriminatedUnions extends EmptyObject ? any : HasNamedKeys> extends true ? IsUnknown> extends true ? any : JoinDiscriminatedUnions : any) => Promise, TRules>>; } & (HasNamedKeys extends true ? _TFields : {}) & CustomNestedProperties & ([TShortcuts['nested']] extends [never] ? {} : { [K in keyof TShortcuts['nested']]: ReturnType[K]> }) & (TRules['$self'] extends RegleRuleDecl ? { /** Represents the status of the parent object. Status only concern the object itself and not its children */readonly $self: RegleFieldStatus, NonNullable, TShortcuts>; } : {}); /** * @internal * @reference {@link RegleStatus} */ interface $InternalRegleStatus extends $InternalRegleCommonStatus { readonly $externalErrors?: $InternalRegleErrorTree; $fields: { [x: string]: $InternalRegleStatusType; }; readonly $issues: Record; readonly $errors: Record; readonly $silentErrors: Record; readonly '~modifiers'?: RegleBehaviourOptions; $extractDirtyFields: (filterNullishValues?: boolean) => Record; $validate: (forceValues?: any) => Promise<$InternalRegleResult>; $validateWithoutRaceconditions: (forceValues?: any) => Promise<$InternalRegleResult>; $id?: string; readonly $self?: $InternalRegleFieldStatus | undefined; } /** * @public */ type InferRegleStatusType, TState extends Record = any, TKey extends PropertyKey = string, TShortcuts extends RegleShortcutDefinition = {}, isUnionOverride extends boolean = false, TRulesTuple extends any[] = never> = HasNamedKeys extends true ? [TState[TKey]] extends [undefined | null] ? RegleFieldStatus : NonNullable extends string | number | boolean | bigint | symbol ? RegleFieldStatus : NonNullable extends Array ? TRule extends RegleCollectionRuleDefinition ? ExtractFromGetter extends ReglePartialRuleTree ? RegleCollectionStatus, TRule, TShortcuts> : RegleFieldStatus : RegleCollectionStatus : TRule extends ReglePartialRuleTree ? NonNullable extends Array ? RegleFieldStatus : NonNullable extends Date | File ? RegleFieldStatus, TRule, TShortcuts> : unknown extends TState[TKey] ? RegleFieldStatus : NonNullable extends Record ? NonNullable extends RegleStaticImpl ? RegleFieldStatus, TRule, TShortcuts> : TRule extends ReglePartialRuleTree ? MaybeVariantStatus : MaybeVariantStatus : RegleFieldStatus : NonNullable extends Date | File ? RegleFieldStatus>, TRule, TShortcuts> : unknown extends TState[TKey] ? RegleFieldStatus : NonNullable extends Record ? NonNullable extends RegleStaticImpl ? RegleFieldStatus, TRule, TShortcuts> : MaybeVariantStatus, TShortcuts, isUnionOverride, []> : RegleFieldStatus : RegleCommonStatus; /** * @internal * @reference {@link InferRegleStatusType} */ type $InternalRegleStatusType = $InternalRegleCollectionStatus | $InternalRegleStatus | $InternalRegleFieldStatus; /** * @public */ type RegleFieldStatus> = Record, TShortcuts extends RegleShortcutDefinition = never> = Omit, '$value' | '$silentValue' | '$initialValue' | '$originalValue'> & { /** A reference to the original validated model. It can be used to bind your form with v-model.*/$value: MaybeOutput>; /** $value variant that will not "touch" the field and update the value silently, running only the rules, so you can easily swap values without impacting user interaction. */ $silentValue: MaybeOutput>; /** * This value reflect the current initial value of the field. * The initial value is different than the original value as the initial value can be mutated when using `$reset`. */ readonly $initialValue: MaybeOutput>; /** * This value reflect the original value of the field at original call. This can't be mutated */ readonly $originalValue: MaybeOutput>; /** Collection of all the error messages, collected for all children properties and nested forms. * * Only contains errors from properties where $dirty equals true. */ readonly $errors: string[]; /** Collection of all the error messages, collected for all children properties and nested forms. */ readonly $silentErrors: string[]; /** * Collect all metadata of validators, Only contains metadata from properties where $dirty equals true. */ readonly $issues: RegleFieldIssue[]; /** * Collect all metadata of validators, including the error message. */ readonly $silentIssues: RegleFieldIssue[]; /** Stores external errors of the current field */ readonly $externalErrors: string[]; /** Stores active tooltips messages of the current field */ readonly $tooltips: string[]; /** Represents the inactive status. Is true when this state have empty rules */ readonly $inactive: boolean; /** Adds runtime rules to the field. */ $addRules: (rules: RegleRuleDecl) => void; /** * Adds runtime rules to the field. * @deprecated Use `$addRules` instead. This alias will be removed in a future version. */ addRules: (rules: RegleRuleDecl) => void; /** Sets the external errors for the field. */ $setExternalErrors(errors: string[]): void; /** Will return a copy of your state with only the fields that are dirty. By default it will filter out nullish values or objects, but you can override it with the first parameter $extractDirtyFields(false). */ $extractDirtyFields: (filterNullishValues?: boolean) => MaybeOutput; /** Sets all properties as dirty, triggering all rules. It returns a promise that will either resolve to false or a type safe copy of your form state. Values that had the required rule will be transformed into a non-nullable value (type only). */ $validate: (forceValues?: IsUnknown extends true ? any : TState) => Promise>; /** This is reactive tree containing all the declared rules of your field. To know more about the rule properties check the rules properties section */ readonly $rules: ComputeFieldRules; } & CustomFieldProperties & ([TShortcuts['fields']] extends [never] ? {} : { [K in keyof TShortcuts['fields']]: ReturnType[K]> }); /** * @internal * @reference {@link RegleFieldStatus} */ interface $InternalRegleFieldStatus extends $InternalRegleCommonStatus { $value: any; $silentValue: any; readonly $rules: Record; readonly $externalErrors?: string[]; readonly $errors: string[]; readonly $tooltips: string[]; readonly $inactive: boolean; readonly $silentErrors: string[]; readonly $issues: RegleFieldIssue[]; readonly $isDebouncing: boolean; readonly $schemaMode?: boolean; readonly '~modifiers'?: FieldRegleBehaviourOptions; $addRules: (rules: RegleRuleDecl) => void; /** @deprecated Use `$addRules` instead. */ addRules: (rules: RegleRuleDecl) => void; $extractDirtyFields: (filterNullishValues?: boolean) => any; $validate: (forceValues?: unknown) => Promise<$InternalRegleResult>; /** * Validates the field synchronously without waiting for async rules. * @internal */ $validateSync: (forceValues?: unknown) => boolean; /** Validate without the await nextTick */ $validateWithoutRaceconditions: (forceValues?: unknown) => Promise<$InternalRegleResult>; } /** * @public */ interface RegleCommonStatus = Record> extends StandardSchemaV1 extends true ? InferOutput : MaybeOrPartial> { /** Indicates whether the field is invalid. It becomes true if any associated rules return false. */ readonly $invalid: boolean; /** * This is not the opposite of `$invalid`. Correct is meant to display UI validation report. * * This will be `true` only if: * - The field has at least one active rule * - Is dirty and not empty * - Passes validation */ readonly $correct: boolean; /** Indicates whether a field has been validated or interacted with by the user at least once. It's typically used to determine if a message should be displayed to the user. You can change this flag manually using the $touch and $reset methods. The $dirty flag is considered true if the current model has been touched or if all its children are dirty.*/ readonly $dirty: boolean; /** Similar to $dirty, with one exception. The $anyDirty flag is considered true if given model was touched or any of its children are $anyDirty which means at least one descendant is $dirty. */ readonly $anyDirty: boolean; /** Indicates whether a field has been touched and if the value is different than the initial one. * On nested elements and collections, it's true only if all its children are also `$edited`. * Use `$anyEdited` to check for any edited children */ readonly $edited: boolean; /** Similar to $edited, with one exception. The $anyEdited flag is considered true if given model was edited or any of its children are $anyEdited which means at least one descendant is $edited. */ readonly $anyEdited: boolean; /** Indicates if any async rule for the field is currently running. Always false for synchronous rules. */ readonly $pending: boolean; /** Convenience flag to easily decide if a message should be displayed. Equivalent to $dirty && !$pending && $invalid. */ readonly $error: boolean; /** Indicates whether the field is ready for submission. Equivalent to !$invalid && !$pending. */ readonly $ready: boolean; /** Return the current key name of the field. */ readonly $name: string; /** Returns the current path of the rule (used internally for tracking) */ readonly $path: string; /** Id used to track collections items */ $id?: string; /** A reference to the original validated model. It can be used to bind your form with v-model.*/ $value: JoinDiscriminatedUnions>; /** * `$value` variant that will not "touch" the field and update the value silently, running only the rules, so you can easily swap values without impacting user interaction. * */ $silentValue: JoinDiscriminatedUnions>; /** * This value reflect the current initial value of the field. * The initial value is different than the original value as the initial value can be mutated when using `$reset`. */ readonly $initialValue: JoinDiscriminatedUnions>; /** * This value reflect the original value of the field at original call. This can't be mutated */ readonly $originalValue: JoinDiscriminatedUnions>; /** * Validates the field synchronously without waiting for async rules. * * This method provides immediate validation feedback by running only synchronous rules. * Async rules are skipped and assumed to be valid. Unlike `$validate`, this method: * - Does NOT wait for async validation results * - Returns a boolean directly instead of a Promise * * Use this when you need immediate validation feedback without side effects, * such as for real-time UI feedback or form gating logic. * * @param forceValues - Optional values to set before validating. Note that due to Vue's * reactivity system, you may need to wait for `nextTick()` after * setting values for rules to recalculate. * @returns `true` if all synchronous rules pass, `false` otherwise. * Always returns `false` in schema mode. * * @example * ```ts * // Basic usage * const isValid = r$.$validateSync(); * * // Field-level validation * const isEmailValid = r$.email.$validateSync(); * * // Use with form submission gating * function handleSubmit() { * if (r$.$validateSync()) { * // Proceed with submission * } * } * ``` * */ $validateSync: (forceValues?: unknown) => boolean; /** Marks the field and all nested properties as $dirty. */ $touch(): void; /** * Reset the validation status to a pristine state while keeping the current form state. * Resets the `$dirty` state on all nested properties of a form. * Rerun rules if `$lazy` is false */ $reset(): void; $reset(options?: ResetOptions): void; /** Clears the $externalErrors state back to an empty object. */ $clearExternalErrors(): void; } interface $InternalRegleCommonStatus extends Omit { $touch(runCommit?: boolean, withConditions?: boolean): void; $unwatch(): void; $watch(): void; $reset(options?: ResetOptions, fromParent?: boolean): void; $abort(): void; $setExternalErrors(errors: RegleExternalErrorTree): void; } /** * @public */ type RegleRuleStatus = { /** The name of the rule type. */readonly $type: string; /** Returns the computed error message or messages for the current rule. */ readonly $message: string | string[]; /** Stores the current rule tooltip or tooltips */ readonly $tooltip: string | string[]; /** Indicates whether or not the rule is enabled (for rules like requiredIf) */ readonly $active: boolean; /** Indicates the state of validation for this validator. */ readonly $valid: boolean; /** If the rule is async, indicates if it's currently pending. Always false if it's synchronous. */ readonly $pending: boolean; /** Returns the current path of the rule (used internally for tracking) */ readonly $path: string; /** Contains the metadata returned by the validator function. */ readonly $metadata: TMetadata extends boolean ? TMetadata : Omit; /** * Run the rule validator asynchronously and compute its properties like `$message` and `$active`. * @returns A promise that resolves to `true` if the rule passes, `false` otherwise. */ $parse(): Promise; /** * Run only the rule validator synchronously, skipping async rules. * * If the rule is async, this method returns `true` (assumes valid) since it cannot * wait for the async result. Use `$parse()` for async rules. * * @returns `true` if the sync rule passes or if the rule is async, `false` otherwise. */ $parseSync(): boolean; /** Reset the $valid, $metadata and $pending states */ $reset(): void; /** Returns the original rule validator function. */ $validator: ((value: IsUnknown extends true ? any : MaybeInput, ...args: any[]) => RegleRuleMetadataDefinition | Promise) & ((value: IsUnknown extends true ? any : TValue, ...args: [TParams] extends [never[]] ? [] : [unknown[]] extends [TParams] ? any[] : TParams) => RegleRuleMetadataDefinition | Promise); } & ([TParams] extends [never[]] ? {} : [unknown[]] extends [TParams] ? { /** Contains the rule parameters when the rule accepts arguments. */readonly $params?: any[]; } : { /** Contains the rule parameters when the rule accepts arguments. */readonly $params: [...TParams]; }); /** * @internal * @reference {@link RegleRuleStatus} */ interface $InternalRegleRuleStatus { $type?: string; $message: string | string[]; $tooltip: string | string[]; $active: boolean; $valid: boolean; $pending: boolean; $path: string; $externalErrors?: string[]; $params?: any[]; $metadata: any; $haveAsync: boolean; $validating: boolean; $fieldDirty: boolean; $fieldInvalid: boolean; $fieldPending: boolean; $fieldCorrect: boolean; $fieldError: boolean; $maybePending: boolean; $validator(value: any, ...args: any[]): RegleRuleMetadataDefinition | Promise; /** @internal */ $parse(): Promise; /** * Run only the rule validator synchronously. Returns `true` for async rules. * @internal */ $parseSync(): boolean; $reset(): void; $unwatch(): void; $watch(): void; } /** * @public */ type RegleCollectionStatus> = Record, TFieldRule extends RegleCollectionRuleDecl = never, TShortcuts extends RegleShortcutDefinition = {}> = Omit, '$value'> & { /** A reference to the original validated model. It can be used to bind your form with v-model.*/$value: MaybeOutput; /** $value variant that will not "touch" the field and update the value silently, running only the rules, so you can easily swap values without impacting user interaction. */ $silentValue: MaybeOutput; /** Collection of status of every item in your collection. Each item will be a field you can access, or map on it to display your elements. */ readonly $each: InferRegleStatusType, NonNullable, number, TShortcuts, IsUnion, UnionToTuple>[]; /** Represents the status of the collection itself. You can have validation rules on the array like minLength, this field represents the isolated status of the collection. */ readonly $self: RegleFieldStatus; /** * Collection of all the issues, collected for all children properties and nested forms. * * Only contains issues from properties where $dirty equals true. */ readonly $issues: RegleCollectionErrors; /** Collection of all the error messages, collected for all children properties and nested forms. * * Only contains errors from properties where $dirty equals true. */ readonly $errors: RegleCollectionErrors; /** Collection of all the error messages, collected for all children properties and nested forms. */ readonly $silentErrors: RegleCollectionErrors; /** Sets the external errors for the field. */ $setExternalErrors(errors: RegleExternalCollectionErrors): void; /** Will return a copy of your state with only the fields that are dirty. By default it will filter out nullish values or objects, but you can override it with the first parameter $extractDirtyFields(false). */ $extractDirtyFields: (filterNullishValues?: boolean) => DeepPartial; /** Sets all properties as dirty, triggering all rules. It returns a promise that will either resolve to false or a type safe copy of your form state. Values that had the required rule will be transformed into a non-nullable value (type only). */ $validate: (value?: JoinDiscriminatedUnions) => Promise>>; } & CustomCollectionProperties & ([TShortcuts['collections']] extends [never] ? {} : { [K in keyof TShortcuts['collections']]: ReturnType[K]> }); /** * @internal * @reference {@link RegleCollectionStatus} */ interface $InternalRegleCollectionStatus extends Omit<$InternalRegleStatus, '$fields' | '$issues' | '$errors' | '$silentErrors' | '~modifiers' | '$externalErrors'> { readonly $self: $InternalRegleFieldStatus; readonly $each: Array<$InternalRegleStatusType>; readonly $issues: $InternalRegleCollectionIssues; readonly $errors: $InternalRegleCollectionErrors; readonly $silentErrors: $InternalRegleCollectionErrors; readonly $externalErrors?: string[]; readonly '~modifiers'?: CollectionRegleBehaviourOptions; $extractDirtyFields: (filterNullishValues?: boolean) => any[]; $validate: (forceValues?: any) => Promise<$InternalRegleResult>; /** Validate without the await nextTick */ $validateWithoutRaceconditions: (forceValues?: any) => Promise<$InternalRegleResult>; } /** * @public */ type ReglePartialRuleTree = Record, TCustomRules extends Partial = Partial> = { [TKey in keyof TForm]?: RegleFormPropertyType } & SelfObjectValidationDecl; type SelfObjectValidationDecl = Record, TCustomRules extends Partial = Partial> = { $self?: MaybeRefOrComputedRef>; }; /** * @public */ type RegleRuleTree, TCustomRules extends Partial = Partial> = HasNamedKeys extends true ? { [TKey in keyof TForm]: RegleFormPropertyType } & SelfObjectValidationDecl : RegleUnknownRulesTree; /** * @public */ type RegleUnknownRulesTree = { [x: string]: RegleRuleDecl | RegleCollectionRuleDecl | RegleUnknownRulesTree; }; /** * @public */ type RegleComputedRules> | DeepReactiveState>, TCustomRules extends Partial | Regle | useRegleFn = Partial, TState = Unwrap>, TCustom = (TCustomRules extends Regle ? R extends ReglePartialRuleTree ? C : Partial : TCustomRules extends useRegleFn ? Rules : {})> = { [TKey in keyof JoinDiscriminatedUnions]?: RegleFormPropertyType[TKey], Omit, keyof TCustom> & Partial> }; /** * @internal * @reference {@link ReglePartialRuleTree} */ type $InternalReglePartialRuleTree = { [x: string]: $InternalFormPropertyTypes; } & { $self?: $InternalRegleRuleDecl; }; /** * @public */ type RegleFormPropertyType = Partial> = [NonNullable] extends [never] ? MaybeRefOrComputedRef> : NonNullable extends PrimitiveTypes ? MaybeRefOrComputedRef, TCustomRules>> : NonNullable extends Array ? RegleCollectionRuleDecl : NonNullable extends Ref ? RegleFormPropertyType : NonNullable extends Record ? NonNullable extends RegleStatic ? MaybeRefOrComputedRef, TCustomRules>> : ReglePartialRuleTree, TCustomRules> : MaybeRefOrComputedRef, TCustomRules>>; /** * @internal * @reference {@link RegleFormPropertyType} */ type $InternalFormPropertyTypes = MaybeRefOrComputedRef<$InternalRegleRuleDecl> | $InternalRegleCollectionRuleDecl | $InternalReglePartialRuleTree | FieldRegleBehaviourOptions; /** * @public * Rule tree for a form property */ type RegleRuleDecl = Partial, TOptions extends Record = FieldRegleBehaviourOptions> = TOptions & { [TKey in keyof RemoveIndexSignature]?: NonNullable extends RegleRuleDefinitionLight ? RegleRuleDefinitionLight, boolean, TMetadata> | InlineRuleDeclaration, any> : TCustomRules[TKey] } & { [x: string]: FormRuleDeclaration | boolean | number | undefined; }; /** * @internal * @reference {@link RegleRuleDecl} */ type $InternalRegleRuleDecl = FieldRegleBehaviourOptions & CollectionRegleBehaviourOptions & Record>; /** * @public */ type RegleCollectionRuleDeclKeyProperty = { $key?: PropertyKey; }; type CollectionEachRuleDecl = Partial> = IsAny extends true ? { $each?: RegleCollectionEachRules; } : MaybeNullable extends true ? { /** * Rules for each item in the collection * * ⚠️ `$each` is required here because your array is potentially undefined. * Regle can't guess the type of the array if it's undefined. * Having an empty `$each: {}` is the only way to tell Regle that the array is a collection. */ $each: RegleCollectionEachRules; } : { /** * Rules for each item in the collection */ $each?: RegleCollectionEachRules; }; /** * @public */ type RegleCollectionRuleDecl = Partial> = (CollectionEachRuleDecl & RegleRuleDecl, TCustomRules, CollectionRegleBehaviourOptions>) | (CollectionEachRuleDecl & CollectionRegleBehaviourOptions); /** @public */ type RegleCollectionEachRules = Partial> = MaybeGetter>, TCustomRules>, ArrayElement, RegleCollectionRuleDeclKeyProperty, RegleFormPropertyType>, TCustomRules>>; /** * @internal * @reference {@link RegleCollectionRuleDecl} */ type $InternalRegleCollectionRuleDecl = $InternalRegleRuleDecl & { $each?: MaybeGetter<$InternalFormPropertyTypes & RegleCollectionRuleDeclKeyProperty, any, {}, { $self?: $InternalRegleFieldStatus; }>; }; /** * @public */ type InlineRuleDeclaration = boolean> = (value: Maybe, ...args: UnwrapRegleUniversalParams) => TReturn; /** * @public * Regroup inline and registered rules * */ type FormRuleDeclaration = RegleRuleMetadataDefinition | Promise, TMetadata extends RegleRuleMetadataDefinition = (TReturn extends Promise ? M : TReturn), TAsync extends boolean = boolean> = RegleRuleWithParamsDefinitionInput | RegleRuleDefinition | RegleRuleWithParamsDefinitionInput | InlineRuleDeclaration; type RegleErrorTree | any[]>, TIssue extends boolean = false, TSchema extends boolean = false> = IsAny extends true ? any : IsUnknown extends true ? any : { readonly [K in keyof JoinDiscriminatedUnions>]: RegleValidationErrors>[K], false, TIssue, TSchema> } & { readonly $self?: string[]; }; type RegleIssuesTree | any[]>, TSchema extends boolean = false, TRules extends ReglePartialRuleTree> = Record> = IsAny extends true ? any : IsUnknown extends true ? any : { readonly [K in keyof JoinDiscriminatedUnions>]: RegleValidationErrors>[K], false, true, TSchema, K extends keyof TRules ? TRules[K] extends RegleFormPropertyType> ? TRules[K] : EmptyObject : EmptyObject> } & { readonly $self?: RegleFieldIssue[]; }; type RegleExternalErrorTree | any[]>, TSchema extends boolean = false> = IsAny extends true ? any : IsUnknown extends true ? any : ({ readonly [K in keyof JoinDiscriminatedUnions>]?: RegleValidationErrors>[K], true, TSchema> } & { readonly $self?: RegleFieldIssue[]; }) | Record | (string & {}), string[]>; type RegleExternalSchemaErrorTree | any[]>, TSchema extends boolean = false> = IsAny extends true ? any : IsUnknown extends true ? any : { readonly [K in keyof JoinDiscriminatedUnions>]?: RegleValidationErrors>[K], true, true, TSchema> }; type ErrorMessageOrIssue> = EmptyObject> = TIssue extends true ? RegleFieldIssue[] : string[]; type RegleValidationErrors | any[] | unknown = never, TExternal extends boolean = false, TIssue extends boolean = false, TSchema extends boolean = false, TRules extends RegleFormPropertyType> = EmptyObject> = IsAny extends true ? any : IsUnknown extends true ? any : HasNamedKeys extends true ? NonNullable extends Array ? TSchema extends false ? TExternal extends false ? RegleCollectionErrors : RegleExternalCollectionErrors : RegleCollectionErrors : NonNullable extends Date | File ? ErrorMessageOrIssue : NonNullable extends Record ? IsRegleStatic> extends true ? ErrorMessageOrIssue : TExternal extends false ? RegleErrorTree : RegleExternalErrorTree : ErrorMessageOrIssue : any; type RegleFieldIssue> = EmptyObject> = { readonly $property: string; readonly $type?: string; readonly $message: string; } & (IsEmptyObject extends true ? { readonly $rule: string; } : { [K in keyof ComputeFieldRules]: ComputeFieldRules[K] extends { $metadata: infer TMetadata; } ? K extends string ? { readonly $rule: K; } & (TMetadata extends boolean ? { readonly $rule: string; } : TMetadata) : { readonly $rule: string; } : { readonly $rule: string; } }[keyof ComputeFieldRules]); type ComputeFieldRules>>> = IsEmptyObject> extends true ? { readonly [x: string]: RegleRuleStatus; } : { readonly [TRuleKey in keyof UnwrapRef as TRuleKey extends '$each' | keyof FieldRegleBehaviourOptions ? never : TRuleKey]: RegleRuleStatus[TRuleKey] extends RegleRuleDefinitionLight ? TParams : [], UnwrapRef[TRuleKey] extends RegleRuleDefinitionLight ? TMetadata : UnwrapRef[TRuleKey] extends InlineRuleDeclaration ? TReturn extends Promise ? P : TReturn : RegleRuleMetadataDefinition> }; type RegleCollectionErrors = { readonly $self: TIssue extends true ? RegleFieldIssue[] : string[]; readonly $each: RegleValidationErrors[]; }; type RegleExternalCollectionErrors = { readonly $self?: TIssue extends true ? RegleFieldIssue[] : string[]; readonly $each?: RegleValidationErrors[]; }; /** @internal */ type $InternalRegleCollectionErrors = { readonly $self?: string[]; readonly $each?: $InternalRegleErrors[]; }; type $InternalRegleErrorTree = { [x: string]: $InternalRegleErrors; }; type $InternalRegleErrors = $InternalRegleCollectionErrors | string[] | $InternalRegleErrorTree; type $InternalRegleIssuesTree = { [x: string]: $InternalRegleIssues; }; type $InternalRegleIssues = $InternalRegleCollectionIssues | RegleFieldIssue[] | $InternalRegleIssuesTree; type $InternalRegleCollectionIssues = { readonly $self?: RegleFieldIssue[]; readonly $each?: $InternalRegleIssues[]; }; type RegleLike> = { $value: TState; $validate: (...args: any[]) => Promise; }; interface SuperCompatibleRegle { r$: SuperCompatibleRegleRoot; } /** Supports both core Regle and schemas Regle for Zod/Valibot */ type SuperCompatibleRegleRoot = SuperCompatibleRegleStatus & { $groups?: { [x: string]: RegleValidationGroupOutput; }; $validate: (...args: any[]) => Promise; '~modifiers'?: RegleBehaviourOptions; }; type SuperCompatibleRegleResult = $InternalRegleResult; type SuperCompatibleRegleStatus = { readonly $fields?: { [x: string]: any; }; readonly $issues: Record>; readonly $errors: Record>; readonly $silentErrors: Record>; $extractDirtyFields: (filterNullishValues?: boolean) => Record; $validate?: (...args: any[]) => Promise; $reset: (options?: ResetOptions) => void; [x: string]: any; }; type SuperCompatibleRegleRuleStatus = Omit<$InternalRegleRuleStatus, '$haveAsync' | '$validating' | '$fieldDirty' | '$fieldInvalid' | '$fieldPending' | '$fieldCorrect' | '$fieldError' | '$unwatch' | '$watch' | '$maybePending'>; type SuperCompatibleRegleCommonStatus = Omit & { $pending?: boolean; }; interface SuperCompatibleRegleFieldStatus extends SuperCompatibleRegleCommonStatus { $value: any; $silentValue: any; readonly $rules: Record; readonly $externalErrors?: string[]; readonly $issues: RegleFieldIssue[]; readonly $silentIssues: RegleFieldIssue[]; readonly $errors: string[]; readonly $inactive: boolean; readonly $silentErrors: string[]; $validate?: (...args: any[]) => Promise; $validateSync?: (...args: any[]) => boolean; } interface SuperCompatibleRegleCollectionStatus extends Omit { readonly $self: SuperCompatibleRegleFieldStatus; readonly $each: Array; readonly $issues: SuperCompatibleRegleCollectionIssues; readonly $errors: SuperCompatibleRegleCollectionErrors; readonly $silentErrors: SuperCompatibleRegleCollectionErrors; readonly $externalErrors?: string[]; $extractDirtyFields: (filterNullishValues?: boolean) => any[]; $validate?: (...args: any[]) => Promise; $validateSync?: (...args: any[]) => boolean; } type SuperCompatibleRegleCollectionErrors = $InternalRegleCollectionErrors; type SuperCompatibleRegleCollectionIssues = $InternalRegleCollectionIssues; /** * Create a typed custom rule that can be used like built-in rules. * The created rule can be declared in global options or used directly. * * Features: * - Automatically detects if the rule is async * - Supports parameters for configurable rules * - Full TypeScript type inference * - Custom metadata support * * @param definition - The rule definition object containing: * - `validator`: The validation function * - `message`: Error message (string or function) * - `type`: Optional rule type identifier * - `active`: Optional function to conditionally activate the rule * - `tooltip`: Optional tooltip message * * @returns A rule definition that is callable if it accepts parameters * * @example * ```ts * import { createRule } from '@regle/core'; * import { isFilled } from '@regle/rules'; * * // Simple rule without params * export const isFoo = createRule({ * validator(value: Maybe) { * if (isFilled(value)) { * return value === 'foo'; * } * return true; * }, * message: "The value should be 'foo'" * }); * * // Rule with parameters * export const minCustom = createRule({ * validator(value: Maybe, min: number) { * if (isFilled(value)) { * return value >= min; * } * return true; * }, * message: ({ $params: [min] }) => `Value must be at least ${min}` * }); * * // Usage * useRegle({ name: '' }, { name: { isFoo } }); * useRegle({ count: 0 }, { count: { minCustom: minCustom(5) } }); * ``` * * @see {@link https://reglejs.dev/core-concepts/rules/reusable-rules Documentation} */ declare function createRule, TMetadata extends RegleRuleMetadataDefinition = (TReturn extends Promise ? M : TReturn), TAsync extends boolean = (TReturn extends Promise ? true : false), TNonEmpty extends boolean = false>(definition: RegleRuleInit): InferRegleRule; /** * Returns a clean list of parameters * Removing Ref and executing function to return the unwrapped value */ declare function unwrapRuleParameters(params: MaybeRefOrGetter[]): TParams; type MergedRegles, TValue = { [K in keyof TRegles]: TRegles[K]['$value'] }> = Omit & { /** Map of merged Regle instances and their properties */readonly $instances: { [K in keyof TRegles]: TRegles[K] }; /** A reference to the original validated model. It can be used to bind your form with v-model.*/ $value: TValue; /** $value variant that will not "touch" the field and update the value silently, running only the rules, so you can easily swap values without impacting user interaction. */ $silentValue: TValue; /** Collection of all the error messages, collected for all children properties and nested forms. * * Only contains errors from properties where $dirty equals true. */ readonly $errors: { [K in keyof TRegles]: TRegles[K]['$errors'] }; /** Collection of all the error messages, collected for all children properties. */ readonly $silentErrors: { [K in keyof TRegles]: TRegles[K]['$silentErrors'] }; readonly $issues: { [K in keyof TRegles]: TRegles[K]['$issues'] }; readonly $silentIssues: { [K in keyof TRegles]: TRegles[K]['$silentIssues'] }; /** Will return a copy of your state with only the fields that are dirty. By default it will filter out nullish values or objects, but you can override it with the first parameter $extractDirtyFields(false). */ $extractDirtyFields: (filterNullishValues?: boolean) => DeepPartial[]; /** Sets all properties as dirty, triggering all rules. It returns a promise that will either resolve to false or a type safe copy of your form state. Values that had the required rule will be transformed into a non-nullable value (type only). */ $validate: (forceValues?: TRegles['$value']) => Promise>; $validateSync: (forceValues?: TRegles['$value']) => boolean; } & (HasNamedKeys extends true ? { [K in keyof TRegles]: TRegles[K] } : {}); type MergedScopedRegles[] = Record[]> = Omit, TValue>, '$instances' | '$errors' | '$silentErrors' | '$value' | '$silentValue' | '$validate' | '$extractDirtyFields'> & { /** Array of scoped Regles instances */readonly $instances: SuperCompatibleRegleRoot[]; /** Collection of all registered Regles instances values */ readonly $value: TValue; /** Collection of all registered Regles instances errors */ readonly $errors: RegleValidationErrors>[]; /** Collection of all registered Regles instances silent errors */ readonly $silentErrors: RegleValidationErrors>[]; /** Collection of all registered Regles instances issues */ readonly $issues: RegleValidationErrors, false, true>[]; /** Collection of all registered Regles instances silent issues */ readonly $silentIssues: RegleValidationErrors, false, true>[]; /** Will return a copy of your state with only the fields that are dirty. By default it will filter out nullish values or objects, but you can override it with the first parameter $extractDirtyFields(false). */ $extractDirtyFields: (filterNullishValues?: boolean) => DeepPartial; /** Sets all properties as dirty, triggering all rules. It returns a promise that will either resolve to false or a type safe copy of your form state. Values that had the required rule will be transformed into a non-nullable value (type only). */ $validate: (forceValues?: TValue) => Promise<{ valid: boolean; data: TValue; errors: RegleValidationErrors>[]; issues: RegleValidationErrors>[]; }>; }; type MergedReglesResult> = { valid: false; data: { [K in keyof TRegles]: Extract>, { valid: false; }>['data'] }; errors: { [K in keyof TRegles]: TRegles[K]['$errors'] }; issues: { [K in keyof TRegles]: TRegles[K]['$issues'] }; } | { valid: true; data: { [K in keyof TRegles]: Extract>, { valid: true; }>['data'] }; errors: EmptyObject; issues: EmptyObject; }; /** * Merge multiple Regle instances into a single validation state. * Useful for combining multiple forms or validation scopes. * * @param regles - An object containing named Regle instances to merge * @param _scoped - Internal flag for scoped validation (default: false) * @returns A merged validation state with all instances' properties combined * * @example * ```ts * import { useRegle, mergeRegles } from '@regle/core'; * import { required } from '@regle/rules'; * * // Create separate validation instances * const { r$: personalInfo } = useRegle( * { name: '', email: '' }, * { name: { required }, email: { required } } * ); * * const { r$: address } = useRegle( * { street: '', city: '' }, * { street: { required }, city: { required } } * ); * * // Merge them together * const merged$ = mergeRegles({ * personalInfo, * address * }); * * // Access combined state * merged$.$valid // true when ALL forms are valid * merged$.$errors // { personalInfo: {...}, address: {...} } * await merged$.$validate() // Validates all forms * ``` * * @see {@link https://reglejs.dev/advanced-usage/merge-regles Documentation} */ declare function mergeRegles, TScoped extends boolean = false>(regles: TRegles, _scoped?: TScoped): TScoped extends false ? MergedRegles : MergedScopedRegles; type useCollectScopeFn = TNamedScoped extends true ? >>(namespace?: MaybeRefOrGetter) => { r$: MergedRegles<{ [K in keyof TValue]: RegleRoot & SuperCompatibleRegleRoot }>; } : [] = Record[]>(namespace?: MaybeRefOrGetter) => { r$: MergedScopedRegles; }; type UseScopedRegleOptions = { namespace?: MaybeRefOrGetter; } & (TAsRecord extends true ? RequireAtLeastOne<{ id: string; /** * @deprecated Use `id` instead */ scopeKey: string; }, 'id' | 'scopeKey'> : {}); type useScopedRegleFn, TShortcuts extends RegleShortcutDefinition, TAsRecord extends boolean> = useRegleFn void; register: () => void; }, UseScopedRegleOptions>; type CreateScopedUseRegleOptions, TAsRecord extends boolean> = { /** * Inject a global configuration to the exported composables to keep your translations and typings */ customUseRegle?: TCustomRegle; /** * Store the collected instances externally */ customStore?: Ref; /** * Collect instances in a Record instead of an array * * ⚠️ Each nested `useScopedRegle` must provide a parameter `id` to be collected. */ asRecord?: TAsRecord; }; /** * Create a scoped validation system for collecting and validating multiple form instances. * Useful for dynamic forms, multi-step wizards, or component-based form architectures. * * @param options - Configuration options * @param options.customUseRegle - Custom useRegle instance with your global config * @param options.customStore - External ref to store collected instances * @param options.asRecord - If true, collect instances in a Record (requires `id` param in useScopedRegle) * @returns Object containing `useScopedRegle` and `useCollectScope` functions * * @example * ```ts * // scoped-config.ts * import { createScopedUseRegle } from '@regle/core'; * * export const { useScopedRegle, useCollectScope } = createScopedUseRegle(); * * // ChildComponent.vue * const { r$ } = useScopedRegle(state, rules, { * namespace: 'myForm' * }); * * // ParentComponent.vue * const { r$: collectedR$ } = useCollectScope('myForm'); * await collectedR$.$validate(); // Validates all child forms * ``` * * @see {@link https://reglejs.dev/advanced-usage/scoped-validation Documentation} */ declare function createScopedUseRegle = useRegleFn>, TAsRecord extends boolean = false, TReturnedRegle extends useRegleFn = (TCustomRegle extends useRegleFn ? useScopedRegleFn : useScopedRegleFn, any, TAsRecord>)>(options?: CreateScopedUseRegleOptions): { useScopedRegle: TReturnedRegle; useCollectScope: useCollectScopeFn; }; /** * Composable to collect and merge all Regle instances created with the default `useScopedRegle` within the same scope. * Returns a merged `r$` object allowing validation across multiple components simultaneously. * * Children properties like `$value` and `$errors` are converted to arrays instead of objects. * You have access to all validation properties like `$error`, `$invalid`, `$validate()`, etc. * * @param namespace - Optional namespace or array of namespaces to filter which scoped instances to collect * @returns Object containing `r$` - the merged Regle instance with array-based properties * * @example * ```ts * // ParentComponent.vue * import { useCollectScope } from '@regle/core'; * * const { r$ } = useCollectScope(); * // Or with namespace filtering * const { r$ } = useCollectScope('contacts'); * * // Validate all collected forms * const { result, data } = await r$.$validate(); * // Access collected errors * console.log(r$.$errors); * ``` * * @see {@link https://reglejs.dev/advanced-usage/scoped-validation Documentation} */ declare const useCollectScope: [] = Record[]>(namespace?: MaybeRefOrGetter) => { r$: MergedScopedRegles; }; /** * Clone of `useRegle` that automatically registers its instance for collection by `useCollectScope`. * Every time it's called, a new instance is added for the parent scope to collect. * * Can be called multiple times anywhere in your app - not restricted to components or DOM. * When the component is unmounted or scope is disposed, the instance is automatically unregistered. * * @param state - Reactive state object to validate * @param rules - Validation rules to apply * @param options - Configuration options including optional `namespace` for scoping * @returns Object containing `r$` (Regle instance), `dispose()` and `register()` methods * * @example * ```ts * // ChildComponent.vue * import { useScopedRegle } from '@regle/core'; * * const { r$ } = useScopedRegle( * { email: '' }, * { email: { required, email } }, * { namespace: 'contacts' } * ); * ``` * * @see {@link https://reglejs.dev/advanced-usage/scoped-validation Documentation} */ declare const useScopedRegle: useScopedRegleFn, never, boolean>; /** * Create variant-based validation rules that depend on a discriminant field value. * Useful for union types where different fields are required based on a type discriminant. * * Note: Autocomplete may not fully work due to TypeScript limitations. * * @param root - The reactive state object * @param discriminantKey - The key used to discriminate between variants * @param variants - Array of variant rule definitions using `literal` for type matching * @returns A computed ref containing the currently active variant rules * * @example * ```ts * import { useRegle, createVariant } from '@regle/core'; * import { required, email, literal } from '@regle/rules'; * * const state = ref({ * type: 'EMAIL' as 'EMAIL' | 'GITHUB', * email: '', * username: '' * }); * * // ⚠️ Use getter syntax for your rules * const { r$ } = useRegle(state, () => { * const variant = createVariant(state, 'type', [ * { type: { literal: literal('EMAIL') }, email: { required, email } }, * { type: { literal: literal('GITHUB') }, username: { required } }, * { type: { required } }, // Default case * ]); * * return { * ...variant.value, * }; * }); * ``` * * @see {@link https://reglejs.dev/advanced-usage/variants Documentation} */ declare function createVariant, TDiscriminant extends keyof JoinDiscriminatedUnions, TVariants extends VariantTuple, TDiscriminant>>(root: MaybeRefOrGetter | DeepReactiveState, discriminantKey: TDiscriminant, variants: [...TVariants]): Ref; /** * Type guard to narrow a variant field to a specific discriminated value. * Enables type-safe access to variant-specific fields. * * @param root - The Regle status object * @param discriminantKey - The key used to discriminate between variants * @param discriminantValue - The specific value to narrow to * @returns `true` if the discriminant matches, with TypeScript narrowing the type * * @example * ```ts * import { narrowVariant } from '@regle/core'; * * if (narrowVariant(r$, 'type', 'EMAIL')) { * // TypeScript knows r$.email exists here * r$.email.$value = 'user@example.com'; * } * ``` * * @see {@link https://reglejs.dev/advanced-usage/variants Documentation} */ declare function narrowVariant, `$${string}` | `~${string}`>, const TValue extends (LazyJoinDiscriminatedUnions[TKey], RegleCollectionStatus | RegleStatus | NarrowVariantExtracts[keyof NarrowVariantExtracts]>> extends { $value: infer V; } ? V : unknown)>(root: TRoot | undefined, discriminantKey: TKey, discriminantValue: TValue): root is NarrowVariant, TKey, TValue>; /** * Create a reactive reference to a narrowed variant. * Useful in templates or when you need a stable ref to the narrowed type. * * @param root - The Regle status object (can be a ref) * @param discriminantKey - The key used to discriminate between variants * @param discriminantValue - The specific value to narrow to * @param options - Optional `{ unsafeAssertion: true }` to assert the variant always exists * @returns A ref containing the narrowed variant (or undefined if not matching) * * @example * ```vue * * ``` * * @see {@link https://reglejs.dev/advanced-usage/variants Documentation} */ declare function variantToRef, const TKey extends keyof TRoot['$fields'], const TValue extends (LazyJoinDiscriminatedUnions | RegleStatus | NarrowVariantExtracts[keyof NarrowVariantExtracts]>> extends { $value: infer V; } ? V : unknown)>(root: MaybeRef, discriminantKey: TKey, discriminantValue: TValue, options: { /** * Assert that the variant is always defined, use with caution */ unsafeAssertion: true; }): Ref>; declare function variantToRef, const TKey extends keyof TRoot['$fields'], const TValue extends (LazyJoinDiscriminatedUnions | RegleStatus | NarrowVariantExtracts[keyof NarrowVariantExtracts]>> extends { $value: infer V; } ? V : unknown)>(root: MaybeRef, discriminantKey: TKey, discriminantValue: TValue): Ref | undefined>; /** * Helper method to wrap a raw rules object with type inference. * Provides autocomplete and type-checking without processing. * * @param rules - The rules object to wrap * @returns The same rules object (passthrough) * * @example * ```ts * import { defineRules } from '@regle/core'; * import { required, string } from '@regle/rules'; * * // defineRules helps catch structure errors * const rules = defineRules({ * firstName: { required, string }, * lastName: { required, string } * }); * ``` * * @see {@link https://reglejs.dev/common-usage/standard-schema Documentation} */ declare function defineRules(rules: TRules): TRules; /** * Refine a rules object to add rules that depend on the state values. * Inspired by Zod's `refine`, this allows writing dynamic rules while maintaining type safety. * * @param rules - The base rules object * @param refinement - A function that receives the typed state and returns additional rules * @returns A function that, given the state ref, returns the merged rules * * @example * ```ts * import { refineRules, type InferInput } from '@regle/core'; * import { required, string, sameAs } from '@regle/rules'; * * const rules = refineRules({ * password: { required, string }, * }, (state) => ({ * // state is typed based on the base rules * confirmPassword: { * required, * sameAs: sameAs(() => state.value.password) * } * })); * * type State = InferInput; * // { password: string; confirmPassword: string } * ``` * * @see {@link https://reglejs.dev/common-usage/standard-schema#refinerules Documentation} */ declare function refineRules> & RegleUnknownRulesTree>(rules: TRules, refinement: (state: Ref>) => TRefinement): (state: Ref>) => Merge; /** * Checks if a value is a Regle instance (`r$`). * Useful for integrations (e.g. Pinia) that need to identify Regle objects. */ declare function isRegleInstance(value: unknown): boolean; /** * Vue plugin to enable Regle devtools integration with Vue Devtools. * Provides debugging capabilities for inspecting validation trees, states, and actions. * * Supports inspection of: `useRegle`, `useRules`, `useRegleSchema`, `useScopedRegle`, `useScopedRegleSchema`. * * Note: If using `@regle/nuxt`, devtools are automatically enabled. * * @example * ```ts * // main.ts * import { createApp } from 'vue'; * import { RegleVuePlugin } from '@regle/core'; * import App from './App.vue'; * * const app = createApp(App); * app.use(RegleVuePlugin); * app.mount('#app'); * ``` * * @see {@link https://reglejs.dev/introduction/devtools Documentation} */ declare const RegleVuePlugin: Plugin; export { type $InternalRegleStatus, type AllRulesDeclarations, type ArrayElement, type CommonAlphaOptions, type CommonComparisonOptions, type CreateScopedUseRegleOptions, type CustomCollectionProperties, type CustomFieldProperties, type CustomNestedProperties, type CustomRules, type DeepMaybeRef, type DeepPartial, type DeepReactiveState, type DefaultValidatorsTree, type DumbJoinDiscriminatedUnions, type ExtendedRulesDeclarations, type ExtendedRulesDeclarationsOverrides, type FormRuleDeclaration, type GlobalConfigOverrides, type HasNamedKeys, type HaveAnyRequiredProps, type InferInput, type InferOutput, type InferRegleRoot, type InferRegleRule, type InferRegleRules, type InferRegleSettings, type InferRegleShortcuts, type InferRegleStatusType, type InferRegleValidationResult, type InferSafeOutput, type InferValidOutput, type InlineRuleDeclaration, InternalRuleType, type IsRegleStatic, type JoinDiscriminatedUnions, type LazyJoinDiscriminatedUnions, type LocalRegleBehaviourOptions, type Maybe, type MaybeInput, type MaybeOutput, type MaybeReadonly, type MaybeVariantStatus, type MergedRegles, type MergedScopedRegles, type NarrowVariant, type NarrowVariantExtracts, type NarrowVariantFieldExtracts, type NoInferLegacy, type NonEmptyTuple, type ParamsToLooseParams, type Prettify, type PrimitiveTypes, type Regle, type RegleBehaviourOptions, type RegleCollectionErrors, type RegleCollectionRuleDecl, type RegleCollectionRuleDefinition, type RegleCollectionStatus, type RegleCommonStatus, type RegleComputedRules, type RegleCustomFieldStatus, type RegleEnforceCustomRequiredRules, type RegleEnforceRequiredRules, type RegleErrorTree, type RegleExternalCollectionErrors, type RegleExternalErrorTree, type RegleExternalSchemaErrorTree, type RegleFieldIssue, type RegleFieldStatus, type RegleFormPropertyType, type RegleInternalRuleDefs, type RegleIssuesTree, type RegleLike, type ReglePartialRuleTree, type RegleResult, type RegleRoot, type RegleRuleCore, type RegleRuleDecl, type RegleRuleDefinition, type RegleRuleDefinitionLight, type RegleRuleDefinitionProcessor, type RegleRuleDefinitionWithMetadataProcessor, type RegleRuleInit, type RegleRuleMetadataConsumer, type RegleRuleMetadataDefinition, type RegleRuleMetadataExtended, type RegleRuleRaw, type RegleRuleStatus, type RegleRuleTypeReturn, type RegleRuleWithParamsDefinition, type RegleRuleWithParamsDefinitionInput, type RegleShortcutDefinition, type RegleSingleField, type RegleStatic, type RegleStaticImpl, type RegleStatus, type RegleUniversalParams, type RegleUnknownRulesTree, type RegleValidationErrors, type RegleValidationGroupEntry, type RegleValidationGroupOutput, type RegleRuleTree as RegleValidationTree, RegleVuePlugin, type ResolvedRegleBehaviourOptions, type ScopedInstancesRecord, type ScopedInstancesRecordLike, type SuperCompatibleRegle, type SuperCompatibleRegleCollectionErrors, type SuperCompatibleRegleCollectionStatus, type SuperCompatibleRegleFieldStatus, type SuperCompatibleRegleResult, type SuperCompatibleRegleRoot, type SuperCompatibleRegleRuleStatus, type SuperCompatibleRegleStatus, type TupleToPlainObj, type Unwrap, type UnwrapRegleUniversalParams, type UnwrapRuleWithParams, type UnwrapStatic, type UrlOptions, type UseScopedRegleOptions, createRule, createScopedUseRegle, createVariant, defineRegleConfig, defineRegleOptions, defineRules, extendRegleConfig, flatErrors, getErrors, getIssues, inferRules, type inferRulesFn, type isEditedHandlerFn, isRegleInstance, markStatic, mergeRegles, narrowVariant, refineRules, unwrapRuleParameters, useCollectScope, type useCollectScopeFn, useRegle, type useRegleFn, useRootStorage, useRules, type useRulesFn, useScopedRegle, type useScopedRegleFn, variantToRef };