npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@astralibx/rule-engine

v1.0.2

Published

Platform-agnostic rule engine with templates, conditions, collection schemas, and join support

Readme

@astralibx/rule-engine

Platform-agnostic rule engine for targeting, template rendering, throttling, and send orchestration across any channel.

Features

  • Factory function returns routes, services, and models in a single call
  • Adapter-based dependency injection — your app controls user queries, data resolution, and delivery
  • Handlebars templates with multi-variant subjects and bodies (A/B rotation)
  • Templates own their data source via collectionName and joins
  • Per-user throttling with daily/weekly caps, cooldown, and deduplication via Redis
  • Distributed run locking to prevent overlapping scheduler executions
  • query targeting (conditions on user fields) and list targeting (explicit identifiers)
  • Cron scheduling per rule with timezone support
  • Full lifecycle hooks: onRunStart, onRuleStart, onSend, beforeSend, onRunComplete
  • Platform wrappers (@astralibx/email-rule-engine, @astralibx/telegram-rule-engine) add rendering on top

Architecture

Consumer App
     │
     ▼
createRuleEngine(config)
     │
     ├─── routes    →  Express Router (mount anywhere)
     ├─── services  →  { template, rule, runner }
     └─── models    →  { Template, Rule, SendLog, RunLog, ErrorLog, ThrottleConfig }

config.adapters
     ├─── queryUsers(target, limit, ctx)     →  fetch matching users from your DB
     ├─── resolveData(user)                  →  map user to Handlebars context
     ├─── send(params)                       →  deliver the rendered message
     ├─── selectAgent(identifierId, ctx)     →  pick a sending account
     └─── findIdentifier(contactValue)       →  resolve contact to RecipientIdentifier

config.collections   →  CollectionSchema[] describing joins available to templates
config.platforms     →  string[] used for enum validation on templates and rules
config.options       →  sendWindow, throttle defaults, jitter, delay between sends
config.hooks         →  lifecycle callbacks (no library internals modified)

Design Principles

  • Factory patterncreateRuleEngine(config) returns everything; no global singletons or static state.
  • Adapter-based DI — five adapter functions decouple the engine from your user model, data layer, and transport.
  • Templates own their data source — each template declares collectionName and joins; the engine resolves data automatically at run time.
  • Shared collections with platform field — one MongoDB connection serves all platforms; platform on every document namespaces the data.
  • Zero business logic — the engine handles infrastructure (throttling, locking, scheduling, logging); adapters define what gets sent to whom.
  • Production-safe defaults — send windows, jitter, per-run caps, and Redis locking are on by default to prevent runaway sends.

Quick Start

import express from 'express';
import mongoose from 'mongoose';
import Redis from 'ioredis';
import { createRuleEngine } from '@astralibx/rule-engine';

const app = express();
app.use(express.json());

const db = mongoose.createConnection('mongodb://localhost:27017/myapp');
const redis = new Redis();

const engine = createRuleEngine({
  db: { connection: db, collectionPrefix: 'myapp_' },
  redis: { connection: redis, keyPrefix: 'myapp:re:' },

  platforms: ['email', 'telegram'],
  audiences: ['users', 'admins'],
  categories: ['onboarding', 'marketing'],

  adapters: {
    queryUsers: async (target, limit, ctx) => {
      // Use target.mode === 'query' for condition-based or 'list' for explicit ids
      return db.collection('users').find({}).limit(limit).toArray();
    },
    resolveData: (user) => ({
      user: { name: user.name, email: user.email },
      platform: { name: 'MyApp' },
    }),
    send: async (params) => {
      // params: { identifierId, contactId, accountId, subject, body, ruleId, autoApprove }
      await myTransport.send(params);
    },
    selectAgent: async (identifierId, ctx) => {
      const account = await myAccountPool.getBest();
      if (!account) return null;
      return { accountId: account.id, contactValue: account.address, metadata: {} };
    },
    findIdentifier: async (contactValue) => {
      const rec = await db.collection('identifiers').findOne({ value: contactValue });
      return rec ? { id: rec._id.toString(), contactId: rec.contactId } : null;
    },
  },

  collections: [
    {
      name: 'orders',
      collectionName: 'myapp_orders',
      label: 'Orders',
      fields: [{ name: 'status', type: 'string' }, { name: 'total', type: 'number' }],
    },
  ],

  hooks: {
    onSend: (info) => console.log(`Sent to ${info.contactValue} — rule: ${info.ruleName}`),
  },
});

app.use('/api/rule-engine', engine.routes);
app.listen(3000);

API Routes

All routes are mounted under the prefix you choose (e.g. /api/rule-engine).

| Resource | Routes | |----------|--------| | Templates | GET /templates · POST /templates · POST /templates/validate · POST /templates/preview · GET /:id · PUT /:id · DELETE /:id · PATCH /:id/toggle · POST /:id/preview · POST /:id/preview-with-data · POST /:id/test-send · POST /:id/clone | | Rules | GET /rules · POST /rules · POST /rules/preview-conditions · GET /:id · PATCH /:id · DELETE /:id · POST /:id/toggle · POST /:id/dry-run · POST /:id/clone | | Runner | POST /runner · GET /runner/status · GET /runner/status/:runId · POST /runner/cancel/:runId · GET /runner/logs | | Sends | GET /sends | | Collections | GET /collections · GET /collections/:name/fields | | Settings | GET /throttle · PUT /throttle |

Platform Wrappers

@astralibx/email-rule-engine and @astralibx/telegram-rule-engine are thin wrappers around this package. They pre-wire platform-specific rendering (MJML + Handlebars for email, Markdown for Telegram) and re-export createRuleEngine as createEmailRuleEngine / createTelegramRuleEngine. Use this core package directly when building a custom channel.

Getting Started

License

MIT