Tsentials rules

From senrecep/tsentials · View interactive version

Tsentials rules is an AI agent skill from the GitHub repository senrecep/tsentials. Use when composing business validation logic — define rules as typed functions returning VoidResult, combine with RuleEngine.and/or/linear/if, evaluate synchronously or asynchronously with evaluateAsync.

How to use this skill

Skill file

tsentials/rules

Composable rule engine for TypeScript. Define business logic as small typed functions and combine them freely. Sync and async rules are separate types; async combinators accept both.

Installation

npm install tsentials

Import

import { RuleEngine } from 'tsentials/rules';
import type { Rule, AsyncRule, TypedRule, TypedAsyncRule } from 'tsentials/rules';

Types

// Sync rule — returns VoidResult directly (NOT a Promise)
type Rule<TContext> = (context: TContext) => VoidResult;

// Async rule: returns Promise<VoidResult> and receives the caller's AbortSignal (if any)
type AsyncRule<TContext> = (context: TContext, signal?: AbortSignal) => Promise<VoidResult>;

// Typed rule — returns a value on success
type TypedRule<TContext, TResult> = (context: TContext) => Result<TResult>;

// Async typed rule
type TypedAsyncRule<TContext, TResult> = (context: TContext, signal?: AbortSignal) => Promise<Result<TResult>>;

Critical: Rule<T> is sync only. Use AsyncRule<T> for async predicates. Do NOT type an async function as Rule<T>.


Defining Rules

import { Result } from 'tsentials/result';
import { Err } from 'tsentials/errors';

type User = { age: number; email: string; emailVerified: boolean };

// Sync rule
const isAdult: Rule<User> = ctx =>
  ctx.age >= 18
    ? Result.ok()
    : Result.failure(Err.validation('User.Underage', 'Must be 18 or older.'));

// Async rule — note: AsyncRule<User>, NOT Rule<User>
const hasVerifiedEmail: AsyncRule<User> = async ctx => {
  const verified = await checkEmailVerification(ctx.email);
  return verified
    ? Result.ok()
    : Result.failure(Err.validation('User.EmailUnverified', 'Verify your email first.'));
};

Factories

`RuleEngine.fromPredicate` — rule from a predicate (sync)

The error argument can be a static AppError or a factory (ctx: T) => AppError.

// Static error
const isAdult = RuleEngine.fromPredicate<User>(
  u => u.age >= 18,
  Err.validation('User.Underage', 'Must be 18+'),
);

// Dynamic error (receives context)
const hasBalance = RuleEngine.fromPredicate<Account>(
  a => a.balance > 0,
  a => Err.validation('Account.Insufficient', `Balance ${a.balance} is too low`),
);

`RuleEngine.fromPredicateAsync` — rule from an async predicate

const isEmailUnique = RuleEngine.fromPredicateAsync<User>(
  async u => !(await emailExistsInDb(u.email)),
  Err.validation('User.EmailTaken', 'Email already in use'),
);

Evaluation

`evaluate` — synchronous, returns `VoidResult` directly

// evaluate() is SYNC — no await needed
const result = RuleEngine.evaluate(isAdult, user);

if (result.ok) {
  console.log('Passed');
} else {
  console.log(result.errors[0]?.description);
}

`evaluateAsync` — asynchronous, returns `Promise<VoidResult>`

// evaluateAsync() takes an AsyncRule<T> (a sync Rule<T> works too)
const result = await RuleEngine.evaluateAsync(hasVerifiedEmail, user, { signal });

if (!result.ok) {
  console.log(result.errors[0]?.description);
}

Throwing rules: `Rule.EvaluationFailed`

evaluate never throws. A rule that throws (or an async rule that rejects) becomes a failure with code Rule.EvaluationFailed, type Unexpected, and the thrown message as description. Every combinator node is guarded the same way, so or can still succeed on a later child and if takes the else branch.

Abort behaviour

With { signal }, evaluateAsync passes the signal to the rule, and the async combinators pass it to every child and check it before each child. When the caller's signal is aborted (before the call, or when a rule throws while it is aborted), the promise rejects with signal.reason instead of returning a failure. An in-flight rule is awaited until it settles, so rules should observe the signal themselves.


Sync Combinators

All sync combinators accept Rule<TContext> and return Rule<TContext>.

Every combinator built from an empty rule list evaluates to the Validation failure EMPTY_RULE_ARRAY ("The rule array is empty."); it never throws and never returns ok.

`RuleEngine.and` — all must pass, stops at first failure

const canRegister = RuleEngine.and(isAdult, hasEmail, isAllowedRegion);

const result = RuleEngine.evaluate(canRegister, user);
// Returns the errors of the first failing rule; later rules are not evaluated

`RuleEngine.andAll` — all must pass, collects ALL failures

const canRegister = RuleEngine.andAll(isAdult, hasEmail, isAllowedRegion);
// Every rule runs; result.errors contains errors from all failing rules

`RuleEngine.linear` — all must pass, stops at first failure

const pipeline = RuleEngine.linear(isAdult, hasEmail, hasCompletedProfile);
// Stops at the first failing rule — subsequent rules are not evaluated
// Use when later rules depend on earlier ones passing

`RuleEngine.or` — at least one must pass

const canAccess = RuleEngine.or(isAdmin, isPremiumUser);

`RuleEngine.if` — conditional branching, returns `Rule<TContext>`

RuleEngine.if returns a new Rule<TContext> — it does NOT take a context argument. Evaluate the returned rule separately.

// Build a conditional rule
const accessRule = RuleEngine.if(
  isAdult,      // condition rule (or a plain boolean)
  grantAccess,  // onTrue branch
  denyAccess,   // onFalse branch (optional)
);

// Evaluate the composed rule
const result = RuleEngine.evaluate(accessRule, user);

// A boolean condition: false takes onFalse, or is ok when there is no onFalse
const featureRule = RuleEngine.if(config.strictMode, strictRule);

Async Combinators

All async combinators accept AsyncRule<TContext> or sync Rule<TContext> (mixed in one call) and return AsyncRule<TContext>.

RuleEngine.andAsync(...rules)       // all must pass, stops on first failure
RuleEngine.andAllAsync(...rules)    // all must pass, collects ALL failures
RuleEngine.linearAsync(...rules)    // stops on first failure
RuleEngine.orAsync(...rules)        // at least one must pass
RuleEngine.ifAsync(cond, onTrue, onFalse?)  // cond: AsyncRule | Rule | boolean, returns AsyncRule<TContext>
const asyncRule = RuleEngine.andAsync(isAdult, isEmailUnique, hasVerifiedEmail); // sync + async
const result = await RuleEngine.evaluateAsync(asyncRule, user);

Typed Combinators

Typed rules carry a result value on success (Result<TResult> instead of VoidResult).

// Sync typed combinators
RuleEngine.linearTyped<TContext, TResult>(...rules: TypedRule<TContext, TResult>[])
RuleEngine.andTyped<TContext, TResult>(...rules: TypedRule<TContext, TResult>[])
RuleEngine.orTyped<TContext, TResult>(...rules: TypedRule<TContext, TResult>[])

// Async typed combinators (each rule may be TypedAsyncRule or sync TypedRule)
RuleEngine.linearTypedAsync<TContext, TResult>(...rules)
RuleEngine.andTypedAsync<TContext, TResult>(...rules)
RuleEngine.orTypedAsync<TContext, TResult>(...rules)

// Typed conditional: runs onTrue when condition succeeds, onFalse when it fails
RuleEngine.ifTyped(condition, onTrue, onFalse?)       // TypedRule<TContext, TResult>
RuleEngine.ifTypedAsync(condition, onTrue, onFalse?)  // TypedAsyncRule<TContext, TResult>

ifTyped / ifTypedAsync return the chosen branch's result. Without onFalse, a failing condition returns its own failure (there is no typed value to fall back to).

All three typed combinators return Result.success(value) when their rules pass: andTyped/andTypedAsync run every rule, collect all errors and on success carry the first rule's value, orTyped/orTypedAsync carry the value of the first passing rule, and linearTyped/linearTypedAsync carry the last rule's value once the whole sequence passes. With zero rules every typed combinator returns the Validation failure EMPTY_RULE_ARRAY, like the untyped ones.


Domain Error Hierarchies with Rules

const RegistrationErrors = {
  underage:      Err.validation('Registration.Underage', 'Applicant must be at least 18.'),
  noEmail:       Err.validation('Registration.NoEmail', 'Email is required.'),
  regionBlocked: Err.forbidden('Registration.RegionBlocked', 'Not available in your region.'),
} as const;

const isAdult: Rule<ApplicantContext> = ctx =>
  ctx.age >= 18 ? Result.ok() : Result.failure(RegistrationErrors.underage);

const hasEmail: Rule<ApplicantContext> = ctx =>
  ctx.email.length > 0 ? Result.ok() : Result.failure(RegistrationErrors.noEmail);

const isAllowedRegion: Rule<ApplicantContext> = ctx =>
  ctx.isAllowedRegion ? Result.ok() : Result.failure(RegistrationErrors.regionBlocked);

// Compose — andAll collects all failures
const canRegister = RuleEngine.andAll(isAdult, hasEmail, isAllowedRegion);

const result = RuleEngine.evaluate(canRegister, applicant);

if (!result.ok) {
  result.errors.forEach(e => console.log(`[${e.type}] ${e.code}: ${e.description}`));
}

Rules with the HTTP Layer

import { fromAsync } from 'tsentials/result';

// evaluate() is sync — call it inside .andThen() to fold it into the async pipeline
const response = await fromAsync(fetchUser(userId))
  .andThen(user => RuleEngine.evaluate(canRegister, user))
  .match(
    () => 'Registration approved',
    errors => `Denied: ${errors.map(e => e.description).join(', ')}`,
  );

Best Practices

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.