ts-rules-composer 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/.github/workflows/publish.yml +1 -1
  2. package/README.md +310 -42
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +335 -55
  6. package/dist/index.d.ts +335 -55
  7. package/dist/index.js +1 -1
  8. package/dist/index.js.map +1 -1
  9. package/eslint.config.mjs +84 -0
  10. package/examples/financial-transaction.example.ts +188 -0
  11. package/examples/model-deployment.example.ts +136 -0
  12. package/examples/user-registration.example.ts +101 -0
  13. package/package.json +21 -6
  14. package/src/lib/combinators/logic/every.spec.ts +1 -1
  15. package/src/lib/combinators/logic/every.ts +17 -7
  16. package/src/lib/combinators/logic/if-else.spec.ts +11 -1
  17. package/src/lib/combinators/logic/if-else.ts +33 -8
  18. package/src/lib/combinators/logic/match.ts +20 -6
  19. package/src/lib/combinators/logic/not.spec.ts +3 -1
  20. package/src/lib/combinators/logic/not.ts +12 -3
  21. package/src/lib/combinators/logic/one-of.spec.ts +7 -7
  22. package/src/lib/combinators/logic/one-of.ts +11 -4
  23. package/src/lib/combinators/logic/unless.spec.ts +1 -1
  24. package/src/lib/combinators/logic/unless.ts +28 -5
  25. package/src/lib/combinators/logic/when.spec.ts +11 -15
  26. package/src/lib/combinators/logic/when.ts +29 -8
  27. package/src/lib/combinators/logic/with-fallback.ts +13 -4
  28. package/src/lib/combinators/utility/index.ts +5 -2
  29. package/src/lib/combinators/utility/inject.ts +1 -1
  30. package/src/lib/combinators/utility/map-error.ts +1 -1
  31. package/src/lib/combinators/utility/tap.spec.ts +63 -63
  32. package/src/lib/combinators/utility/tap.ts +18 -28
  33. package/src/lib/combinators/utility/validate-field.spec.ts +1 -1
  34. package/src/lib/combinators/utility/validate-field.ts +10 -3
  35. package/src/lib/combinators/utility/with-debug.spec.ts +1 -1
  36. package/src/lib/combinators/utility/with-debug.ts +1 -1
  37. package/src/lib/combinators/utility/with-memoize.spec.ts +1 -1
  38. package/src/lib/combinators/utility/with-memoize.ts +12 -4
  39. package/src/lib/combinators/utility/with-retry.spec.ts +1 -1
  40. package/src/lib/combinators/utility/with-retry.ts +4 -2
  41. package/src/lib/combinators/utility/with-safe-error.spec.ts +137 -0
  42. package/src/lib/combinators/utility/with-safe-error.ts +56 -0
  43. package/src/lib/combinators/utility/with-safe-predicate.spec.ts +176 -0
  44. package/src/lib/combinators/utility/with-safe-predicate.ts +64 -0
  45. package/src/lib/combinators/utility/with-tap.spec.ts +104 -0
  46. package/src/lib/combinators/utility/with-tap.ts +46 -0
  47. package/src/lib/combinators/utility/with-timeout.spec.ts +1 -1
  48. package/src/lib/combinators/utility/with-timeout.ts +10 -3
  49. package/src/lib/composition/compose-rules.spec.ts +1 -1
  50. package/src/lib/composition/compose-rules.ts +16 -8
  51. package/src/lib/composition/pipe-rules.spec.ts +1 -1
  52. package/src/lib/composition/pipe-rules.ts +15 -7
  53. package/src/lib/composition/pipe.ts +1 -0
  54. package/src/lib/helpers/clone/clone.ts +12 -0
  55. package/src/lib/helpers/clone/getCloneFn.ts +17 -0
  56. package/src/lib/helpers/clone/shallowClone.ts +12 -0
  57. package/src/lib/helpers/context/require-context.ts +1 -1
  58. package/src/lib/helpers/context/with-lazy-context.spec.ts +1 -1
  59. package/src/lib/helpers/context/with-lazy-context.ts +1 -1
  60. package/src/lib/helpers/index.ts +2 -0
  61. package/src/lib/helpers/result/fail.ts +1 -1
  62. package/src/lib/helpers/result/pass.ts +1 -1
  63. package/src/lib/helpers/retry/calculate-delay.ts +1 -1
  64. package/src/lib/helpers/safety/get-normalized-rule.spec.ts +209 -0
  65. package/src/lib/helpers/safety/get-normalized-rule.ts +14 -0
  66. package/src/lib/helpers/safety/get-normalized-rules.spec.ts +138 -0
  67. package/src/lib/helpers/safety/get-normalized-rules.ts +14 -0
  68. package/src/lib/index.ts +1 -1
  69. package/src/lib/types/composition-options.ts +28 -3
  70. package/src/lib/types/debug-options.ts +1 -1
  71. package/src/lib/types/index.ts +8 -4
  72. package/src/lib/types/predicate-result.ts +20 -0
  73. package/src/lib/types/predicate-safe.ts +10 -0
  74. package/src/lib/types/predicate-safety-options.ts +27 -0
  75. package/src/lib/types/predicate.ts +8 -0
  76. package/src/lib/types/prettify.ts +3 -0
  77. package/src/lib/types/rule-safety-options.ts +34 -0
  78. package/src/lib/types/rule.ts +1 -1
  79. package/src/lib/types/safety-options.ts +7 -0
  80. package/src/test/financial-transaction.spec.ts +251 -0
  81. package/src/test/helpers/get-rule-error.ts +1 -1
  82. package/src/test/integration.spec.ts +3 -3
  83. package/src/test/model-deployment.spec.ts +209 -0
  84. package/src/test/user-registration.spec.ts +164 -0
  85. package/tsconfig.json +5 -4
  86. package/tsup.config.ts +15 -15
  87. package/typedoc/tsconfig.typedoc.json +15 -0
  88. package/typedoc/typedoc.json +14 -0
  89. package/.eslintrc.json +0 -66
@@ -0,0 +1,137 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { withSafeError } from "./with-safe-error";
3
+ import { pass, fail } from "../../helpers";
4
+ import type { Rule, RuleResult } from "../../types";
5
+
6
+ describe("withSafeError", () => {
7
+ // Mock rules for testing
8
+ const passingRule = vi.fn(() => pass());
9
+ const failingRule = vi.fn(() => fail("Expected error"));
10
+ const errorThrowingRule = vi.fn(() => {
11
+ throw new Error("Boom!");
12
+ });
13
+ const stringThrowingRule = vi.fn(() => {
14
+ throw "Just a string error";
15
+ });
16
+ const objectThrowingRule = vi.fn(() => {
17
+ throw { code: 500, message: "Custom error" };
18
+ });
19
+ const invalidRule = vi.fn(() => "not a RuleResult" as unknown as RuleResult);
20
+
21
+ beforeEach(() => {
22
+ vi.clearAllMocks();
23
+ });
24
+
25
+ // 1. Basic functionality tests
26
+ it("should pass through successful results unchanged", async () => {
27
+ const safeRule = withSafeError(passingRule);
28
+ const result = await safeRule({});
29
+ expect(result).toEqual(pass());
30
+ });
31
+
32
+ it("should pass through failed results unchanged", async () => {
33
+ const safeRule = withSafeError(failingRule);
34
+ const result = await safeRule({});
35
+ expect(result).toEqual(fail("Expected error"));
36
+ });
37
+
38
+ // 2. Error handling tests
39
+ it("should catch Error objects and use their message", async () => {
40
+ const safeRule = withSafeError(errorThrowingRule);
41
+ const result = await safeRule({});
42
+ expect(result).toEqual(fail(new Error("Boom!")));
43
+ });
44
+
45
+ it("should catch string errors and preserve them", async () => {
46
+ const safeRule = withSafeError(stringThrowingRule);
47
+ const result = await safeRule({});
48
+ expect(result).toEqual(fail("Just a string error"));
49
+ });
50
+
51
+ it("should preserve object error structure", async () => {
52
+ const safeRule = withSafeError(objectThrowingRule);
53
+ const result = await safeRule({});
54
+ expect(result).toEqual(fail({ code: 500, message: "Custom error" }));
55
+ });
56
+
57
+ // 3. Invalid rule behavior tests
58
+ it("should handle rules that return invalid results", async () => {
59
+ const safeRule = withSafeError(invalidRule);
60
+ const result = await safeRule({});
61
+ expect(result.status).toBe("failed");
62
+ expect((result as any).error).toEqual(
63
+ new Error("Invalid rule - did not return RuleResult"),
64
+ );
65
+ });
66
+
67
+ // 4. Custom error transformation tests
68
+ it("should use custom error transformation when provided", async () => {
69
+ const customTransform = vi.fn((error: unknown) => ({
70
+ code: 500,
71
+ message: String(error),
72
+ }));
73
+
74
+ const safeRule = withSafeError(errorThrowingRule, customTransform);
75
+ const result = await safeRule({});
76
+
77
+ expect(result).toEqual(
78
+ fail({
79
+ code: 500,
80
+ message: "Error: Boom!",
81
+ }),
82
+ );
83
+ expect(customTransform).toHaveBeenCalledWith(expect.any(Error));
84
+ });
85
+
86
+ // 5. Type safety tests
87
+ it("should preserve custom error types when specified", async () => {
88
+ interface CustomError {
89
+ code: number;
90
+ details: string;
91
+ }
92
+ const customError: CustomError = {
93
+ code: 400,
94
+ details: "Validation failed",
95
+ };
96
+
97
+ const customErrorRule: Rule<number, CustomError> = () => {
98
+ throw customError;
99
+ };
100
+
101
+ const safeRule = withSafeError<number, CustomError>(customErrorRule);
102
+ const result = await safeRule(123);
103
+
104
+ expect(result).toEqual(fail(customError));
105
+ });
106
+
107
+ // 6. Context handling tests
108
+ it("should pass context to the wrapped rule", async () => {
109
+ const context = { userId: 123 };
110
+ const contextAwareRule = vi.fn((_: unknown, ctx: any) =>
111
+ ctx?.userId === 123 ? pass() : fail("Wrong user"),
112
+ );
113
+
114
+ const safeRule = withSafeError(contextAwareRule);
115
+ await safeRule({}, context);
116
+ expect(contextAwareRule).toHaveBeenCalledWith({}, context);
117
+ });
118
+
119
+ // 7. Async behavior tests
120
+ it("should handle async rules that throw", async () => {
121
+ const asyncErrorRule = vi.fn(async () => {
122
+ await Promise.resolve();
123
+ throw new Error("Async boom!");
124
+ });
125
+
126
+ const safeRule = withSafeError(asyncErrorRule);
127
+ const result = await safeRule({});
128
+ expect(result).toEqual(fail(new Error("Async boom!")));
129
+ });
130
+
131
+ // 8. Edge case tests
132
+ it("should handle null/undefined input safely", async () => {
133
+ const safeRule = withSafeError(passingRule);
134
+ await expect(safeRule(null as any)).resolves.not.toThrow();
135
+ await expect(safeRule(undefined as any)).resolves.not.toThrow();
136
+ });
137
+ });
@@ -0,0 +1,56 @@
1
+ import { fail } from "../../helpers";
2
+ import type { Rule, RuleResult } from "../../types";
3
+
4
+ /**
5
+ * Wraps a rule to catch errors and convert them to failed RuleResults
6
+ * @template TInput - The input type
7
+ * @template TError - The error type (defaults to string)
8
+ * @template TContext - The context type
9
+ * @param rule - The rule to protect
10
+ * @param errorMapper - Optional error transformation logic
11
+ * @returns A protected version of the rule
12
+ * @example
13
+ * // Basic usage with default error handling
14
+ * const safeRule = withSafeError(riskyRule);
15
+ *
16
+ * // With custom error transformation
17
+ * const customSafeRule = withSafeError(riskyRule, e => ({
18
+ * code: 500,
19
+ * message: String(e)
20
+ * }));
21
+ *
22
+ * @caveats
23
+ *
24
+ * - Generic parameters must be explicitly set for custom error types
25
+ * - Doesn't verify error types match TError at runtime
26
+ */
27
+ export const withSafeError = <TInput, TError = string, TContext = unknown>(
28
+ rule: Rule<TInput, TError, TContext>,
29
+ errorTransform: (error: unknown) => TError = (e) => {
30
+ // Preserve object structure if TError is object-like
31
+ if (typeof e === "object" && e !== null) return e as TError;
32
+ // Default to string for primitives/errors
33
+ return (e instanceof Error ? e.message : String(e)) as TError;
34
+ },
35
+ ): Rule<TInput, TError, TContext> => {
36
+ return async (
37
+ input: TInput,
38
+ context?: TContext,
39
+ ): Promise<RuleResult<TError>> => {
40
+ try {
41
+ const result = await rule(input, context);
42
+
43
+ // Preserve existing RuleResults
44
+ if (result && typeof result === "object" && "status" in result) {
45
+ return result;
46
+ }
47
+
48
+ // Handle invalid rule implementations that don't return RuleResult
49
+ return fail(
50
+ errorTransform(new Error(`Invalid rule - did not return RuleResult`)),
51
+ );
52
+ } catch (error) {
53
+ return fail(errorTransform(error));
54
+ }
55
+ };
56
+ };
@@ -0,0 +1,176 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { withSafePredicate } from "./with-safe-predicate";
3
+
4
+ describe("withSafePredicate", () => {
5
+ const mockPredicate = vi.fn();
6
+ const mockErrorTransform = vi.fn();
7
+
8
+ beforeEach(() => {
9
+ vi.clearAllMocks();
10
+ mockErrorTransform.mockImplementation((e) => `Transformed: ${String(e)}`);
11
+ });
12
+
13
+ describe("Basic functionality", () => {
14
+ it("should pass through boolean results (true)", async () => {
15
+ mockPredicate.mockResolvedValue(true);
16
+ const safePred = withSafePredicate(mockPredicate);
17
+ const result = await safePred("test");
18
+
19
+ expect(result).toEqual({ status: "passed", value: true });
20
+ expect(mockPredicate).toHaveBeenCalledWith("test", undefined);
21
+ });
22
+
23
+ it("should pass through boolean results (false)", async () => {
24
+ mockPredicate.mockResolvedValue(false);
25
+ const safePred = withSafePredicate(mockPredicate);
26
+ const result = await safePred("test");
27
+
28
+ expect(result).toEqual({ status: "passed", value: false });
29
+ });
30
+
31
+ it("should handle sync predicates", async () => {
32
+ mockPredicate.mockReturnValue(true);
33
+ const safePred = withSafePredicate(mockPredicate);
34
+ const result = await safePred("test");
35
+
36
+ expect(result).toEqual({ status: "passed", value: true });
37
+ });
38
+ });
39
+
40
+ describe("Error handling", () => {
41
+ it("should catch thrown errors", async () => {
42
+ mockPredicate.mockImplementation(() => {
43
+ throw new Error("Boom!");
44
+ });
45
+ const safePred = withSafePredicate(mockPredicate);
46
+ const result = await safePred("test");
47
+
48
+ expect(result.status).toBe("failed");
49
+ expect((result as any).error).toEqual(new Error("Boom!"));
50
+ });
51
+
52
+ it("should catch rejected promises", async () => {
53
+ mockPredicate.mockRejectedValue(new Error("Async boom!"));
54
+ const safePred = withSafePredicate(mockPredicate);
55
+ const result = await safePred("test");
56
+
57
+ expect(result.status).toBe("failed");
58
+ expect((result as any).error).toEqual(new Error("Async boom!"));
59
+ });
60
+
61
+ it("should handle non-Error throws", async () => {
62
+ mockPredicate.mockImplementation(() => {
63
+ throw "String error";
64
+ });
65
+ const safePred = withSafePredicate(mockPredicate);
66
+ const result = await safePred("test");
67
+
68
+ expect(result.status).toBe("failed");
69
+ expect((result as any).error).toBe("String error");
70
+ });
71
+
72
+ it("should use custom error transform", async () => {
73
+ mockPredicate.mockRejectedValue(new Error("Original"));
74
+ const safePred = withSafePredicate(mockPredicate, mockErrorTransform);
75
+ const result = await safePred("test");
76
+
77
+ expect(result.status).toBe("failed");
78
+ expect((result as any).error).toBe("Transformed: Error: Original");
79
+ expect(mockErrorTransform).toHaveBeenCalledWith(expect.any(Error));
80
+ });
81
+ });
82
+
83
+ describe("Type safety enforcement", () => {
84
+ it("should fail on non-boolean returns (undefined)", async () => {
85
+ mockPredicate.mockResolvedValue(undefined);
86
+ const safePred = withSafePredicate(mockPredicate);
87
+ const result = await safePred("test");
88
+
89
+ expect(result.status).toBe("failed");
90
+ expect((result as any).error.message).toContain(
91
+ "Predicate must return boolean",
92
+ );
93
+ });
94
+
95
+ it("should fail on non-boolean returns (object)", async () => {
96
+ mockPredicate.mockResolvedValue({ not: "boolean" });
97
+ const safePred = withSafePredicate(mockPredicate);
98
+ const result = await safePred("test");
99
+
100
+ expect(result.status).toBe("failed");
101
+ expect((result as any).error.message).toContain("got object");
102
+ });
103
+
104
+ it("should fail on non-boolean returns (null)", async () => {
105
+ mockPredicate.mockResolvedValue(null);
106
+ const safePred = withSafePredicate(mockPredicate);
107
+ const result = await safePred("test");
108
+
109
+ expect(result.status).toBe("failed");
110
+ expect((result as any).error.message).toContain("got object");
111
+ });
112
+ });
113
+
114
+ describe("Context handling", () => {
115
+ it("should pass context to predicate", async () => {
116
+ const context = { auth: true };
117
+ mockPredicate.mockResolvedValue(true);
118
+ const safePred = withSafePredicate(mockPredicate);
119
+ await safePred("test", context);
120
+
121
+ expect(mockPredicate).toHaveBeenCalledWith("test", context);
122
+ });
123
+
124
+ it("should handle undefined context", async () => {
125
+ mockPredicate.mockResolvedValue(true);
126
+ const safePred = withSafePredicate(mockPredicate);
127
+ await safePred("test");
128
+
129
+ expect(mockPredicate).toHaveBeenCalledWith("test", undefined);
130
+ });
131
+ });
132
+
133
+ describe("Edge cases", () => {
134
+ it("should handle custom error types", async () => {
135
+ interface CustomError {
136
+ code: number;
137
+ details: string;
138
+ }
139
+ const errorTransform = (e: unknown): CustomError => ({
140
+ code: 500,
141
+ details: String(e),
142
+ });
143
+
144
+ mockPredicate.mockRejectedValue(new Error("Test"));
145
+ const safePred = withSafePredicate(mockPredicate, errorTransform);
146
+ const result = await safePred("test");
147
+
148
+ expect(result.status).toBe("failed");
149
+ expect((result as any).error).toEqual({
150
+ code: 500,
151
+ details: "Error: Test",
152
+ });
153
+ });
154
+
155
+ it("should preserve object error structure when configured", async () => {
156
+ const originalError = { code: 400, message: "Bad request" };
157
+ mockPredicate.mockRejectedValue(originalError);
158
+
159
+ // No transform - should preserve object structure
160
+ const safePred = withSafePredicate(mockPredicate);
161
+ const result = await safePred("test");
162
+
163
+ expect(result.status).toBe("failed");
164
+ expect((result as any).error).toEqual(originalError);
165
+ });
166
+
167
+ it("should handle falsy values (empty string)", async () => {
168
+ mockPredicate.mockImplementation(() => "");
169
+ const safePred = withSafePredicate(mockPredicate);
170
+ const result = await safePred("test");
171
+
172
+ expect(result.status).toBe("failed");
173
+ expect((result as any).error.message).toContain("got string");
174
+ });
175
+ });
176
+ });
@@ -0,0 +1,64 @@
1
+ import type { Predicate, PredicateSafe, PredicateResult } from "../../types";
2
+
3
+ /**
4
+ * Wraps a predicate function with error handling and type safety.
5
+ * @template TInput - The input type
6
+ * @template TError - The error type (defaults to string)
7
+ * @template TContext - The context type
8
+ * @param predicate - The predicate function to wrap
9
+ * @param errorTransform - Optional function to transform errors
10
+ * @returns A safe predicate that never throws
11
+ *
12
+ * @example
13
+ * const safePredicate = withSafePredicate(
14
+ * (input: string) => input.length > 5,
15
+ * (err) => `Predicate failed: ${String(err)}`
16
+ * );
17
+ *
18
+ * @caveats
19
+ * **Error Handling Behavior**:
20
+ * - Will catch both synchronous throws and Promise rejections
21
+ * - Errors in the errorTransform itself will propagate (not caught)
22
+ * - The default transformer converts all errors to strings except Error objects
23
+ *
24
+ * **Edge Cases**:
25
+ * - Returns failed result for non-boolean returns (including null/undefined)
26
+ * - Returns failed result for Promise<non-boolean> resolutions
27
+ * - Returns failed result for Promise rejections (transformed via errorTransform)
28
+ * - Returns failed result for thrown non-Error values (like `throw "string"`)
29
+ */
30
+ export const withSafePredicate = <TInput, TError = string, TContext = unknown>(
31
+ predicate: Predicate<TInput, TContext>,
32
+ errorTransform: (error: unknown) => TError = (e) => {
33
+ // Preserve object structure if TError is object-like
34
+ if (typeof e === "object" && e !== null) return e as TError;
35
+ // Default to string for primitives/errors
36
+ return (e instanceof Error ? e.message : String(e)) as TError;
37
+ },
38
+ ): PredicateSafe<TInput, TError, TContext> => {
39
+ return async (
40
+ input: TInput,
41
+ context?: TContext,
42
+ ): Promise<PredicateResult<TError>> => {
43
+ try {
44
+ const result = await predicate(input, context);
45
+
46
+ // Check if result is a boolean
47
+ if (typeof result === "boolean") {
48
+ return { status: "passed", value: result };
49
+ }
50
+
51
+ return {
52
+ status: "failed",
53
+ error: errorTransform(
54
+ new Error(`Predicate must return boolean, got ${typeof result}`),
55
+ ),
56
+ };
57
+ } catch (error) {
58
+ return {
59
+ status: "failed",
60
+ error: errorTransform(error),
61
+ };
62
+ }
63
+ };
64
+ };
@@ -0,0 +1,104 @@
1
+ import { describe, vi, beforeEach, it, expect } from "vitest";
2
+ import { pipeRules } from "../../composition/pipe-rules";
3
+ import { fail, pass } from "../../helpers";
4
+ import type { Rule } from "../../types";
5
+ import { withTap } from "./with-tap";
6
+
7
+ describe("tap (standalone)", () => {
8
+ const mockEffect = vi.fn();
9
+ const mockRule = vi.fn(() => pass());
10
+ const mockContext = { logger: console };
11
+
12
+ beforeEach(() => {
13
+ vi.clearAllMocks();
14
+ });
15
+
16
+ // Basic functionality
17
+ it("should call effect without modifying rule result", async () => {
18
+ const tappedRule = withTap(mockEffect)(mockRule);
19
+ const input = { test: "value" };
20
+ const result = await tappedRule(input);
21
+
22
+ expect(result).toEqual(pass());
23
+ expect(mockEffect).toHaveBeenCalledWith(input, pass(), undefined);
24
+ expect(mockRule).toHaveBeenCalledWith(input, undefined);
25
+ });
26
+
27
+ // Error handling
28
+ it("should not propagate effect errors", async () => {
29
+ const errorEffect = vi.fn(() => {
30
+ throw new Error("Effect failed");
31
+ });
32
+ const tappedRule = withTap(errorEffect)(mockRule);
33
+
34
+ await expect(tappedRule({})).resolves.toEqual(pass());
35
+ expect(errorEffect).toHaveBeenCalled();
36
+ });
37
+
38
+ // Context handling
39
+ it("should pass context to both rule and effect", async () => {
40
+ const tappedRule = withTap(mockEffect)(mockRule);
41
+ await tappedRule({}, mockContext);
42
+
43
+ expect(mockRule).toHaveBeenCalledWith({}, mockContext);
44
+ expect(mockEffect).toHaveBeenCalledWith({}, pass(), mockContext);
45
+ });
46
+
47
+ // Async effects
48
+ it("should handle async effects", async () => {
49
+ const asyncEffect = vi.fn(async () => {
50
+ await Promise.resolve();
51
+ });
52
+ const tappedRule = withTap(asyncEffect)(mockRule);
53
+ await tappedRule({});
54
+
55
+ expect(asyncEffect).toHaveBeenCalled();
56
+ });
57
+
58
+ // Composition
59
+ it("should work with manual composition", async () => {
60
+ const rule1 = vi.fn(() => pass());
61
+ const rule2 = vi.fn(() => fail("Error"));
62
+ const effect1 = vi.fn();
63
+ const effect2 = vi.fn();
64
+
65
+ const pipeline = withTap(effect2)(
66
+ pipeRules([withTap(effect1)(rule1), rule2]),
67
+ );
68
+
69
+ await pipeline({});
70
+ expect(effect1).toHaveBeenCalledWith({}, pass(), undefined);
71
+ expect(effect2).toHaveBeenCalledWith({}, fail("Error"), undefined);
72
+ });
73
+
74
+ // Type safety tests
75
+ it("should enforce input type matching", () => {
76
+ type StrictInput = { id: string };
77
+ const typedRule: Rule<StrictInput> = () => pass();
78
+
79
+ // Valid usage
80
+ withTap((input: StrictInput) => console.log(input.id))(typedRule);
81
+
82
+ // @ts-expect-error - Should fail if effect expects wrong input type
83
+ withTap((input: { other: number }) => {})(typedRule);
84
+ });
85
+
86
+ // Edge cases
87
+ it("should handle null/undefined inputs", async () => {
88
+ const effect = vi.fn();
89
+ const rule = () => pass();
90
+ const tappedRule = withTap(effect)(rule);
91
+
92
+ await tappedRule(null as any);
93
+ expect(effect).toHaveBeenCalledWith(null, pass(), undefined);
94
+ });
95
+
96
+ it("should handle effect returning Promise<void>", async () => {
97
+ const asyncEffect = async () => {
98
+ await Promise.resolve();
99
+ };
100
+ const tappedRule = withTap(asyncEffect)(mockRule);
101
+
102
+ await expect(tappedRule({})).resolves.toEqual(pass());
103
+ });
104
+ });
@@ -0,0 +1,46 @@
1
+ import { getNormalizedRule } from "../../helpers";
2
+ import type { Rule, RuleResult, RuleSafetyOptions } from "../../types";
3
+
4
+ /**
5
+ * Creates a rule wrapper that performs side effects without modifying the result.
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 effect - Side effect function receiving input, result and context
10
+ * @param options - Configuration for error handling safety
11
+ * @param options.errorHandlingMode - Determines how errors are handled:
12
+ * - 'safe': (default) Converts thrown errors to validation failures
13
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
14
+ * @param options.errorTransform - Custom transformation for caught errors
15
+ * @returns A function that wraps a rule with the tap effect
16
+ * @example
17
+ * const withLogging = tap((input, result) => {
18
+ * console.log(`Validation result for ${input}:`, result);
19
+ * });
20
+ *
21
+ * const rule = withLogging(validateInput);
22
+ * @caveats
23
+ * - Errors in the effect are caught and logged but don't affect rule execution
24
+ * - Doesn't modify the rule's result
25
+ */
26
+ export const withTap = <TInput, TError = string, TContext = unknown>(
27
+ effect: (
28
+ input: TInput,
29
+ result: RuleResult<TError>,
30
+ context?: TContext,
31
+ ) => Promise<void> | void,
32
+ options?: RuleSafetyOptions<TError>,
33
+ ): ((
34
+ rule: Rule<TInput, TError, TContext>,
35
+ ) => Rule<TInput, TError, TContext>) => {
36
+ return (rule) => async (input, context) => {
37
+ const safeRule = getNormalizedRule(rule, options);
38
+ const result = await safeRule(input, context);
39
+ try {
40
+ await effect(input, result, context);
41
+ } catch (error) {
42
+ console.error("Tap effect failed:", error);
43
+ }
44
+ return result;
45
+ };
46
+ };
@@ -8,7 +8,7 @@ import {
8
8
  expect,
9
9
  } from "vitest";
10
10
  import { pass, fail } from "../../helpers";
11
- import { Rule } from "../../types";
11
+ import type { Rule } from "../../types";
12
12
  import { withTimeout } from "./with-timeout";
13
13
  import { getRuleError } from "../../../test/helpers/get-rule-error";
14
14
 
@@ -1,5 +1,5 @@
1
- import { fail } from "../../helpers";
2
- import { Rule, RuleResult } from "../../types";
1
+ import { fail, getNormalizedRule } from "../../helpers";
2
+ import type { Rule, RuleResult, RuleSafetyOptions } from "../../types";
3
3
 
4
4
  /**
5
5
  * Wraps a rule with timeout functionality.
@@ -9,6 +9,11 @@ import { Rule, RuleResult } from "../../types";
9
9
  * @param rule - The rule to wrap with timeout
10
10
  * @param timeoutMs - Timeout duration in milliseconds
11
11
  * @param timeoutError - Error to return if timeout occurs
12
+ * @param options - Configuration for error handling safety
13
+ * @param options.errorHandlingMode - Determines how errors are handled:
14
+ * - 'safe': (default) Converts thrown errors to validation failures
15
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
16
+ * @param options.errorTransform - Custom transformation for caught errors
12
17
  * @returns A new rule that fails with timeoutError if execution takes longer than timeoutMs
13
18
  * @example
14
19
  * const rule = withTimeout(
@@ -24,11 +29,13 @@ export const withTimeout = <TInput, TError, TContext>(
24
29
  rule: Rule<TInput, TError, TContext>,
25
30
  timeoutMs: number,
26
31
  timeoutError: TError,
32
+ options?: RuleSafetyOptions<TError>,
27
33
  ): Rule<TInput, TError, TContext> => {
28
34
  return async (input, context) => {
35
+ const safeRule = getNormalizedRule(rule, options);
29
36
  const timeout = new Promise<RuleResult<TError>>((resolve) =>
30
37
  setTimeout(() => resolve(fail(timeoutError)), timeoutMs),
31
38
  );
32
- return Promise.race([rule(input, context), timeout]);
39
+ return Promise.race([safeRule(input, context), timeout]);
33
40
  };
34
41
  };
@@ -1,7 +1,7 @@
1
1
  import { composeRules } from "./compose-rules";
2
2
  import { fail, pass } from "../helpers";
3
3
  import { beforeEach, describe, expect, it, vi } from "vitest";
4
- import { Rule } from "../types";
4
+ import type { Rule } from "../types";
5
5
 
6
6
  describe("composeRules", () => {
7
7
  const alwaysPass = vi.fn(() => pass());
@@ -1,5 +1,6 @@
1
- import { pass } from "../helpers";
2
- import { CompositionOptions, Rule } from "../types";
1
+ import { getNormalizedRules, pass } from "../helpers";
2
+ import { getCloneFn } from "../helpers/clone/getCloneFn";
3
+ import type { CompositionOptions, Rule } from "../types";
3
4
 
4
5
  /**
5
6
  * Composes multiple rules into a single rule that runs them in right-to-left order (fail-fast).
@@ -11,6 +12,10 @@ import { CompositionOptions, Rule } from "../types";
11
12
  * @param rules - Array of rules to compose
12
13
  * @param options - Configuration options
13
14
  * @param options.cloneContext - Whether to clone the context for each rule (default: false)
15
+ * @param options.errorHandlingMode - Determines how errors are handled:
16
+ * - 'safe': (default) Converts thrown errors to validation failures
17
+ * - 'unsafe': Lets errors propagate (use only in performance-critical paths)
18
+ * @param options.errorTransform - Custom transformation for caught errors
14
19
  * @returns A new rule that composes all input rules
15
20
  *
16
21
  * @example
@@ -25,19 +30,22 @@ import { CompositionOptions, Rule } from "../types";
25
30
  * @caveats
26
31
  * - Rules are executed from **right to left**
27
32
  * - Rules are executed sequentially (not in parallel)
28
- * - Context clone uses structuredClone from Node.js
33
+ * - Cloning behavior follows this priority:
34
+ * 1. Uses shallowClone if options.shallowClone = true
35
+ * 2. Uses structuredClone if available and options.structuredClone = true
36
+ * 3. Falls back to JSON clone otherwise
29
37
  */
30
38
  export const composeRules = <TInput, TError = string, TContext = unknown>(
31
39
  rules: Rule<TInput, TError, TContext>[],
32
40
  options: CompositionOptions = {},
33
41
  ): Rule<TInput, TError, TContext> => {
34
42
  return async (input: TInput, context?: TContext) => {
35
- const currentContext = options?.cloneContext
36
- ? structuredClone(context)
37
- : context;
43
+ const cloneFn = getCloneFn(options);
44
+ const currentContext = options?.cloneContext ? cloneFn(context) : context;
45
+ const normalizedRules = getNormalizedRules(rules);
38
46
 
39
- for (let i = rules.length - 1; i >= 0; i--) {
40
- const result = await rules[i](input, currentContext);
47
+ for (let i = normalizedRules.length - 1; i >= 0; i--) {
48
+ const result = await normalizedRules[i](input, currentContext);
41
49
  if (result.status === "failed") {
42
50
  return result;
43
51
  }