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.
Files changed (83) hide show
  1. package/.editorconfig +15 -0
  2. package/.eslintrc.json +66 -0
  3. package/.github/CONTRIBUTING.md +3 -0
  4. package/.github/ISSUE_TEMPLATE.md +9 -0
  5. package/.github/PULL_REQUEST_TEMPLATE.md +7 -0
  6. package/.github/workflows/docs.yml +29 -0
  7. package/.github/workflows/publish.yml +25 -0
  8. package/.github/workflows/test.yml +37 -0
  9. package/.prettierignore +2 -0
  10. package/.releaserc +11 -0
  11. package/LICENSE +21 -0
  12. package/README.md +625 -0
  13. package/dist/index.cjs +2 -0
  14. package/dist/index.cjs.map +1 -0
  15. package/dist/index.d.cts +634 -0
  16. package/dist/index.d.ts +634 -0
  17. package/dist/index.js +2 -0
  18. package/dist/index.js.map +1 -0
  19. package/package.json +64 -0
  20. package/src/lib/combinators/index.ts +2 -0
  21. package/src/lib/combinators/logic/every.spec.ts +264 -0
  22. package/src/lib/combinators/logic/every.ts +47 -0
  23. package/src/lib/combinators/logic/if-else.spec.ts +72 -0
  24. package/src/lib/combinators/logic/if-else.ts +39 -0
  25. package/src/lib/combinators/logic/index.ts +8 -0
  26. package/src/lib/combinators/logic/match.spec.ts +186 -0
  27. package/src/lib/combinators/logic/match.ts +92 -0
  28. package/src/lib/combinators/logic/not.spec.ts +62 -0
  29. package/src/lib/combinators/logic/not.ts +25 -0
  30. package/src/lib/combinators/logic/one-of.spec.ts +68 -0
  31. package/src/lib/combinators/logic/one-of.ts +41 -0
  32. package/src/lib/combinators/logic/unless.spec.ts +61 -0
  33. package/src/lib/combinators/logic/unless.ts +27 -0
  34. package/src/lib/combinators/logic/when.spec.ts +123 -0
  35. package/src/lib/combinators/logic/when.ts +29 -0
  36. package/src/lib/combinators/logic/with-fallback.spec.ts +72 -0
  37. package/src/lib/combinators/logic/with-fallback.ts +37 -0
  38. package/src/lib/combinators/utility/index.ts +8 -0
  39. package/src/lib/combinators/utility/inject.spec.ts +55 -0
  40. package/src/lib/combinators/utility/inject.ts +25 -0
  41. package/src/lib/combinators/utility/map-error.spec.ts +63 -0
  42. package/src/lib/combinators/utility/map-error.ts +35 -0
  43. package/src/lib/combinators/utility/tap.spec.ts +102 -0
  44. package/src/lib/combinators/utility/tap.ts +38 -0
  45. package/src/lib/combinators/utility/validate-field.spec.ts +150 -0
  46. package/src/lib/combinators/utility/validate-field.ts +59 -0
  47. package/src/lib/combinators/utility/with-debug.spec.ts +71 -0
  48. package/src/lib/combinators/utility/with-debug.ts +55 -0
  49. package/src/lib/combinators/utility/with-memoize.spec.ts +82 -0
  50. package/src/lib/combinators/utility/with-memoize.ts +81 -0
  51. package/src/lib/combinators/utility/with-retry.spec.ts +220 -0
  52. package/src/lib/combinators/utility/with-retry.ts +68 -0
  53. package/src/lib/combinators/utility/with-timeout.spec.ts +115 -0
  54. package/src/lib/combinators/utility/with-timeout.ts +34 -0
  55. package/src/lib/composition/compose-rules.spec.ts +211 -0
  56. package/src/lib/composition/compose-rules.ts +47 -0
  57. package/src/lib/composition/index.ts +3 -0
  58. package/src/lib/composition/pipe-rules.spec.ts +220 -0
  59. package/src/lib/composition/pipe-rules.ts +44 -0
  60. package/src/lib/composition/pipe.spec.ts +47 -0
  61. package/src/lib/composition/pipe.ts +106 -0
  62. package/src/lib/helpers/context/has-context.ts +13 -0
  63. package/src/lib/helpers/context/index.ts +3 -0
  64. package/src/lib/helpers/context/require-context.spec.ts +55 -0
  65. package/src/lib/helpers/context/require-context.ts +61 -0
  66. package/src/lib/helpers/context/with-lazy-context.spec.ts +74 -0
  67. package/src/lib/helpers/context/with-lazy-context.ts +35 -0
  68. package/src/lib/helpers/index.ts +6 -0
  69. package/src/lib/helpers/result/fail.ts +15 -0
  70. package/src/lib/helpers/result/index.ts +2 -0
  71. package/src/lib/helpers/result/pass.ts +14 -0
  72. package/src/lib/helpers/retry/calculate-delay.ts +31 -0
  73. package/src/lib/index.ts +4 -0
  74. package/src/lib/types/composition-options.ts +7 -0
  75. package/src/lib/types/debug-options.ts +36 -0
  76. package/src/lib/types/index.ts +4 -0
  77. package/src/lib/types/rule-result.ts +16 -0
  78. package/src/lib/types/rule.ts +21 -0
  79. package/src/test/helpers/get-rule-error.ts +23 -0
  80. package/src/test/integration.spec.ts +285 -0
  81. package/tsconfig.json +55 -0
  82. package/tsup.config.ts +36 -0
  83. package/vitest.config.ts +16 -0
@@ -0,0 +1,634 @@
1
+ /**
2
+ * Options for rule composition functions.
3
+ * @property cloneContext - Whether to clone the context for each rule
4
+ */
5
+ type CompositionOptions = {
6
+ cloneContext?: boolean;
7
+ };
8
+
9
+ /**
10
+ * Represents the result of a rule evaluation.
11
+ * @template TError - The type of the error (defaults to string)
12
+ * @example
13
+ * // Passed result
14
+ * const passed: RuleResult = { status: "passed" };
15
+ *
16
+ * // Failed result
17
+ * const failed: RuleResult = {
18
+ * status: "failed",
19
+ * error: "Validation failed"
20
+ * };
21
+ */
22
+ type RuleResult<TError = string> = {
23
+ readonly status: "passed";
24
+ } | {
25
+ readonly status: "failed";
26
+ readonly error: TError;
27
+ };
28
+
29
+ /**
30
+ * Configuration options for debug functionality.
31
+ * @template TInput - The type of the input to validate
32
+ * @template TError - The type of the error
33
+ * @template TContext - The type of the context object
34
+ * @property name - Unique identifier for the rule
35
+ * @property onStart - Called before rule execution
36
+ * @property onEnd - Called after rule completes
37
+ * @property onError - Called when rule throws
38
+ */
39
+ type DebugOptions<TInput, TError, TContext> = {
40
+ /** Unique identifier for the rule */
41
+ name?: string;
42
+ /** Called before rule execution */
43
+ onStart?: (input: TInput, context?: TContext) => void;
44
+ /** Called after rule completes */
45
+ onEnd?: (input: TInput, result: RuleResult<TError>, context?: TContext, meta?: {
46
+ ruleName: string;
47
+ duration: number;
48
+ startTime: number;
49
+ }) => void;
50
+ /** Called when rule throws */
51
+ onError?: (error: unknown, input: TInput, context?: TContext, duration?: number) => void;
52
+ };
53
+
54
+ /**
55
+ * A function that validates an input and returns a RuleResult.
56
+ * @template TInput - The type of the input to validate
57
+ * @template TError - The type of the error (defaults to string)
58
+ * @template TContext - The type of the context object (optional)
59
+ * @param input - The input value to validate
60
+ * @param context - Optional context object that can be used during validation
61
+ * @returns Either a Promise of RuleResult or RuleResult directly
62
+ * @example
63
+ * const isEven: Rule<number> = (input) => {
64
+ * return input % 2 === 0
65
+ * ? { status: "passed" }
66
+ * : { status: "failed", error: "Number must be even" };
67
+ * };
68
+ */
69
+ type Rule<TInput, TError = string, TContext = unknown> = (input: TInput, context?: TContext) => Promise<RuleResult<TError>> | RuleResult<TError>;
70
+
71
+ /**
72
+ * Composes multiple rules into a single rule that runs them all and collects all errors.
73
+ * @template TInput - The type of the input to validate
74
+ * @template TError - The type of the error (defaults to string)
75
+ * @template TContext - The type of the context object (optional)
76
+ * @param rules - Array of rules to compose
77
+ * @param options - Configuration options
78
+ * @param options.cloneContext - Whether to clone the context for each rule (default: false)
79
+ * @returns A new rule that returns all errors from all failing rules
80
+ * @example
81
+ * const rule = every([
82
+ * validatePresence,
83
+ * validateEmail,
84
+ * validateUnique
85
+ * ]);
86
+ *
87
+ * const result = await rule("invalid-email");
88
+ * if (result.status === "failed") {
89
+ * console.log(result.error); // Array of all errors
90
+ * }
91
+ * @caveats
92
+ * - Rules are executed in parallel (using Promise.all)
93
+ * - All rules are executed even if some fail
94
+ */
95
+ declare const every: <TInput, TError = string, TContext = unknown>(rules: Rule<TInput, TError, TContext>[], options?: CompositionOptions) => Rule<TInput, TError[], TContext>;
96
+
97
+ /**
98
+ * Conditionally executes one of two rules based on a predicate
99
+ * @template TInput - The type of the input to validate
100
+ * @template TError - The type of the error (defaults to string)
101
+ * @template TContext - The type of the context object (optional)
102
+ * @param predicate - Function that determines which rule to execute
103
+ * @param ifRule - Rule to execute when predicate returns true
104
+ * @param elseRule - Rule to execute when predicate returns false (optional)
105
+ * @returns A new rule that conditionally executes one of two rules
106
+ * @example
107
+ * const rule = branch(
108
+ * (user) => user.age >= 18,
109
+ * validateAdultAccount,
110
+ * validateMinorAccount
111
+ * );
112
+ *
113
+ * // Without elseRule (passes when predicate is false)
114
+ * const adultOnlyRule = branch(
115
+ * (user) => user.age >= 18,
116
+ * validateAdultAccount
117
+ * );
118
+ */
119
+ declare const ifElse: <TInput, TError = string, TContext = unknown>(predicate: (input: TInput, context?: TContext) => boolean | Promise<boolean>, ifRule: Rule<TInput, TError, TContext>, elseRule?: Rule<TInput, TError, TContext>) => Rule<TInput, TError, TContext>;
120
+
121
+ /**
122
+ * Pattern-matching combinator that selects a rule based on a key extracted from input.
123
+ * @template TInput - The type of the input to validate
124
+ * @template TError - The type of the error (defaults to string)
125
+ * @template TContext - The type of the context object (optional)
126
+ * @template TKey - The type of the branch key (must be string | number | symbol)
127
+ * @param accessor - Function that extracts the match key from input
128
+ * @param cases - Object mapping keys to their corresponding rules
129
+ * @param defaultCase - Optional default rule or error when no match is found
130
+ * @returns A new rule that executes the matching case's rule
131
+ * @example
132
+ * // Basic usage with string error type
133
+ * const validatePayment = match(
134
+ * (order) => order.paymentMethod,
135
+ * {
136
+ * credit: validateCreditCard,
137
+ * paypal: validatePayPal,
138
+ * crypto: validateCrypto
139
+ * },
140
+ * "Unsupported payment method"
141
+ * );
142
+ *
143
+ * @example
144
+ * // With custom error type
145
+ * interface ValidationError { code: number; message: string }
146
+ * const validateStatus = match<Order, ValidationError>(
147
+ * (order) => order.status,
148
+ * {
149
+ * pending: validatePendingOrder,
150
+ * completed: validateCompletedOrder
151
+ * },
152
+ * { code: 400, message: "Invalid status" }
153
+ * );
154
+ *
155
+ * @example
156
+ * // With default rule instead of error
157
+ * const validateProduct = match(
158
+ * (product) => product.type,
159
+ * {
160
+ * book: validateBook,
161
+ * digital: validateDigitalProduct
162
+ * },
163
+ * validateGenericProduct
164
+ * );
165
+ *
166
+ * @caveats
167
+ * - The accessor function should return a primitive value (string/number/symbol)
168
+ * - If no matching case is found and no default is provided, returns a failed result with:
169
+ * - A string error when TError is string (default)
170
+ * - A type-asserted error when TError is custom (may require type casting)
171
+ * - All case rules must have compatible input/context types
172
+ * - For conditional branching (true/false), consider using `branch` instead
173
+ */
174
+ declare const match: <TInput, TError = string, TContext = unknown, TKey extends string | number | symbol = string>(accessor: (input: TInput, context?: TContext) => TKey | Promise<TKey>, cases: Record<TKey, Rule<TInput, TError, TContext>>, defaultCase?: Rule<TInput, TError, TContext> | TError) => Rule<TInput, TError, TContext>;
175
+
176
+ /**
177
+ * Inverts the logic of a rule - passes when original fails and vice versa.
178
+ * @template TInput - The type of the input to validate
179
+ * @template TError - The type of the error (defaults to string)
180
+ * @param rule - The rule to invert
181
+ * @param error - The error to return when original rule passes
182
+ * @returns A new rule with inverted logic
183
+ * @example
184
+ * const isNotAdmin = not(isAdmin, "User must not be admin");
185
+ * @caveats
186
+ * - The original rule's error is discarded when it fails
187
+ * - Always uses the provided error when original passes
188
+ */
189
+ declare const not: <TInput, TError = string>(rule: Rule<TInput, TError>, error: TError) => Rule<TInput, TError>;
190
+
191
+ /**
192
+ * Creates a rule that passes if any of the provided rules pass (short-circuiting).
193
+ * @template TInput - The type of the input to validate
194
+ * @template TError - The type of the error (defaults to string)
195
+ * @template TContext - The type of the context object (optional)
196
+ * @param rules - Rules to try (in order)
197
+ * @returns A rule that passes if any rule passes, or fails with all errors
198
+ * @example
199
+ * const rule = oneOf(
200
+ * validateEmail,
201
+ * validatePhone,
202
+ * validateUsername
203
+ * );
204
+ * @caveats
205
+ * - Rules are executed in sequence until one passes
206
+ * - Returns all errors if all rules fail
207
+ */
208
+ declare const oneOf: <TInput, TError = string, TContext = unknown>(...rules: Rule<TInput, TError, TContext>[]) => Rule<TInput, TError[], TContext>;
209
+
210
+ /**
211
+ * Executes a rule only if the predicate returns false.
212
+ * @template TInput - The type of the input to validate
213
+ * @template TError - The type of the error (defaults to string)
214
+ * @template TContext - The type of the context object (optional)
215
+ * @param predicate - Condition to check
216
+ * @param rule - Rule to execute when predicate is false
217
+ * @returns A rule that conditionally executes based on the predicate
218
+ * @example
219
+ * const rule = unless(
220
+ * (user) => user.isVerified,
221
+ * requireVerification
222
+ * );
223
+ * @caveats
224
+ * - Opposite behavior of `when`
225
+ * - Automatically passes when predicate is true
226
+ */
227
+ declare const unless: <TInput, TError = string, TContext = unknown>(predicate: (input: TInput) => Promise<boolean> | boolean, rule: Rule<TInput, TError, TContext>) => Rule<TInput, TError, TContext>;
228
+
229
+ /**
230
+ * Conditionally executes a rule based on a predicate.
231
+ * Similar to branch but without an else case.
232
+ * @template TInput - The type of the input to validate
233
+ * @template TError - The type of the error (defaults to string)
234
+ * @param predicate - Function that determines whether to execute the rule
235
+ * @param rule - Rule to execute when predicate returns true
236
+ * @returns A new rule that conditionally executes the input rule
237
+ * @example
238
+ * const rule = when(
239
+ * (user) => user.role === "admin",
240
+ * validateAdminPrivileges
241
+ * );
242
+ * @caveats
243
+ * - The predicate can be async
244
+ * - If predicate returns false, the rule automatically passes
245
+ */
246
+ declare const when: <TInput, TError = string>(predicate: (input: TInput) => boolean | Promise<boolean>, rule: Rule<TInput, TError>) => Rule<TInput, TError>;
247
+
248
+ /**
249
+ * Creates a rule that falls back to an alternative rule if the main rule fails.
250
+ * @template TInput - Input type
251
+ * @template TError - Error type
252
+ * @template TContext - Context type
253
+ * @param mainRule - Primary rule to execute first
254
+ * @param fallbackRule - Rule to execute if main rule fails
255
+ * @param options - Configuration options
256
+ * @param options.onlyFallbackOn - Predicate to conditionally enable fallback
257
+ * @returns A new composite rule
258
+ * @example
259
+ * const rule = withFallback(
260
+ * premiumValidation,
261
+ * basicValidation,
262
+ * { onlyFallbackOn: err => err.code !== 'FATAL' }
263
+ * );
264
+ */
265
+ declare const withFallback: <TInput, TError, TContext>(mainRule: Rule<TInput, TError, TContext>, fallbackRule: Rule<TInput, TError, TContext>, options?: {
266
+ onlyFallbackOn?: (error: TError) => boolean;
267
+ }) => Rule<TInput, TError, TContext>;
268
+
269
+ /**
270
+ * Injects a dependency into a rule creation function, returning a configured rule.
271
+ * @template TInput - The type of the input to validate
272
+ * @template TError - The type of the error
273
+ * @template TDep - The type of the dependency to inject
274
+ * @param dependency - The dependency to inject
275
+ * @param rule - A function that creates a rule when given the dependency
276
+ * @returns A configured rule that uses the injected dependency
277
+ * @example
278
+ * const createDbRule = (db: Database) => (input: string) =>
279
+ * db.exists(input) ? pass() : fail("Not found");
280
+ *
281
+ * const dbRule = inject(database, createDbRule);
282
+ * @caveats
283
+ * - The dependency is injected at rule creation time, not execution time
284
+ */
285
+ declare const inject: <TInput, TError, TDep>(dependency: TDep, rule: (dep: TDep) => Rule<TInput, TError>) => Rule<TInput, TError>;
286
+
287
+ /**
288
+ * Transforms the error of a rule using a mapping function.
289
+ * @template TInput - The type of the input to validate
290
+ * @template TError - The original error type
291
+ * @template TNewError - The new error type
292
+ * @param rule - The rule whose errors should be transformed
293
+ * @param transform - Function to transform the error
294
+ * @returns A new rule that produces transformed errors
295
+ * @example
296
+ * const rule = mapError(
297
+ * validateEmail,
298
+ * (error) => `Validation failed: ${error}`
299
+ * );
300
+ *
301
+ * // Can also change error types:
302
+ * const numericErrorRule = mapError(
303
+ * stringErrorRule,
304
+ * (error) => error.length // Convert string error to number
305
+ * );
306
+ * @caveats
307
+ * - Only transforms failed results, passes successful results through unchanged
308
+ * - The transform function is not called for successful results
309
+ */
310
+ declare const mapError: <TInput, TError, TNewError>(rule: Rule<TInput, TError>, transform: (error: TError) => TNewError) => Rule<TInput, TNewError>;
311
+
312
+ /**
313
+ * Creates a memoized version of a rule that caches results based on input keys.
314
+ * @template TInput - The type of the input to validate
315
+ * @template TError - The type of the error (defaults to string)
316
+ * @template TContext - The type of the context object (optional)
317
+ * @param rule - The rule to memoize
318
+ * @param keyFn - Function that generates a cache key from the input
319
+ * @param options - Memoization options
320
+ * @param options.ttl - Time-to-live for cache entries in milliseconds
321
+ * @param options.maxSize - Maximum number of entries to keep in cache
322
+ * @returns A memoized version of the rule
323
+ * @example
324
+ * const memoizedRule = withMemoize(
325
+ * expensiveValidationRule,
326
+ * (input) => input.id,
327
+ * { ttl: 60000, maxSize: 100 }
328
+ * );
329
+ * @caveats
330
+ * - Context changes don't invalidate cache by default
331
+ * - Cache cleanup happens during rule execution
332
+ * - Rejected promises are automatically evicted from cache
333
+ */
334
+ declare const withMemoize: <TInput, TError = string, TContext = unknown>(rule: Rule<TInput, TError, TContext>, keyFn: (input: TInput) => string, options?: {
335
+ ttl?: number;
336
+ maxSize?: number;
337
+ }) => Rule<TInput, TError, TContext>;
338
+
339
+ /**
340
+ * Creates a rule that extracts a value using a getter function and validates it.
341
+ * @template TInput - The type of the input object
342
+ * @template TValue - The type of the extracted value
343
+ * @template TError - The type of the error
344
+ * @template TContext - The type of the context object
345
+ * @param getter - Function that extracts the value from input
346
+ * @param rule - Rule to apply to the extracted value
347
+ * @param defaultValue - Optional default value if getter returns undefined
348
+ * @returns A new rule that validates the extracted value
349
+ * @example
350
+ * const validateName = validateField(
351
+ * (user: User) => user.profile.name,
352
+ * (name) => name.length > 3 ? pass() : fail('Name too short')
353
+ * );
354
+ *
355
+ * const validateAge = validateField(
356
+ * (user: User) => user.age,
357
+ * (age) => age >= 18 ? pass() : fail('Must be adult'),
358
+ * 18 // default value
359
+ * );
360
+ *
361
+ * @caveats
362
+ * **Null/Undefined Handling**:
363
+ * - The getter function should handle optional properties (use optional chaining)
364
+ * - If getter returns undefined and no default is provided, the rule will fail
365
+ *
366
+ * **Type Safety**:
367
+ * - The rule's input type must match the getter's return type exactly
368
+ * - No automatic type narrowing (e.g., string | undefined won't become string even with default)
369
+ *
370
+ * **Default Values**:
371
+ * - Defaults are applied before rule execution (the rule sees the default value)
372
+ * - Default values aren't type-checked against potentially undefined returns
373
+ */
374
+ declare function validateField<TInput, TValue, TError = string, TContext = unknown>(getter: (input: TInput) => TValue | undefined, rule: Rule<TValue, TError, TContext>, defaultValue?: TValue): Rule<TInput, TError, TContext>;
375
+
376
+ /**
377
+ * Creates a rule wrapper that performs side effects without modifying the result.
378
+ * @template TInput - The type of the input to validate
379
+ * @template TError - The type of the error (defaults to string)
380
+ * @template TContext - The type of the context object (optional)
381
+ * @param effect - Side effect function receiving input, result and context
382
+ * @returns A function that wraps a rule with the tap effect
383
+ * @example
384
+ * const withLogging = tap((input, result) => {
385
+ * console.log(`Validation result for ${input}:`, result);
386
+ * });
387
+ *
388
+ * const rule = withLogging(validateInput);
389
+ * @caveats
390
+ * - Errors in the effect are caught and logged but don't affect rule execution
391
+ * - Doesn't modify the rule's result
392
+ */
393
+ declare const tap: <TInput, TError = string, TContext = unknown>(effect: (input: TInput, result: RuleResult<TError>, context?: TContext) => Promise<void> | void) => ((rule: Rule<TInput, TError, TContext>) => Rule<TInput, TError, TContext>);
394
+
395
+ /**
396
+ * Wraps a rule with debugging capabilities.
397
+ * @template TInput - The type of the input to validate
398
+ * @template TError - The type of the error
399
+ * @template TContext - The type of the context object
400
+ * @param rule - The rule to wrap with debug capabilities
401
+ * @param options - Debug configuration or simple name string
402
+ * @param options.name - Name for the debug output
403
+ * @param options.onStart - Callback when rule starts executing
404
+ * @param options.onEnd - Callback when rule completes successfully
405
+ * @param options.onError - Callback when rule throws an error
406
+ * @returns A new rule with debug capabilities
407
+ * @example
408
+ * const rule = withDebug(expensiveValidation, {
409
+ * name: "Expensive Validation",
410
+ * onStart: (input) => console.log(`Starting with input: ${input}`),
411
+ * onEnd: (input, result, ctx, { duration }) => {
412
+ * console.log(`Completed in ${duration}ms`);
413
+ * }
414
+ * });
415
+ * @caveats
416
+ * - Debug callbacks are executed synchronously and may impact performance
417
+ * - Errors in callbacks will propagate and potentially mask rule errors
418
+ */
419
+ declare const withDebug: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>, options: DebugOptions<TInput, TError, TContext> | string) => Rule<TInput, TError, TContext>;
420
+
421
+ type RetryStrategy = "fixed" | "linear" | "exponential" | ((attempt: number) => number);
422
+ /**
423
+ * Wraps a rule with retry logic for handling transient failures.
424
+ * @template TInput - The type of the input to validate
425
+ * @template TError - The type of the error (defaults to string)
426
+ * @template TContext - The type of the context object (optional)
427
+ * @param rule - The rule to wrap with retry logic
428
+ * @param options - Retry configuration
429
+ * @param options.attempts - Maximum number of attempts (default: 3)
430
+ * @param options.delayMs - Delay between attempts in milliseconds (default: 100)
431
+ * @param options.shouldRetry - Function to determine if a failure should be retried
432
+ * @returns A new rule with retry capability
433
+ * @example
434
+ * const rule = withRetry(apiCheckRule, {
435
+ * attempts: 5,
436
+ * delayMs: 500,
437
+ * shouldRetry: (error) => error.statusCode === 503
438
+ * });
439
+ * @caveats
440
+ * - Only retries on failed RuleResults, not on thrown exceptions
441
+ * - The final error will be "MAX_RETRIES_EXCEEDED" if all attempts fail
442
+ */
443
+ declare const withRetry: <TInput, TError = string, TContext = unknown>(rule: Rule<TInput, TError, TContext>, options?: {
444
+ attempts?: number;
445
+ delayMs?: number;
446
+ retryStrategy?: RetryStrategy;
447
+ shouldRetry?: (error: TError | unknown, attempt: number) => boolean;
448
+ }) => Rule<TInput, TError | "MAX_RETRIES_EXCEEDED", TContext>;
449
+
450
+ /**
451
+ * Wraps a rule with timeout functionality.
452
+ * @template TInput - The type of the input to validate
453
+ * @template TError - The type of the error
454
+ * @template TContext - The type of the context object
455
+ * @param rule - The rule to wrap with timeout
456
+ * @param timeoutMs - Timeout duration in milliseconds
457
+ * @param timeoutError - Error to return if timeout occurs
458
+ * @returns A new rule that fails with timeoutError if execution takes longer than timeoutMs
459
+ * @example
460
+ * const rule = withTimeout(
461
+ * slowNetworkRequestRule,
462
+ * 5000, // 5 seconds
463
+ * "Request timed out"
464
+ * );
465
+ * @caveats
466
+ * - The original rule's execution isn't aborted when timeout occurs
467
+ * - Only fails if the rule doesn't complete before timeout, not if it fails before timeout
468
+ */
469
+ declare const withTimeout: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>, timeoutMs: number, timeoutError: TError) => Rule<TInput, TError, TContext>;
470
+
471
+ /**
472
+ * Composes multiple rules into a single rule that runs them in right-to-left order (fail-fast).
473
+ * Stops at the first failure and returns the error.
474
+ *
475
+ * @template TInput - The type of the input to validate
476
+ * @template TError - The type of the error (defaults to string)
477
+ * @template TContext - The type of the context object (optional)
478
+ * @param rules - Array of rules to compose
479
+ * @param options - Configuration options
480
+ * @param options.cloneContext - Whether to clone the context for each rule (default: false)
481
+ * @returns A new rule that composes all input rules
482
+ *
483
+ * @example
484
+ * const rule = composeRules([
485
+ * finalCheck,
486
+ * normalizeInput,
487
+ * validateBase
488
+ * ]);
489
+ *
490
+ * const result = await rule(input);
491
+ *
492
+ * @caveats
493
+ * - Rules are executed from **right to left**
494
+ * - Rules are executed sequentially (not in parallel)
495
+ * - Context clone uses structuredClone from Node.js
496
+ */
497
+ declare const composeRules: <TInput, TError = string, TContext = unknown>(rules: Rule<TInput, TError, TContext>[], options?: CompositionOptions) => Rule<TInput, TError, TContext>;
498
+
499
+ /**
500
+ * Pipes multiple rules into a single rule that runs them sequentially (fail-fast).
501
+ * Stops at the first failure and returns the error.
502
+ * @template TInput - The type of the input to validate
503
+ * @template TError - The type of the error (defaults to string)
504
+ * @template TContext - The type of the context object (optional)
505
+ * @param rules - Array of rules to compose
506
+ * @param options - Configuration options
507
+ * @param options.cloneContext - Whether to clone the context for each rule (default: false)
508
+ * @returns A new rule that pipes all input rules
509
+ * @example
510
+ * const rule = pipeRules([
511
+ * validateString,
512
+ * validateLength,
513
+ * validateFormat
514
+ * ]);
515
+ *
516
+ * const result = await rule("test@example.com");
517
+ * @caveats
518
+ * - Rules are execute from left to right
519
+ * - Rules are executed in sequence, not in parallel
520
+ * - Context clone uses structuredClone Nodejs implementation
521
+ */
522
+ declare const pipeRules: <TInput, TError = string, TContext = unknown>(rules: Rule<TInput, TError, TContext>[], options?: CompositionOptions) => Rule<TInput, TError, TContext>;
523
+
524
+ /**
525
+ * Pipes a value through a series of functions (left-to-right composition).
526
+ * @template A - The input type
527
+ * @template B - The output type after first function
528
+ * @param value - The initial value
529
+ * @param fns - Functions to apply sequentially
530
+ * @returns The result of applying all functions to the initial value
531
+ * @example
532
+ * const result = pipe(
533
+ * 5,
534
+ * (x) => x * 2,
535
+ * (x) => x + 3,
536
+ * (x) => `Result: ${x}`
537
+ * ); // "Result: 13"
538
+ * @caveats
539
+ * - Currently supports up to 10 functions with proper type inference
540
+ * - For more functions, type information will be lost
541
+ */
542
+ declare function pipe<A>(value: A): A;
543
+ declare function pipe<A, B>(value: A, fn1: (arg: A) => B): B;
544
+ declare function pipe<A, B, C>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C): C;
545
+ declare function pipe<A, B, C, D>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D): D;
546
+ declare function pipe<A, B, C, D, E>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D, fn4: (arg: D) => E): E;
547
+ declare function pipe<A, B, C, D, E, F>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D, fn4: (arg: D) => E, fn5: (arg: E) => F): F;
548
+ declare function pipe<A, B, C, D, E, F, G>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D, fn4: (arg: D) => E, fn5: (arg: E) => F, fn6: (arg: F) => G): G;
549
+ declare function pipe<A, B, C, D, E, F, G, H>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D, fn4: (arg: D) => E, fn5: (arg: E) => F, fn6: (arg: F) => G, fn7: (arg: G) => H): H;
550
+ declare function pipe<A, B, C, D, E, F, G, H, I>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D, fn4: (arg: D) => E, fn5: (arg: E) => F, fn6: (arg: F) => G, fn7: (arg: G) => H, fn8: (arg: H) => I): I;
551
+ declare function pipe<A, B, C, D, E, F, G, H, I, J>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D, fn4: (arg: D) => E, fn5: (arg: E) => F, fn6: (arg: F) => G, fn7: (arg: G) => H, fn8: (arg: H) => I, fn9: (arg: I) => J): J;
552
+ declare function pipe<A, B, C, D, E, F, G, H, I, J, K>(value: A, fn1: (arg: A) => B, fn2: (arg: B) => C, fn3: (arg: C) => D, fn4: (arg: D) => E, fn5: (arg: E) => F, fn6: (arg: F) => G, fn7: (arg: G) => H, fn8: (arg: H) => I, fn9: (arg: I) => J, fn10: (arg: J) => K): K;
553
+
554
+ /**
555
+ * Type guard to check if context exists and is of type T.
556
+ * @template T - The expected context type
557
+ * @param ctx - The context to check
558
+ * @returns Boolean indicating if context exists and matches type
559
+ * @example
560
+ * if (hasContext<AdminContext>(context)) {
561
+ * // context is now typed as AdminContext
562
+ * }
563
+ */
564
+ declare const hasContext: <T>(ctx: T | undefined) => ctx is T;
565
+
566
+ /**
567
+ * Creates a rule that requires specific context to be present.
568
+ * @template TInput - The type of the input to validate
569
+ * @template TError - The type of the error
570
+ * @template TContext - The base context type
571
+ * @template TRequiredContext - The required context type
572
+ * @param error - Error to return if context is invalid
573
+ * @param rule - Rule that requires the specific context
574
+ * @param contextCheck - Optional type guard for context validation
575
+ * @returns A rule that validates context before execution
576
+ * @example
577
+ * const adminRule = requireContextRule(
578
+ * "Admin context required",
579
+ * (input, context: AdminContext) => { ... },
580
+ * (ctx): ctx is AdminContext => ctx?.role === "admin"
581
+ * );
582
+ * @caveats
583
+ * - Fails immediately if context check fails
584
+ * - Provides type safety for context requirements
585
+ */
586
+ declare const requireContextRule: <TInput, TError, TContext, TRequiredContext extends TContext>(error: TError, rule: (input: TInput, context: TRequiredContext) => Promise<RuleResult<TError>> | RuleResult<TError>, contextCheck?: (context: TContext | undefined) => context is TRequiredContext) => Rule<TInput, TError, TContext>;
587
+
588
+ /**
589
+ * Creates a rule that loads context lazily before execution.
590
+ * @template TInput - The type of the input to validate
591
+ * @template TError - The type of the error
592
+ * @template TContext - The type of the context object
593
+ * @param loader - Function to load context from input
594
+ * @param rule - Rule that requires the context
595
+ * @returns A rule that loads context before execution
596
+ * @example
597
+ * const rule = withLazyContext(
598
+ * async (userId) => await loadUserContext(userId),
599
+ * validateUser
600
+ * );
601
+ * @caveats
602
+ * - Context loading failures are converted to validation failures
603
+ * - The loader is called for every rule execution
604
+ */
605
+ declare const withLazyContext: <TInput, TError, TContext>(loader: (input: TInput) => Promise<TContext> | TContext, rule: Rule<TInput, TError, TContext>) => Rule<TInput, TError>;
606
+
607
+ /**
608
+ * Creates a failed RuleResult with the provided error.
609
+ * @template TError - The type of the error (defaults to string)
610
+ * @param error - The error to include in the failed result
611
+ * @returns A RuleResult with status "failed" and the provided error
612
+ * @example
613
+ * const result = fail("Invalid input"); // { status: "failed", error: "Invalid input" }
614
+ *
615
+ * // Used in rule implementations:
616
+ * const alwaysFails: Rule<string> = () => fail("Always fails");
617
+ */
618
+ declare const fail: <TError = string>(error: TError) => RuleResult<TError>;
619
+
620
+ /**
621
+ * Creates a successful RuleResult with "passed" status.
622
+ * @template TError - The type of the error (defaults to string)
623
+ * @returns A RuleResult with status "passed"
624
+ * @example
625
+ * const result = pass(); // { status: "passed" }
626
+ *
627
+ * // Used in rule implementations:
628
+ * const alwaysPasses: Rule<string> = () => pass();
629
+ */
630
+ declare const pass: <TError = string>() => RuleResult<TError>;
631
+
632
+ declare const calculateDelay: (strategy: RetryStrategy | undefined, attempt: number, initialDelayMs: number) => number;
633
+
634
+ export { type CompositionOptions, type DebugOptions, type RetryStrategy, type Rule, type RuleResult, calculateDelay, composeRules, every, fail, hasContext, ifElse, inject, mapError, match, not, oneOf, pass, pipe, pipeRules, requireContextRule, tap, unless, validateField, when, withDebug, withFallback, withLazyContext, withMemoize, withRetry, withTimeout };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ 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)}export{m as calculateDelay,Cr as composeRules,B as every,a as fail,E as hasContext,v as ifElse,U as inject,Z as mapError,S as match,K as not,J as oneOf,s as pass,yr as pipe,gr as pipeRules,d as requireContextRule,Tr as tap,V as unless,or as validateField,j as when,sr as withDebug,$ as withFallback,A as withLazyContext,tr as withMemoize,ir as withRetry,mr as withTimeout};//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map