@bufbuild/protovalidate
Version:
Protocol Buffer Validation for ECMAScript
89 lines (88 loc) • 3.05 kB
TypeScript
import { type DescMessage, type Message, type MessageShape, type MessageValidType, type Registry } from "@bufbuild/protobuf";
import { CompilationError, RuntimeError, ValidationError, type Violation } from "./error.js";
import { type RegexMatcher } from "./cel.js";
/**
* Options for creating a validator.
*/
export type ValidatorOptions = {
/**
* To validate messages with user-defined predefined rules, pass the extensions
* to the validator via the registry.
*
* By default, the validator is unaware of any predefined rules, and will not
* validate them.
*
* The registry is also passed to the CEL environment, where it may be used to
* unpack google.protobuf.Any messages.
*/
registry?: Registry;
/**
* With this option enabled, validation fails on the first rule violation
* encountered. By default, all violations are accumulated.
*/
failFast?: boolean;
/**
* RE2 compliant regex matcher to use.
*
* ECMAScript supports most, but not all RE expressions. You can use a custom
* regex engine to support the unsupported features of RE2.
*
* Know limitations of default RE (ECMAScript) matcher:
* * Cannot change flags mid-sequence e.g. 'John(?i)Doe'.
* * Doesn't support the 'U' flag.
*/
regexMatch?: RegexMatcher;
/**
* With this option enabled, proto2 fields with the `required` label, and fields
* with the edition feature `field_presence=LEGACY_REQUIRED` are validated to
* be set.
*
* By default, legacy required field are not validated.
*/
legacyRequired?: boolean;
};
/**
* A validator.
*/
export type Validator = {
/**
* Validate the given message satisfies its rules, and return the result.
*
* Rules are defined within the Protobuf file as options from the
* buf.validate package.
*
* The result is one of:
* - valid: The message passed all validation rules.
* - invalid: The message violated one or more validation rules.
* - error: An error occurred while compiling or evaluating a rule.
*/
validate<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>): ValidationResult<MessageValidType<Desc>, MessageShape<Desc>>;
};
/**
* The result of validating a Protobuf message with protovalidate.
*
* It is one of:
* - valid: The message passed all validation rules.
* - invalid: The message violated one or more validation rules.
* - error: An error occurred while compiling or evaluating a rule.
*/
export type ValidationResult<Valid = Message, Invalid = Message> = {
kind: "valid";
message: Valid;
error: undefined;
violations: undefined;
} | {
kind: "invalid";
message: Invalid;
error: ValidationError;
violations: Violation[];
} | {
kind: "error";
message: Invalid;
error: CompilationError | RuntimeError;
violations: undefined;
};
/**
* Create a validator.
*/
export declare function createValidator(opt?: ValidatorOptions): Validator;