Scan your whole stack
From OX Research Newsroom
Are you using ts-rules-composer?
Find out what’s in your code.
Scan your apps free in minutes (opens in a new tab)Latest version: v2.0.0
ts-rules-composer was last scanned on 29 Nov 2026 at version 2.0.0. Risk score 0 of 100. No malicious behavior was detected.
| Version | Published | Status |
|---|---|---|
| 2.0.0 LATEST | 29 Nov 2026 | No rules fired |
| 1.7.0 | 17 Nov 2026 | No rules fired |
| 1.5.0 | 13 Nov 2026 | No rules fired |
| 1.4.0 | 11 Nov 2026 | Not shown |
| 1.3.0 | 11 Nov 2026 | Not shown |
Findings for v2.0.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.
The score describes 2.0.0; other versions have their own rules, not their own score.
The publisher’s own README, as collected from the registry.
A dependency-free, type-safe engine for composing business rules and policy checks into pipelines.
Schema validators answer "is this data shaped correctly?". Business rules ask more: does this user have permission, is this order within their limit, did the fraud service say yes before the timeout? Those checks need shared context, async calls, branching, retries and timeouts.
ts-rules-composer treats each check as a small function (a rule) and gives you combinators to wire rules together, with the input, context and error types inferred end to end. It complements schema validators such as zod; it does not replace them.
Because a pipeline is plain data, you can also draw it: toMermaid turns the rules you actually ship into a flowchart, without running them. The diagram comes from the code, so it never goes stale.
npm install ts-rules-composer
# or
yarn add ts-rules-composer
# or
pnpm add ts-rules-composer
Requires Node.js 22 or later, or a modern browser.
import { fail, match, named, pass, pipeRules } from "ts-rules-composer";
type Order = { items: number; total: number; payment: "card" | "paypal" };
type Ctx = { limit: number };
// A rule is a function: (input, context?) => pass() | fail(error)
const hasItems = (order: Order) =>
order.items > 0 ? pass() : fail("Cart is empty");
const withinLimit = (order: Order, ctx?: Ctx) =>
order.total <= (ctx?.limit ?? 1000) ? pass() : fail("Over the spending limit");
const validateCard = (order: Order) =>
order.total > 0 ? pass() : fail("Invalid amount");
const validatePaypal = (_order: Order) => pass();
// Combinators wire rules together; context reaches every rule
const validateCheckout = pipeRules<Order, string, Ctx>([
hasItems,
withinLimit,
match(named("payment", (order: Order) => order.payment), {
card: validateCard,
paypal: validatePaypal,
}),
]);
await validateCheckout({ items: 2, total: 40, payment: "card" }, { limit: 500 });
// → { outcome: "passed" }
await validateCheckout({ items: 0, total: 40, payment: "card" });
// → { outcome: "failed", error: "Cart is empty" }
await validateCheckout({ items: 1, total: 900, payment: "paypal" }, { limit: 500 });
// → { outcome: "failed", error: "Over the spending limit" }
pipeRules runs rules in order and stops at the first failure. See Core concepts for the model and the API reference for every combinator.
The same pipeline, drawn without running it:
import { toMermaid } from "ts-rules-composer/mermaid";
console.log(toMermaid(validateCheckout));
flowchart TD
input([input])
root_steps_0["hasItems"]
root_steps_1["withinLimit"]
root_steps_2{"payment"}
root_steps_2_cases_0["validateCard"]
root_steps_2_cases_1["validatePaypal"]
passed([passed])
input --> root_steps_0
root_steps_2 -->|"card"| root_steps_2_cases_0
root_steps_2 -->|"paypal"| root_steps_2_cases_1
root_steps_0 --> root_steps_1
root_steps_1 --> root_steps_2
root_steps_2_cases_0 --> passed
root_steps_2_cases_1 --> passed
Diagrams show the names the engine can find, which is why the match accessor above uses named("payment", ...). Unnamed functions print as rule #1. See Diagrams for options and naming tips.
when, unless, match, every and mapErrordefineOutcomes, merged by precedencetoMermaid turns any pipeline into a flowchart that always matches the code, without running itsideEffects: false)Rule typewithDebug and withTap for logging and metricsAt the heart of ts-rules-composer lies the Rule — a function that performs a single validation step.
Rules are:
context can be passed to any rule for dependency injection, configuration, or shared state.type Rule<TInput, TError = string, TContext = unknown> =
(input: TInput, context?: TContext) => Promise<RuleResult<TError>> | RuleResult<TError>;
TInput – the type of input the rule receivesTError – the type of error returned on failure (defaults to string)TContext – optional shared context object passed to the ruleResult – your rule can return synchronously or asynchronouslyRules must return one of two outcomes:
type RuleResult<TError = string> =
| { outcome: "passed" }
| { outcome: "failed"; error: TError };
Aggregating combinators change the error type: every and oneOf return a rule whose error is TError[] (one entry per failed rule), while pipeRules, composeRules and the rest keep a single TError.
Use the utility functions pass() and fail(error) to return results:
import { pass, fail } from 'ts-rules-composer';
const isEven = (n: number) =>
n % 2 === 0 ? pass() : fail("Must be even");
Context is optional but powerful. It lets rules access external services, user configuration, or metadata.
type Ctx = { threshold: number };
const isAboveThreshold = (n: number, ctx?: Ctx) =>
n > (ctx?.threshold ?? 0) ? pass() : fail("Below threshold");
When composing rules, context will be passed automatically to all child rules.
Rules are designed to be combined using combinators like pipeRules, every, oneOf, when, and match.
import { pipeRules } from 'ts-rules-composer';
const validate = pipeRules([
isEven,
isAboveThreshold
]);
const result = await validate(4, { threshold: 2 });
// → { outcome: "passed" }
const result2 = await validate(3, { threshold: 2 });
// → { outcome: "failed", error: "Must be even" }
Each rule is a unit of validation that plugs into powerful composition pipelines. You write simple rules and then combine them into expressive, testable flows using composable logic.
Complete, type-checked examples (they are compiled by npm run typecheck):
A sketch of how the combinators compose. Helper rules and services (fraudService, validateCardNumber, bankAuthCheck and so on) are assumed; see the linked file above for the runnable version.
import {
pipeRules,
match,
withRetry,
withMemoize,
withTimeout,
when
} from 'ts-rules-composer';
// 1. Basic validators
const validateAmount = (tx: Transaction) =>
tx.amount > 0 ? pass() : fail("Amount must be positive");
const validateCurrency = (tx: Transaction) =>
SUPPORTED_CURRENCIES.includes(tx.currency)
? pass()
: fail(`Unsupported currency: ${tx.currency}`);
// 2. Memoized fraud check (cached for 5 minutes)
const checkFraudRisk = withMemoize(
async (tx: Transaction) => {
const risk = await fraudService.assess(tx);
return risk.score < 5 ? pass() : fail("High fraud risk");
},
tx => JSON.stringify([tx.userId, tx.amount, tx.recipient]),
{ ttl: 300000 }
);
// 3. Payment method handling
const validatePaymentMethod = match(
tx => tx.paymentType,
{
"credit_card": pipeRules([
validateCardNumber,
validateExpiry,
withTimeout(bankAuthCheck, 3000, "Bank auth timeout")
]),
"crypto": validateWalletAddress,
"bank_transfer": validateIBAN
}
);
// 4. Complete pipeline
const validateTransaction = pipeRules([
validateAmount,
validateCurrency,
// Only run fraud check for transactions > $1000
when(
tx => tx.amount > 1000,
withRetry(checkFraudRisk, { attempts: 2 })
),
validatePaymentMethod,
// Compliance check (different for business/personal)
match(
tx => tx.accountType,
{
"business": validateBusinessTransfer,
"personal": validatePersonalTransfer
}
)
]);
// Usage
const result = await validateTransaction(paymentRequest);
A rule answers yes or no: passed or failed. A decision picks one outcome from a set you declare, such as declined, review or approved. It is still a plain function, (input, context?) => { outcome }, sync or async.
import { defineOutcomes, type OutcomeOf } from "ts-rules-composer";
const credit = defineOutcomes(["declined", "review", "approved"], {
onError: "review",
});
type CreditOutcome = OutcomeOf<typeof credit>; // "declined" | "review" | "approved"
Declaration order is precedence: an earlier outcome outranks every later one. onError is the outcome any failure while deciding resolves to (see When something goes wrong). defineOutcomes returns a frozen toolkit bound to this set:
| Member | What it does |
|---|---|
outcome(label) |
Builds a typed result for a decision you write yourself, like pass() / fail() for rules. |
ifElse(predicate, whenTrue, whenFalse) |
Picks a branch from a yes/no question. |
match(accessor, cases, defaultCase) |
Picks a branch by key. The default is required. |
combine(decisions, { resolver? }) |
Runs decisions one at a time, in order, and merges their outcomes. Stops early (see Precedence). |
combineAll(decisions, { resolver? }) |
Runs every decision at once and merges their outcomes. |
mapOutcome(rule, { failed, passed? }) |
Turns a rule into a decision of this toolkit. |
resolvers |
strongestWins (the default) and runEveryCheck, for the resolver option. |
outcomes, onError |
The declared set, in order, and its onError. |
A branch or case is either a declared outcome as a bare string ("review"), which ends the path there, or another decision. Labels are typo-checked against CreditOutcome. Each builder checks its arguments when you call it and throws a TypeError for bad configuration, never later while running.
A credit policy built from rules, branches and three external services: a sanctions lookup, then a credit bureau and a fraud service checked in parallel (sanctionsService, creditBureau and fraudService are assumed; the policy is tested as written in src/test/helpers/credit-policy.ts):
const SUPPORTED_COUNTRIES = ["US", "GB", "DE"];
const isAdult: Rule<CreditApplication> = named(
"applicant is an adult",
(app) => (app.age >= 18 ? pass() : fail("Applicant must be an adult")),
);
const isSupportedCountry: Rule<CreditApplication> = named(
"country is supported",
(app) =>
SUPPORTED_COUNTRIES.includes(app.country)
? pass()
: fail(`Unsupported country: ${app.country}`),
);
const isNotSanctioned: Rule<CreditApplication> = named(
"applicant is not sanctioned",
async (app) =>
(await sanctionsService.isListed(app.applicantId))
? fail("Applicant is on a sanctions list")
: pass(),
);
// A failed eligibility check declines. A check that throws is an outage,
// not a "no": it gives onError ("review").
const eligibility = credit.mapOutcome(
pipeRules([isAdult, isSupportedCountry]),
{ failed: "declined" },
);
// This check declines a listed applicant and gives "review" for a
// sanctions-service outage.
const sanctions = credit.mapOutcome(isNotSanctioned, { failed: "declined" });
const debtToIncome = (app: CreditApplication) =>
app.monthlyDebt / app.monthlyIncome;
const debtToIncomeAbove = (percent: number) =>
named(
`debt to income above ${percent}%`,
(app: CreditApplication) => debtToIncome(app) > percent / 100,
);
const affordability = credit.ifElse(
debtToIncomeAbove(50),
"declined",
credit.ifElse(debtToIncomeAbove(35), "review", "approved"),
);
const employment = credit.match(
named("employment", (app: CreditApplication) => app.employment),
{ employed: "approved", self_employed: "review", unemployed: "declined" },
"review",
);
const bureauScore: Decision<CreditApplication, CreditOutcome> = named(
"credit bureau score",
async (app) => {
const score = await creditBureau.score(app.applicantId);
if (score >= 700) {
return credit.outcome("approved");
}
if (score >= 600) {
return credit.outcome("review");
}
return credit.outcome("declined");
},
);
const fraudRisk: Decision<CreditApplication, CreditOutcome> = named(
"fraud risk",
async (app) => {
const risk = await fraudService.riskScore(app);
if (risk > 0.7) {
return credit.outcome("declined");
}
if (risk > 0.3) {
return credit.outcome("review");
}
return credit.outcome("approved");
},
);
// A new account asking for a lot gets at least a review.
const newAccountLargeLoan = credit.ifElse(
named(
"new account asking over 20k",
(app: CreditApplication) =>
app.accountAgeDays < 90 && app.requestedAmount > 20_000,
),
"review",
"approved",
);
// Independent paid checks run in parallel.
const externalChecks = credit.combineAll([bureauScore, fraudRisk]);
// Sequential: the strongest outcome wins and the run stops at "declined", so
// an ineligible applicant never reaches the paid checks.
const creditPolicy = credit.combine([
eligibility,
sanctions,
affordability,
employment,
newAccountLargeLoan,
externalChecks,
]);
await creditPolicy(applicant); // { outcome: "approved" }
await creditPolicy({ ...applicant, employment: "self_employed" }); // { outcome: "review" }
await creditPolicy({ ...applicant, age: 16 }); // { outcome: "declined" }, no service called
Find threats in your stack.
OX Radar can check high-priority threats, like critical package CVEs, against your context.
Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.
The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).
The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.