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.
Files changed (82) hide show
  1. package/README.md +310 -42
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +335 -55
  5. package/dist/index.d.ts +335 -55
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +1 -1
  8. package/package.json +27 -6
  9. package/.editorconfig +0 -15
  10. package/.eslintrc.json +0 -66
  11. package/.github/CONTRIBUTING.md +0 -3
  12. package/.github/ISSUE_TEMPLATE.md +0 -9
  13. package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
  14. package/.github/workflows/docs.yml +0 -29
  15. package/.github/workflows/publish.yml +0 -25
  16. package/.github/workflows/test.yml +0 -37
  17. package/.prettierignore +0 -2
  18. package/.releaserc +0 -11
  19. package/src/lib/combinators/index.ts +0 -2
  20. package/src/lib/combinators/logic/every.spec.ts +0 -264
  21. package/src/lib/combinators/logic/every.ts +0 -47
  22. package/src/lib/combinators/logic/if-else.spec.ts +0 -72
  23. package/src/lib/combinators/logic/if-else.ts +0 -39
  24. package/src/lib/combinators/logic/index.ts +0 -8
  25. package/src/lib/combinators/logic/match.spec.ts +0 -186
  26. package/src/lib/combinators/logic/match.ts +0 -92
  27. package/src/lib/combinators/logic/not.spec.ts +0 -62
  28. package/src/lib/combinators/logic/not.ts +0 -25
  29. package/src/lib/combinators/logic/one-of.spec.ts +0 -68
  30. package/src/lib/combinators/logic/one-of.ts +0 -41
  31. package/src/lib/combinators/logic/unless.spec.ts +0 -61
  32. package/src/lib/combinators/logic/unless.ts +0 -27
  33. package/src/lib/combinators/logic/when.spec.ts +0 -123
  34. package/src/lib/combinators/logic/when.ts +0 -29
  35. package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
  36. package/src/lib/combinators/logic/with-fallback.ts +0 -37
  37. package/src/lib/combinators/utility/index.ts +0 -8
  38. package/src/lib/combinators/utility/inject.spec.ts +0 -55
  39. package/src/lib/combinators/utility/inject.ts +0 -25
  40. package/src/lib/combinators/utility/map-error.spec.ts +0 -63
  41. package/src/lib/combinators/utility/map-error.ts +0 -35
  42. package/src/lib/combinators/utility/tap.spec.ts +0 -102
  43. package/src/lib/combinators/utility/tap.ts +0 -38
  44. package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
  45. package/src/lib/combinators/utility/validate-field.ts +0 -59
  46. package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
  47. package/src/lib/combinators/utility/with-debug.ts +0 -55
  48. package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
  49. package/src/lib/combinators/utility/with-memoize.ts +0 -81
  50. package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
  51. package/src/lib/combinators/utility/with-retry.ts +0 -68
  52. package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
  53. package/src/lib/combinators/utility/with-timeout.ts +0 -34
  54. package/src/lib/composition/compose-rules.spec.ts +0 -211
  55. package/src/lib/composition/compose-rules.ts +0 -47
  56. package/src/lib/composition/index.ts +0 -3
  57. package/src/lib/composition/pipe-rules.spec.ts +0 -220
  58. package/src/lib/composition/pipe-rules.ts +0 -44
  59. package/src/lib/composition/pipe.spec.ts +0 -47
  60. package/src/lib/composition/pipe.ts +0 -106
  61. package/src/lib/helpers/context/has-context.ts +0 -13
  62. package/src/lib/helpers/context/index.ts +0 -3
  63. package/src/lib/helpers/context/require-context.spec.ts +0 -55
  64. package/src/lib/helpers/context/require-context.ts +0 -61
  65. package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
  66. package/src/lib/helpers/context/with-lazy-context.ts +0 -35
  67. package/src/lib/helpers/index.ts +0 -6
  68. package/src/lib/helpers/result/fail.ts +0 -15
  69. package/src/lib/helpers/result/index.ts +0 -2
  70. package/src/lib/helpers/result/pass.ts +0 -14
  71. package/src/lib/helpers/retry/calculate-delay.ts +0 -31
  72. package/src/lib/index.ts +0 -4
  73. package/src/lib/types/composition-options.ts +0 -7
  74. package/src/lib/types/debug-options.ts +0 -36
  75. package/src/lib/types/index.ts +0 -4
  76. package/src/lib/types/rule-result.ts +0 -16
  77. package/src/lib/types/rule.ts +0 -21
  78. package/src/test/helpers/get-rule-error.ts +0 -23
  79. package/src/test/integration.spec.ts +0 -285
  80. package/tsconfig.json +0 -55
  81. package/tsup.config.ts +0 -36
  82. package/vitest.config.ts +0 -16
@@ -1,92 +0,0 @@
1
- import { fail } from "../../helpers";
2
- import { Rule, RuleResult } from "../../types";
3
-
4
- const isRule = <TInput, TError, TContext>(
5
- value: unknown,
6
- ): value is Rule<TInput, TError, TContext> => {
7
- return typeof value === "function";
8
- };
9
-
10
- /**
11
- * Pattern-matching combinator that selects a rule based on a key extracted from input.
12
- * @template TInput - The type of the input to validate
13
- * @template TError - The type of the error (defaults to string)
14
- * @template TContext - The type of the context object (optional)
15
- * @template TKey - The type of the branch key (must be string | number | symbol)
16
- * @param accessor - Function that extracts the match key from input
17
- * @param cases - Object mapping keys to their corresponding rules
18
- * @param defaultCase - Optional default rule or error when no match is found
19
- * @returns A new rule that executes the matching case's rule
20
- * @example
21
- * // Basic usage with string error type
22
- * const validatePayment = match(
23
- * (order) => order.paymentMethod,
24
- * {
25
- * credit: validateCreditCard,
26
- * paypal: validatePayPal,
27
- * crypto: validateCrypto
28
- * },
29
- * "Unsupported payment method"
30
- * );
31
- *
32
- * @example
33
- * // With custom error type
34
- * interface ValidationError { code: number; message: string }
35
- * const validateStatus = match<Order, ValidationError>(
36
- * (order) => order.status,
37
- * {
38
- * pending: validatePendingOrder,
39
- * completed: validateCompletedOrder
40
- * },
41
- * { code: 400, message: "Invalid status" }
42
- * );
43
- *
44
- * @example
45
- * // With default rule instead of error
46
- * const validateProduct = match(
47
- * (product) => product.type,
48
- * {
49
- * book: validateBook,
50
- * digital: validateDigitalProduct
51
- * },
52
- * validateGenericProduct
53
- * );
54
- *
55
- * @caveats
56
- * - The accessor function should return a primitive value (string/number/symbol)
57
- * - If no matching case is found and no default is provided, returns a failed result with:
58
- * - A string error when TError is string (default)
59
- * - A type-asserted error when TError is custom (may require type casting)
60
- * - All case rules must have compatible input/context types
61
- * - For conditional branching (true/false), consider using `branch` instead
62
- */
63
- export const match = <
64
- TInput,
65
- TError = string,
66
- TContext = unknown,
67
- TKey extends string | number | symbol = string,
68
- >(
69
- accessor: (input: TInput, context?: TContext) => TKey | Promise<TKey>,
70
- cases: Record<TKey, Rule<TInput, TError, TContext>>,
71
- defaultCase?: Rule<TInput, TError, TContext> | TError,
72
- ): Rule<TInput, TError, TContext> => {
73
- return async (
74
- input: TInput,
75
- context?: TContext,
76
- ): Promise<RuleResult<TError>> => {
77
- const key = await accessor(input, context);
78
- const matchedRule = cases[key];
79
-
80
- if (matchedRule) {
81
- return matchedRule(input, context);
82
- }
83
-
84
- if (defaultCase !== undefined) {
85
- return isRule<TInput, TError, TContext>(defaultCase)
86
- ? defaultCase(input, context)
87
- : fail(defaultCase);
88
- }
89
-
90
- return fail(`No matching rule for key: ${String(key)}` as TError);
91
- };
92
- };
@@ -1,62 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import { fail, pass } from "../../helpers";
3
- import { not } from "./not";
4
-
5
- describe("not combinator", () => {
6
- const mockRule = vi.fn(() => pass());
7
- const errorMsg = "Inverted error";
8
-
9
- beforeEach(() => {
10
- vi.clearAllMocks();
11
- });
12
-
13
- it("should invert pass to fail", async () => {
14
- const invertedRule = not(mockRule, errorMsg);
15
- const result = await invertedRule({});
16
-
17
- expect(result).toEqual(fail(errorMsg));
18
- expect(mockRule).toHaveBeenCalled();
19
- });
20
-
21
- it("should invert fail to pass", async () => {
22
- const failingRule = vi.fn(() => fail("Original error"));
23
- const invertedRule = not(failingRule, errorMsg);
24
- const result = await invertedRule({});
25
-
26
- expect(result).toEqual(pass());
27
- expect(failingRule).toHaveBeenCalled();
28
- });
29
-
30
- it("should preserve context", async () => {
31
- const context = { userId: 123 };
32
- const contextAwareRule = vi.fn((_, ctx) =>
33
- ctx?.userId === 123 ? pass() : fail("Wrong user"),
34
- );
35
-
36
- const invertedRule = not(contextAwareRule, errorMsg);
37
- await invertedRule({}, context);
38
-
39
- expect(contextAwareRule).toHaveBeenCalledWith({}, context);
40
- });
41
-
42
- it("should handle async rules", async () => {
43
- const asyncRule = vi.fn(async () => {
44
- await Promise.resolve();
45
- return pass();
46
- });
47
-
48
- const invertedRule = not(asyncRule, errorMsg);
49
- const result = await invertedRule({});
50
-
51
- expect(result).toEqual(fail(errorMsg));
52
- });
53
-
54
- it("should propagate rule errors", async () => {
55
- const errorRule = vi.fn(() => {
56
- throw new Error("Boom!");
57
- });
58
-
59
- const invertedRule = not(errorRule, errorMsg);
60
- await expect(invertedRule({})).rejects.toThrow("Boom!");
61
- });
62
- });
@@ -1,25 +0,0 @@
1
- import { pass, fail } from "../../helpers";
2
- import { Rule } from "../../types/rule";
3
-
4
- /**
5
- * Inverts the logic of a rule - passes when original fails and vice versa.
6
- * @template TInput - The type of the input to validate
7
- * @template TError - The type of the error (defaults to string)
8
- * @param rule - The rule to invert
9
- * @param error - The error to return when original rule passes
10
- * @returns A new rule with inverted logic
11
- * @example
12
- * const isNotAdmin = not(isAdmin, "User must not be admin");
13
- * @caveats
14
- * - The original rule's error is discarded when it fails
15
- * - Always uses the provided error when original passes
16
- */
17
- export const not = <TInput, TError = string>(
18
- rule: Rule<TInput, TError>,
19
- error: TError,
20
- ): Rule<TInput, TError> => {
21
- return async (input: TInput, context?: unknown) => {
22
- const result = await rule(input, context);
23
- return result.status === "passed" ? fail(error) : pass();
24
- };
25
- };
@@ -1,68 +0,0 @@
1
- import { describe, beforeEach, it, expect, vi } from "vitest";
2
- import { fail, pass } from "../../helpers";
3
- import { Rule } from "../../types";
4
- import { oneOf } from "./one-of";
5
-
6
- describe("oneOf combinator", () => {
7
- const passingRule = vi.fn(() => pass());
8
- const failingRule1 = vi.fn(() => fail("Error 1"));
9
- const failingRule2 = vi.fn(() => fail("Error 2"));
10
-
11
- beforeEach(() => {
12
- vi.clearAllMocks();
13
- });
14
-
15
- it("should pass if any rule passes", async () => {
16
- const validator = oneOf(failingRule1, passingRule, failingRule2);
17
- const result = await validator({});
18
-
19
- expect(result).toEqual(pass());
20
- expect(failingRule1).toHaveBeenCalled();
21
- expect(passingRule).toHaveBeenCalled();
22
- expect(failingRule2).not.toHaveBeenCalled(); // Short-circuits
23
- });
24
-
25
- it("should fail with all errors if no rules pass", async () => {
26
- const validator = oneOf(failingRule1, failingRule2);
27
- const result = await validator({});
28
-
29
- expect(result).toEqual(fail(["Error 1", "Error 2"]));
30
- });
31
-
32
- it("should handle empty rules array", async () => {
33
- const validator = oneOf();
34
- const result = await validator({});
35
-
36
- expect(result).toEqual(pass()); // Vacuous truth
37
- });
38
-
39
- it("should pass context to all rules", async () => {
40
- const context = { userId: 123 };
41
- const rule = vi.fn(() => pass());
42
-
43
- await oneOf(rule)({}, context);
44
- expect(rule).toHaveBeenCalledWith({}, context);
45
- });
46
-
47
- it("should work with async rules", async () => {
48
- const asyncRule = vi.fn(async () => {
49
- await Promise.resolve();
50
- return pass();
51
- });
52
-
53
- const result = await oneOf(asyncRule)({});
54
- expect(result).toEqual(pass());
55
- });
56
-
57
- // Type safety tests
58
- it("should enforce rule type matching", () => {
59
- type StrictInput = { id: string };
60
- const typedRule: Rule<StrictInput, string> = () => pass();
61
-
62
- // Valid usage
63
- oneOf(typedRule, () => fail("Error"));
64
-
65
- // @ts-expect-error - Should fail if input types mismatch
66
- oneOf(typedRule, (input: { other: number }) => pass());
67
- });
68
- });
@@ -1,41 +0,0 @@
1
- import { fail, pass } from "../../helpers";
2
- import { Rule } from "../../types";
3
-
4
- /**
5
- * Creates a rule that passes if any of the provided rules pass (short-circuiting).
6
- * @template TInput - The type of the input to validate
7
- * @template TError - The type of the error (defaults to string)
8
- * @template TContext - The type of the context object (optional)
9
- * @param rules - Rules to try (in order)
10
- * @returns A rule that passes if any rule passes, or fails with all errors
11
- * @example
12
- * const rule = oneOf(
13
- * validateEmail,
14
- * validatePhone,
15
- * validateUsername
16
- * );
17
- * @caveats
18
- * - Rules are executed in sequence until one passes
19
- * - Returns all errors if all rules fail
20
- */
21
- export const oneOf = <TInput, TError = string, TContext = unknown>(
22
- ...rules: Rule<TInput, TError, TContext>[]
23
- ): Rule<TInput, TError[], TContext> => {
24
- return async (input: TInput, context?: TContext) => {
25
- const errors: TError[] = [];
26
-
27
- if (!rules || rules.length === 0) {
28
- return pass();
29
- }
30
-
31
- for (const rule of rules) {
32
- const result = await rule(input, context);
33
- if (result.status === "passed") {
34
- return pass();
35
- }
36
- errors.push(result.error);
37
- }
38
-
39
- return fail(errors);
40
- };
41
- };
@@ -1,61 +0,0 @@
1
- import { describe, vi, beforeEach, it, expect } from "vitest";
2
- import { fail, pass } from "../../helpers";
3
- import { Rule } from "../../types";
4
- import { unless } from "./unless";
5
-
6
- describe("unless combinator", () => {
7
- const mockRule = vi.fn(() => fail("Rule executed"));
8
- const isAdmin = (input: { role: string }) => input.role === "admin";
9
-
10
- beforeEach(() => {
11
- vi.clearAllMocks();
12
- });
13
-
14
- it("should skip rule when predicate is true", async () => {
15
- const validateUnlessAdmin = unless(isAdmin, mockRule);
16
- const result = await validateUnlessAdmin({ role: "admin" });
17
-
18
- expect(result).toEqual(pass());
19
- expect(mockRule).not.toHaveBeenCalled();
20
- });
21
-
22
- it("should run rule when predicate is false", async () => {
23
- const validateUnlessAdmin = unless(isAdmin, mockRule);
24
- const result = await validateUnlessAdmin({ role: "user" });
25
-
26
- expect(result).toEqual(fail("Rule executed"));
27
- expect(mockRule).toHaveBeenCalled();
28
- });
29
-
30
- it("should pass context to the rule", async () => {
31
- const context = { logger: console };
32
- const rule = vi.fn(() => pass());
33
- const validator = unless(() => false, rule);
34
-
35
- await validator({}, context);
36
- expect(rule).toHaveBeenCalledWith({}, context);
37
- });
38
-
39
- it("should handle async predicates", async () => {
40
- const asyncPredicate = async (input: { id: number }) => {
41
- await Promise.resolve();
42
- return input.id > 10;
43
- };
44
- const validator = unless(asyncPredicate, mockRule);
45
-
46
- await validator({ id: 5 });
47
- expect(mockRule).toHaveBeenCalled();
48
- });
49
-
50
- // Type safety tests
51
- it("should enforce predicate input type", () => {
52
- type StrictInput = { id: string };
53
- const typedRule: Rule<StrictInput> = () => pass();
54
-
55
- // Valid usage
56
- unless((input: StrictInput) => !!input.id, typedRule);
57
-
58
- // @ts-expect-error - Should fail if predicate expects wrong type
59
- unless((input: { other: number }) => true, typedRule);
60
- });
61
- });
@@ -1,27 +0,0 @@
1
- import type { Rule } from "../../types";
2
- import { pass } from "../../helpers";
3
-
4
- /**
5
- * Executes a rule only if the predicate returns false.
6
- * @template TInput - The type of the input to validate
7
- * @template TError - The type of the error (defaults to string)
8
- * @template TContext - The type of the context object (optional)
9
- * @param predicate - Condition to check
10
- * @param rule - Rule to execute when predicate is false
11
- * @returns A rule that conditionally executes based on the predicate
12
- * @example
13
- * const rule = unless(
14
- * (user) => user.isVerified,
15
- * requireVerification
16
- * );
17
- * @caveats
18
- * - Opposite behavior of `when`
19
- * - Automatically passes when predicate is true
20
- */
21
- export const unless = <TInput, TError = string, TContext = unknown>(
22
- predicate: (input: TInput) => Promise<boolean> | boolean,
23
- rule: Rule<TInput, TError, TContext>,
24
- ): Rule<TInput, TError, TContext> => {
25
- return async (input: TInput, context?: TContext) =>
26
- (await predicate(input)) ? pass() : rule(input, context);
27
- };
@@ -1,123 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import { when } from "./when";
3
- import { pass } from "../../helpers/result/pass";
4
- import { fail } from "../../helpers/result/fail";
5
-
6
- describe("when combinator", () => {
7
- const mockRule = vi.fn(() => pass());
8
- const mockPredicateTrue = vi.fn((_: any) => true);
9
- const mockPredicateFalse = vi.fn((_: any) => false);
10
-
11
- beforeEach(() => {
12
- vi.clearAllMocks();
13
- });
14
-
15
- // Basic functionality
16
- it("should apply rule when condition is true", async () => {
17
- const conditionalRule = when(mockPredicateTrue, mockRule);
18
- const input = { active: true };
19
-
20
- await conditionalRule(input);
21
-
22
- expect(mockPredicateTrue).toHaveBeenCalledWith(input);
23
- expect(mockRule).toHaveBeenCalledWith(input, undefined);
24
- });
25
-
26
- it("should skip rule when condition is false", async () => {
27
- const conditionalRule = when(mockPredicateFalse, mockRule);
28
- const input = { active: false };
29
- const result = await conditionalRule(input);
30
-
31
- expect(mockPredicateFalse).toHaveBeenCalledWith(input);
32
- expect(result).toEqual(pass());
33
- expect(mockRule).not.toHaveBeenCalled();
34
- });
35
-
36
- it("should work with async predicates", async () => {
37
- const conditionalRule = when(async (input: { id: number }) => {
38
- await Promise.resolve();
39
- return input.id > 10;
40
- }, mockRule);
41
-
42
- await conditionalRule({ id: 20 });
43
- expect(mockRule).toHaveBeenCalled();
44
-
45
- mockRule.mockClear();
46
- await conditionalRule({ id: 5 });
47
- expect(mockRule).not.toHaveBeenCalled();
48
- });
49
-
50
- it("should handle mixed async predicates with sync rules", async () => {
51
- const conditionalRule = when(async (input: { value: number }) => {
52
- await Promise.resolve();
53
- return input.value > 5;
54
- }, mockRule);
55
-
56
- await conditionalRule({ value: 10 });
57
- expect(mockRule).toHaveBeenCalled();
58
- });
59
-
60
- it("should handle falsy conditions", async () => {
61
- const testCases = [
62
- { condition: false, shouldRun: false },
63
- { condition: 0, shouldRun: false },
64
- { condition: "", shouldRun: false },
65
- { condition: null, shouldRun: false },
66
- { condition: undefined, shouldRun: false },
67
- ];
68
-
69
- for (const { condition, shouldRun } of testCases) {
70
- const conditionalRule = when(() => condition as any, mockRule);
71
- await conditionalRule({});
72
- expect(mockRule.mock.calls.length).toBe(shouldRun ? 1 : 0);
73
- mockRule.mockClear();
74
- }
75
- });
76
-
77
- it("should pass context to rule but not predicate", async () => {
78
- const context = { authToken: "xyz" };
79
- const rule = vi.fn(() => pass());
80
-
81
- await when(mockPredicateTrue, rule)({}, context);
82
-
83
- expect(mockPredicateTrue).toHaveBeenCalledWith({});
84
- expect(rule).toHaveBeenCalledWith({}, context);
85
- });
86
-
87
- it("should work with async rules needing context", async () => {
88
- const context = {
89
- db: {
90
- findUser: async (_id: string) => true,
91
- },
92
- };
93
- const validate = when(
94
- (input: { id: string }) => !!input.id,
95
- async (input, ctx: any) => {
96
- const exists = await ctx.db.findUser(input.id);
97
- return exists ? pass() : fail("Not found");
98
- },
99
- );
100
-
101
- await validate({ id: "123" }, context);
102
- });
103
-
104
- // Error cases
105
- it("should propagate condition errors", async () => {
106
- const errorCondition = () => {
107
- throw new Error("Condition failed");
108
- };
109
- const conditionalRule = when(errorCondition, mockRule);
110
-
111
- expect(conditionalRule({})).rejects.toThrow("Condition failed");
112
- expect(mockRule).not.toHaveBeenCalled();
113
- });
114
-
115
- it("should propagate rule errors when condition passes", async () => {
116
- const errorRule = () => {
117
- throw new Error("Rule failed");
118
- };
119
- const conditionalRule = when(() => true, errorRule);
120
-
121
- expect(conditionalRule({})).rejects.toThrow("Rule failed");
122
- });
123
- });
@@ -1,29 +0,0 @@
1
- import { pass } from "../../helpers/result/pass";
2
- import { Rule } from "../../types/rule";
3
-
4
- /**
5
- * Conditionally executes a rule based on a predicate.
6
- * Similar to branch but without an else case.
7
- * @template TInput - The type of the input to validate
8
- * @template TError - The type of the error (defaults to string)
9
- * @param predicate - Function that determines whether to execute the rule
10
- * @param rule - Rule to execute when predicate returns true
11
- * @returns A new rule that conditionally executes the input rule
12
- * @example
13
- * const rule = when(
14
- * (user) => user.role === "admin",
15
- * validateAdminPrivileges
16
- * );
17
- * @caveats
18
- * - The predicate can be async
19
- * - If predicate returns false, the rule automatically passes
20
- */
21
- export const when = <TInput, TError = string>(
22
- predicate: (input: TInput) => boolean | Promise<boolean>,
23
- rule: Rule<TInput, TError>,
24
- ): Rule<TInput, TError> => {
25
- return async (input: TInput, context?: unknown) => {
26
- const shouldRun = await predicate(input);
27
- return shouldRun ? rule(input, context) : pass();
28
- };
29
- };
@@ -1,72 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { fail, pass } from "../../helpers";
3
- import { withFallback } from "./with-fallback";
4
-
5
- describe("withFallback", () => {
6
- const mockMainRule = vi.fn();
7
- const mockFallback = vi.fn();
8
-
9
- beforeEach(() => {
10
- mockMainRule.mockReset();
11
- mockFallback.mockReset();
12
- });
13
-
14
- it("should execute fallback when main rule fails", async () => {
15
- mockMainRule.mockResolvedValue(fail("Main failed"));
16
- mockFallback.mockResolvedValue(pass());
17
-
18
- const rule = withFallback(mockMainRule, mockFallback);
19
- const result = await rule("test");
20
-
21
- expect(mockMainRule).toHaveBeenCalledWith("test", undefined);
22
- expect(mockFallback).toHaveBeenCalledWith("test", undefined);
23
- expect(result).toEqual(pass());
24
- });
25
-
26
- it("should not execute fallback when main rule passes", async () => {
27
- mockMainRule.mockResolvedValue(pass());
28
-
29
- const rule = withFallback(mockMainRule, mockFallback);
30
- const result = await rule("test");
31
-
32
- expect(mockFallback).not.toHaveBeenCalled();
33
- expect(result).toEqual(pass());
34
- });
35
-
36
- it("should respect conditional fallback predicate", async () => {
37
- mockMainRule.mockResolvedValue(fail({ code: "RETRYABLE" }));
38
- mockFallback.mockResolvedValue(pass());
39
-
40
- const rule = withFallback(mockMainRule, mockFallback, {
41
- onlyFallbackOn: (err) => (err as any).code === "RETRYABLE",
42
- });
43
-
44
- await rule("test");
45
- expect(mockFallback).toHaveBeenCalled();
46
-
47
- mockMainRule.mockResolvedValue(fail({ code: "FATAL" }));
48
- await rule("test");
49
- expect(mockFallback).toHaveBeenCalledTimes(1); // Not called for FATAL
50
- });
51
-
52
- it("should preserve context", async () => {
53
- const context = { auth: true };
54
- mockMainRule.mockResolvedValue(fail("Failed"));
55
- mockFallback.mockResolvedValue(pass());
56
-
57
- const rule = withFallback(mockMainRule, mockFallback);
58
- await rule("test", context);
59
-
60
- expect(mockMainRule).toHaveBeenCalledWith("test", context);
61
- expect(mockFallback).toHaveBeenCalledWith("test", context);
62
- });
63
-
64
- it("should maintain type safety", async () => {
65
- // Type test - no runtime assertion needed
66
- const stringRule = (_: string) => pass();
67
- const numberRule = (_: number) => pass();
68
-
69
- // @ts-expect-error - Should fail type check
70
- withFallback(stringRule, numberRule);
71
- });
72
- });
@@ -1,37 +0,0 @@
1
- import { Rule } from "../../types";
2
-
3
- /**
4
- * Creates a rule that falls back to an alternative rule if the main rule fails.
5
- * @template TInput - Input type
6
- * @template TError - Error type
7
- * @template TContext - Context type
8
- * @param mainRule - Primary rule to execute first
9
- * @param fallbackRule - Rule to execute if main rule fails
10
- * @param options - Configuration options
11
- * @param options.onlyFallbackOn - Predicate to conditionally enable fallback
12
- * @returns A new composite rule
13
- * @example
14
- * const rule = withFallback(
15
- * premiumValidation,
16
- * basicValidation,
17
- * { onlyFallbackOn: err => err.code !== 'FATAL' }
18
- * );
19
- */
20
- export const withFallback = <TInput, TError, TContext>(
21
- mainRule: Rule<TInput, TError, TContext>,
22
- fallbackRule: Rule<TInput, TError, TContext>,
23
- options: {
24
- onlyFallbackOn?: (error: TError) => boolean;
25
- } = {},
26
- ): Rule<TInput, TError, TContext> => {
27
- return async (input: TInput, context?: TContext) => {
28
- const result = await mainRule(input, context);
29
- if (
30
- result.status === "failed" &&
31
- (!options.onlyFallbackOn || options.onlyFallbackOn(result.error))
32
- ) {
33
- return fallbackRule(input, context);
34
- }
35
- return result;
36
- };
37
- };
@@ -1,8 +0,0 @@
1
- export * from "./inject";
2
- export * from "./map-error";
3
- export * from "./with-memoize";
4
- export * from "./validate-field";
5
- export * from "./tap";
6
- export * from "./with-debug";
7
- export * from "./with-retry";
8
- export * from "./with-timeout";