@phr3nzy/rulekit
Version:
A powerful and flexible toolkit for building rule-based matching and filtering systems
1,374 lines (1,351 loc) • 41.9 kB
text/typescript
/**
* 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>;
/**
* Type-safe attribute value type that changes based on the attribute type.
* Provides compile-time type checking for attribute values.
*
* @template T - The attribute type
* @typedef {T extends AttributeType} AttributeValue
*
* @example
* ```typescript
* // String attribute
* const name: AttributeValue<typeof AttributeType.STRING> = 'John';
*
* // Number attribute
* const age: AttributeValue<typeof AttributeType.NUMBER> = 25;
*
* // Array attribute
* const tags: AttributeValue<typeof AttributeType.ARRAY> = ['new', 'featured'];
* ```
*/
type AttributeValue<T extends AttributeTypeValue> = 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 ? unknown[] : never;
/**
* Container type for storing multiple dynamic attributes.
* Includes a validation flag to track attribute validation status.
*
* @interface DynamicAttributes
*
* @property {boolean} __validated - Flag indicating if attributes are validated
* @property {unknown} [key: string] - Dynamic attribute values
*
* @example
* ```typescript
* const attributes: DynamicAttributes = {
* name: 'Product A',
* price: 1999,
* inStock: true,
* __validated: true
* };
* ```
*/
type DynamicAttributes = {
[key: string]: unknown;
} & {
readonly __validated: boolean;
};
/**
* Represents a base entity that can be used with the rule engine.
* Entities are the core objects that rules are evaluated against.
*
* @example
* ```typescript
* const user: Entity = {
* id: 'user-123',
* name: 'John Doe',
* attributes: {
* age: 25,
* role: 'admin'
* }
* };
* ```
*/
type Entity = {
/**
* Unique identifier for the entity
*/
id: string;
/**
* Display name of the entity
*/
name: string;
/**
* Dynamic attributes that have been validated against their definitions
*/
attributes: DynamicAttributes;
};
/**
* Defines the available comparison operators for rule conditions.
* These operators are used to compare values in rule definitions.
*
* @remarks
* - eq: Equal to
* - ne: Not equal to
* - gt: Greater than
* - gte: Greater than or equal to
* - lt: Less than
* - lte: Less than or equal to
* - in: Value exists in array
* - notIn: Value does not exist in array
*
* @example
* ```typescript
* const rule = {
* age: { [ComparisonOperators.gte]: 18 }
* };
* ```
*/
declare const ComparisonOperators$1: {
readonly eq: "eq";
readonly ne: "ne";
readonly gt: "gt";
readonly gte: "gte";
readonly lt: "lt";
readonly lte: "lte";
readonly in: "in";
readonly notIn: "notIn";
};
/**
* Union type of all available comparison operators.
* Extracted from the keys of ComparisonOperators constant.
*
* @see {@link ComparisonOperators} for the full list of operators
*/
type ComparisonOperator$1 = keyof typeof ComparisonOperators$1;
/**
* Represents the valid types that can be used as values in rule conditions.
*
* @remarks
* - string: For text comparisons
* - number: For numeric comparisons
* - boolean: For true/false conditions
* - Array<string | number>: For 'in' and 'notIn' operators
*
* @example
* ```typescript
* const stringValue: RuleValue = 'admin';
* const numberValue: RuleValue = 25;
* const boolValue: RuleValue = true;
* const arrayValue: RuleValue = ['user', 'admin'];
* ```
*/
type RuleValue = string | number | boolean | Array<string | number>;
/**
* Defines the structure of a filter that can be applied using comparison operators.
* Each key in the filter must be a valid comparison operator.
*
* @example
* ```typescript
* const ageFilter: BaseFilter = {
* gte: 18,
* lte: 65
* };
*
* const roleFilter: BaseFilter = {
* in: ['admin', 'moderator']
* };
* ```
*/
type BaseFilter = {
[K in ComparisonOperator$1]?: RuleValue;
};
/**
* Represents a single rule or a group of rules that can be combined using logical operators.
* Rules can be nested using 'and' and 'or' operators for complex conditions.
*
* @remarks
* - and: Array of rules that must all evaluate to true
* - or: Array of rules where at least one must evaluate to true
* - attributes: Object containing attribute-specific filters
*
* @example
* ```typescript
* const rule: Rule = {
* and: [
* { age: { gte: 18 } },
* {
* or: [
* { role: { eq: 'admin' } },
* { permissions: { in: ['manage_users'] } }
* ]
* }
* ]
* };
* ```
*/
type Rule = {
[key: string]: BaseFilter | Rule[] | {
[key: string]: BaseFilter;
} | undefined;
and?: Rule[];
or?: Rule[];
attributes?: {
[key: string]: BaseFilter;
};
};
/**
* Defines a set of rules for matching entities in a from/to relationship.
* Used to determine if entities can be connected or related to each other.
*
* @remarks
* - fromRules: Rules that must be satisfied by the source entity
* - toRules: Rules that must be satisfied by the target entity
*
* @example
* ```typescript
* const ruleSet: RuleSet = {
* fromRules: [{ role: { eq: 'admin' } }],
* toRules: [{ status: { eq: 'active' } }]
* };
* ```
*/
type RuleSet = {
fromRules: Rule[];
toRules: Rule[];
};
/**
* Configuration object for defining a complete rule-based matching setup.
* Contains metadata about the matching configuration along with its rules.
*
* @remarks
* - id: Unique identifier for the configuration
* - name: Display name for the configuration
* - description: Optional detailed description
* - ruleSet: The actual rules for matching
* - isActive: Whether this configuration is currently active
* - createdAt: Timestamp of creation
* - updatedAt: Timestamp of last update
*
* @example
* ```typescript
* const config: MatchingConfig = {
* id: 'config-123',
* name: 'Admin User Matching',
* description: 'Rules for admin user relationships',
* ruleSet: {
* fromRules: [...],
* toRules: [...]
* },
* isActive: true,
* createdAt: new Date(),
* updatedAt: new Date()
* };
* ```
*/
type MatchingConfig = {
id: string;
name: string;
description?: string;
ruleSet: RuleSet;
isActive: boolean;
createdAt: Date;
updatedAt: Date;
};
/**
* Custom error class for rule validation failures.
* Provides specific error messages for validation issues.
*
* @class RuleValidationError
* @extends Error
*
* @example
* ```typescript
* throw new RuleValidationError('Invalid operator type');
* // Error: "Rule validation failed: Invalid operator type"
* ```
*/
declare class RuleValidationError extends Error {
constructor(message: string);
}
/**
* Type assertion function to validate a rule structure.
* Ensures the rule matches the Rule type definition.
*
* @param {unknown} rule - The rule to validate
* @throws {RuleValidationError} If validation fails
*
* @remarks
* Validates:
* - Rule structure (must be an object)
* - AND/OR conditions (must be arrays)
* - Nested rules (recursive validation)
* - Filters (operator/value validation)
*
* @example
* ```typescript
* validateRule({
* and: [
* { role: { eq: 'admin' } },
* { status: { in: ['active', 'pending'] } }
* ]
* }) // valid
* ```
*/
declare function validateRule(rule: unknown): asserts rule is Rule;
/**
* Type assertion function to validate a rule set structure.
* Ensures the rule set contains valid from/to rules.
*
* @param {unknown} ruleSet - The rule set to validate
* @throws {RuleValidationError} If validation fails
*
* @remarks
* Validates:
* - Rule set structure (must be an object)
* - From rules (must be non-empty array)
* - To rules (must be non-empty array)
* - All rules in both arrays
*
* @example
* ```typescript
* validateRuleSet({
* fromRules: [{ role: { eq: 'admin' } }],
* toRules: [{ status: { eq: 'active' } }]
* }) // valid
* ```
*/
declare function validateRuleSet(ruleSet: unknown): asserts ruleSet is RuleSet;
/**
* Type assertion function to validate a matching configuration.
* Ensures the configuration contains all required fields with valid values.
*
* @param {unknown} config - The configuration to validate
* @throws {RuleValidationError} If validation fails
*
* @remarks
* Validates:
* - Configuration structure (must be an object)
* - Required fields (id, name, ruleSet, isActive, dates)
* - Optional fields (description)
* - Field types and constraints
* - Rule set validity
*
* @example
* ```typescript
* validateMatchingConfig({
* id: 'config-1',
* name: 'Admin Rules',
* ruleSet: {
* fromRules: [{ role: { eq: 'admin' } }],
* toRules: [{ status: { eq: 'active' } }]
* },
* isActive: true,
* createdAt: new Date(),
* updatedAt: new Date()
* }) // valid
* ```
*/
declare function validateMatchingConfig(config: unknown): asserts config is MatchingConfig;
type validation_RuleValidationError = RuleValidationError;
declare const validation_RuleValidationError: typeof RuleValidationError;
declare const validation_validateMatchingConfig: typeof validateMatchingConfig;
declare const validation_validateRule: typeof validateRule;
declare const validation_validateRuleSet: typeof validateRuleSet;
declare namespace validation {
export { validation_RuleValidationError as RuleValidationError, validation_validateMatchingConfig as validateMatchingConfig, validation_validateRule as validateRule, validation_validateRuleSet as validateRuleSet };
}
/**
* Interface defining the contract for rule evaluation implementations.
* Provides methods for evaluating entities against rules in various combinations.
*
* @interface RuleEvaluator
*/
interface RuleEvaluator {
/**
* Evaluates a single entity against a single rule.
* Core method for determining if an entity matches specific criteria.
*/
evaluateRule(entity: Entity, rule: Rule): boolean;
/**
* Evaluates multiple entities against a single rule efficiently.
* Optimized for batch processing of entities.
*/
evaluateRuleBatch(entities: Entity[], rule: Rule): boolean[];
/**
* Evaluates a single entity against multiple rules.
* Useful for checking if an entity matches any rule in a set.
*/
evaluateRules(entity: Entity, rules: Rule[]): boolean;
/**
* Clears any internal state or caches.
*/
clear(): void;
}
/**
* Configuration interface for the RuleEngine service.
*/
interface RuleEngineConfig {
evaluator?: RuleEvaluator;
maxBatchSize?: number;
}
/**
* Core service for evaluating and matching entities based on rule configurations.
* Provides methods for finding matching entities based on complex rule sets.
*/
declare class RuleEngine {
private readonly evaluator;
private readonly config;
constructor(config?: Partial<RuleEngineConfig>);
/**
* Finds entities that satisfy all provided 'from' rules.
*/
findMatchingFrom(entities: Entity[], rules: Rule[]): Entity[];
/**
* Finds target entities that can be matched with source entities based on 'to' rules.
*/
findMatchingTo(fromEntities: Entity[], toRules: Rule[], allEntities: Entity[]): Entity[];
/**
* Splits entities into optimal batch sizes based on complexity
*/
private getBatchSize;
/**
* Processes entities in optimally-sized batches
*/
private processBatch;
/**
* Processes a complete matching configuration to find both source and target entities.
*/
processConfig(config: MatchingConfig, entities: Entity[]): {
fromEntities: Entity[];
toEntities: Entity[];
};
}
/**
* Service class for managing and validating product attribute definitions.
* Provides a centralized registry for attribute metadata and validation.
*
* @class ProductAttributeRegistry
*
* @remarks
* This class handles:
* - Registration of attribute definitions
* - Attribute metadata storage
* - Validation of attribute values
* - Custom validation rules
*
* @example
* ```typescript
* const registry = new ProductAttributeRegistry();
*
* // Register an attribute
* registry.registerAttribute({
* name: 'price',
* type: AttributeType.NUMBER,
* description: 'Product price in cents',
* validation: {
* type: AttributeType.NUMBER,
* required: true,
* min: 0
* }
* });
*
* // Validate attributes
* await registry.validateAttributes({
* price: 1999,
* name: 'Product A'
* });
* ```
*/
declare class ProductAttributeRegistry {
private registry;
/**
* Registers a new attribute definition in the registry.
* Throws if an attribute with the same name already exists.
*
* @param {AttributeDefinition} definition - The attribute definition to register
* @throws {Error} If attribute name is already registered
*
* @remarks
* - Attribute names must be unique
* - Definition includes metadata and validation rules
* - Once registered, attributes can be used for validation
*
* @example
* ```typescript
* registry.registerAttribute({
* name: 'category',
* type: AttributeType.ENUM,
* description: 'Product category',
* validation: {
* type: AttributeType.ENUM,
* required: true,
* enum: ['electronics', 'clothing', 'books']
* }
* });
* ```
*/
registerAttribute(definition: AttributeDefinition): void;
/**
* Retrieves an attribute definition by its name.
* Returns undefined if the attribute is not found.
*
* @param {string} name - Name of the attribute to retrieve
* @returns {AttributeDefinition | undefined} The attribute definition or undefined
*
* @example
* ```typescript
* const priceDef = registry.getAttribute('price');
* if (priceDef) {
* console.log(`Price validation: ${JSON.stringify(priceDef.validation)}`);
* }
* ```
*/
getAttribute(name: string): AttributeDefinition | undefined;
/**
* Removes an attribute definition from the registry.
* Returns true if the attribute was found and removed.
*
* @param {string} name - Name of the attribute to remove
* @returns {boolean} True if attribute was removed, false if not found
*
* @example
* ```typescript
* if (registry.removeAttribute('oldField')) {
* console.log('Old field definition removed');
* }
* ```
*/
removeAttribute(name: string): boolean;
/**
* Returns an array of all registered attribute definitions.
* Useful for inspecting or iterating over all attributes.
*
* @returns {AttributeDefinition[]} Array of all attribute definitions
*
* @example
* ```typescript
* const allAttributes = registry.getAllAttributes();
* console.log(`Registered attributes: ${allAttributes.map(a => a.name).join(', ')}`);
* ```
*/
getAllAttributes(): AttributeDefinition[];
/**
* Validates a set of attributes against their registered definitions.
* Performs both basic and custom validations in the correct order.
*
* @param {Record<string, unknown>} attributes - Object containing attribute values
* @throws {Error} If validation fails or unknown attributes are found
*
* @remarks
* Validation process:
* 1. Checks for required attributes
* 2. Validates known attributes
* 3. Rejects unknown attributes
* 4. Runs basic validations first
* 5. Runs custom validations last
*
* @example
* ```typescript
* try {
* await registry.validateAttributes({
* price: 1999,
* category: 'electronics',
* inStock: true
* });
* console.log('Attributes are valid');
* } catch (error) {
* console.error('Validation failed:', error.message);
* }
* ```
*/
validateAttributes(attributes: Record<string, unknown>): Promise<void>;
/**
* Removes all attribute definitions from the registry.
* Useful when resetting the registry or changing attribute schemas.
*
* @example
* ```typescript
* // Clear existing definitions
* registry.clear();
*
* // Register new definitions
* registry.registerAttribute(newDefinition);
* ```
*/
clear(): void;
}
/**
* Custom error class for attribute validation failures.
* Provides detailed error messages with attribute context.
*
* @class AttributeValidationError
* @extends Error
*
* @property {string} attributeName - Name of the attribute that failed validation
*
* @example
* ```typescript
* throw new AttributeValidationError('price', 'Value must be positive');
* // Error: "Validation failed for attribute "price": Value must be positive"
* ```
*/
declare class AttributeValidationError extends Error {
readonly attributeName: string;
constructor(attributeName: string, message: string);
}
/**
* Validates a single attribute value against its definition and validation rules.
* Performs type checking and rule-specific validations.
*
* @param {string} name - Name of the attribute being validated
* @param {unknown} value - Value to validate
* @param {AttributeDefinition} definition - Attribute definition containing validation rules
* @param {Record<string, unknown>} [allAttributes] - Optional object containing all attributes
* @throws {AttributeValidationError} If validation fails
*
* @remarks
* Validation process:
* 1. Checks if value is required
* 2. Runs custom validation if provided
* 3. Performs type validation
* 4. Runs type-specific validations
*
* @example
* ```typescript
* const definition: AttributeDefinition = {
* name: 'price',
* type: AttributeType.NUMBER,
* description: 'Product price',
* validation: {
* type: AttributeType.NUMBER,
* required: true,
* min: 0
* }
* };
*
* await validateAttribute('price', 100, definition);
* ```
*/
declare function validateAttribute(name: string, value: unknown, definition: AttributeDefinition, allAttributes?: Record<string, unknown>): Promise<void>;
/**
* Base implementation of the RuleEvaluator interface providing core rule evaluation logic.
* This class implements fundamental rule matching capabilities without caching or optimization.
*
* @class BaseRuleEvaluator
* @implements {RuleEvaluator}
*/
declare class BaseRuleEvaluator implements RuleEvaluator {
private static readonly validOperators;
/**
* Evaluates if a single entity matches the given rule.
* Handles complex rule structures including nested AND/OR conditions.
*/
evaluateRule(entity: Entity, rule: Rule): boolean;
/**
* Efficiently evaluates multiple entities against a single rule.
*/
evaluateRuleBatch(entities: Entity[], rule: Rule): boolean[];
/**
* Evaluates if an entity matches any rule from a set of rules.
*/
evaluateRules(entity: Entity, rules: Rule[]): boolean;
/**
* Clears any internal caches or state.
* Base implementation is a no-op as it maintains no state.
*/
clear(): void;
/**
* Internal method to evaluate a filter against a value.
*/
private evaluateFilter;
/**
* Internal method to evaluate a single comparison operator.
*/
private evaluateOperator;
}
/**
* Core interface component types for RuleKit.
* These types are interface-agnostic and can be used across different rendering contexts.
*/
/**
* Available component types that can be rendered in any interface.
*/
declare const ComponentType: {
readonly INPUT: "input";
readonly CHOICE: "choice";
readonly MULTI: "multi";
readonly RANGE: "range";
};
type ComponentTypeValue = (typeof ComponentType)[keyof typeof ComponentType];
/**
* Base constraints that can be applied to any component.
*/
type ComponentConstraints = {
required?: boolean;
min?: number;
max?: number;
pattern?: string;
step?: number;
};
/**
* Base component interface that all specific components extend.
*/
type BaseComponent<T = unknown> = {
type: ComponentTypeValue;
value: T;
identifier: string;
constraints?: ComponentConstraints;
metadata?: Record<string, unknown>;
};
/**
* Component for selecting from predefined options.
*/
type ChoiceComponent = BaseComponent<string> & {
type: typeof ComponentType.CHOICE;
options: Array<{
identifier: string;
value: string;
metadata?: {
count?: number;
percentage?: number;
};
}>;
};
/**
* Component for free-form input with optional format constraints.
*/
type InputComponent = BaseComponent<string> & {
type: typeof ComponentType.INPUT;
format?: 'text' | 'number' | 'date';
};
/**
* Component for selecting multiple values from predefined options.
*/
type MultiComponent = BaseComponent<string[]> & {
type: typeof ComponentType.MULTI;
options: Array<{
identifier: string;
value: string;
metadata?: {
count?: number;
percentage?: number;
};
}>;
};
/**
* Component for selecting a value within a numeric range.
*/
type RangeComponent = BaseComponent<number> & {
type: typeof ComponentType.RANGE;
constraints: {
min: number;
max: number;
step?: number;
};
};
/**
* Union type of all available component types.
*/
type Component = ChoiceComponent | InputComponent | MultiComponent | RangeComponent;
/**
* Error thrown when component validation fails.
*/
declare class ComponentError extends Error {
constructor(message: string);
}
/**
* Extended comparison operators for interface components.
* These operators are only used within the interface components and converters,
* and do not affect the core ComparisonOperators.
*/
declare const InterfaceOperators: {
readonly between: "between";
readonly exists: "exists";
readonly eq: "eq";
readonly ne: "ne";
readonly gt: "gt";
readonly gte: "gte";
readonly lt: "lt";
readonly lte: "lte";
readonly in: "in";
readonly notIn: "notIn";
};
/**
* Base interface for all component adapters.
* Adapters are responsible for converting our interface-agnostic components
* into interface-specific implementations.
*/
interface ComponentAdapter<T = unknown> {
/**
* Convert a component to its interface-specific representation
*/
adapt(component: Component): T;
/**
* Extract a value from an interface-specific representation
*/
extractValue(adapted: T): unknown;
/**
* Validate a value against a component's constraints
*/
validate(value: unknown, component: Component): boolean;
}
/**
* Error thrown when component adaptation fails
*/
declare class AdapterError extends Error {
constructor(message: string);
}
/**
* Base class for implementing component adapters
*/
declare abstract class BaseComponentAdapter<T = unknown> implements ComponentAdapter<T> {
/**
* Convert a component to its interface-specific representation
*/
abstract adapt(component: Component): T;
/**
* Extract a value from an interface-specific representation
*/
abstract extractValue(adapted: T): unknown;
/**
* Default validation implementation that can be extended
*/
validate(value: unknown, component: Component): boolean;
/**
* Helper method to ensure a component is of a specific type
*/
protected ensureType<T extends Component>(component: Component, type: T['type'], methodName: string): asserts component is T;
}
/**
* Error thrown when rule conversion fails
*/
declare class RuleConversionError extends Error {
constructor(message: string);
}
/**
* Converts interface-agnostic components to RuleKit rule format
*/
declare class RuleConverter {
/**
* Convert a component's value to a rule filter
*/
convertComponentToFilter(component: Component): BaseFilter;
/**
* Convert a range component to a filter
*/
private convertRangeComponent;
/**
* Convert a choice component to a filter
*/
private convertChoiceComponent;
/**
* Convert a multi-select component to a filter
*/
private convertMultiComponent;
/**
* Convert an input component to a filter
*/
private convertInputComponent;
/**
* Convert a set of components to a complete rule
*/
convertComponentsToRule(components: Array<{
field: string;
component: Component;
}>): Rule;
}
/**
* Types for the data analysis system that helps generate appropriate components
* based on input data characteristics.
*/
/**
* Supported data types for analysis
*/
declare const DataType: {
readonly NUMBER: "number";
readonly STRING: "string";
readonly BOOLEAN: "boolean";
readonly DATE: "date";
};
type DataTypeValue = (typeof DataType)[keyof typeof DataType];
/**
* Statistical information about numeric data
*/
type NumericStatistics = {
min: number;
max: number;
average: number;
median: number;
standardDeviation: number;
};
/**
* Statistical information about categorical data
*/
type CategoryStatistics = {
categories: Array<{
value: string;
count: number;
percentage: number;
}>;
};
/**
* Combined statistics for a field
*/
type FieldStatistics = {
count: number;
uniqueValues: number;
nullCount: number;
numeric?: NumericStatistics;
categorical?: CategoryStatistics;
};
/**
* Complete analysis for a single field
*/
type FieldAnalysis = {
fieldName: string;
dataType: DataTypeValue;
statistics: FieldStatistics;
suggestedComponent: Component;
};
/**
* Analysis results for all fields in a dataset
*/
type DataAnalysis = Record<string, FieldAnalysis>;
/**
* Configuration options for the analyzer
*/
type AnalyzerOptions = {
/**
* Maximum number of unique values before suggesting a range/input
* instead of a choice component
*/
maxChoiceOptions?: number;
/**
* Whether to include detailed statistics in the metadata
*/
includeDetailedStats?: boolean;
/**
* Custom rules for suggesting components
*/
componentSuggestionRules?: Array<{
condition: (analysis: FieldAnalysis) => boolean;
suggest: (analysis: FieldAnalysis) => Component;
}>;
};
/**
* Error thrown when data analysis fails
*/
declare class AnalysisError extends Error {
constructor(message: string);
}
/**
* Analyzes data to generate appropriate interface components and statistics.
*/
declare class DataAnalyzer {
private options;
constructor(options?: AnalyzerOptions);
/**
* Analyzes an array of data objects to generate field analyses and component suggestions.
*/
analyze(data: Array<Record<string, unknown>>): DataAnalysis;
/**
* Extracts unique field names from the data.
*/
private extractFields;
/**
* Detects the data type of a field based on its values.
*/
private detectDataType;
/**
* Calculates statistics for a field based on its values and data type.
*/
private calculateStatistics;
/**
* Calculates numeric statistics for number fields.
*/
private calculateNumericStatistics;
/**
* Calculates category statistics for string/boolean fields.
*/
private calculateCategoryStatistics;
/**
* Suggests an appropriate component based on field analysis.
*/
private suggestComponent;
/**
* Suggests a component for numeric fields.
*/
private suggestNumericComponent;
/**
* Suggests a component for boolean fields.
*/
private suggestBooleanComponent;
/**
* Suggests a component for date fields.
*/
private suggestDateComponent;
/**
* Suggests a component for string fields.
*/
private suggestStringComponent;
/**
* Suggests a component for array fields.
*/
private suggestMultiComponent;
/**
* Calculates an appropriate step value for range components.
*/
private calculateStep;
}
/**
* Defines the available condition types for UI rule configuration.
* These types represent different ways to compare values in the UI.
*/
declare const UIConditionType: {
readonly IS: "Is";
readonly IS_NOT: "IsNot";
readonly CONTAINS: "Contains";
readonly DOES_NOT_CONTAIN: "DoesNotContain";
readonly IN: "In";
};
type UIConditionTypeValue = (typeof UIConditionType)[keyof typeof UIConditionType];
/**
* Defines the available UI component types for rendering rule conditions.
*/
declare const UIComponentType: {
readonly SELECT: "select";
readonly TEXT: "text";
readonly OPTIONS: "options";
readonly MULTISELECTOR: "MULTISELECTOR";
};
type UIComponentTypeValue = (typeof UIComponentType)[keyof typeof UIComponentType];
/**
* Represents a single condition configuration for UI rendering.
*/
type UICondition = {
condition: UIConditionTypeValue;
min?: number | string | null;
max?: number | string | null;
type: UIComponentTypeValue;
component?: UIComponentTypeValue;
};
/**
* Defines a named filter with associated conditions for UI rendering.
*/
type UIFilter = {
name: string;
meta?: Record<string, unknown>;
conditions: UICondition[];
};
/**
* Represents a rule for matching entities with specific conditions.
*/
type UIMatchingRule = {
name: string;
conditions: UICondition[];
values?: string[];
};
/**
* Defines the complete UI configuration structure for rule-based matching.
*/
type UIRuleConfiguration = {
filters?: UIFilter[];
matchingFrom?: UIMatchingRule[];
matchingTo?: UIMatchingRule[];
source?: UIMatchingRule[];
recommendations?: UIMatchingRule[];
};
/**
* Custom error class for UI configuration validation failures.
*/
declare class UIConfigurationError extends Error {
constructor(message: string);
}
/**
* Converts a complete UI configuration to internal rule format.
* Processes all rule types and combines them into from/to rule sets.
*
* @param {UIRuleConfiguration} config - The UI configuration to convert
* @returns {{ fromRules: Rule[]; toRules: Rule[] }} Converted rule sets
*
* @remarks
* Processes multiple rule types:
* - Filters (added to fromRules)
* - Matching From rules
* - Matching To rules
* - Legacy source rules (added to fromRules)
* - Legacy recommendation rules (added to toRules)
*
* @example
* ```typescript
* const config: UIRuleConfiguration = {
* filters: [{
* name: 'price',
* conditions: [{ type: UIComponentType.TEXT, condition: UIConditionType.IS, max: 100 }]
* }],
* matchingFrom: [{
* name: 'role',
* conditions: [{ type: UIComponentType.SELECT, condition: UIConditionType.IS }],
* values: ['admin']
* }]
* };
* const { fromRules, toRules } = convertUIConfigurationToRules(config);
* ```
*/
declare function convertUIConfigurationToRules(config: UIRuleConfiguration): {
fromRules: Rule[];
toRules: Rule[];
};
/**
* Validates a UI configuration for correctness and completeness.
* Checks all required fields and relationships between rules.
*
* @param {UIRuleConfiguration} config - The configuration to validate
* @throws {UIConfigurationError} If validation fails
*
* @remarks
* Validates:
* - Presence of at least one rule type
* - Filter names and conditions
* - Matching rule names, conditions, and values
* - Legacy rule formats
*
* @example
* ```typescript
* const config: UIRuleConfiguration = {
* filters: [{
* name: 'price',
* conditions: [{ type: UIComponentType.TEXT, condition: UIConditionType.IS, max: 100 }]
* }]
* };
*
* try {
* validateUIConfiguration(config);
* console.log('Configuration is valid');
* } catch (error) {
* if (error instanceof UIConfigurationError) {
* console.error('Invalid configuration:', error.message);
* }
* }
* ```
*/
declare function validateUIConfiguration(config: UIRuleConfiguration): void;
/**
* @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;
};
/**
* 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 Filter<T extends AttributeTypeValue, TArrayType extends AttributeTypeValue | undefined = undefined> = {
[K in ComparisonOperator]?: K extends 'in' | 'notIn' ? T extends typeof AttributeType.ARRAY ? TArrayType extends AttributeTypeValue ? Array<ExtractAttributeValue<TArrayType>> : unknown[] : Array<ExtractAttributeValue<T>> : ExtractAttributeValue<T, TArrayType>;
};
/**
* 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>;
/**
* Legacy v2 namespace exports
* @deprecated Use latest v3 exports instead
* @packageDocumentation
*/
declare const v2: {
ruleEngine: typeof RuleEngine;
validation: typeof validation;
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";
};
};
export { AdapterError, AnalysisError, type AnalyzerOptions, type AttributeDefinition, type AttributeRegistry, type AttributeSchema, AttributeType, type AttributeTypeValue, AttributeValidationError, type AttributeValue, type Attributes, type BaseComponent, BaseComponentAdapter, type BaseFilter, BaseRuleEvaluator, type CategoryStatistics, type ChoiceComponent, type ComparisonOperator$1 as ComparisonOperator, ComparisonOperators$1 as ComparisonOperators, type Component, type ComponentAdapter, type ComponentConstraints, ComponentError, ComponentType, type ComponentTypeValue, type DataAnalysis, DataAnalyzer, DataType, type DataTypeValue, type DynamicAttributes, type Entity, type ExtractAttributeValue, type ExtractSchemaValue, type FieldAnalysis, type FieldStatistics, type Filter, type InputComponent, InterfaceOperators, type MatchingConfig, type MultiComponent, type NumericStatistics, ProductAttributeRegistry, type RangeComponent, type Rule, RuleConversionError, RuleConverter, RuleEngine, type RuleEvaluator, type RuleSet, RuleValidationError, type RuleValue, UIComponentType, type UIComponentTypeValue, type UICondition, UIConditionType, type UIConditionTypeValue, UIConfigurationError, type UIFilter, type UIMatchingRule, type UIRuleConfiguration, type ValidationRule$1 as ValidationRule, convertUIConfigurationToRules, isValidAttributeValue, isValidSchemaObject, v2, validateAttribute, validateMatchingConfig, validateRule, validateRuleSet, validateUIConfiguration };