Complete API documentation for @usex/rule-engine.
The main class for rule evaluation and management.
new RuleEngine(options?: RuleEngineOptions)| Property | Type | Default | Description |
|---|---|---|---|
logger |
Logger |
console |
Custom logger implementation |
cache |
boolean |
true |
Enable/disable mutation caching |
mutations |
Map<string, MutationFunction> |
new Map() |
Initial mutations |
Evaluates a rule against criteria.
async evaluate<R = any>(
rule: RuleType<R>,
criteria: any | any[],
trustRule?: boolean
): Promise<EvaluationResult<R> | EvaluationResult<R>[]>Parameters:
rule: The rule to evaluatecriteria: Single object or array of objects to evaluate againsttrustRule: Skip rule validation if true (default: false)
Returns:
- Single
EvaluationResultfor single criteria - Array of
EvaluationResultfor array criteria
Example:
const engine = new RuleEngine();
const result = await engine.evaluate(rule, { age: 25 });
// { value: true, isPassed: true }Simple boolean check if rule passes.
async checkIsPassed(
rule: RuleType<any>,
criteria: any | any[],
trustRule?: boolean
): Promise<boolean>Parameters:
- Same as
evaluate
Returns:
trueif rule passes,falseotherwise
Example:
const passed = await engine.checkIsPassed(rule, { age: 25 });
// trueGet only result values without evaluation metadata.
async getEvaluateResult<R = any>(
rule: RuleType<R>,
criteria: any | any[],
trustRule?: boolean
): Promise<R | R[]>Parameters:
- Same as
evaluate
Returns:
- Result value(s) only, without
isPassedflag
Example:
const result = await engine.getEvaluateResult(rule, data);
// { discount: 0.15, message: "15% off" }Evaluate multiple rules against same criteria.
async evaluateMany<R = any>(
rules: RuleType<R>[],
criteria: any,
trustRule?: boolean
): Promise<EvaluationResult<R>[]>Parameters:
rules: Array of rules to evaluatecriteria: Single criteria objecttrustRule: Skip validation for all rules
Returns:
- Array of evaluation results
Example:
const results = await engine.evaluateMany([rule1, rule2], data);
// [{ value: true, isPassed: true }, { value: false, isPassed: false }]Validates rule structure.
validate(rule: RuleType<any>): ValidationResultParameters:
rule: Rule to validate
Returns:
interface ValidationResult {
isValid: boolean;
error?: {
message: string;
path?: string;
details?: any;
};
}Example:
const validation = engine.validate(rule);
if (!validation.isValid) {
console.error(validation.error.message);
}Analyzes rule for possible input ranges.
introspect(rule: RuleType<any>): IntrospectionResultParameters:
rule: Rule to analyze
Returns:
interface IntrospectionResult {
possibleCriteria: any[];
fields: string[];
operators: string[];
constraints: ConstraintInfo[];
}Example:
const analysis = engine.introspect(rule);
console.log(analysis.fields); // ["age", "country"]Get a new rule builder instance.
builder(): RuleBuilderReturns:
- New
RuleBuilderinstance
Example:
const builder = engine.builder();
const rule = builder
.add({ and: [...] })
.default({ value: false })
.build();Add a criteria preprocessor.
addMutation(name: string, fn: MutationFunction): voidParameters:
name: Unique mutation namefn: Function that transforms criteria
Example:
engine.addMutation('normalize', (criteria) => {
if (criteria.email) {
criteria.email = criteria.email.toLowerCase();
}
return criteria;
});Remove a mutation by name.
removeMutation(name: string): booleanParameters:
name: Mutation name to remove
Returns:
trueif removed,falseif not found
Clear mutation result cache.
clearMutationCache(name?: string): voidParameters:
name: Optional specific mutation to clear (clears all if omitted)
All instance methods are available as static methods on the RuleEngine class:
RuleEngine.evaluate(rule, criteria, trustRule?)
RuleEngine.checkIsPassed(rule, criteria, trustRule?)
RuleEngine.getEvaluateResult(rule, criteria, trustRule?)
RuleEngine.evaluateMany(rules, criteria, trustRule?)
RuleEngine.validate(rule)
RuleEngine.introspect(rule)
RuleEngine.builder()Utilities for working with objects and JSONPath expressions.
Resolves a property value from an object using path or JSONPath.
static resolveProperty(
path: string,
json: any
): anyParameters:
path: Property path or JSONPath expressionjson: Object to resolve from
Returns:
- Resolved value or undefined
Example:
const value = ObjectDiscovery.resolveProperty("$.user.profile.age", data);
// 25Updates a property value in an object.
static updateProperty(
path: string,
json: any,
value: any
): voidParameters:
path: Property path or JSONPath expressionjson: Object to updatevalue: New value to set
Example:
ObjectDiscovery.updateProperty("$.user.age", data, 26);Resolves JSONPath expressions in template strings.
static resolveTextPathExpressions(
text: string,
criteria: any
): stringParameters:
text: Template string with JSONPath expressionscriteria: Data object for resolution
Returns:
- Resolved string
Example:
const result = ObjectDiscovery.resolveTextPathExpressions(
"Hello $.user.name, you have $.points points",
{ user: { name: "John" }, points: 100 }
);
// "Hello John, you have 100 points"Check if object is a valid condition.
static isCondition(obj: any): obj is ConditionExample:
if (ObjectDiscovery.isCondition(obj)) {
// obj is typed as Condition
}Check if object is a valid constraint.
static isConstraint(obj: any): obj is ConstraintExample:
if (ObjectDiscovery.isConstraint(obj)) {
// obj is typed as Constraint
}Check if rule has result values.
static isGranular(rule: RuleType<any>): booleanExample:
if (ObjectDiscovery.isGranular(rule)) {
// Rule has result values in conditions
}Fluent API for constructing rules programmatically.
Add a condition to the rule.
add(condition: Condition<R>): RuleBuilder<R>Example:
builder.add({
and: [
{ field: "age", operator: "greater-than", value: 18 }
],
result: { allowed: true }
})Set default result.
default(result: R): RuleBuilder<R>Example:
builder.default({ allowed: false })Build the final rule.
build(validate?: boolean): RuleType<R>Parameters:
validate: Validate rule before returning (default: false)
Returns:
- Complete rule object
Example:
const rule = builder.build(true); // Validates before returningconst rule = RuleEngine.builder()
.add({
and: [
{ field: "age", operator: "greater-than", value: 21 },
{ field: "country", operator: "equals", value: "US" }
],
result: { canDrink: true }
})
.add({
and: [
{ field: "age", operator: "greater-than", value: 18 },
{ field: "country", operator: "not-equals", value: "US" }
],
result: { canDrink: true }
})
.default({ canDrink: false })
.build(true);Main rule structure.
interface RuleType<R = any> {
conditions: Condition<R> | Condition<R>[];
default?: R;
}Logical grouping of constraints.
interface Condition<R = any> {
or?: Array<Constraint | Condition<R>>;
and?: Array<Constraint | Condition<R>>;
none?: Array<Constraint | Condition<R>>;
result?: R;
}Basic evaluation unit.
interface Constraint {
field: string;
operator: string;
value: any;
message?: string;
}Result of rule evaluation.
interface EvaluationResult<T = any> {
value: T;
isPassed: boolean;
message?: string;
}Result of rule validation.
interface ValidationResult {
isValid: boolean;
error?: {
message: string;
path?: string;
details?: any;
};
}Result of rule introspection.
interface IntrospectionResult {
possibleCriteria: any[];
fields: string[];
operators: string[];
constraints: Array<{
field: string;
operator: string;
value: any;
path: string;
}>;
}enum ConditionType {
Or = "or",
And = "and",
None = "none"
}See Operators Documentation for complete list.
class RuleEngineError extends Error {
constructor(message: string, public code?: string, public details?: any)
}// Parse various date formats
parseDate(value: any): Date
// Format date to ISO string
formatDate(date: Date): string
// Check if valid date
isValidDate(value: any): boolean// Check if value is object
isObject(value: any): boolean
// Check if value is empty
isEmpty(value: any): boolean
// Deep clone object
deepClone<T>(obj: T): TFor more information, see the main documentation.