New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@ivandt/json-rules

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ivandt/json-rules

Rule parsing engine for JSON rules

latest
Source
npmnpm
Version
2.2.0
Version published
Maintainers
1
Created
Source

npm version

StatementsFunctionsLines
StatementsFunctionsLines

JsonRules Engine

A rule engine for JavaScript & TypeScript

Define business logic with JSON rules

TypeScript npm

Overview

JsonRules is a rule engine that allows you to define business logic as JSON and evaluate it against data. It provides a simple way to externalize decision-making logic from your application code.

Use Cases

  • E-commerce: Pricing rules, discount eligibility, shipping calculations
  • User Management: Access control, feature flags, user segmentation
  • Content: Filtering, moderation, recommendations
  • Workflows: Approval processes, notifications
  • Configuration: A/B testing, feature rollouts

Features

  • Type-safe with full TypeScript support
  • 40+ built-in operators for common operations
  • Support for complex nested conditions
  • Template variables for dynamic rules
  • Validation for rule structure and syntax
  • Works in Node.js and browsers

Installation

npm install @ivandt/json-rules

Dependencies

This library has one dependency:

  • validator - Used for advanced validation operators (email, URL, phone numbers, etc.)

Quick Start

import { JsonRules, Rule } from "@ivandt/json-rules";

// Define a rule
const rule: Rule = {
  conditions: {
    all: [
      { field: "age", operator: "is greater than or equal", value: 18 },
      { field: "country", operator: "is equal", value: "US" }
    ]
  }
};

// Evaluate against data
const user = { age: 25, country: "US" };
const result = JsonRules.evaluate(rule, user);
console.log(result); // true

Operators

JsonRules provides operators for common data operations:

Equality & Comparison

OperatorDescriptionAcceptsExample
is equalEqual tostring | number | boolean | Date | null{ field: "status", operator: "is equal", value: "active" }
is not equalNot equal tostring | number | boolean | Date | null{ field: "status", operator: "is not equal", value: "banned" }
is greater thanGreater than comparisonstring | number | Date{ field: "age", operator: "is greater than", value: 18 }
is less thanLess than comparisonstring | number | Date{ field: "price", operator: "is less than", value: 100 }
is greater than or equalGreater than or equalstring | number | Date{ field: "score", operator: "is greater than or equal", value: 80 }
is less than or equalLess than or equalstring | number | Date{ field: "items", operator: "is less than or equal", value: 10 }

Range & Between

OperatorDescriptionAcceptsExample
is between numbersNumber within range (inclusive)[number, number]{ field: "age", operator: "is between numbers", value: [18, 65] }
is not between numbersNumber outside range[number, number]{ field: "temperature", operator: "is not between numbers", value: [32, 100] }
is between datesDate within range (inclusive)[Date, Date]{ field: "eventDate", operator: "is between dates", value: [startDate, endDate] }
is not between datesDate outside range[Date, Date]{ field: "blackoutDate", operator: "is not between dates", value: [holiday1, holiday2] }

Collection & Array

OperatorDescriptionAcceptsExample
inValue exists in array(string | number | boolean | object | null)[]{ field: "country", operator: "in", value: ["US", "CA", "UK"] }
not inValue not in array(string | number | boolean | object | null)[]{ field: "status", operator: "not in", value: ["banned", "suspended"] }
array containsArray field contains valuestring | number | boolean | object | null{ field: "skills", operator: "array contains", value: "javascript" }
array no containsArray field doesn't contain valuestring | number | boolean | object | null{ field: "permissions", operator: "array no contains", value: "admin" }

String Operations

OperatorDescriptionAcceptsExample
containsString contains substringstring{ field: "email", operator: "contains", value: "@company.com" }
not containsString doesn't contain substringstring{ field: "message", operator: "not contains", value: "spam" }
contains anyString contains any substringstring[]{ field: "title", operator: "contains any", value: ["urgent", "critical"] }
not contains anyString contains none of substringsstring[]{ field: "content", operator: "not contains any", value: ["spam", "scam"] }
starts withString starts with prefixstring{ field: "productCode", operator: "starts with", value: "PRD-" }
ends withString ends with suffixstring{ field: "filename", operator: "ends with", value: ".pdf" }

Pattern Matching

OperatorDescriptionAcceptsExample
matchesMatches regex pattern{ regex: string, flags?: string }{ field: "email", operator: "matches", value: { regex: "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$" } }
not matchesDoesn't match regex pattern{ regex: string, flags?: string }{ field: "username", operator: "not matches", value: { regex: "^(admin|root)$", flags: "i" } }

Date Operations

OperatorDescriptionAcceptsExample
is beforeDate is before specified datestring | number | Date{ field: "expiry", operator: "is before", value: new Date('2024-12-31') }
is afterDate is after specified datestring | number | Date{ field: "startDate", operator: "is after", value: new Date('2024-01-01') }
is on or beforeDate is on or before specified datestring | number | Date{ field: "deadline", operator: "is on or before", value: new Date() }
is on or afterDate is on or after specified datestring | number | Date{ field: "validFrom", operator: "is on or after", value: new Date() }

Math & Number Validation

OperatorDescriptionAcceptsExample
is evenNumber is evennone{ field: "quantity", operator: "is even" }
is oddNumber is oddnone{ field: "productId", operator: "is odd" }
is positiveNumber is positive (> 0)none{ field: "balance", operator: "is positive" }
is negativeNumber is negative (< 0)none{ field: "adjustment", operator: "is negative" }
is emptyValue is null, undefined, or empty string/arraynone{ field: "optionalField", operator: "is empty" }
is not emptyValue is not emptynone{ field: "requiredField", operator: "is not empty" }

Data Validation

OperatorDescriptionAcceptsExample
is valid emailValid email addressEmailValidationConfig (optional){ field: "email", operator: "is valid email" }
is valid phoneValid phone numberPhoneValidationConfig{ field: "phone", operator: "is valid phone", value: { locale: "us" } }
is URLValid URLURLValidationConfig{ field: "website", operator: "is URL", value: { requireTld: false } }
is UUIDValid UUIDUUIDValidationConfig{ field: "id", operator: "is UUID", value: { version: 4 } }
is EANValid EAN barcodenone{ field: "barcode", operator: "is EAN" }
is IMEIValid IMEI numberIMEIValidationConfig{ field: "deviceId", operator: "is IMEI", value: { allowHyphens: true } }
is unitValid unit of measurementUnitType{ field: "distance", operator: "is unit", value: "length" }
is countryValid country identifierCountryValidationConfig{ field: "country", operator: "is country", value: { format: "iso2" } }
is domainValid domain nameDomainValidationConfig{ field: "domain", operator: "is domain", value: { requireTld: true } }

Rule Structure

Basic Rule

interface Rule {
  conditions: Condition | Condition[];
  default?: any;
}

Conditions

Rules support three logical operators:

TypeLogicDescription
allANDAll constraints must be true
anyORAt least one constraint must be true
noneNOTNo constraints should be true

Constraints

{
  field: string,           // Property path (supports dot notation)
  operator: string,        // Comparison operator
  value: any              // Expected value or template reference
}

Examples

Basic Example

const rule: Rule = {
  conditions: {
    all: [
      { field: "age", operator: "is greater than or equal", value: 21 },
      { field: "country", operator: "in", value: ["US", "CA"] }
    ]
  }
};

const user = { age: 25, country: "US" };
const result = JsonRules.evaluate(rule, user); // true

Complex Conditions

const complexRule: Rule = {
  conditions: {
    any: [
      {
        all: [
          { field: "membershipTier", operator: "is equal", value: "premium" },
          { field: "accountAge", operator: "is greater than", value: 365 }
        ]
      },
      {
        all: [
          { field: "totalSpent", operator: "is greater than", value: 1000 },
          { field: "lastPurchase", operator: "is after", value: new Date('2024-01-01') }
        ]
      }
    ]
  }
};

Validation Operators

const validationRule: Rule = {
  conditions: {
    all: [
      { field: "email", operator: "is valid email", value: null },
      { field: "phone", operator: "is valid phone", value: { locale: "us" } },
      { field: "website", operator: "is URL", value: { protocols: ["https"] } }
    ]
  }
};

Template Variables

const dynamicRule: Rule = {
  conditions: {
    all: [
      { field: "endDate", operator: "is after", value: "{startDate}" },
      { field: "price", operator: "is less than", value: "{maxBudget}" }
    ]
  }
};

API Reference

JsonRules.evaluate()

static evaluate<T>(
  rule: Rule, 
  criteria: object | object[], 
  trustRule?: boolean
): T | boolean

JsonRules.validate()

static validate(rule: Rule): ValidationResult

ValidationResult

interface ValidationResult {
  isValid: boolean;
  error?: ValidationError;
}

Phone Number Validation

To use phone validation, import the specific locale validators:

// Import specific locales
import "@ivandt/json-rules/validators/phone/us";
import "@ivandt/json-rules/validators/phone/gb";
import "@ivandt/json-rules/validators/phone/de";

const rule: Rule = {
  conditions: {
    all: [
      { field: "phone", operator: "is valid phone", value: { locale: "us" } }
    ]
  }
};

Contributing

  • Fork the repository
  • Create a feature branch: git checkout -b feature/new-feature
  • Make your changes with tests
  • Run the test suite: npm test
  • Submit a pull request

License

MIT License - see LICENSE file for details.

Keywords

rules

FAQs

Package last updated on 24 Sep 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts