UNPKG

@phr3nzy/rulekit

Version:

A powerful and flexible toolkit for building rule-based matching and filtering systems

303 lines (297 loc) 10.9 kB
/** * Defines the core attribute types supported by the system. * Each type represents a different kind of value that can be stored and validated. * * @remarks * - STRING: Text values * - NUMBER: Numeric values * - BOOLEAN: True/false values * - DATE: Date/time values * - ENUM: Values from a predefined set * - ARRAY: List of values of a specific type * * @example * ```typescript * const definition = { * type: AttributeType.STRING, * validation: { * required: true, * pattern: '^[A-Z].*$' * } * }; * ``` */ declare const AttributeType: { readonly STRING: "string"; readonly NUMBER: "number"; readonly BOOLEAN: "boolean"; readonly DATE: "date"; readonly ENUM: "enum"; readonly ARRAY: "array"; }; type AttributeTypeValue = (typeof AttributeType)[keyof typeof AttributeType]; /** * Defines the structure for attribute validation rules. * Combines type checking with additional validation constraints. * * @interface ValidationRule * * @property {AttributeTypeValue} type - The type of value to validate * @property {boolean} [required] - Whether the attribute is required * @property {number} [min] - Minimum value (for numbers) or length (for strings/arrays) * @property {number} [max] - Maximum value (for numbers) or length (for strings/arrays) * @property {string} [pattern] - Regular expression pattern for string validation * @property {readonly string[]} [enum] - Valid values for enum types * @property {AttributeTypeValue} [arrayType] - Type of elements in array * @property {Function} [custom] - Custom validation function * * @example * ```typescript * const numberRule: ValidationRule = { * type: AttributeType.NUMBER, * required: true, * min: 0, * max: 100 * }; * * const enumRule: ValidationRule = { * type: AttributeType.ENUM, * required: true, * enum: ['draft', 'published', 'archived'] as const * }; * * const arrayRule: ValidationRule = { * type: AttributeType.ARRAY, * arrayType: AttributeType.STRING, * max: 5 * }; * ``` */ type ValidationRule$1 = { type: AttributeTypeValue; required?: boolean; min?: number; max?: number; pattern?: string; enum?: readonly string[]; arrayType?: AttributeTypeValue; /** * Custom validation function that can access other attributes * @param value - The value to validate * @param attributes - Optional object containing all attributes being validated * @returns boolean or Promise<boolean> indicating if validation passed */ custom?: (value: unknown, attributes?: Record<string, unknown>) => boolean | Promise<boolean>; }; /** * Defines the complete structure of an attribute including metadata. * Used to define and document attributes in the system. * * @interface AttributeDefinition * * @property {string} name - Unique identifier for the attribute * @property {AttributeTypeValue} type - The attribute's data type * @property {string} description - Human-readable description * @property {ValidationRule} validation - Rules for validating values * @property {unknown} [defaultValue] - Default value if none provided * * @example * ```typescript * const priceAttribute: AttributeDefinition = { * name: 'price', * type: AttributeType.NUMBER, * description: 'Product price in cents', * validation: { * type: AttributeType.NUMBER, * required: true, * min: 0 * }, * defaultValue: 0 * }; * ``` */ type AttributeDefinition = { name: string; type: AttributeTypeValue; description: string; validation: ValidationRule$1; defaultValue?: unknown; }; /** * Registry type for storing and managing attribute definitions. * Provides a centralized store for attribute metadata. * * @typedef {Map<string, AttributeDefinition>} AttributeRegistry * * @example * ```typescript * const registry: AttributeRegistry = new Map(); * * registry.set('price', { * name: 'price', * type: AttributeType.NUMBER, * description: 'Product price', * validation: { type: AttributeType.NUMBER, min: 0 } * }); * ``` */ type AttributeRegistry = Map<string, AttributeDefinition>; /** * @file Core type definitions for RuleKit v3 * Provides type-safe schema definitions and utilities */ /** * Type-level utility to extract the actual value type from an attribute type */ type ExtractAttributeValue<T extends AttributeTypeValue, TArrayType extends AttributeTypeValue | undefined = undefined> = T extends typeof AttributeType.STRING ? string : T extends typeof AttributeType.NUMBER ? number : T extends typeof AttributeType.BOOLEAN ? boolean : T extends typeof AttributeType.DATE ? Date : T extends typeof AttributeType.ENUM ? string : T extends typeof AttributeType.ARRAY ? TArrayType extends AttributeTypeValue ? Array<ExtractAttributeValue<TArrayType>> : unknown[] : never; /** * Validation rule with improved type safety */ type ValidationRule<T extends AttributeTypeValue> = { type: T; required?: boolean; min?: T extends typeof AttributeType.NUMBER ? number : T extends typeof AttributeType.STRING | typeof AttributeType.ARRAY ? number : never; max?: T extends typeof AttributeType.NUMBER ? number : T extends typeof AttributeType.STRING | typeof AttributeType.ARRAY ? number : never; pattern?: T extends typeof AttributeType.STRING ? string : never; enum?: T extends typeof AttributeType.ENUM ? readonly string[] : never; arrayType?: T extends typeof AttributeType.ARRAY ? AttributeTypeValue : never; custom?: (value: ExtractAttributeValue<T>, attributes?: Record<string, unknown>) => boolean | Promise<boolean>; }; /** * Type-safe attribute schema definition */ interface AttributeSchema { [key: string]: { type: AttributeTypeValue; validation: ValidationRule<AttributeTypeValue>; }; } /** * Utility type to extract the actual value type from a schema field */ type ExtractSchemaValue<T extends { type: AttributeTypeValue; validation: ValidationRule<AttributeTypeValue>; }> = ExtractAttributeValue<T['type'], T['type'] extends typeof AttributeType.ARRAY ? T['validation']['arrayType'] : undefined>; /** * Type-safe attributes object derived from schema */ type Attributes<TSchema extends AttributeSchema> = { [K in keyof TSchema]: ExtractSchemaValue<TSchema[K]>; } & { readonly __validated: boolean; }; /** * Type-safe entity with generic schema */ type Entity<TSchema extends AttributeSchema> = { id: string; name: string; attributes: Attributes<TSchema>; }; /** * Available comparison operators with type safety */ declare const ComparisonOperators: { readonly eq: "eq"; readonly ne: "ne"; readonly gt: "gt"; readonly gte: "gte"; readonly lt: "lt"; readonly lte: "lte"; readonly in: "in"; readonly notIn: "notIn"; }; type ComparisonOperator = keyof typeof ComparisonOperators; /** * Type-safe filter based on attribute type */ type NumericFilterValue<T extends AttributeTypeValue> = T extends typeof AttributeType.NUMBER ? number : never; type EqualityFilterValue<T extends AttributeTypeValue, TArrayType extends AttributeTypeValue | undefined> = T extends typeof AttributeType.ARRAY ? TArrayType extends AttributeTypeValue ? Array<ExtractAttributeValue<TArrayType>> : unknown[] : ExtractAttributeValue<T>; type ArrayFilterValue<T extends AttributeTypeValue, TArrayType extends AttributeTypeValue | undefined> = T extends typeof AttributeType.ARRAY ? TArrayType extends AttributeTypeValue ? Array<ExtractAttributeValue<TArrayType>> : unknown[] : Array<ExtractAttributeValue<T>>; type Filter<T extends AttributeTypeValue, TArrayType extends AttributeTypeValue | undefined = undefined> = { eq?: EqualityFilterValue<T, TArrayType>; ne?: EqualityFilterValue<T, TArrayType>; gt?: NumericFilterValue<T>; gte?: NumericFilterValue<T>; lt?: NumericFilterValue<T>; lte?: NumericFilterValue<T>; in?: ArrayFilterValue<T, TArrayType>; notIn?: ArrayFilterValue<T, TArrayType>; }; /** * Type-safe rule with generic schema */ type Rule<TSchema extends AttributeSchema> = { and?: Array<Rule<TSchema>>; or?: Array<Rule<TSchema>>; attributes?: { [K in keyof TSchema]?: Filter<TSchema[K]['type'], TSchema[K]['type'] extends typeof AttributeType.ARRAY ? TSchema[K]['validation']['arrayType'] : undefined>; }; }; /** * Type-safe rule set with generic schema */ type RuleSet<TSchema extends AttributeSchema> = { fromRules: Rule<TSchema>[]; toRules: Rule<TSchema>[]; }; /** * Type-safe matching configuration with generic schema */ type MatchingConfig<TSchema extends AttributeSchema> = { id: string; name: string; description?: string; ruleSet: RuleSet<TSchema>; isActive: boolean; createdAt: Date; updatedAt: Date; }; /** * Type guard to check if a value matches an attribute type */ declare function isValidAttributeValue<T extends AttributeTypeValue>(value: unknown, type: T, arrayType?: AttributeTypeValue): value is ExtractAttributeValue<T>; /** * Type guard to check if an object matches a schema */ declare function isValidSchemaObject<TSchema extends AttributeSchema>(obj: unknown, schema: TSchema): obj is Attributes<TSchema>; /** * @file Enhanced rule engine with generic type support * Provides type-safe rule evaluation and matching */ /** * Configuration interface for the RuleEngine */ interface RuleEngineConfig { maxBatchSize?: number; } /** * Enhanced rule engine with generic type support */ declare class RuleEngine<TSchema extends AttributeSchema> { private readonly schema; private readonly config; constructor(schema: TSchema, config?: Partial<RuleEngineConfig>); /** * Evaluates a single rule against an entity's attributes (assumes pre-validation) */ private evaluateRule; /** * Splits entities into optimal batch sizes based on complexity heuristic */ private getBatchSize; /** * Processes entities in optimally-sized batches, applying rules with validation and short-circuiting */ private processBatch; /** * Finds entities that satisfy all provided 'from' rules */ findMatchingFrom(entities: Entity<TSchema>[], rules: Rule<TSchema>[]): Entity<TSchema>[]; /** * Finds target entities that can be matched with source entities based on 'to' rules */ findMatchingTo(fromEntities: Entity<TSchema>[], toRules: Rule<TSchema>[], allEntities: Entity<TSchema>[]): Entity<TSchema>[]; } export { type AttributeDefinition, type AttributeRegistry, type AttributeSchema, AttributeType, type AttributeTypeValue, type Attributes, type ComparisonOperator, ComparisonOperators, type Entity, type ExtractAttributeValue, type ExtractSchemaValue, type Filter, type MatchingConfig, type Rule, RuleEngine, type RuleSet, type ValidationRule$1 as ValidationRule, isValidAttributeValue, isValidSchemaObject };