ts-rules-composer 1.4.0 β 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -221
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +107 -36
- package/dist/index.d.ts +107 -36
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mermaid.cjs +3 -0
- package/dist/mermaid.cjs.map +1 -0
- package/dist/mermaid.d.cts +11 -0
- package/dist/mermaid.d.ts +11 -0
- package/dist/mermaid.js +3 -0
- package/dist/mermaid.js.map +1 -0
- package/dist/rule-C3RlYflY.d.cts +37 -0
- package/dist/rule-C3RlYflY.d.ts +37 -0
- package/dist/to-graph-C-KK0y4c.js +2 -0
- package/dist/to-graph-C-KK0y4c.js.map +1 -0
- package/dist/to-graph-DRYHiuLU.cjs +2 -0
- package/dist/to-graph-DRYHiuLU.cjs.map +1 -0
- package/package.json +11 -1
package/README.md
CHANGED
|
@@ -1,36 +1,32 @@
|
|
|
1
|
-
# TS Rules Composer
|
|
1
|
+
# TS Rules Composer
|
|
2
2
|
|
|
3
3
|
[](https://npmjs.com/package/ts-rules-composer)
|
|
4
4
|
[](https://bundlephobia.com/package/ts-rules-composer)
|
|
5
5
|
[](LICENSE)
|
|
6
6
|
|
|
7
|
-
A **dependency-free**, type-safe
|
|
7
|
+
A **dependency-free**, type-safe engine for composing business rules and policy checks into pipelines.
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
// Example: E-commerce checkout
|
|
11
|
-
const validateCheckout = pipeRules([
|
|
12
|
-
validateCart,
|
|
13
|
-
match((order) => order.paymentMethod, {
|
|
14
|
-
'credit_card': validateCreditCard,
|
|
15
|
-
'paypal': validatePaypal
|
|
16
|
-
}),
|
|
17
|
-
withRetry(validateInventory, { attempts: 3 })
|
|
18
|
-
]);
|
|
9
|
+
## Why
|
|
19
10
|
|
|
20
|
-
|
|
21
|
-
|
|
11
|
+
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.
|
|
12
|
+
|
|
13
|
+
`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.
|
|
22
14
|
|
|
23
|
-
##
|
|
15
|
+
## Contents
|
|
24
16
|
|
|
25
|
-
-
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
-
|
|
29
|
-
-
|
|
30
|
-
-
|
|
31
|
-
-
|
|
32
|
-
-
|
|
33
|
-
-
|
|
17
|
+
- [Installation](#installation)
|
|
18
|
+
- [Quick start](#quick-start)
|
|
19
|
+
- [Features](#features)
|
|
20
|
+
- [Core concepts](#core-concepts)
|
|
21
|
+
- [Usage examples](#usage-examples)
|
|
22
|
+
- [Error handling](#error-handling-standardization)
|
|
23
|
+
- [Guardrails and policy checks](#guardrails-and-policy-checks)
|
|
24
|
+
- [Context cloning](#context-cloning-options)
|
|
25
|
+
- [Best practices](#best-practices)
|
|
26
|
+
- [Comparison to other libraries](#comparison-to-other-libraries)
|
|
27
|
+
- [API reference](#api-reference)
|
|
28
|
+
- [Cheat sheet](#cheat-sheet)
|
|
29
|
+
- [Contributing](#contributing)
|
|
34
30
|
|
|
35
31
|
## Installation
|
|
36
32
|
|
|
@@ -42,9 +38,64 @@ yarn add ts-rules-composer
|
|
|
42
38
|
pnpm add ts-rules-composer
|
|
43
39
|
```
|
|
44
40
|
|
|
41
|
+
Requires Node.js 22 or later, or a modern browser.
|
|
42
|
+
|
|
43
|
+
## Quick start
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
import { fail, match, pass, pipeRules } from "ts-rules-composer";
|
|
47
|
+
|
|
48
|
+
type Order = { items: number; total: number; payment: "card" | "paypal" };
|
|
49
|
+
type Ctx = { limit: number };
|
|
50
|
+
|
|
51
|
+
// A rule is a function: (input, context?) => pass() | fail(error)
|
|
52
|
+
const hasItems = (order: Order) =>
|
|
53
|
+
order.items > 0 ? pass() : fail("Cart is empty");
|
|
54
|
+
|
|
55
|
+
const withinLimit = (order: Order, ctx?: Ctx) =>
|
|
56
|
+
order.total <= (ctx?.limit ?? 1000) ? pass() : fail("Over the spending limit");
|
|
57
|
+
|
|
58
|
+
const validateCard = (order: Order) =>
|
|
59
|
+
order.total > 0 ? pass() : fail("Invalid amount");
|
|
60
|
+
const validatePaypal = (_order: Order) => pass();
|
|
61
|
+
|
|
62
|
+
// Combinators wire rules together; context reaches every rule
|
|
63
|
+
const validateCheckout = pipeRules<Order, string, Ctx>([
|
|
64
|
+
hasItems,
|
|
65
|
+
withinLimit,
|
|
66
|
+
match((order: Order) => order.payment, {
|
|
67
|
+
card: validateCard,
|
|
68
|
+
paypal: validatePaypal,
|
|
69
|
+
}),
|
|
70
|
+
]);
|
|
71
|
+
|
|
72
|
+
await validateCheckout({ items: 2, total: 40, payment: "card" }, { limit: 500 });
|
|
73
|
+
// β { status: "passed" }
|
|
74
|
+
|
|
75
|
+
await validateCheckout({ items: 0, total: 40, payment: "card" });
|
|
76
|
+
// β { status: "failed", error: "Cart is empty" }
|
|
77
|
+
|
|
78
|
+
await validateCheckout({ items: 1, total: 900, payment: "paypal" }, { limit: 500 });
|
|
79
|
+
// β { status: "failed", error: "Over the spending limit" }
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`pipeRules` runs rules in order and stops at the first failure. See [Core concepts](#core-concepts) for the model and the [API reference](#api-reference) for every combinator.
|
|
83
|
+
|
|
84
|
+
## Features
|
|
85
|
+
|
|
86
|
+
- **Composable**: build pipelines from combinators such as `when`, `unless`, `match`, `every` and `mapError`
|
|
87
|
+
- **Zero dependencies**: small and tree-shakeable (`sideEffects: false`)
|
|
88
|
+
- **TypeScript first**: inference for inputs, contexts and errors
|
|
89
|
+
- **Async ready**: mix sync and async rules
|
|
90
|
+
- **Context-aware**: share state, services and configuration across rules
|
|
91
|
+
- **Resilient**: retries, timeouts, memoization and fallbacks built in
|
|
92
|
+
- **Extensible**: write your own combinators with the same `Rule` type
|
|
93
|
+
- **Instrumented**: `withDebug` and `withTap` for logging and metrics
|
|
94
|
+
- **Portable**: Node.js 22+ and modern browsers
|
|
95
|
+
|
|
45
96
|
## Core Concepts
|
|
46
97
|
|
|
47
|
-
###
|
|
98
|
+
### The Rule
|
|
48
99
|
|
|
49
100
|
At the heart of `ts-rules-composer` lies the **Rule** β a function that performs a single validation step.
|
|
50
101
|
|
|
@@ -56,7 +107,7 @@ Rules are:
|
|
|
56
107
|
- **Async-compatible**: all rules can be sync or async, and combinators handle both transparently.
|
|
57
108
|
- **Context-aware**: optional `context` can be passed to any rule for dependency injection, configuration, or shared state.
|
|
58
109
|
|
|
59
|
-
####
|
|
110
|
+
#### Rule signature
|
|
60
111
|
|
|
61
112
|
```ts
|
|
62
113
|
type Rule<TInput, TError = string, TContext = unknown> =
|
|
@@ -68,16 +119,18 @@ type Rule<TInput, TError = string, TContext = unknown> =
|
|
|
68
119
|
- `TContext` β optional shared context object passed to the rule
|
|
69
120
|
- `Result` β your rule can return synchronously or asynchronously
|
|
70
121
|
|
|
71
|
-
####
|
|
122
|
+
#### Rule result
|
|
72
123
|
|
|
73
124
|
Rules must return one of two outcomes:
|
|
74
125
|
|
|
75
126
|
```ts
|
|
76
127
|
type RuleResult<TError = string> =
|
|
77
128
|
| { status: "passed" }
|
|
78
|
-
| { status: "failed"; error: TError
|
|
129
|
+
| { status: "failed"; error: TError };
|
|
79
130
|
```
|
|
80
131
|
|
|
132
|
+
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`.
|
|
133
|
+
|
|
81
134
|
Use the utility functions `pass()` and `fail(error)` to return results:
|
|
82
135
|
|
|
83
136
|
```ts
|
|
@@ -87,7 +140,7 @@ const isEven = (n: number) =>
|
|
|
87
140
|
n % 2 === 0 ? pass() : fail("Must be even");
|
|
88
141
|
```
|
|
89
142
|
|
|
90
|
-
####
|
|
143
|
+
#### Context example
|
|
91
144
|
|
|
92
145
|
Context is optional but powerful. It lets rules access external services, user configuration, or metadata.
|
|
93
146
|
|
|
@@ -100,7 +153,7 @@ const isAboveThreshold = (n: number, ctx?: Ctx) =>
|
|
|
100
153
|
|
|
101
154
|
When composing rules, context will be passed automatically to all child rules.
|
|
102
155
|
|
|
103
|
-
####
|
|
156
|
+
#### Composing rules
|
|
104
157
|
|
|
105
158
|
Rules are designed to be combined using **combinators** like `pipeRules`, `every`, `oneOf`, `when`, and `match`.
|
|
106
159
|
|
|
@@ -121,27 +174,19 @@ const result2 = await validate(3, { threshold: 2 });
|
|
|
121
174
|
|
|
122
175
|
---
|
|
123
176
|
|
|
124
|
-
#### π§° Summary
|
|
125
|
-
|
|
126
|
-
| Feature | Supported |
|
|
127
|
-
| ----------------- | --------- |
|
|
128
|
-
| Sync & Async | β
|
|
|
129
|
-
| Error Aggregation | β
|
|
|
130
|
-
| Context Injection | β
|
|
|
131
|
-
| Type Inference | β
|
|
|
132
|
-
| Composition | β
|
|
|
133
|
-
|
|
134
177
|
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.
|
|
135
178
|
|
|
136
179
|
## Usage Examples
|
|
137
180
|
|
|
138
|
-
Complete examples
|
|
181
|
+
Complete, type-checked examples (they are compiled by `npm run typecheck`):
|
|
139
182
|
|
|
140
|
-
-
|
|
141
|
-
-
|
|
142
|
-
-
|
|
183
|
+
- [User Registration](./examples/user-registration.example.ts)
|
|
184
|
+
- [Financial Transaction Validation](./examples/financial-transaction.example.ts)
|
|
185
|
+
- [Model Deployment Validator](./examples/model-deployment.example.ts)
|
|
143
186
|
|
|
144
|
-
###
|
|
187
|
+
### Sketch: financial transaction pipeline
|
|
188
|
+
|
|
189
|
+
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.
|
|
145
190
|
|
|
146
191
|
```typescript
|
|
147
192
|
import {
|
|
@@ -168,7 +213,7 @@ const checkFraudRisk = withMemoize(
|
|
|
168
213
|
const risk = await fraudService.assess(tx);
|
|
169
214
|
return risk.score < 5 ? pass() : fail("High fraud risk");
|
|
170
215
|
},
|
|
171
|
-
tx =>
|
|
216
|
+
tx => JSON.stringify([tx.userId, tx.amount, tx.recipient]),
|
|
172
217
|
{ ttl: 300000 }
|
|
173
218
|
);
|
|
174
219
|
|
|
@@ -213,137 +258,6 @@ const validateTransaction = pipeRules([
|
|
|
213
258
|
const result = await validateTransaction(paymentRequest);
|
|
214
259
|
```
|
|
215
260
|
|
|
216
|
-
### Example 2: User Registration
|
|
217
|
-
|
|
218
|
-
```typescript
|
|
219
|
-
import { pipeRules, every, match } from 'ts-rules-composer';
|
|
220
|
-
|
|
221
|
-
const validateUser = pipeRules([
|
|
222
|
-
// Sequential validation
|
|
223
|
-
validateUsernameFormat,
|
|
224
|
-
withMemoize(checkUsernameAvailability, { ttl: 60000 }),
|
|
225
|
-
|
|
226
|
-
// Parallel validation
|
|
227
|
-
every([
|
|
228
|
-
validatePasswordStrength,
|
|
229
|
-
validateEmailFormat,
|
|
230
|
-
checkEmailUnique
|
|
231
|
-
]),
|
|
232
|
-
|
|
233
|
-
// pattern matching routing
|
|
234
|
-
match(
|
|
235
|
-
user => user.role,
|
|
236
|
-
{
|
|
237
|
-
'admin': validateAdminPrivileges,
|
|
238
|
-
'user': validateStandardUser
|
|
239
|
-
},
|
|
240
|
-
fail('Unknown role')
|
|
241
|
-
)
|
|
242
|
-
]);
|
|
243
|
-
```
|
|
244
|
-
|
|
245
|
-
### Example 3: Healthcare Appointment System
|
|
246
|
-
|
|
247
|
-
```typescript
|
|
248
|
-
const bookAppointment = pipeRules([
|
|
249
|
-
// Context-aware validation
|
|
250
|
-
requireContextRule(
|
|
251
|
-
"Missing schedule data",
|
|
252
|
-
(appt, ctx: ScheduleContext) => validateDoctorAvailability(appt, ctx)
|
|
253
|
-
),
|
|
254
|
-
|
|
255
|
-
// Error transformation
|
|
256
|
-
mapError(
|
|
257
|
-
validateInsurance,
|
|
258
|
-
error => `Insurance error: ${error.code}`
|
|
259
|
-
),
|
|
260
|
-
|
|
261
|
-
// Time-sensitive check
|
|
262
|
-
withTimeout(
|
|
263
|
-
checkFacilityCapacity,
|
|
264
|
-
5000,
|
|
265
|
-
"System timeout"
|
|
266
|
-
)
|
|
267
|
-
]);
|
|
268
|
-
|
|
269
|
-
// Usage
|
|
270
|
-
const result = await bookAppointment(newAppointment, clinicSchedule);
|
|
271
|
-
```
|
|
272
|
-
|
|
273
|
-
### Example 4: Content Moderation System
|
|
274
|
-
|
|
275
|
-
```typescript
|
|
276
|
-
import {
|
|
277
|
-
pipeRules,
|
|
278
|
-
validateField,
|
|
279
|
-
requireContextRule,
|
|
280
|
-
inject,
|
|
281
|
-
tap
|
|
282
|
-
} from 'ts-rules-composer';
|
|
283
|
-
|
|
284
|
-
// 1. Strongly typed context
|
|
285
|
-
type ModerationContext = {
|
|
286
|
-
moderatorId: string;
|
|
287
|
-
permissions: string[];
|
|
288
|
-
environment: 'staging' | 'production';
|
|
289
|
-
};
|
|
290
|
-
|
|
291
|
-
// 2. Rule factory with dependency injection
|
|
292
|
-
const createModerationRules = (logger: LoggerService) =>
|
|
293
|
-
pipeRules([
|
|
294
|
-
// Enforce context requirements
|
|
295
|
-
requireContextRule(
|
|
296
|
-
"Moderator context required",
|
|
297
|
-
(post, ctx: ModerationContext) => pipeRules([
|
|
298
|
-
|
|
299
|
-
// Core validations
|
|
300
|
-
validateField(post => post.content, content =>
|
|
301
|
-
content.length > 0 || fail("Empty content")
|
|
302
|
-
),
|
|
303
|
-
|
|
304
|
-
// Environment-specific rule
|
|
305
|
-
when(
|
|
306
|
-
(_, ctx) => ctx.environment === 'production',
|
|
307
|
-
validateField(post => post.tags, tags =>
|
|
308
|
-
tags.length <= 5 || fail("Too many tags")
|
|
309
|
-
)
|
|
310
|
-
),
|
|
311
|
-
|
|
312
|
-
// Permission-based rule
|
|
313
|
-
when(
|
|
314
|
-
(_, ctx) => ctx.permissions.includes('FLAG_SENSITIVE'),
|
|
315
|
-
validateField(post => post.content, checkSensitiveContent)
|
|
316
|
-
),
|
|
317
|
-
|
|
318
|
-
// Logging side effect
|
|
319
|
-
tap((post, ctx) => {
|
|
320
|
-
logger.log({
|
|
321
|
-
action: 'moderate',
|
|
322
|
-
moderator: ctx.moderatorId,
|
|
323
|
-
postId: post.id
|
|
324
|
-
});
|
|
325
|
-
})
|
|
326
|
-
])
|
|
327
|
-
)
|
|
328
|
-
]);
|
|
329
|
-
|
|
330
|
-
// 3. Inject dependencies
|
|
331
|
-
const moderatePost = inject(
|
|
332
|
-
{ logger: new Logger() },
|
|
333
|
-
createModerationRules
|
|
334
|
-
);
|
|
335
|
-
|
|
336
|
-
// 4. Usage
|
|
337
|
-
const postModerationResult = await moderatePost(
|
|
338
|
-
{ id: "post123", content: "Hello", tags: ["a"] },
|
|
339
|
-
{
|
|
340
|
-
moderatorId: "user456",
|
|
341
|
-
permissions: ["FLAG_SENSITIVE"],
|
|
342
|
-
environment: "production"
|
|
343
|
-
}
|
|
344
|
-
);
|
|
345
|
-
```
|
|
346
|
-
|
|
347
261
|
## Error Handling Standardization
|
|
348
262
|
|
|
349
263
|
This library provides consistent error handling across all validation operations through a standardized system:
|
|
@@ -390,7 +304,7 @@ graph TD
|
|
|
390
304
|
E --> F[Return Failed Result]
|
|
391
305
|
```
|
|
392
306
|
|
|
393
|
-
###
|
|
307
|
+
### Error Handling Recipes
|
|
394
308
|
|
|
395
309
|
1. **For validation logic**:
|
|
396
310
|
|
|
@@ -423,7 +337,7 @@ graph TD
|
|
|
423
337
|
Enable debug mode to get enhanced error information:
|
|
424
338
|
|
|
425
339
|
```typescript
|
|
426
|
-
import { withDebug } from '
|
|
340
|
+
import { withDebug } from 'ts-rules-composer';
|
|
427
341
|
|
|
428
342
|
const debugRule = withDebug(myRule, {
|
|
429
343
|
onError: (error) => console.error('Rule failed:', error)
|
|
@@ -446,7 +360,7 @@ graph TD
|
|
|
446
360
|
1. **Composition-Level Setting** (Highest priority)
|
|
447
361
|
- `pipeRules/composeRules/every/oneOf` configurations
|
|
448
362
|
2. **Rule-Level Configuration** (Only applies if composition allows)
|
|
449
|
-
- `
|
|
363
|
+
- `getNormalizedRule` settings
|
|
450
364
|
3. **Global Default** (`safe` mode)
|
|
451
365
|
|
|
452
366
|
#### Behavior Matrix
|
|
@@ -487,7 +401,7 @@ graph TD
|
|
|
487
401
|
// All rules will use safe mode regardless of their own config
|
|
488
402
|
const pipeline = pipeRules([
|
|
489
403
|
unsafeRule, // Will be forced to safe mode
|
|
490
|
-
|
|
404
|
+
getNormalizedRule(rule, { // Configuration ignored
|
|
491
405
|
errorHandlingMode: 'unsafe'
|
|
492
406
|
})
|
|
493
407
|
], {
|
|
@@ -501,7 +415,7 @@ const pipeline = pipeRules([
|
|
|
501
415
|
// Rules can specify their own mode since composition allows it
|
|
502
416
|
const pipeline = pipeRules([
|
|
503
417
|
unsafeRule, // Runs in unsafe mode
|
|
504
|
-
|
|
418
|
+
getNormalizedRule(rule, { // Runs in safe mode
|
|
505
419
|
errorHandlingMode: 'safe'
|
|
506
420
|
})
|
|
507
421
|
], {
|
|
@@ -509,6 +423,17 @@ const pipeline = pipeRules([
|
|
|
509
423
|
})
|
|
510
424
|
```
|
|
511
425
|
|
|
426
|
+
## Guardrails and policy checks
|
|
427
|
+
|
|
428
|
+
When a rule decides whether something is allowed (a permission check, a safety policy, an LLM or fraud judge), a wrong "pass" costs more than a wrong "fail". These defaults and habits keep the failure side safe.
|
|
429
|
+
|
|
430
|
+
- **Fail closed on errors.** In the default `safe` mode a thrown exception becomes a failed result, so a crashing check never passes. Do not use `errorHandlingMode: "unsafe"` on policy rules unless the caller handles exceptions. See [Error handling modes](#error-handling-modes).
|
|
431
|
+
- **Never retry a decision.** `withRetry` retries failed results by default, so a "no" can be retried into a "yes". For policy checks use `retryOn: "thrown"`, which retries only transient exceptions. See [`withRetry`](#withretryrule-options).
|
|
432
|
+
- **Keep the reason when retries run out.** `onExhausted: "last-error"` returns the final error instead of `"MAX_RETRIES_EXCEEDED"`.
|
|
433
|
+
- **Key caches by identity.** `withMemoize` shares entries between callers with the same key, so include everything the verdict depends on (user, tenant, input id), build keys with `JSON.stringify([...])` rather than joining strings, and key by context when the result depends on who is asking. See [`withMemoize`](#withmemoizerule-keyfn-options).
|
|
434
|
+
- **Time out as a failure.** `withTimeout` returns your `timeoutError` as a failed result, so a slow dependency blocks the action instead of letting it through.
|
|
435
|
+
- **Test the failure paths.** Assert that thrown errors, timeouts and exhausted retries all produce `status: "failed"`.
|
|
436
|
+
|
|
512
437
|
## Context Cloning Options
|
|
513
438
|
|
|
514
439
|
The library provides flexible context cloning strategies to balance between performance and correctness. You can control cloning behavior through `CompositionOptions`:
|
|
@@ -519,31 +444,30 @@ made by one child Rule are visible to the others; the original Context is left
|
|
|
519
444
|
unchanged.
|
|
520
445
|
|
|
521
446
|
```typescript
|
|
522
|
-
|
|
447
|
+
type CompositionOptions = {
|
|
523
448
|
cloneContext?: boolean; // Enable/disable cloning
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
}
|
|
449
|
+
cloneStrategy?: "shallow" | "json" | "structured"; // Defaults to "json"
|
|
450
|
+
} & RuleSafetyOptions; // errorHandlingMode, errorTransform (see Error Handling)
|
|
527
451
|
```
|
|
528
452
|
|
|
529
453
|
### Cloning Strategies
|
|
530
454
|
|
|
531
|
-
The
|
|
455
|
+
The clone method is chosen by `cloneStrategy`. Without it, the JSON clone is used (it is never auto-upgraded to `structuredClone`):
|
|
532
456
|
|
|
533
|
-
|
|
|
534
|
-
|
|
535
|
-
| `
|
|
536
|
-
| `
|
|
537
|
-
|
|
|
457
|
+
| `cloneStrategy` | Speed | Depth | Special Types* | Circular Refs | Node.js | Browser |
|
|
458
|
+
|-------------------|--------|-------|----------------|---------------|---------|---------|
|
|
459
|
+
| `"shallow"` | π Fast | Shallow | β No | β
Yes | β
| β
|
|
|
460
|
+
| `"structured"` | π’ Slow | Deep | β
Yes | β
Yes | β
| Modern |
|
|
461
|
+
| `"json"` (default) | π Fast | Deep | β No | β No | β
| β
|
|
|
538
462
|
|
|
539
463
|
*Special Types: Date, Map, Set, RegExp, etc.
|
|
540
464
|
|
|
541
|
-
###
|
|
465
|
+
### Cloning examples
|
|
542
466
|
|
|
543
|
-
**1. Default Behavior (
|
|
467
|
+
**1. Default Behavior (JSON clone)**
|
|
544
468
|
|
|
545
469
|
```typescript
|
|
546
|
-
//
|
|
470
|
+
// Uses the JSON clone
|
|
547
471
|
pipeRules(rules, { cloneContext: true })
|
|
548
472
|
```
|
|
549
473
|
|
|
@@ -551,15 +475,15 @@ pipeRules(rules, { cloneContext: true })
|
|
|
551
475
|
|
|
552
476
|
```typescript
|
|
553
477
|
// Fastest option - only clones top-level properties
|
|
554
|
-
pipeRules(rules, { cloneContext: true,
|
|
478
|
+
pipeRules(rules, { cloneContext: true, cloneStrategy: "shallow" })
|
|
555
479
|
```
|
|
556
480
|
|
|
557
481
|
**3. Force Structured Clone**
|
|
558
482
|
|
|
559
483
|
```typescript
|
|
560
484
|
// Most accurate - preserves special object types
|
|
561
|
-
pipeRules(rules, { cloneContext: true,
|
|
562
|
-
// Falls back to JSON clone if structuredClone isn't available
|
|
485
|
+
pipeRules(rules, { cloneContext: true, cloneStrategy: "structured" })
|
|
486
|
+
// Falls back to the JSON clone if structuredClone isn't available
|
|
563
487
|
```
|
|
564
488
|
|
|
565
489
|
## Best Practices
|
|
@@ -570,7 +494,7 @@ pipeRules(rules, { cloneContext: true, structuredClone: true })
|
|
|
570
494
|
4. **Type Narrowing** - Use `requireContextRule` for safety
|
|
571
495
|
5. **Instrument** - Add metrics in production
|
|
572
496
|
|
|
573
|
-
##
|
|
497
|
+
## Comparison to Other Libraries
|
|
574
498
|
|
|
575
499
|
While many libraries focus on schema validation or static rules, `ts-rules-composer` is designed specifically for **composable business logic**, dynamic workflows, and contextual validation pipelines.
|
|
576
500
|
|
|
@@ -578,7 +502,7 @@ Hereβs how it compares to popular alternatives:
|
|
|
578
502
|
|
|
579
503
|
| Library | Type | Async | Context-Aware | Type Inference | Size (gzipped) | Notes |
|
|
580
504
|
| ------------------------------------------------------------------------ | ----------------------- | ----- | ------------- | -------------- | ------------- | ------------------------------------------------ |
|
|
581
|
-
| **`ts-rules-composer`** | Rule engine, functional | β
| β
| β
| \~
|
|
505
|
+
| **`ts-rules-composer`** | Rule engine, functional | β
| β
| β
| \~2.3KB | Built for composing complex, contextual rules |
|
|
582
506
|
| [`zod`](https://github.com/colinhacks/zod) | Schema validation | β
| β | β
| \~40KB | Excellent for static object validation |
|
|
583
507
|
| [`io-ts`](https://github.com/gcanti/io-ts) | Runtime type validation | β
| β | β
| \~5KB+ | Powerful but requires deep functional patterns |
|
|
584
508
|
| [`json-rules-engine`](https://github.com/CacheControl/json-rules-engine) | Declarative JSON rules | β
| β | β | \~25KB | Config-based rules, limited type safety |
|
|
@@ -586,7 +510,7 @@ Hereβs how it compares to popular alternatives:
|
|
|
586
510
|
|
|
587
511
|
---
|
|
588
512
|
|
|
589
|
-
###
|
|
513
|
+
### When to use `ts-rules-composer`
|
|
590
514
|
|
|
591
515
|
Choose `ts-rules-composer` when your validation or rule logic:
|
|
592
516
|
|
|
@@ -715,7 +639,7 @@ const validateWithFallback = withFallback(
|
|
|
715
639
|
|
|
716
640
|
### Error Handling
|
|
717
641
|
|
|
718
|
-
#### `mapError(rule, transform
|
|
642
|
+
#### `mapError(rule, transform)`
|
|
719
643
|
|
|
720
644
|
Transforms error output
|
|
721
645
|
|
|
@@ -841,7 +765,7 @@ const authRule = requireContextRule(
|
|
|
841
765
|
)
|
|
842
766
|
```
|
|
843
767
|
|
|
844
|
-
#### `withLazyContext(loader, rule
|
|
768
|
+
#### `withLazyContext(loader, rule)`
|
|
845
769
|
|
|
846
770
|
Lazy-loads context
|
|
847
771
|
|
|
@@ -875,7 +799,7 @@ const debugRule = withDebug(validateOrder, {
|
|
|
875
799
|
})
|
|
876
800
|
```
|
|
877
801
|
|
|
878
|
-
#### `tap(effect
|
|
802
|
+
#### `tap(effect)`
|
|
879
803
|
|
|
880
804
|
Creates a standalone tap effect for use in composition pipelines
|
|
881
805
|
|
|
@@ -916,16 +840,6 @@ Creates failure result
|
|
|
916
840
|
const failure = fail("Invalid input")
|
|
917
841
|
```
|
|
918
842
|
|
|
919
|
-
#### `getRuleError(result)`
|
|
920
|
-
|
|
921
|
-
Extracts error from failed result
|
|
922
|
-
|
|
923
|
-
```typescript
|
|
924
|
-
if (result.status === "failed") {
|
|
925
|
-
const error = getRuleError(result)
|
|
926
|
-
}
|
|
927
|
-
```
|
|
928
|
-
|
|
929
843
|
#### `validateField(getter, rule, defaultValue?)`
|
|
930
844
|
|
|
931
845
|
Validates object fields
|
|
@@ -948,7 +862,9 @@ const createDbRule = (db: Database) => (input: string) =>
|
|
|
948
862
|
const dbRule = inject(database, createDbRule)
|
|
949
863
|
```
|
|
950
864
|
|
|
951
|
-
|
|
865
|
+
## Cheat Sheet
|
|
866
|
+
|
|
867
|
+
### Core
|
|
952
868
|
|
|
953
869
|
| Function | Description | Example |
|
|
954
870
|
|----------|-------------|---------|
|
|
@@ -958,30 +874,30 @@ const dbRule = inject(database, createDbRule)
|
|
|
958
874
|
| `match` | Pattern matching routing | `match(getUserType, { admin: ruleA, user: ruleB })` |
|
|
959
875
|
| `ifElse` | Conditional routing | `ifElse(isUnderAge, validateMinorAccount, validateAdultAccount)` |
|
|
960
876
|
|
|
961
|
-
### Combinators
|
|
877
|
+
### Combinators (summary)
|
|
962
878
|
|
|
963
879
|
| Combinator | Purpose | Example |
|
|
964
880
|
|------------|---------|---------|
|
|
965
881
|
| `when` | Conditional execution | `when(isAdmin, validateAdmin)` |
|
|
966
882
|
| `unless` | Negative condition | `unless(isGuest, validateAccount)` |
|
|
967
883
|
| `not` | Invert rule logic | `not(isBanned, "Must not be banned")` |
|
|
968
|
-
| `oneOf` | First-successful validation | `oneOf(validateV1, validateV2)` |
|
|
884
|
+
| `oneOf` | First-successful validation | `oneOf([validateV1, validateV2])` |
|
|
969
885
|
| `withFallback` | Fallback rule | `withFallback(primary, backup)` |
|
|
970
886
|
|
|
971
|
-
### Performance
|
|
887
|
+
### Performance (summary)
|
|
972
888
|
|
|
973
889
|
| Utility | Use Case | Example |
|
|
974
890
|
|---------|----------|---------|
|
|
975
|
-
| `withMemoize` | Cache results | `withMemoize(expensiveCheck, { ttl: 30000 })` |
|
|
891
|
+
| `withMemoize` | Cache results | `withMemoize(expensiveCheck, input => input.id, { ttl: 30000 })` |
|
|
976
892
|
| `withTimeout` | Add time limit | `withTimeout(networkCall, 3000, "Timeout")` |
|
|
977
893
|
| `withRetry` | Automatic retries | `withRetry(unstableAPI, { attempts: 3 })` |
|
|
978
894
|
|
|
979
|
-
### Instrumentation
|
|
895
|
+
### Instrumentation (summary)
|
|
980
896
|
|
|
981
897
|
| Tool | Purpose | Example |
|
|
982
898
|
|------|---------|---------|
|
|
983
899
|
| `withDebug` | Debug logging | `withDebug(rule, { name: "Validation" })` |
|
|
984
|
-
| `tap` | Side effects | `tap((input,
|
|
900
|
+
| `tap` | Side effects | `tap((input, context) => log(input))` |
|
|
985
901
|
|
|
986
902
|
## Contributing
|
|
987
903
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=e=>e!==void 0,
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./to-graph-DRYHiuLU.cjs"),t=e=>e!==void 0,n=e=>({status:`failed`,error:e}),r=()=>({status:`passed`}),i=(e,t,r)=>{let i=r||(e=>e!==void 0);return async(r,a)=>i(a)?t(r,a):n(e)},a=(e,t)=>async r=>{try{return t(r,await e(r))}catch(e){let t=e instanceof Error?e.message:`Context loading failed`;return n(t)}},o=(e,t,n)=>{let r={fixed:()=>n,linear:e=>n*e,exponential:e=>n*2**(e-1)};if(!e)return r.fixed(t);if(typeof e==`string`){let i=r[e];return i?i(t):n}return typeof e==`function`?e(t):r.fixed(t)},s=(e,t)=>t?.errorHandlingMode===`unsafe`?e:x(e,t?.errorTransform),c=(e,t)=>t?.errorHandlingMode===`unsafe`?e:(e||[])?.map(e=>x(e,t?.errorTransform)),l=e=>{if(!e)return{};try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},u=e=>{if(!e)return{};try{return{...e}}catch(t){return console.warn(`Clone failed for ${e?.constructor?.name}, returning empty object`,t),{}}},d=e=>{let t=typeof structuredClone<`u`;return e.cloneStrategy===`shallow`?u:e.cloneStrategy===`structured`&&t?structuredClone:l};function f(e,t,i){let a=c([...e],t),o=d(t),s=t.cloneContext;return async(e,t)=>{let c=s?o(t):t;if(i===`parallelCollect`){let t=(await Promise.all(a.map(t=>t(e,c)))).flatMap(e=>e.status===`failed`?[e.error]:[]);return t.length>0?n(t):r()}let l=i===`forwardFailFast`?a:[...a].reverse();for(let t of l){let n=await t(e,c);if(n.status===`failed`)return n}return r()}}const p=(t,n={})=>e.r(f(t,n,`parallelCollect`),{kind:`all`,rules:[...t]}),m=(t,n)=>{let r=n(t),i=e.n(r),a=e.a(r)??(i?{kind:`rule`,label:i}:void 0),o=()=>(e,t)=>r(e,t);return a?e.r(o(),a):o()},h=(t,i)=>e.r(async(e,a)=>{let o=await t(e,a);return o.status===`failed`?n(i(o.error)):r()},{kind:`decorator`,decorator:`mapError`,rule:t,params:{}}),g=t=>e.r(async(e,n)=>{try{await t(e,n)}catch(e){console.error(`Tap effect failed: `,e)}return r()},{kind:`effect`,effect:t});function _(t,r,i,a){return e.r(async(e,o)=>{let c=t(e),l=c===void 0?i:c,u=s(r,a);return l===void 0?n(`Missing required value`):u(l,o)},{kind:`field`,getter:t,rule:r})}const v=(t,n)=>{let r=typeof n==`string`?{name:n}:n;return e.r(async(e,n)=>{let i=performance.now(),a=r.name||t.name||`anonymous_rule`;try{r.onStart?.(e,n);let o=await t(e,n),s=performance.now()-i;return r.onEnd?.(e,o,n,{ruleName:a,duration:s,startTime:i}),o}catch(t){let a=performance.now()-i;throw r.onError?.(t,e,n,a),t}},{kind:`decorator`,decorator:`debug`,rule:t,params:r.name?{name:r.name}:{}})},y=(t,n,r={})=>{let i=/* @__PURE__ */ new Map;return e.r(async(e,a)=>{let o=n(e,a),c=Date.now();if(r.ttl)for(let[e,t]of i)c-t.timestamp>r.ttl&&i.delete(e);let l=i.get(o);if(l)return l.result;if(r.maxSize&&i.size>=r.maxSize){let e=i.keys().next().value;e!==void 0&&i.delete(e)}let u=s(t,r)(e,a);return i.set(o,{result:u,timestamp:c}),u instanceof Promise&&u.catch(()=>i.delete(o)),u},{kind:`decorator`,decorator:`memoize`,rule:t,params:{}})};function b(t,r={}){let{attempts:i=3,delayMs:a=100,shouldRetry:s=()=>!0,retryOn:c=`both`,onExhausted:l=`max-retries`}=r;return e.r(async(e,u)=>{let d,f;for(let l=1;l<=i;l++){try{let n=await t(e,u);if(n.status===`passed`)return n;d=n.error,f=!1}catch(e){d=e,f=!0}if(c!==`both`&&c!==(f?`thrown`:`failed`)||!s(d,l))return n(d);if(l<i&&a>0){let e=o(r?.retryStrategy,l,a);await new Promise(t=>setTimeout(t,e))}}return n(l===`last-error`?d:`MAX_RETRIES_EXCEEDED`)},{kind:`decorator`,decorator:`retry`,rule:t,params:{attempts:e.i(i),retryOn:c}})}const x=(e,t=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(r,i)=>{try{let a=await e(r,i);return a&&typeof a==`object`&&`status`in a?a:n(t(/* @__PURE__ */ Error(`Invalid rule - did not return RuleResult`)))}catch(e){return n(t(e))}},S=(e,t=e=>typeof e==`object`&&e?e:e instanceof Error?e.message:String(e))=>async(n,r)=>{try{let i=await e(n,r);return typeof i==`boolean`?{status:`passed`,value:i}:{status:`failed`,error:t(/* @__PURE__ */ Error(`Predicate must return boolean, got ${typeof i}`))}}catch(e){return{status:`failed`,error:t(e)}}},C=(t,n)=>r=>e.r(async(e,i)=>{let a=await s(r,n)(e,i);try{await t(e,a,i)}catch(e){console.error(`Tap effect failed:`,e)}return a},{kind:`decorator`,decorator:`tap`,rule:r,params:{}}),w=(t,r,i,a)=>e.r(async(e,o)=>{let c=s(t,a),l=new Promise(e=>setTimeout(()=>e(n(i)),r));return Promise.race([c(e,o),l])},{kind:`decorator`,decorator:`timeout`,rule:t,params:{ms:e.i(r)}}),T=(t,i,a,o)=>e.r(async(e,s)=>{let l=await S(t,o?.predicateErrorTransform)(e,s);if(l.status===`failed`)return n(l.error);let[u,d]=c([i,a],o);return l.value?u(e,s):a?d(e,s):r()},{kind:`branch`,test:t,ifTrue:i,...a?{ifFalse:a}:{}}),E=e=>typeof e==`function`,D=(t,r,i,a)=>e.r(async(e,o)=>{let c=await t(e,o),l=r[c];return l?s(l,a)(e,o):i===void 0?n(`No matching rule for key: ${String(c)}`):E(i)?s(i,a)(e,o):n(i)},{kind:`switch`,selector:t,cases:Object.fromEntries(Reflect.ownKeys(r).filter(e=>typeof r[e]==`function`).map(e=>[e,r[e]])),...i===void 0?{}:E(i)?{default:i}:{defaultError:i}}),O=(t,i,a)=>e.r(async(e,o)=>(await s(t,a)(e,o)).status===`passed`?n(i):r(),{kind:`not`,rule:t}),k=(t,i)=>e.r(async(e,a)=>{let o=c(t,i),s=[];if(!t||t.length===0)return r();for(let t of o){let n=await t(e,a);if(n.status===`passed`)return r();s.push(n.error)}return n(s)},{kind:`any`,rules:Array.isArray(t)?[...t]:[]}),A=(t,i,a)=>e.r(async(e,o)=>{let c=s(i,a),l=await S(t,a?.predicateErrorTransform)(e,o);return l.status===`failed`?n(l.error):l.value?r():c(e,o)},{kind:`branch`,test:t,ifFalse:i}),j=(t,i,a)=>e.r(async(e,o)=>{let c=s(i,a),l=await S(t,a?.predicateErrorTransform)(e,o);return l.status===`failed`?n(l.error):l.value?c(e,o):r()},{kind:`branch`,test:t,ifTrue:i}),M=(t,n,r={})=>e.r(async(e,i)=>{let[a,o]=c([t,n],r),s=await a(e,i);return s.status===`failed`&&(!r.onlyFallbackOn||r.onlyFallbackOn(s.error))?o(e,i):s},{kind:`fallback`,main:t,fallback:n,...r.onlyFallbackOn?{guard:r.onlyFallbackOn}:{}}),N=(t,n={})=>e.r(f(t,n,`reverseFailFast`),{kind:`sequence`,via:`composeRules`,steps:[...t].reverse()});function P(e,...t){return t.reduce((e,t)=>t(e),e)}const F=(t,n={})=>e.r(f(t,n,`forwardFailFast`),{kind:`sequence`,via:`pipeRules`,steps:[...t]}),I=(t,n,r)=>e.r(((...e)=>n(...e)),{kind:`rule`,label:t,...r?.params?{params:r.params}:{}});exports.calculateDelay=o,exports.composeRules=N,exports.every=p,exports.fail=n,exports.getNormalizedRule=s,exports.getNormalizedRules=c,exports.hasContext=t,exports.ifElse=T,exports.inject=m,exports.mapError=h,exports.match=D,exports.named=I,exports.not=O,exports.oneOf=k,exports.pass=r,exports.pipe=P,exports.pipeRules=F,exports.requireContextRule=i,exports.tap=g,exports.toGraph=e.t,exports.unless=A,exports.validateField=_,exports.when=j,exports.withDebug=v,exports.withFallback=M,exports.withLazyContext=a,exports.withMemoize=y,exports.withRetry=b,exports.withSafeError=x,exports.withSafePredicate=S,exports.withTap=C,exports.withTimeout=w;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|