ts-rules-composer 0.0.1
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/.editorconfig +15 -0
- package/.eslintrc.json +66 -0
- package/.github/CONTRIBUTING.md +3 -0
- package/.github/ISSUE_TEMPLATE.md +9 -0
- package/.github/PULL_REQUEST_TEMPLATE.md +7 -0
- package/.github/workflows/docs.yml +29 -0
- package/.github/workflows/publish.yml +25 -0
- package/.github/workflows/test.yml +37 -0
- package/.prettierignore +2 -0
- package/.releaserc +11 -0
- package/LICENSE +21 -0
- package/README.md +625 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +634 -0
- package/dist/index.d.ts +634 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -0
- package/src/lib/combinators/index.ts +2 -0
- package/src/lib/combinators/logic/every.spec.ts +264 -0
- package/src/lib/combinators/logic/every.ts +47 -0
- package/src/lib/combinators/logic/if-else.spec.ts +72 -0
- package/src/lib/combinators/logic/if-else.ts +39 -0
- package/src/lib/combinators/logic/index.ts +8 -0
- package/src/lib/combinators/logic/match.spec.ts +186 -0
- package/src/lib/combinators/logic/match.ts +92 -0
- package/src/lib/combinators/logic/not.spec.ts +62 -0
- package/src/lib/combinators/logic/not.ts +25 -0
- package/src/lib/combinators/logic/one-of.spec.ts +68 -0
- package/src/lib/combinators/logic/one-of.ts +41 -0
- package/src/lib/combinators/logic/unless.spec.ts +61 -0
- package/src/lib/combinators/logic/unless.ts +27 -0
- package/src/lib/combinators/logic/when.spec.ts +123 -0
- package/src/lib/combinators/logic/when.ts +29 -0
- package/src/lib/combinators/logic/with-fallback.spec.ts +72 -0
- package/src/lib/combinators/logic/with-fallback.ts +37 -0
- package/src/lib/combinators/utility/index.ts +8 -0
- package/src/lib/combinators/utility/inject.spec.ts +55 -0
- package/src/lib/combinators/utility/inject.ts +25 -0
- package/src/lib/combinators/utility/map-error.spec.ts +63 -0
- package/src/lib/combinators/utility/map-error.ts +35 -0
- package/src/lib/combinators/utility/tap.spec.ts +102 -0
- package/src/lib/combinators/utility/tap.ts +38 -0
- package/src/lib/combinators/utility/validate-field.spec.ts +150 -0
- package/src/lib/combinators/utility/validate-field.ts +59 -0
- package/src/lib/combinators/utility/with-debug.spec.ts +71 -0
- package/src/lib/combinators/utility/with-debug.ts +55 -0
- package/src/lib/combinators/utility/with-memoize.spec.ts +82 -0
- package/src/lib/combinators/utility/with-memoize.ts +81 -0
- package/src/lib/combinators/utility/with-retry.spec.ts +220 -0
- package/src/lib/combinators/utility/with-retry.ts +68 -0
- package/src/lib/combinators/utility/with-timeout.spec.ts +115 -0
- package/src/lib/combinators/utility/with-timeout.ts +34 -0
- package/src/lib/composition/compose-rules.spec.ts +211 -0
- package/src/lib/composition/compose-rules.ts +47 -0
- package/src/lib/composition/index.ts +3 -0
- package/src/lib/composition/pipe-rules.spec.ts +220 -0
- package/src/lib/composition/pipe-rules.ts +44 -0
- package/src/lib/composition/pipe.spec.ts +47 -0
- package/src/lib/composition/pipe.ts +106 -0
- package/src/lib/helpers/context/has-context.ts +13 -0
- package/src/lib/helpers/context/index.ts +3 -0
- package/src/lib/helpers/context/require-context.spec.ts +55 -0
- package/src/lib/helpers/context/require-context.ts +61 -0
- package/src/lib/helpers/context/with-lazy-context.spec.ts +74 -0
- package/src/lib/helpers/context/with-lazy-context.ts +35 -0
- package/src/lib/helpers/index.ts +6 -0
- package/src/lib/helpers/result/fail.ts +15 -0
- package/src/lib/helpers/result/index.ts +2 -0
- package/src/lib/helpers/result/pass.ts +14 -0
- package/src/lib/helpers/retry/calculate-delay.ts +31 -0
- package/src/lib/index.ts +4 -0
- package/src/lib/types/composition-options.ts +7 -0
- package/src/lib/types/debug-options.ts +36 -0
- package/src/lib/types/index.ts +4 -0
- package/src/lib/types/rule-result.ts +16 -0
- package/src/lib/types/rule.ts +21 -0
- package/src/test/helpers/get-rule-error.ts +23 -0
- package/src/test/integration.spec.ts +285 -0
- package/tsconfig.json +55 -0
- package/tsup.config.ts +36 -0
- package/vitest.config.ts +16 -0
package/README.md
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
# TS Rules Composer 🎼
|
|
2
|
+
|
|
3
|
+
[](https://npmjs.com/package/ts-rules-composer)
|
|
4
|
+
[](https://bundlephobia.com/package/ts-rules-composer)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
A **dependency-free**, type-safe validation engine for composing complex business rules with elegant pipelines.
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
// Example: E-commerce checkout
|
|
11
|
+
const validateCheckout = pipeRules([
|
|
12
|
+
validateCart,
|
|
13
|
+
match(paymentMethod, {
|
|
14
|
+
'credit_card': validateCreditCard,
|
|
15
|
+
'paypal': validatePaypal
|
|
16
|
+
}),
|
|
17
|
+
withRetry(validateInventory, { attempts: 3 })
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
const result = await validateCheckout(order);
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Features ✨
|
|
24
|
+
|
|
25
|
+
- 🧩 **Composable** - Build pipelines with 25+ combinators (`when`, `unless`, `mapError`, etc.)
|
|
26
|
+
- 🚀 **Zero Dependencies** - Lightweight (under 5KB gzipped)
|
|
27
|
+
- 🦾 **TypeScript First** - Full inference for inputs, contexts, and errors
|
|
28
|
+
- ⏱ **Async Ready** - Mix sync/async rules seamlessly
|
|
29
|
+
- 🛡 **Context-Aware** - Shared validation state
|
|
30
|
+
- 🔌 **Extensible** - Easily create custom combinators that integrate seamlessly
|
|
31
|
+
- 📊 **Instrumentation** - Debugging & metrics out-of-the-box
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm install ts-rules-composer
|
|
37
|
+
# or
|
|
38
|
+
yarn add ts-rules-composer
|
|
39
|
+
# or
|
|
40
|
+
pnpm add ts-rules-composer
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Core Concepts
|
|
44
|
+
|
|
45
|
+
### 1. Rules
|
|
46
|
+
|
|
47
|
+
The atomic validation unit:
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
type Rule<TInput, TError = string, TContext = unknown> = (
|
|
51
|
+
input: TInput,
|
|
52
|
+
context?: TContext
|
|
53
|
+
) => Promise<RuleResult<TError>> | RuleResult<TError>;
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### 2. Results
|
|
57
|
+
|
|
58
|
+
Always returns:
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
type RuleResult<TError> =
|
|
62
|
+
| { readonly status: "passed" }
|
|
63
|
+
| { readonly status: "failed"; readonly error: TError };
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Usage Examples
|
|
67
|
+
|
|
68
|
+
### Example 1: Financial Transaction Validation
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
import {
|
|
72
|
+
pipeRules,
|
|
73
|
+
match,
|
|
74
|
+
withRetry,
|
|
75
|
+
withMemoize,
|
|
76
|
+
withTimeout,
|
|
77
|
+
when
|
|
78
|
+
} from 'ts-rules-composer';
|
|
79
|
+
|
|
80
|
+
// 1. Basic validators
|
|
81
|
+
const validateAmount = (tx: Transaction) =>
|
|
82
|
+
tx.amount > 0 ? pass() : fail("Amount must be positive");
|
|
83
|
+
|
|
84
|
+
const validateCurrency = (tx: Transaction) =>
|
|
85
|
+
SUPPORTED_CURRENCIES.includes(tx.currency)
|
|
86
|
+
? pass()
|
|
87
|
+
: fail(`Unsupported currency: ${tx.currency}`);
|
|
88
|
+
|
|
89
|
+
// 2. Memoized fraud check (cached for 5 minutes)
|
|
90
|
+
const checkFraudRisk = withMemoize(
|
|
91
|
+
async (tx: Transaction) => {
|
|
92
|
+
const risk = await fraudService.assess(tx);
|
|
93
|
+
return risk.score < 5 ? pass() : fail("High fraud risk");
|
|
94
|
+
},
|
|
95
|
+
tx => `${tx.userId}-${tx.amount}-${tx.recipient}`,
|
|
96
|
+
{ ttl: 300000 }
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
// 3. Payment method handling
|
|
100
|
+
const validatePaymentMethod = match(
|
|
101
|
+
tx => tx.paymentType,
|
|
102
|
+
{
|
|
103
|
+
"credit_card": pipeRules([
|
|
104
|
+
validateCardNumber,
|
|
105
|
+
validateExpiry,
|
|
106
|
+
withTimeout(bankAuthCheck, 3000, "Bank auth timeout")
|
|
107
|
+
]),
|
|
108
|
+
"crypto": validateWalletAddress,
|
|
109
|
+
"bank_transfer": validateIBAN
|
|
110
|
+
}
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
// 4. Complete pipeline
|
|
114
|
+
const validateTransaction = pipeRules([
|
|
115
|
+
validateAmount,
|
|
116
|
+
validateCurrency,
|
|
117
|
+
|
|
118
|
+
// Only run fraud check for transactions > $1000
|
|
119
|
+
when(
|
|
120
|
+
tx => tx.amount > 1000,
|
|
121
|
+
withRetry(checkFraudRisk, { attempts: 2 })
|
|
122
|
+
),
|
|
123
|
+
|
|
124
|
+
validatePaymentMethod,
|
|
125
|
+
|
|
126
|
+
// Compliance check (different for business/personal)
|
|
127
|
+
match(
|
|
128
|
+
tx => tx.accountType,
|
|
129
|
+
{
|
|
130
|
+
"business": validateBusinessTransfer,
|
|
131
|
+
"personal": validatePersonalTransfer
|
|
132
|
+
}
|
|
133
|
+
)
|
|
134
|
+
]);
|
|
135
|
+
|
|
136
|
+
// Usage
|
|
137
|
+
const result = await validateTransaction(paymentRequest, {
|
|
138
|
+
userKycStatus: await getKycStatus(userId)
|
|
139
|
+
});
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### Example 2: User Registration
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
import { pipeRules, every, match, withMetrics } from 'ts-rules-composer';
|
|
146
|
+
|
|
147
|
+
const validateUser = pipeRules([
|
|
148
|
+
// Sequential validation
|
|
149
|
+
validateUsernameFormat,
|
|
150
|
+
withMemoize(checkUsernameAvailability, { ttl: 60000 }),
|
|
151
|
+
|
|
152
|
+
// Parallel validation
|
|
153
|
+
every([
|
|
154
|
+
validatePasswordStrength,
|
|
155
|
+
validateEmailFormat,
|
|
156
|
+
checkEmailUnique
|
|
157
|
+
]),
|
|
158
|
+
|
|
159
|
+
// pattern matching routing
|
|
160
|
+
match(
|
|
161
|
+
user => user.role,
|
|
162
|
+
{
|
|
163
|
+
'admin': validateAdminPrivileges,
|
|
164
|
+
'user': validateStandardUser
|
|
165
|
+
},
|
|
166
|
+
fail('Unknown role')
|
|
167
|
+
)
|
|
168
|
+
]);
|
|
169
|
+
|
|
170
|
+
// With instrumentation
|
|
171
|
+
const instrumentedValidation = withMetrics(validateUser, {
|
|
172
|
+
onEnd: (result) => trackAnalytics(result)
|
|
173
|
+
});
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Example 3: Healthcare Appointment System
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
const bookAppointment = pipeRules([
|
|
180
|
+
// Context-aware validation
|
|
181
|
+
requireContextRule(
|
|
182
|
+
"Missing schedule data",
|
|
183
|
+
(appt, ctx: ScheduleContext) => validateDoctorAvailability(appt, ctx)
|
|
184
|
+
),
|
|
185
|
+
|
|
186
|
+
// Error transformation
|
|
187
|
+
mapError(
|
|
188
|
+
validateInsurance,
|
|
189
|
+
error => `Insurance error: ${error.code}`
|
|
190
|
+
),
|
|
191
|
+
|
|
192
|
+
// Time-sensitive check
|
|
193
|
+
withTimeout(
|
|
194
|
+
checkFacilityCapacity,
|
|
195
|
+
5000,
|
|
196
|
+
"System timeout"
|
|
197
|
+
)
|
|
198
|
+
]);
|
|
199
|
+
|
|
200
|
+
// Usage
|
|
201
|
+
const result = await bookAppointment(newAppointment, clinicSchedule);
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### Example 4: Content Moderation System
|
|
205
|
+
|
|
206
|
+
```typescript
|
|
207
|
+
import {
|
|
208
|
+
pipeRules,
|
|
209
|
+
validateField,
|
|
210
|
+
requireContextRule,
|
|
211
|
+
inject,
|
|
212
|
+
tap
|
|
213
|
+
} from 'ts-rules-composer';
|
|
214
|
+
|
|
215
|
+
// 1. Strongly typed context
|
|
216
|
+
type ModerationContext = {
|
|
217
|
+
moderatorId: string;
|
|
218
|
+
permissions: string[];
|
|
219
|
+
environment: 'staging' | 'production';
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
// 2. Rule factory with dependency injection
|
|
223
|
+
const createModerationRules = (logger: LoggerService) =>
|
|
224
|
+
pipeRules([
|
|
225
|
+
// Enforce context requirements
|
|
226
|
+
requireContextRule(
|
|
227
|
+
"Moderator context required",
|
|
228
|
+
(post, ctx: ModerationContext) => pipeRules([
|
|
229
|
+
|
|
230
|
+
// Core validations
|
|
231
|
+
validateField(post => post.content, content =>
|
|
232
|
+
content.length > 0 || fail("Empty content")
|
|
233
|
+
),
|
|
234
|
+
|
|
235
|
+
// Environment-specific rule
|
|
236
|
+
when(
|
|
237
|
+
(_, ctx) => ctx.environment === 'production',
|
|
238
|
+
validateField(post => post.tags, tags =>
|
|
239
|
+
tags.length <= 5 || fail("Too many tags")
|
|
240
|
+
)
|
|
241
|
+
),
|
|
242
|
+
|
|
243
|
+
// Permission-based rule
|
|
244
|
+
when(
|
|
245
|
+
(_, ctx) => ctx.permissions.includes('FLAG_SENSITIVE'),
|
|
246
|
+
validateField(post => post.content, checkSensitiveContent)
|
|
247
|
+
),
|
|
248
|
+
|
|
249
|
+
// Logging side effect
|
|
250
|
+
tap((post, ctx) => {
|
|
251
|
+
logger.log({
|
|
252
|
+
action: 'moderate',
|
|
253
|
+
moderator: ctx.moderatorId,
|
|
254
|
+
postId: post.id
|
|
255
|
+
});
|
|
256
|
+
})
|
|
257
|
+
])
|
|
258
|
+
)
|
|
259
|
+
]);
|
|
260
|
+
|
|
261
|
+
// 3. Inject dependencies
|
|
262
|
+
const moderatePost = inject(
|
|
263
|
+
{ logger: new Logger() },
|
|
264
|
+
createModerationRules
|
|
265
|
+
);
|
|
266
|
+
|
|
267
|
+
// 4. Usage
|
|
268
|
+
const postModerationResult = await moderatePost(
|
|
269
|
+
{ id: "post123", content: "Hello", tags: ["a"] },
|
|
270
|
+
{
|
|
271
|
+
moderatorId: "user456",
|
|
272
|
+
permissions: ["FLAG_SENSITIVE"],
|
|
273
|
+
environment: "production"
|
|
274
|
+
}
|
|
275
|
+
);
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
## API Reference
|
|
279
|
+
|
|
280
|
+
### Core Functions
|
|
281
|
+
|
|
282
|
+
#### `pipeRules(rules, options?)`
|
|
283
|
+
|
|
284
|
+
Sequentially executes rules left-to-right (fails fast)
|
|
285
|
+
|
|
286
|
+
```typescript
|
|
287
|
+
const validateUser = pipeRules([
|
|
288
|
+
validateEmailFormat,
|
|
289
|
+
checkEmailUnique,
|
|
290
|
+
validatePassword
|
|
291
|
+
], { cloneContext: true })
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
#### `composeRules(rules, options?)`
|
|
295
|
+
|
|
296
|
+
Sequentially executes rules right-to-left (fails fast)
|
|
297
|
+
|
|
298
|
+
```typescript
|
|
299
|
+
const processInput = composeRules([
|
|
300
|
+
normalizeData,
|
|
301
|
+
validateInput,
|
|
302
|
+
sanitizeInput
|
|
303
|
+
])
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
#### `every(rules, options?)`
|
|
307
|
+
|
|
308
|
+
Runs rules in parallel (collects all errors)
|
|
309
|
+
|
|
310
|
+
```typescript
|
|
311
|
+
const validateProfile = every([
|
|
312
|
+
validateAvatar,
|
|
313
|
+
validateBio,
|
|
314
|
+
validateLinks
|
|
315
|
+
])
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
### Control Flow
|
|
319
|
+
|
|
320
|
+
#### `match(accessor, cases, defaultCase?)`
|
|
321
|
+
|
|
322
|
+
Pattern matching routing
|
|
323
|
+
|
|
324
|
+
```typescript
|
|
325
|
+
const validatePayment = match(
|
|
326
|
+
order => order.payment.type,
|
|
327
|
+
{
|
|
328
|
+
credit: validateCreditCard,
|
|
329
|
+
paypal: validatePaypal,
|
|
330
|
+
crypto: validateCrypto
|
|
331
|
+
},
|
|
332
|
+
fail("Unsupported payment method")
|
|
333
|
+
)
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
#### `when(condition, rule)`
|
|
337
|
+
|
|
338
|
+
Executes only if condition is true
|
|
339
|
+
|
|
340
|
+
```typescript
|
|
341
|
+
const validateAdmin = when(
|
|
342
|
+
user => user.role === "admin",
|
|
343
|
+
checkAdminPrivileges
|
|
344
|
+
)
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
#### `unless(condition, rule)`
|
|
348
|
+
|
|
349
|
+
Executes only if condition is false
|
|
350
|
+
|
|
351
|
+
```typescript
|
|
352
|
+
const validateGuest = unless(
|
|
353
|
+
user => user.isVerified,
|
|
354
|
+
requireVerification
|
|
355
|
+
)
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
#### `ifElse(condition, ifRule, elseRule?)`
|
|
359
|
+
|
|
360
|
+
Branch between two rules
|
|
361
|
+
|
|
362
|
+
```typescript
|
|
363
|
+
const validateAge = ifElse(
|
|
364
|
+
user => user.age >= 18,
|
|
365
|
+
validateAdult,
|
|
366
|
+
validateMinor
|
|
367
|
+
)
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
#### `oneOf(...rules)`
|
|
371
|
+
|
|
372
|
+
Tries rules until one passes
|
|
373
|
+
|
|
374
|
+
```typescript
|
|
375
|
+
const validateContact = oneOf(
|
|
376
|
+
validateEmail,
|
|
377
|
+
validatePhone,
|
|
378
|
+
validateUsername
|
|
379
|
+
)
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
#### `withFallback(mainRule, fallbackRule, options?)`
|
|
383
|
+
|
|
384
|
+
Fallback when main rule fails
|
|
385
|
+
|
|
386
|
+
```typescript
|
|
387
|
+
const validateWithFallback = withFallback(
|
|
388
|
+
primaryValidation,
|
|
389
|
+
backupValidation
|
|
390
|
+
)
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
### Error Handling
|
|
394
|
+
|
|
395
|
+
#### `mapError(rule, transform)`
|
|
396
|
+
|
|
397
|
+
Transforms error output
|
|
398
|
+
|
|
399
|
+
```typescript
|
|
400
|
+
const friendlyErrors = mapError(
|
|
401
|
+
validatePassword,
|
|
402
|
+
err => `Security error: ${err}`
|
|
403
|
+
)
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
#### `not(rule, error)`
|
|
407
|
+
|
|
408
|
+
Inverts rule logic
|
|
409
|
+
|
|
410
|
+
```typescript
|
|
411
|
+
const isNotBanned = not(
|
|
412
|
+
checkBanStatus,
|
|
413
|
+
"Account must be active"
|
|
414
|
+
)
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
### Performance
|
|
418
|
+
|
|
419
|
+
#### `withMemoize(rule, keyFn, options?)`
|
|
420
|
+
|
|
421
|
+
Caches rule results
|
|
422
|
+
|
|
423
|
+
```typescript
|
|
424
|
+
const cachedCheck = withMemoize(
|
|
425
|
+
dbUserLookup,
|
|
426
|
+
user => user.id,
|
|
427
|
+
{ ttl: 30000, maxSize: 100 }
|
|
428
|
+
)
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
#### `withTimeout(rule, ms, timeoutError)`
|
|
432
|
+
|
|
433
|
+
Adds execution timeout
|
|
434
|
+
|
|
435
|
+
```typescript
|
|
436
|
+
const timeboundRule = withTimeout(
|
|
437
|
+
apiCheck,
|
|
438
|
+
3000,
|
|
439
|
+
"Request timed out"
|
|
440
|
+
)
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
#### `withRetry(rule, options)`
|
|
444
|
+
|
|
445
|
+
Automatic retries on failure
|
|
446
|
+
|
|
447
|
+
```typescript
|
|
448
|
+
const resilientRule = withRetry(
|
|
449
|
+
flakyServiceCheck,
|
|
450
|
+
{ attempts: 3, delayMs: 1000 }
|
|
451
|
+
)
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
### Context Management
|
|
455
|
+
|
|
456
|
+
#### `requireContextRule(error, rule, typeGuard?)`
|
|
457
|
+
|
|
458
|
+
Enforces context requirements
|
|
459
|
+
|
|
460
|
+
```typescript
|
|
461
|
+
const authRule = requireContextRule(
|
|
462
|
+
"Authentication required",
|
|
463
|
+
(input, ctx: AuthContext) => checkPermissions(ctx.token),
|
|
464
|
+
(ctx): ctx is AuthContext => !!ctx?.token
|
|
465
|
+
)
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
#### `withLazyContext(loader, rule)`
|
|
469
|
+
|
|
470
|
+
Lazy-loads context
|
|
471
|
+
|
|
472
|
+
```typescript
|
|
473
|
+
const profileRule = withLazyContext(
|
|
474
|
+
userId => fetchProfile(userId),
|
|
475
|
+
validateProfile
|
|
476
|
+
)
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
#### `hasContext(ctx)`
|
|
480
|
+
|
|
481
|
+
Type guard for context
|
|
482
|
+
|
|
483
|
+
```typescript
|
|
484
|
+
if (hasContext<AuthContext>(context)) {
|
|
485
|
+
// context is now typed as AuthContext
|
|
486
|
+
}
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
### Instrumentation
|
|
490
|
+
|
|
491
|
+
#### `withDebug(rule, options)`
|
|
492
|
+
|
|
493
|
+
Adds debug logging
|
|
494
|
+
|
|
495
|
+
```typescript
|
|
496
|
+
const debugRule = withDebug(validateOrder, {
|
|
497
|
+
name: "OrderValidation",
|
|
498
|
+
onEnd: (input, result) => console.log(result)
|
|
499
|
+
})
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
#### `tap(effect)`
|
|
503
|
+
|
|
504
|
+
Performs side effects
|
|
505
|
+
|
|
506
|
+
```typescript
|
|
507
|
+
const loggedRule = tap((input, result) => {
|
|
508
|
+
analytics.trackValidation(input, result)
|
|
509
|
+
})
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
### Utilities
|
|
513
|
+
|
|
514
|
+
#### `pass()`
|
|
515
|
+
|
|
516
|
+
Creates success result
|
|
517
|
+
|
|
518
|
+
```typescript
|
|
519
|
+
const success = pass()
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
#### `fail(error)`
|
|
523
|
+
|
|
524
|
+
Creates failure result
|
|
525
|
+
|
|
526
|
+
```typescript
|
|
527
|
+
const failure = fail("Invalid input")
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
#### `getRuleError(result)`
|
|
531
|
+
|
|
532
|
+
Extracts error from failed result
|
|
533
|
+
|
|
534
|
+
```typescript
|
|
535
|
+
if (result.status === "failed") {
|
|
536
|
+
const error = getRuleError(result)
|
|
537
|
+
}
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
#### `validateField(getter, rule, defaultValue?)`
|
|
541
|
+
|
|
542
|
+
Validates object fields
|
|
543
|
+
|
|
544
|
+
```typescript
|
|
545
|
+
const validateEmail = validateField(
|
|
546
|
+
user => user.email,
|
|
547
|
+
validateEmailFormat
|
|
548
|
+
)
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
#### `inject(dependency, ruleFactory)`
|
|
552
|
+
|
|
553
|
+
Dependency injection
|
|
554
|
+
|
|
555
|
+
```typescript
|
|
556
|
+
const createDbRule = (db: Database) => (input: string) =>
|
|
557
|
+
db.exists(input) ? pass() : fail("Not found")
|
|
558
|
+
|
|
559
|
+
const dbRule = inject(database, createDbRule)
|
|
560
|
+
```
|
|
561
|
+
|
|
562
|
+
### Core Functions
|
|
563
|
+
|
|
564
|
+
| Function | Description | Example |
|
|
565
|
+
|----------|-------------|---------|
|
|
566
|
+
| `pipeRules` | Sequential validation left-right (fail-fast) | `pipeRules([checkA, checkB])` |
|
|
567
|
+
| `composeRules` | Sequential validation right-left (fail-fast) | `composeRules([checkA, checkB])` |
|
|
568
|
+
| `every` | Parallel validation (collect all errors) | `every([checkX, checkY])` |
|
|
569
|
+
| `match` | Pattern matching routing | `match(getUserType, { admin: ruleA, user: ruleB })` |
|
|
570
|
+
| `ifElse` | Conditional routing | `ifElse(isUnderAge, validateMinorAccount, validateAdultAccount)` |
|
|
571
|
+
|
|
572
|
+
### Combinators
|
|
573
|
+
|
|
574
|
+
| Combinator | Purpose | Example |
|
|
575
|
+
|------------|---------|---------|
|
|
576
|
+
| `when` | Conditional execution | `when(isAdmin, validateAdmin)` |
|
|
577
|
+
| `unless` | Negative condition | `unless(isGuest, validateAccount)` |
|
|
578
|
+
| `not` | Invert rule logic | `not(isBanned, "Must not be banned")` |
|
|
579
|
+
| `oneOf` | First-successful validation | `oneOf(validateV1, validateV2)` |
|
|
580
|
+
| `withFallback` | Fallback rule | `withFallback(primary, backup)` |
|
|
581
|
+
|
|
582
|
+
### Performance
|
|
583
|
+
|
|
584
|
+
| Utility | Use Case | Example |
|
|
585
|
+
|---------|----------|---------|
|
|
586
|
+
| `withMemoize` | Cache results | `withMemoize(expensiveCheck, { ttl: 30000 })` |
|
|
587
|
+
| `withTimeout` | Add time limit | `withTimeout(networkCall, 3000, "Timeout")` |
|
|
588
|
+
| `withRetry` | Automatic retries | `withRetry(unstableAPI, { attempts: 3 })` |
|
|
589
|
+
|
|
590
|
+
### Instrumentation
|
|
591
|
+
|
|
592
|
+
| Tool | Purpose | Example |
|
|
593
|
+
|------|---------|---------|
|
|
594
|
+
| `withDebug` | Debug logging | `withDebug(rule, { name: "Validation" })` |
|
|
595
|
+
| `tap` | Side effects | `tap((input, result) => log(result))` |
|
|
596
|
+
|
|
597
|
+
## Best Practices
|
|
598
|
+
|
|
599
|
+
1. **Small Rules** - Keep each rule focused
|
|
600
|
+
2. **Pure Functions** - Avoid side effects in rules
|
|
601
|
+
3. **Memoize** - Cache expensive validations
|
|
602
|
+
4. **Type Narrowing** - Use `requireContextRule` for safety
|
|
603
|
+
5. **Instrument** - Add metrics in production
|
|
604
|
+
|
|
605
|
+
```mermaid
|
|
606
|
+
graph TD
|
|
607
|
+
A[Input] --> B{Valid?}
|
|
608
|
+
B -->|Yes| C[Process]
|
|
609
|
+
B -->|No| D[Collect Errors]
|
|
610
|
+
C --> E[Output]
|
|
611
|
+
D --> E
|
|
612
|
+
```
|
|
613
|
+
|
|
614
|
+
## Contributing
|
|
615
|
+
|
|
616
|
+
1. Fork the repository
|
|
617
|
+
2. Create a feature branch (`git checkout -b feat/amazing-feature`)
|
|
618
|
+
3. Commit changes (`git commit -m 'Add amazing feature'`)
|
|
619
|
+
4. Push to branch (`git push origin feat/amazing-feature`)
|
|
620
|
+
5. Open a Pull Request
|
|
621
|
+
|
|
622
|
+
## License
|
|
623
|
+
|
|
624
|
+
MIT © Breno Magalhães
|
|
625
|
+
**Like this project?** ⭐️ [Star it on GitHub](https://github.com/Brenopms/ts-rules-composer)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var E=n=>n!==void 0;var a=n=>({status:"failed",error:n});var s=()=>({status:"passed"});var d=(n,e,t)=>{let o=t||(u=>u!==void 0);return async(u,T)=>o(T)?e(u,T):a(n)};var A=(n,e)=>async t=>{try{let r=await n(t);return e(t,r)}catch(r){let o=r instanceof Error?r.message:"Context loading failed";return a(o)}};var m=(n,e,t)=>{let r={fixed:()=>t,linear:o=>t*o,exponential:o=>t*2**(o-1)};if(!n)return r.fixed(e);if(typeof n=="string"){let o=r[n];return o?o(e):t}return typeof n=="function"?n(e):r.fixed(e)};var B=(n,e={})=>async(t,r)=>{let o=e!=null&&e.cloneContext?structuredClone(r):r,T=(await Promise.all(n.map(p=>p(t,o)))).flatMap(p=>p.status==="failed"?[p.error]:[]);return T.length>0?a(T):s()};var v=(n,e,t)=>async(r,o)=>await n(r,o)?e(r,o):t?t(r,o):s();var x=n=>typeof n=="function",S=(n,e,t)=>async(r,o)=>{let u=await n(r,o),T=e[u];return T?T(r,o):t!==void 0?x(t)?t(r,o):a(t):a(`No matching rule for key: ${String(u)}`)};var K=(n,e)=>async(t,r)=>(await n(t,r)).status==="passed"?a(e):s();var J=(...n)=>async(e,t)=>{let r=[];if(!n||n.length===0)return s();for(let o of n){let u=await o(e,t);if(u.status==="passed")return s();r.push(u.error);}return a(r)};var V=(n,e)=>async(t,r)=>await n(t)?s():e(t,r);var j=(n,e)=>async(t,r)=>await n(t)?e(t,r):s();var $=(n,e,t={})=>async(r,o)=>{let u=await n(r,o);return u.status==="failed"&&(!t.onlyFallbackOn||t.onlyFallbackOn(u.error))?e(r,o):u};var U=(n,e)=>{let t=e(n);return r=>t(r)};var Z=(n,e)=>async(t,r)=>{let o=await n(t,r);return o.status==="failed"?a(e(o.error)):s()};var tr=(n,e,t={})=>{let r=new Map;return async(o,u)=>{let T=e(o),p=Date.now();if(t.ttl)for(let[l,f]of r)p-f.timestamp>t.ttl&&r.delete(l);if(t.maxSize&&r.size>=t.maxSize){let l=r.keys().next().value;l&&r.delete(l);}if(r.has(T))return r.get(T).result;let i=n(o,u);return r.set(T,{result:i,timestamp:p}),i instanceof Promise&&i.catch(()=>r.delete(T)),i}};function or(n,e,t){return async(r,o)=>{let u=n(r),T=u!==void 0?u:t;return T===void 0?a("Missing required value"):e(T,o)}}var Tr=n=>e=>async(t,r)=>{let o=await e(t,r);try{await n(t,o,r);}catch(u){console.error("Tap effect failed:",u);}return o};var sr=(n,e)=>{let t=typeof e=="string"?{name:e}:e;return async(r,o)=>{var p,i,l;let u=performance.now(),T=t.name||n.name||"anonymous_rule";try{(p=t.onStart)==null||p.call(t,r,o);let f=await n(r,o),c=performance.now()-u;return (i=t.onEnd)==null||i.call(t,r,f,o,{ruleName:T,duration:c,startTime:u}),f}catch(f){let c=performance.now()-u;throw (l=t.onError)==null||l.call(t,f,r,o,c),f}}};var ir=(n,e={})=>{let{attempts:t=3,delayMs:r=100,shouldRetry:o=()=>true}=e;return async(u,T)=>{let p;for(let i=1;i<=t;i++){try{let l=await n(u,T);if(l.status==="passed")return l;p=l.error;}catch(l){p=l;}if(!o(p,i))return a(p);if(i<t&&r>0){let l=m(e==null?void 0:e.retryStrategy,i,r);await new Promise(f=>setTimeout(f,l));}}return a("MAX_RETRIES_EXCEEDED")}};var mr=(n,e,t)=>async(r,o)=>{let u=new Promise(T=>setTimeout(()=>T(a(t)),e));return Promise.race([n(r,o),u])};var Cr=(n,e={})=>async(t,r)=>{let o=e!=null&&e.cloneContext?structuredClone(r):r;for(let u=n.length-1;u>=0;u--){let T=await n[u](t,o);if(T.status==="failed")return T}return s()};var gr=(n,e={})=>async(t,r)=>{let o=e!=null&&e.cloneContext?structuredClone(r):r;for(let u of n){let T=await u(t,o);if(T.status==="failed")return T}return s()};function yr(n,...e){return e.reduce((t,r)=>r(t),n)}exports.calculateDelay=m;exports.composeRules=Cr;exports.every=B;exports.fail=a;exports.hasContext=E;exports.ifElse=v;exports.inject=U;exports.mapError=Z;exports.match=S;exports.not=K;exports.oneOf=J;exports.pass=s;exports.pipe=yr;exports.pipeRules=gr;exports.requireContextRule=d;exports.tap=Tr;exports.unless=V;exports.validateField=or;exports.when=j;exports.withDebug=sr;exports.withFallback=$;exports.withLazyContext=A;exports.withMemoize=tr;exports.withRetry=ir;exports.withTimeout=mr;//# sourceMappingURL=index.cjs.map
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|