ts-rules-composer 0.0.1 → 1.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/README.md +310 -42
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +335 -55
- package/dist/index.d.ts +335 -55
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +27 -6
- package/.editorconfig +0 -15
- package/.eslintrc.json +0 -66
- package/.github/CONTRIBUTING.md +0 -3
- package/.github/ISSUE_TEMPLATE.md +0 -9
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
- package/.github/workflows/docs.yml +0 -29
- package/.github/workflows/publish.yml +0 -25
- package/.github/workflows/test.yml +0 -37
- package/.prettierignore +0 -2
- package/.releaserc +0 -11
- package/src/lib/combinators/index.ts +0 -2
- package/src/lib/combinators/logic/every.spec.ts +0 -264
- package/src/lib/combinators/logic/every.ts +0 -47
- package/src/lib/combinators/logic/if-else.spec.ts +0 -72
- package/src/lib/combinators/logic/if-else.ts +0 -39
- package/src/lib/combinators/logic/index.ts +0 -8
- package/src/lib/combinators/logic/match.spec.ts +0 -186
- package/src/lib/combinators/logic/match.ts +0 -92
- package/src/lib/combinators/logic/not.spec.ts +0 -62
- package/src/lib/combinators/logic/not.ts +0 -25
- package/src/lib/combinators/logic/one-of.spec.ts +0 -68
- package/src/lib/combinators/logic/one-of.ts +0 -41
- package/src/lib/combinators/logic/unless.spec.ts +0 -61
- package/src/lib/combinators/logic/unless.ts +0 -27
- package/src/lib/combinators/logic/when.spec.ts +0 -123
- package/src/lib/combinators/logic/when.ts +0 -29
- package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
- package/src/lib/combinators/logic/with-fallback.ts +0 -37
- package/src/lib/combinators/utility/index.ts +0 -8
- package/src/lib/combinators/utility/inject.spec.ts +0 -55
- package/src/lib/combinators/utility/inject.ts +0 -25
- package/src/lib/combinators/utility/map-error.spec.ts +0 -63
- package/src/lib/combinators/utility/map-error.ts +0 -35
- package/src/lib/combinators/utility/tap.spec.ts +0 -102
- package/src/lib/combinators/utility/tap.ts +0 -38
- package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
- package/src/lib/combinators/utility/validate-field.ts +0 -59
- package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
- package/src/lib/combinators/utility/with-debug.ts +0 -55
- package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
- package/src/lib/combinators/utility/with-memoize.ts +0 -81
- package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
- package/src/lib/combinators/utility/with-retry.ts +0 -68
- package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
- package/src/lib/combinators/utility/with-timeout.ts +0 -34
- package/src/lib/composition/compose-rules.spec.ts +0 -211
- package/src/lib/composition/compose-rules.ts +0 -47
- package/src/lib/composition/index.ts +0 -3
- package/src/lib/composition/pipe-rules.spec.ts +0 -220
- package/src/lib/composition/pipe-rules.ts +0 -44
- package/src/lib/composition/pipe.spec.ts +0 -47
- package/src/lib/composition/pipe.ts +0 -106
- package/src/lib/helpers/context/has-context.ts +0 -13
- package/src/lib/helpers/context/index.ts +0 -3
- package/src/lib/helpers/context/require-context.spec.ts +0 -55
- package/src/lib/helpers/context/require-context.ts +0 -61
- package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
- package/src/lib/helpers/context/with-lazy-context.ts +0 -35
- package/src/lib/helpers/index.ts +0 -6
- package/src/lib/helpers/result/fail.ts +0 -15
- package/src/lib/helpers/result/index.ts +0 -2
- package/src/lib/helpers/result/pass.ts +0 -14
- package/src/lib/helpers/retry/calculate-delay.ts +0 -31
- package/src/lib/index.ts +0 -4
- package/src/lib/types/composition-options.ts +0 -7
- package/src/lib/types/debug-options.ts +0 -36
- package/src/lib/types/index.ts +0 -4
- package/src/lib/types/rule-result.ts +0 -16
- package/src/lib/types/rule.ts +0 -21
- package/src/test/helpers/get-rule-error.ts +0 -23
- package/src/test/integration.spec.ts +0 -285
- package/tsconfig.json +0 -55
- package/tsup.config.ts +0 -36
- package/vitest.config.ts +0 -16
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ A **dependency-free**, type-safe validation engine for composing complex busines
|
|
|
10
10
|
// Example: E-commerce checkout
|
|
11
11
|
const validateCheckout = pipeRules([
|
|
12
12
|
validateCart,
|
|
13
|
-
match(paymentMethod, {
|
|
13
|
+
match((order) => order.paymentMethod, {
|
|
14
14
|
'credit_card': validateCreditCard,
|
|
15
15
|
'paypal': validatePaypal
|
|
16
16
|
}),
|
|
@@ -23,12 +23,14 @@ const result = await validateCheckout(order);
|
|
|
23
23
|
## Features ✨
|
|
24
24
|
|
|
25
25
|
- 🧩 **Composable** - Build pipelines with 25+ combinators (`when`, `unless`, `mapError`, etc.)
|
|
26
|
-
- 🚀 **Zero Dependencies** - Lightweight (under
|
|
26
|
+
- 🚀 **Zero Dependencies** - Lightweight (under 2KB gzipped)
|
|
27
27
|
- 🦾 **TypeScript First** - Full inference for inputs, contexts, and errors
|
|
28
28
|
- ⏱ **Async Ready** - Mix sync/async rules seamlessly
|
|
29
29
|
- 🛡 **Context-Aware** - Shared validation state
|
|
30
30
|
- 🔌 **Extensible** - Easily create custom combinators that integrate seamlessly
|
|
31
31
|
- 📊 **Instrumentation** - Debugging & metrics out-of-the-box
|
|
32
|
+
- 🧪 **Rigorously Tested** - 95+% test coverage with 300+ test cases covering all edge cases
|
|
33
|
+
- 🌐 **Node.js + Browser Compatible** – Works in modern browsers and most Node.js versions (14+)
|
|
32
34
|
|
|
33
35
|
## Installation
|
|
34
36
|
|
|
@@ -59,12 +61,18 @@ Always returns:
|
|
|
59
61
|
|
|
60
62
|
```typescript
|
|
61
63
|
type RuleResult<TError> =
|
|
62
|
-
| { readonly status: "passed" }
|
|
63
|
-
| { readonly status: "failed"; readonly error: TError };
|
|
64
|
+
| { readonly status: "passed" }; // pass()
|
|
65
|
+
| { readonly status: "failed"; readonly error: TError }; // fail(error)
|
|
64
66
|
```
|
|
65
67
|
|
|
66
68
|
## Usage Examples
|
|
67
69
|
|
|
70
|
+
Complete examples can be found here:
|
|
71
|
+
|
|
72
|
+
- 🧑💻 [User Registration](./examples/user-registration.example.ts)
|
|
73
|
+
- 💳 [Financial Transaction Validation](./examples/financial-transaction.example.ts)
|
|
74
|
+
- 🚀 [Model Deployment Validator](./examples/model-deployment.example.ts)
|
|
75
|
+
|
|
68
76
|
### Example 1: Financial Transaction Validation
|
|
69
77
|
|
|
70
78
|
```typescript
|
|
@@ -134,15 +142,13 @@ const validateTransaction = pipeRules([
|
|
|
134
142
|
]);
|
|
135
143
|
|
|
136
144
|
// Usage
|
|
137
|
-
const result = await validateTransaction(paymentRequest
|
|
138
|
-
userKycStatus: await getKycStatus(userId)
|
|
139
|
-
});
|
|
145
|
+
const result = await validateTransaction(paymentRequest);
|
|
140
146
|
```
|
|
141
147
|
|
|
142
148
|
### Example 2: User Registration
|
|
143
149
|
|
|
144
150
|
```typescript
|
|
145
|
-
import { pipeRules, every, match
|
|
151
|
+
import { pipeRules, every, match } from 'ts-rules-composer';
|
|
146
152
|
|
|
147
153
|
const validateUser = pipeRules([
|
|
148
154
|
// Sequential validation
|
|
@@ -166,11 +172,6 @@ const validateUser = pipeRules([
|
|
|
166
172
|
fail('Unknown role')
|
|
167
173
|
)
|
|
168
174
|
]);
|
|
169
|
-
|
|
170
|
-
// With instrumentation
|
|
171
|
-
const instrumentedValidation = withMetrics(validateUser, {
|
|
172
|
-
onEnd: (result) => trackAnalytics(result)
|
|
173
|
-
});
|
|
174
175
|
```
|
|
175
176
|
|
|
176
177
|
### Example 3: Healthcare Appointment System
|
|
@@ -275,6 +276,255 @@ const postModerationResult = await moderatePost(
|
|
|
275
276
|
);
|
|
276
277
|
```
|
|
277
278
|
|
|
279
|
+
## Error Handling Standardization
|
|
280
|
+
|
|
281
|
+
This library provides consistent error handling across all validation operations through a standardized system:
|
|
282
|
+
|
|
283
|
+
### Core Principles
|
|
284
|
+
|
|
285
|
+
1. **No Uncaught Exceptions** - All errors are converted to `RuleResult` objects
|
|
286
|
+
2. **Type Safety** - Custom error types are preserved throughout operations
|
|
287
|
+
3. **Flexible Control** - Choose between safety and performance with error handling modes
|
|
288
|
+
|
|
289
|
+
### Standardization Functions
|
|
290
|
+
|
|
291
|
+
| Function | Purpose |
|
|
292
|
+
|-------------------------|-------------------------------------------------------------------------|
|
|
293
|
+
| `withSafeError` | Wraps rules to catch exceptions and convert to failed validation results|
|
|
294
|
+
| `withSafePredicate` | Safely handles predicate functions that may throw |
|
|
295
|
+
| `getNormalizedRule` | Applies consistent error handling to single rules |
|
|
296
|
+
| `getNormalizedRules` | Batch processes multiple rules with standardized error handling |
|
|
297
|
+
|
|
298
|
+
### Error Handling Modes
|
|
299
|
+
|
|
300
|
+
Configure via `RuleSafetyOptions`:
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
{
|
|
304
|
+
errorHandlingMode?: 'safe' | 'unsafe', // Default: 'safe'
|
|
305
|
+
errorTransform?: (error: unknown) => TError // Custom error conversion
|
|
306
|
+
}
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
**Modes**:
|
|
310
|
+
|
|
311
|
+
- `safe`: (Default) All errors are caught and converted to validation failures
|
|
312
|
+
- `unsafe`: Lets exceptions propagate (for performance-critical paths)
|
|
313
|
+
|
|
314
|
+
### Error Flow
|
|
315
|
+
|
|
316
|
+
```mermaid
|
|
317
|
+
graph TD
|
|
318
|
+
A[Raw Error] -->|Thrown| B{Handling Mode?}
|
|
319
|
+
B -->|safe| C[Convert to RuleResult]
|
|
320
|
+
B -->|unsafe| D[Propagate Exception]
|
|
321
|
+
C --> E[Apply errorTransform if provided]
|
|
322
|
+
E --> F[Return Failed Result]
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
### Best Practices
|
|
326
|
+
|
|
327
|
+
1. **For validation logic**:
|
|
328
|
+
|
|
329
|
+
```typescript
|
|
330
|
+
// Safe mode with custom error transformation
|
|
331
|
+
const rule = getNormalizedRule(myRule, {
|
|
332
|
+
errorTransform: (e) => ({ code: 500, message: String(e) })
|
|
333
|
+
});
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
2. **For performance-critical paths**:
|
|
337
|
+
|
|
338
|
+
```typescript
|
|
339
|
+
// Unsafe mode - ensure calling code handles exceptions
|
|
340
|
+
const fastRule = getNormalizedRule(highPerfRule, {
|
|
341
|
+
errorHandlingMode: 'unsafe'
|
|
342
|
+
});
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
3. **Custom error types**:
|
|
346
|
+
|
|
347
|
+
```typescript
|
|
348
|
+
type APIError = { status: number };
|
|
349
|
+
const apiRule: Rule<string, APIError> = /*...*/;
|
|
350
|
+
// Preserves APIError type through all transformations
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### Debugging Tips
|
|
354
|
+
|
|
355
|
+
Enable debug mode to get enhanced error information:
|
|
356
|
+
|
|
357
|
+
```typescript
|
|
358
|
+
import { withDebug } from './combinators';
|
|
359
|
+
|
|
360
|
+
const debugRule = withDebug(myRule, {
|
|
361
|
+
onError: (error) => console.error('Rule failed:', error)
|
|
362
|
+
});
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
### Error Handling Precedence Rules
|
|
366
|
+
|
|
367
|
+
**Key Principle**: Composition configuration always overrides individual rule settings. This ensures consistent behavior within each composition block.
|
|
368
|
+
|
|
369
|
+
```mermaid
|
|
370
|
+
graph TD
|
|
371
|
+
A[Composition Config] -->|Overrides| B[Individual Rule Config]
|
|
372
|
+
style A stroke:#28cc9e,stroke-width:2px
|
|
373
|
+
style B stroke:#ff9f43
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
#### Hierarchy of Control
|
|
377
|
+
|
|
378
|
+
1. **Composition-Level Setting** (Highest priority)
|
|
379
|
+
- `pipeRules/composeRules/every/oneOf` configurations
|
|
380
|
+
2. **Rule-Level Configuration** (Only applies if composition allows)
|
|
381
|
+
- `withSafeError` or `getNormalizedRule` settings
|
|
382
|
+
3. **Global Default** (`safe` mode)
|
|
383
|
+
|
|
384
|
+
#### Behavior Matrix
|
|
385
|
+
|
|
386
|
+
| Composition Mode | Rule Mode | Effective Behavior |
|
|
387
|
+
|------------------|-----------------|--------------------------|
|
|
388
|
+
| `safe` | Any | All rules run in safe mode |
|
|
389
|
+
| `unsafe` | Not specified | Rule's native behavior |
|
|
390
|
+
| `unsafe` | `safe` | Rule runs in safe mode |
|
|
391
|
+
| `unsafe` | `unsafe` | Rule runs in unsafe mode |
|
|
392
|
+
|
|
393
|
+
#### Complete Error Flow
|
|
394
|
+
|
|
395
|
+
```mermaid
|
|
396
|
+
graph TD
|
|
397
|
+
A[Raw Error] --> B{Composition<br>Configuration?}
|
|
398
|
+
B -->|safe| C[Force Safe Handling]
|
|
399
|
+
B -->|unsafe| D{Individual Rule<br>Configuration?}
|
|
400
|
+
D -->|safe or not specified| C[Propagate Exception]
|
|
401
|
+
D -->|unsafe| E
|
|
402
|
+
C --> F[Apply errorTransform]
|
|
403
|
+
F --> G[Return Failed Result]
|
|
404
|
+
E --> H[Propagate Raw Exception]
|
|
405
|
+
|
|
406
|
+
style B stroke:#28cc9e,stroke-width:2px
|
|
407
|
+
style D stroke:#ff9f43
|
|
408
|
+
classDef green fill:#e6f7e6,stroke:#28cc9e
|
|
409
|
+
classDef yellow fill:#fff8e6,stroke:#ff9f43
|
|
410
|
+
class B,D green,yellow
|
|
411
|
+
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
#### Examples
|
|
415
|
+
|
|
416
|
+
**1. Composition Forces Safe Mode** (Overrides all rules)
|
|
417
|
+
|
|
418
|
+
```typescript
|
|
419
|
+
// All rules will use safe mode regardless of their own config
|
|
420
|
+
const pipeline = pipeRules([
|
|
421
|
+
unsafeRule, // Will be forced to safe mode
|
|
422
|
+
withSafeError(rule, { // Configuration ignored
|
|
423
|
+
errorHandlingMode: 'unsafe'
|
|
424
|
+
})
|
|
425
|
+
], {
|
|
426
|
+
errorHandlingMode: 'safe' // ← Takes precedence
|
|
427
|
+
})
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
**2. Unsafe Composition with Mixed Rules**
|
|
431
|
+
|
|
432
|
+
```typescript
|
|
433
|
+
// Rules can specify their own mode since composition allows it
|
|
434
|
+
const pipeline = pipeRules([
|
|
435
|
+
unsafeRule, // Runs in unsafe mode
|
|
436
|
+
withSafeError(rule, { // Runs in safe mode
|
|
437
|
+
errorHandlingMode: 'safe'
|
|
438
|
+
})
|
|
439
|
+
], {
|
|
440
|
+
errorHandlingMode: 'unsafe' // ← Allows rule-level configs
|
|
441
|
+
})
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
## Context Cloning Options
|
|
445
|
+
|
|
446
|
+
The library provides flexible context cloning strategies to balance between performance and correctness. You can control cloning behavior through `CompositionOptions`:
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
interface CompositionOptions {
|
|
450
|
+
cloneContext?: boolean; // Enable/disable cloning
|
|
451
|
+
shallowClone?: boolean; // Use shallow clone when true
|
|
452
|
+
structuredClone?: boolean; // Force structuredClone when true
|
|
453
|
+
}
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
### Cloning Strategies
|
|
457
|
+
|
|
458
|
+
The library automatically selects the best available cloning method based on your options and runtime environment:
|
|
459
|
+
|
|
460
|
+
| Option | Priority | Speed | Depth | Special Types* | Circular Refs | Node.js | Browser |
|
|
461
|
+
|-------------------|----------|--------|-------|----------------|---------------|---------|---------|
|
|
462
|
+
| `shallowClone` | 1st | 🚀 Fast | Shallow | ❌ No | ✅ Yes | ✅ | ✅ |
|
|
463
|
+
| `structuredClone` | 2nd | 🐢 Slow | Deep | ✅ Yes | ✅ Yes | 17+ | Modern |
|
|
464
|
+
| JSON Clone | Fallback | 🏎 Fast | Deep | ❌ No | ❌ No | ✅ | ✅ |
|
|
465
|
+
|
|
466
|
+
*Special Types: Date, Map, Set, RegExp, etc.
|
|
467
|
+
|
|
468
|
+
### Usage Examples
|
|
469
|
+
|
|
470
|
+
**1. Default Behavior (Smart Auto-Detect)**
|
|
471
|
+
|
|
472
|
+
```typescript
|
|
473
|
+
// Automatically uses the best available clone method
|
|
474
|
+
pipeRules(rules, { cloneContext: true })
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
**2. Force Shallow Clone**
|
|
478
|
+
|
|
479
|
+
```typescript
|
|
480
|
+
// Fastest option - only clones top-level properties
|
|
481
|
+
pipeRules(rules, { cloneContext: true, shallowClone: true })
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
**3. Force Structured Clone**
|
|
485
|
+
|
|
486
|
+
```typescript
|
|
487
|
+
// Most accurate - preserves special object types
|
|
488
|
+
pipeRules(rules, { cloneContext: true, structuredClone: true })
|
|
489
|
+
// Falls back to JSON clone if structuredClone isn't available
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
## Best Practices
|
|
493
|
+
|
|
494
|
+
1. **Small Rules** - Keep each rule focused
|
|
495
|
+
2. **Pure Functions** - Avoid side effects in rules
|
|
496
|
+
3. **Memoize** - Cache expensive validations
|
|
497
|
+
4. **Type Narrowing** - Use `requireContextRule` for safety
|
|
498
|
+
5. **Instrument** - Add metrics in production
|
|
499
|
+
|
|
500
|
+
## 🔍 Comparison to Other Libraries
|
|
501
|
+
|
|
502
|
+
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.
|
|
503
|
+
|
|
504
|
+
Here’s how it compares to popular alternatives:
|
|
505
|
+
|
|
506
|
+
| Library | Type | Async | Context-Aware | Type Inference | Size (gzipped) | Notes |
|
|
507
|
+
| ------------------------------------------------------------------------ | ----------------------- | ----- | ------------- | -------------- | ------------- | ------------------------------------------------ |
|
|
508
|
+
| **`ts-rules-composer`** | Rule engine, functional | ✅ | ✅ | ✅ | \~4KB | Built for composing complex, contextual rules |
|
|
509
|
+
| [`zod`](https://github.com/colinhacks/zod) | Schema validation | ✅ | ❌ | ✅ | \~40KB | Excellent for static object validation |
|
|
510
|
+
| [`io-ts`](https://github.com/gcanti/io-ts) | Runtime type validation | ✅ | ❌ | ✅ | \~5KB+ | Powerful but requires deep functional patterns |
|
|
511
|
+
| [`json-rules-engine`](https://github.com/CacheControl/json-rules-engine) | Declarative JSON rules | ✅ | ❌ | ❌ | \~25KB | Config-based rules, limited type safety |
|
|
512
|
+
| [`casl`](https://casl.js.org/) | Authorization DSL | ✅ | ✅ | ⚠️ Limited | \~6KB | Great for access control, not general validation |
|
|
513
|
+
|
|
514
|
+
---
|
|
515
|
+
|
|
516
|
+
### 🧠 When to Use `ts-rules-composer`
|
|
517
|
+
|
|
518
|
+
Choose `ts-rules-composer` when your validation or rule logic:
|
|
519
|
+
|
|
520
|
+
- Involves **multiple branching paths**, retries, timeouts, or side effects
|
|
521
|
+
- Requires **shared context** (e.g. user metadata, database, external services)
|
|
522
|
+
- Needs **clean separation** of rule logic and pipeline composition
|
|
523
|
+
- Must run in both **Node.js or the browser**
|
|
524
|
+
- Should remain **type-safe** and **composable**
|
|
525
|
+
|
|
526
|
+
This library is not meant to replace schema validators like `zod`, but to complement them — it's ideal when your business logic **cannot be expressed declaratively** or **requires orchestration** of multiple validation steps.
|
|
527
|
+
|
|
278
528
|
## API Reference
|
|
279
529
|
|
|
280
530
|
### Core Functions
|
|
@@ -317,7 +567,7 @@ const validateProfile = every([
|
|
|
317
567
|
|
|
318
568
|
### Control Flow
|
|
319
569
|
|
|
320
|
-
#### `match(accessor, cases, defaultCase?)`
|
|
570
|
+
#### `match(accessor, cases, defaultCase?, options?)`
|
|
321
571
|
|
|
322
572
|
Pattern matching routing
|
|
323
573
|
|
|
@@ -333,7 +583,7 @@ const validatePayment = match(
|
|
|
333
583
|
)
|
|
334
584
|
```
|
|
335
585
|
|
|
336
|
-
#### `when(condition, rule)`
|
|
586
|
+
#### `when(condition, rule, options?)`
|
|
337
587
|
|
|
338
588
|
Executes only if condition is true
|
|
339
589
|
|
|
@@ -344,7 +594,7 @@ const validateAdmin = when(
|
|
|
344
594
|
)
|
|
345
595
|
```
|
|
346
596
|
|
|
347
|
-
#### `unless(condition, rule)`
|
|
597
|
+
#### `unless(condition, rule, options?)`
|
|
348
598
|
|
|
349
599
|
Executes only if condition is false
|
|
350
600
|
|
|
@@ -355,7 +605,7 @@ const validateGuest = unless(
|
|
|
355
605
|
)
|
|
356
606
|
```
|
|
357
607
|
|
|
358
|
-
#### `ifElse(condition, ifRule, elseRule?)`
|
|
608
|
+
#### `ifElse(condition, ifRule, elseRule?, options?)`
|
|
359
609
|
|
|
360
610
|
Branch between two rules
|
|
361
611
|
|
|
@@ -367,7 +617,7 @@ const validateAge = ifElse(
|
|
|
367
617
|
)
|
|
368
618
|
```
|
|
369
619
|
|
|
370
|
-
#### `oneOf(
|
|
620
|
+
#### `oneOf(rules, options?)`
|
|
371
621
|
|
|
372
622
|
Tries rules until one passes
|
|
373
623
|
|
|
@@ -392,7 +642,7 @@ const validateWithFallback = withFallback(
|
|
|
392
642
|
|
|
393
643
|
### Error Handling
|
|
394
644
|
|
|
395
|
-
#### `mapError(rule, transform)`
|
|
645
|
+
#### `mapError(rule, transform, options?)`
|
|
396
646
|
|
|
397
647
|
Transforms error output
|
|
398
648
|
|
|
@@ -403,7 +653,7 @@ const friendlyErrors = mapError(
|
|
|
403
653
|
)
|
|
404
654
|
```
|
|
405
655
|
|
|
406
|
-
#### `not(rule, error)`
|
|
656
|
+
#### `not(rule, error, options?)`
|
|
407
657
|
|
|
408
658
|
Inverts rule logic
|
|
409
659
|
|
|
@@ -414,6 +664,28 @@ const isNotBanned = not(
|
|
|
414
664
|
)
|
|
415
665
|
```
|
|
416
666
|
|
|
667
|
+
#### `withSafeError(rule, errorTransform?)`
|
|
668
|
+
|
|
669
|
+
Wraps a rule to catch errors and convert them to failed RuleResults
|
|
670
|
+
|
|
671
|
+
```typescript
|
|
672
|
+
const customSafeRule = withSafeError(riskyRule, e => ({
|
|
673
|
+
code: 500,
|
|
674
|
+
message: String(e)
|
|
675
|
+
}));
|
|
676
|
+
```
|
|
677
|
+
|
|
678
|
+
#### `withSafePredicate(rule, errorTransform?)`
|
|
679
|
+
|
|
680
|
+
Wraps a predicate function with error handling and type safety
|
|
681
|
+
|
|
682
|
+
```typescript
|
|
683
|
+
const safePredicate = withSafePredicate(
|
|
684
|
+
(input: string) => input.length > 5,
|
|
685
|
+
(err) => `Predicate failed: ${String(err)}`
|
|
686
|
+
);
|
|
687
|
+
```
|
|
688
|
+
|
|
417
689
|
### Performance
|
|
418
690
|
|
|
419
691
|
#### `withMemoize(rule, keyFn, options?)`
|
|
@@ -428,7 +700,7 @@ const cachedCheck = withMemoize(
|
|
|
428
700
|
)
|
|
429
701
|
```
|
|
430
702
|
|
|
431
|
-
#### `withTimeout(rule, ms, timeoutError)`
|
|
703
|
+
#### `withTimeout(rule, ms, timeoutError, options?)`
|
|
432
704
|
|
|
433
705
|
Adds execution timeout
|
|
434
706
|
|
|
@@ -465,7 +737,7 @@ const authRule = requireContextRule(
|
|
|
465
737
|
)
|
|
466
738
|
```
|
|
467
739
|
|
|
468
|
-
#### `withLazyContext(loader, rule)`
|
|
740
|
+
#### `withLazyContext(loader, rule, options?)`
|
|
469
741
|
|
|
470
742
|
Lazy-loads context
|
|
471
743
|
|
|
@@ -499,14 +771,27 @@ const debugRule = withDebug(validateOrder, {
|
|
|
499
771
|
})
|
|
500
772
|
```
|
|
501
773
|
|
|
502
|
-
#### `tap(effect)`
|
|
774
|
+
#### `tap(effect, options?)`
|
|
775
|
+
|
|
776
|
+
Creates a standalone tap effect for use in composition pipelines
|
|
777
|
+
|
|
778
|
+
```typescript
|
|
779
|
+
pipeRules([
|
|
780
|
+
tap((input) => console.log('Processing: ', input)),
|
|
781
|
+
validateInput
|
|
782
|
+
])
|
|
783
|
+
```
|
|
784
|
+
|
|
785
|
+
#### `withTap(effect, options?)`
|
|
503
786
|
|
|
504
|
-
|
|
787
|
+
Wraps a rule with side effects without modifying its result
|
|
505
788
|
|
|
506
789
|
```typescript
|
|
507
|
-
const loggedRule =
|
|
790
|
+
const loggedRule = withTap((input, result) => {
|
|
508
791
|
analytics.trackValidation(input, result)
|
|
509
792
|
})
|
|
793
|
+
|
|
794
|
+
const ruleResult = await loggedRule(input)
|
|
510
795
|
```
|
|
511
796
|
|
|
512
797
|
### Utilities
|
|
@@ -594,23 +879,6 @@ const dbRule = inject(database, createDbRule)
|
|
|
594
879
|
| `withDebug` | Debug logging | `withDebug(rule, { name: "Validation" })` |
|
|
595
880
|
| `tap` | Side effects | `tap((input, result) => log(result))` |
|
|
596
881
|
|
|
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
882
|
## Contributing
|
|
615
883
|
|
|
616
884
|
1. Fork the repository
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var w=e=>e!==void 0;var l=e=>({status:"failed",error:e});var p=()=>({status:"passed"});var k=(e,t,r)=>{let o=r||(a=>a!==void 0);return async(a,s)=>o(s)?t(a,s):l(e)};var D=(e,t)=>async r=>{try{let n=await e(r);return t(r,n)}catch(n){let o=n instanceof Error?n.message:"Context loading failed";return l(o)}};var C=(e,t,r)=>{let n={fixed:()=>r,linear:o=>r*o,exponential:o=>r*2**(o-1)};if(!e)return n.fixed(t);if(typeof e=="string"){let o=n[e];return o?o(t):r}return typeof e=="function"?e(t):n.fixed(t)};var f=(e,t)=>(t==null?void 0:t.errorHandlingMode)==="unsafe"?e:x(e,t==null?void 0:t.errorTransform);var m=(e,t)=>{var n;return (t==null?void 0:t.errorHandlingMode)==="unsafe"?e:(n=e||[])==null?void 0:n.map(o=>x(o,t==null?void 0:t.errorTransform))};var d=e=>{var t;if(!e)return {};try{return JSON.parse(JSON.stringify(e))}catch(r){return console.warn(`Clone failed for ${(t=e==null?void 0:e.constructor)==null?void 0:t.name}, returning empty object`,r),{}}};var g=e=>{var t;if(!e)return {};try{return {...e}}catch(r){return console.warn(`Clone failed for ${(t=e==null?void 0:e.constructor)==null?void 0:t.name}, returning empty object`,r),{}}};var R=e=>{let t=typeof structuredClone!="undefined";return e.cloneStrategy==="shallow"?g:e.cloneStrategy==="structured"&&t?structuredClone:d};var X=(e,t={})=>async(r,n)=>{let o=R(t),a=t!=null&&t.cloneContext?o(n):n,s=m(e,t),T=(await Promise.all(s.map(i=>i(r,a)))).flatMap(i=>i.status==="failed"?[i.error]:[]);return T.length>0?l(T):p()};var L=(e,t)=>{let r=t(e);return n=>r(n)};var W=(e,t)=>async(r,n)=>{let o=await e(r,n);return o.status==="failed"?l(t(o.error)):p()};var j=e=>async(t,r)=>{try{await e(t,r);}catch(n){console.error("Tap effect failed: ",n);}return p()};var er=(e,t)=>r=>async(n,o)=>{let s=await f(r,t)(n,o);try{await e(n,s,o);}catch(u){console.error("Tap effect failed:",u);}return s};function ur(e,t,r,n){return async(o,a)=>{let s=e(o),u=s!==void 0?s:r,T=f(t,n);return u===void 0?l("Missing required value"):T(u,a)}}var sr=(e,t)=>{let r=typeof t=="string"?{name:t}:t;return async(n,o)=>{var u,T,i;let a=performance.now(),s=r.name||e.name||"anonymous_rule";try{(u=r.onStart)==null||u.call(r,n,o);let c=await e(n,o),y=performance.now()-a;return (T=r.onEnd)==null||T.call(r,n,c,o,{ruleName:s,duration:y,startTime:a}),c}catch(c){let y=performance.now()-a;throw (i=r.onError)==null||i.call(r,c,n,o,y),c}}};var ir=(e,t,r={})=>{let n=new Map;return async(o,a)=>{let s=t(o),u=Date.now();if(r.ttl)for(let[c,y]of n)u-y.timestamp>r.ttl&&n.delete(c);if(r.maxSize&&n.size>=r.maxSize){let c=n.keys().next().value;c&&n.delete(c);}if(n.has(s))return n.get(s).result;let i=f(e,r)(o,a);return n.set(s,{result:i,timestamp:u}),i instanceof Promise&&i.catch(()=>n.delete(s)),i}};var cr=(e,t={})=>{let{attempts:r=3,delayMs:n=100,shouldRetry:o=()=>true}=t;return async(a,s)=>{let u;for(let T=1;T<=r;T++){try{let i=await e(a,s);if(i.status==="passed")return i;u=i.error;}catch(i){u=i;}if(!o(u,T))return l(u);if(T<r&&n>0){let i=C(t==null?void 0:t.retryStrategy,T,n);await new Promise(c=>setTimeout(c,i));}}return l("MAX_RETRIES_EXCEEDED")}};var x=(e,t=r=>typeof r=="object"&&r!==null?r:r instanceof Error?r.message:String(r))=>async(r,n)=>{try{let o=await e(r,n);return o&&typeof o=="object"&&"status"in o?o:l(t(new Error("Invalid rule - did not return RuleResult")))}catch(o){return l(t(o))}};var E=(e,t=r=>typeof r=="object"&&r!==null?r:r instanceof Error?r.message:String(r))=>async(r,n)=>{try{let o=await e(r,n);return typeof o=="boolean"?{status:"passed",value:o}:{status:"failed",error:t(new Error(`Predicate must return boolean, got ${typeof o}`))}}catch(o){return {status:"failed",error:t(o)}}};var Cr=(e,t,r,n)=>async(o,a)=>{let s=f(e,n),u=new Promise(T=>setTimeout(()=>T(l(r)),t));return Promise.race([s(o,a),u])};var wr=(e,t,r,n)=>async(o,a)=>{let u=await E(e,n==null?void 0:n.predicateErrorTransform)(o,a);if(u.status==="failed")return l(u.error);let[T,i]=m([t,r],n);return u.value?T(o,a):r?i(o,a):p()};var I=e=>typeof e=="function",Or=(e,t,r,n)=>async(o,a)=>{let s=await e(o,a),u=t[s];return u?f(u,n)(o,a):r!==void 0?I(r)?f(r,n)(o,a):l(r):l(`No matching rule for key: ${String(s)}`)};var zr=(e,t,r)=>async(n,o)=>(await f(e,r)(n,o)).status==="passed"?l(t):p();var Fr=(e,t)=>async(r,n)=>{let o=m(e,t),a=[];if(!e||e.length===0)return p();for(let s of o){let u=await s(r,n);if(u.status==="passed")return p();a.push(u.error);}return l(a)};var br=(e,t,r)=>async(n,o)=>{let a=f(t,r),u=await E(e,r==null?void 0:r.predicateErrorTransform)(n,o);return u.status==="failed"?l(u.error):u.value?p():a(n,o)};var Kr=(e,t,r)=>async(n,o)=>{let a=f(t,r),u=await E(e,r==null?void 0:r.predicateErrorTransform)(n,o);return u.status==="failed"?l(u.error):u.value?a(n,o):p()};var _r=(e,t,r={})=>async(n,o)=>{let[a,s]=m([e,t]),u=await a(n,o);return u.status==="failed"&&(!r.onlyFallbackOn||r.onlyFallbackOn(u.error))?s(n,o):u};var Ur=(e,t={})=>async(r,n)=>{let o=R(t),a=t!=null&&t.cloneContext?o(n):n,s=m(e);for(let u=s.length-1;u>=0;u--){let T=await s[u](r,a);if(T.status==="failed")return T}return p()};var Zr=(e,t={})=>async(r,n)=>{let o=R(t),a=t!=null&&t.cloneContext?o(n):n,s=m(e);for(let u of s){let T=await u(r,a);if(T.status==="failed")return T}return p()};function rt(e,...t){return t.reduce((r,n)=>n(r),e)}exports.calculateDelay=C;exports.composeRules=Ur;exports.every=X;exports.fail=l;exports.getNormalizedRule=f;exports.getNormalizedRules=m;exports.hasContext=w;exports.ifElse=wr;exports.inject=L;exports.mapError=W;exports.match=Or;exports.not=zr;exports.oneOf=Fr;exports.pass=p;exports.pipe=rt;exports.pipeRules=Zr;exports.requireContextRule=k;exports.tap=j;exports.unless=br;exports.validateField=ur;exports.when=Kr;exports.withDebug=sr;exports.withFallback=_r;exports.withLazyContext=D;exports.withMemoize=ir;exports.withRetry=cr;exports.withSafeError=x;exports.withSafePredicate=E;exports.withTap=er;exports.withTimeout=Cr;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|