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,264 +0,0 @@
1
- import { pass, fail } from "../../helpers";
2
-
3
- import { beforeEach, describe, expect, it, vi } from "vitest";
4
- import { Rule } from "../../types";
5
- import { every } from "./every";
6
-
7
- describe("every", () => {
8
- const delay = (ms: number) =>
9
- new Promise((resolve) => setTimeout(resolve, ms));
10
-
11
- it("should return pass if no rules are provided", async () => {
12
- const result = await every([])({});
13
- expect(result).toEqual(pass());
14
- });
15
-
16
- it("should return pass if all rules pass", async () => {
17
- const rule1 = vi.fn(() => pass());
18
- const rule2 = vi.fn(() => pass());
19
- const validator = every([rule1, rule2]);
20
- const input = { foo: "bar" };
21
-
22
- const result = await validator(input);
23
-
24
- expect(result).toEqual(pass());
25
- expect(rule1).toHaveBeenCalledWith(input, undefined);
26
- expect(rule2).toHaveBeenCalledWith(input, undefined);
27
- });
28
-
29
- it("should collect all errors in parallel", async () => {
30
- const error1 = "Error 1";
31
- const error2 = "Error 2";
32
- const rule1 = vi.fn(() => fail(error1));
33
- const rule2 = vi.fn(async () => {
34
- await delay(10); // Ensure parallel execution
35
- return fail(error2);
36
- });
37
- const validator = every([rule1, rule2]);
38
- const input = { foo: "bar" };
39
-
40
- const result = await validator(input);
41
-
42
- expect(result).toEqual(fail([error1, error2]));
43
- expect(rule1).toHaveBeenCalledWith(input, undefined);
44
- expect(rule2).toHaveBeenCalledWith(input, undefined);
45
- });
46
-
47
- it("should maintain error order when rules fail", async () => {
48
- const error1 = "Error 1";
49
- const error2 = "Error 2";
50
- const rule1 = vi.fn(async () => {
51
- await delay(20);
52
- return fail(error1);
53
- });
54
- const rule2 = vi.fn(async () => {
55
- await delay(10);
56
- return fail(error2);
57
- });
58
- const validator = every([rule1, rule2]);
59
-
60
- const result = await validator({});
61
-
62
- // Order should match input rule order, not completion order
63
- expect(result).toEqual(fail([error1, error2]));
64
- });
65
-
66
- it("should pass context to all rules", async () => {
67
- const rule1 = vi.fn(() => pass());
68
- const rule2 = vi.fn(() => pass());
69
- const validator = every([rule1, rule2]);
70
- const input = { foo: "bar" };
71
- const context = { userId: 123 };
72
-
73
- await validator(input, context);
74
-
75
- expect(rule1).toHaveBeenCalledWith(input, context);
76
- expect(rule2).toHaveBeenCalledWith(input, context);
77
- });
78
- });
79
-
80
- describe("Niche errors", () => {
81
- it("should preserve custom error types", async () => {
82
- type CustomError = { code: number; message: string };
83
- const rule: Rule<unknown, CustomError> = () =>
84
- fail({ code: 400, message: "Bad" });
85
-
86
- const validator = every([rule]);
87
- const result = await validator({});
88
-
89
- expect(result).toEqual(fail([{ code: 400, message: "Bad" }]));
90
- });
91
-
92
- // Mixed sync/async rules
93
- it("should handle mixed sync/async rules", async () => {
94
- const syncRule = () => fail("Sync error");
95
- const asyncRule = async () => fail("Async error");
96
-
97
- const validator = every([syncRule, asyncRule]);
98
- const result = await validator({});
99
-
100
- expect(result).toEqual(fail(["Sync error", "Async error"]));
101
- });
102
-
103
- it("should handle 1000+ parallel rules", async () => {
104
- const manyRules = Array(1000).fill(() => pass());
105
- const validator = every(manyRules);
106
- await expect(validator({})).resolves.toEqual(pass());
107
- });
108
-
109
- it('should handle falsy error values (false, 0, "")', async () => {
110
- const rules = [() => fail(false), () => fail(0), () => fail("")];
111
- const validator = every(rules as any);
112
- const result = await validator({});
113
- expect(result).toEqual(fail([false, 0, ""]));
114
- });
115
- });
116
- // Error type propagation
117
-
118
- describe("Context behavior tests", () => {
119
- const countingRule = vi.fn((_: unknown, ctx: any) => {
120
- ctx.count = (ctx.count || 0) + 1;
121
- return pass();
122
- });
123
-
124
- // Context checker rule
125
- const expectCountRule = (expected: number) =>
126
- vi.fn((_: unknown, ctx: any) =>
127
- ctx.count === expected
128
- ? pass()
129
- : fail(`Expected count ${expected}, got ${ctx.count}`),
130
- );
131
-
132
- beforeEach(() => {
133
- vi.clearAllMocks();
134
- });
135
-
136
- it("should allow context mutation by default (shared reference)", async () => {
137
- const context = { count: 0 };
138
- const validator = every(
139
- [countingRule, countingRule, expectCountRule(2)], // Expect both mutations to apply
140
- );
141
-
142
- const result = await validator({}, context);
143
-
144
- expect(result).toEqual(pass());
145
- expect(context.count).toBe(2); // Original context modified
146
- });
147
-
148
- it("should prevent context mutations when cloneContext=true", async () => {
149
- const context = { count: 0 };
150
- const validator = every([countingRule, expectCountRule(1)], {
151
- cloneContext: true,
152
- });
153
-
154
- const result = await validator({}, context);
155
-
156
- expect(result).toEqual(pass());
157
- expect(context.count).toBe(0); // Original context untouched
158
- expect(countingRule.mock.calls[0][1].count).toBe(1); // First clone
159
- });
160
-
161
- it("should deep clone complex context objects", async () => {
162
- const context = { nested: { value: 0 } };
163
- const mutateNested = vi.fn((_, ctx) => {
164
- ctx.nested.value++;
165
- return pass();
166
- });
167
-
168
- const validator = every([mutateNested, mutateNested], {
169
- cloneContext: true,
170
- });
171
-
172
- await validator({}, context);
173
-
174
- expect(context.nested.value).toBe(0); // Original unchanged
175
- expect(mutateNested.mock.calls[0][1].nested.value).toBe(2); // First clone
176
- expect(mutateNested.mock.calls[1][1].nested.value).toBe(2); // Fresh clone
177
- });
178
-
179
- it("should handle null/undefined context", async () => {
180
- const nullValidator = every([], { cloneContext: true });
181
- await expect(nullValidator({}, null)).resolves.not.toThrow();
182
- await expect(nullValidator({}, undefined)).resolves.not.toThrow();
183
- });
184
-
185
- it("should shallow clone when possible for performance", async () => {
186
- const context = { simple: "value" };
187
- const validator = every(
188
- [
189
- (_, ctx) => {
190
- (ctx as any).simple = "changed";
191
- return pass();
192
- },
193
- ],
194
- { cloneContext: true },
195
- );
196
-
197
- await validator({}, context);
198
- expect(context.simple).toBe("value"); // Original unchanged
199
- });
200
- });
201
-
202
- it("should prevent accidental context mutation", async () => {
203
- const context = { count: 0 };
204
-
205
- const rule1 = (_: any, ctx: any) => {
206
- (ctx as any).count++; // Bad practice but test should handle
207
- return pass();
208
- };
209
-
210
- const rule2 = (_: any, ctx: any) => {
211
- if ((ctx as any).count !== 0) {
212
- return fail("Context mutated");
213
- }
214
- return pass();
215
- };
216
-
217
- const validator = every([rule1, rule2]);
218
- await expect(validator({}, context)).resolves.toEqual(
219
- fail(["Context mutated"]),
220
- );
221
- });
222
-
223
- it("should preserve custom generic types through composition", async () => {
224
- type CustomInput = { id: string };
225
- type CustomError = { severity: number };
226
-
227
- const rule: Rule<CustomInput, CustomError> = (input) =>
228
- input.id ? pass() : fail({ severity: 5 });
229
-
230
- const validator = every([rule]);
231
- const result1 = await validator({ id: "test" });
232
- const result2 = await validator({} as CustomInput);
233
-
234
- expect(result1).toEqual(pass());
235
- expect(result2).toEqual(fail([{ severity: 5 }]));
236
- });
237
-
238
- it("should not retain rule references after execution", async () => {
239
- let heavyObject = new Array(1e6).fill(0); // 1MB object
240
- const rule = () => {
241
- heavyObject = null!; // Simulate cleanup
242
- return pass();
243
- };
244
-
245
- const validator = every([rule]);
246
- await validator({});
247
-
248
- // This would fail if composition held references
249
- expect(() => heavyObject.length).toThrow();
250
- });
251
-
252
- it("should handle circular reference errors", async () => {
253
- const obj: any = { self: null };
254
- obj.self = obj;
255
-
256
- const validator = every([() => fail(obj), () => pass()]);
257
- const result = await validator({});
258
-
259
- expect(result.status).toBe("failed");
260
- // Check circular reference is preserved
261
- const errors = (result as any).error;
262
- expect(errors[0].self).toBe(errors[0]); // Verify circularity
263
- expect(errors).toEqual([obj]); // Verify error content
264
- });
@@ -1,47 +0,0 @@
1
- import { fail, pass } from "../../helpers";
2
- import { CompositionOptions, Rule } from "../../types";
3
-
4
- /**
5
- * Composes multiple rules into a single rule that runs them all and collects all errors.
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 - Array of rules to compose
10
- * @param options - Configuration options
11
- * @param options.cloneContext - Whether to clone the context for each rule (default: false)
12
- * @returns A new rule that returns all errors from all failing rules
13
- * @example
14
- * const rule = every([
15
- * validatePresence,
16
- * validateEmail,
17
- * validateUnique
18
- * ]);
19
- *
20
- * const result = await rule("invalid-email");
21
- * if (result.status === "failed") {
22
- * console.log(result.error); // Array of all errors
23
- * }
24
- * @caveats
25
- * - Rules are executed in parallel (using Promise.all)
26
- * - All rules are executed even if some fail
27
- */
28
- export const every = <TInput, TError = string, TContext = unknown>(
29
- rules: Rule<TInput, TError, TContext>[],
30
- options: CompositionOptions = {},
31
- ): Rule<TInput, TError[], TContext> => {
32
- return async (input: TInput, context?: TContext) => {
33
- const currentContext = options?.cloneContext
34
- ? structuredClone(context)
35
- : context;
36
-
37
- const results = await Promise.all(
38
- rules.map((rule) => rule(input, currentContext)),
39
- );
40
-
41
- const errors = results.flatMap((r) =>
42
- r.status === "failed" ? [r.error] : [],
43
- );
44
-
45
- return errors.length > 0 ? fail(errors) : pass();
46
- };
47
- };
@@ -1,72 +0,0 @@
1
- import { describe, vi, beforeEach, it, expect } from "vitest";
2
- import { pass, fail } from "../../helpers";
3
- import { Rule } from "../../types";
4
- import { ifElse } from "./if-else";
5
-
6
- describe("branch", () => {
7
- const mockTruePredicate = vi.fn(() => true);
8
- const mockFalsePredicate = vi.fn(() => false);
9
- const asyncTruePredicate = vi.fn(async () => true);
10
-
11
- const passingRule: Rule<string> = vi.fn(() => pass());
12
- const failingRule: Rule<string> = vi.fn(() => fail("Failed rule"));
13
- const contextAwareRule: Rule<string, string, { mode: string }> = vi.fn(
14
- (_, ctx) => (ctx?.mode === "test" ? pass() : fail("Invalid context")),
15
- );
16
-
17
- beforeEach(() => {
18
- vi.clearAllMocks();
19
- });
20
-
21
- it("should execute ifRule when predicate returns true", async () => {
22
- const rule = ifElse(mockTruePredicate, passingRule);
23
- const result = await rule("input");
24
- expect(result.status).toBe("passed");
25
- expect(mockTruePredicate).toHaveBeenCalledWith("input", undefined);
26
- expect(passingRule).toHaveBeenCalled();
27
- });
28
-
29
- it("should execute elseRule when provided and predicate returns false", async () => {
30
- const rule = ifElse(mockFalsePredicate, failingRule, passingRule);
31
- const result = await rule("input");
32
- expect(result.status).toBe("passed");
33
- expect(passingRule).toHaveBeenCalled();
34
- });
35
-
36
- it("should return pass() when no elseRule provided and predicate returns false", async () => {
37
- const rule = ifElse(mockFalsePredicate, failingRule);
38
- const result = await rule("input");
39
- expect(result.status).toBe("passed");
40
- expect(failingRule).not.toHaveBeenCalled();
41
- });
42
-
43
- it("should work with async predicates", async () => {
44
- const rule = ifElse(asyncTruePredicate, passingRule);
45
- const result = await rule("input");
46
- expect(result.status).toBe("passed");
47
- expect(asyncTruePredicate).toHaveBeenCalled();
48
- expect(passingRule).toHaveBeenCalled();
49
- });
50
-
51
- it("should pass context to both predicate and rules", async () => {
52
- const context = { mode: "test" };
53
- const rule = ifElse((_, ctx) => ctx?.mode === "test", contextAwareRule);
54
- const result = await rule("input", context);
55
- expect(result.status).toBe("passed");
56
- expect(contextAwareRule).toHaveBeenCalledWith("input", context);
57
- });
58
-
59
- it("should handle failing ifRule", async () => {
60
- const rule = ifElse(mockTruePredicate, failingRule);
61
- const result = await rule("input");
62
- expect(result.status).toBe("failed");
63
- expect(result).toEqual(fail("Failed rule"));
64
- });
65
-
66
- it("should handle failing elseRule", async () => {
67
- const rule = ifElse(mockFalsePredicate, passingRule, failingRule);
68
- const result = await rule("input");
69
- expect(result.status).toBe("failed");
70
- expect(result).toEqual(fail("Failed rule"));
71
- });
72
- });
@@ -1,39 +0,0 @@
1
- import { pass } from "../../helpers";
2
- import { Rule } from "../../types";
3
-
4
- /**
5
- * Conditionally executes one of two rules based on a predicate
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 - Function that determines which rule to execute
10
- * @param ifRule - Rule to execute when predicate returns true
11
- * @param elseRule - Rule to execute when predicate returns false (optional)
12
- * @returns A new rule that conditionally executes one of two rules
13
- * @example
14
- * const rule = branch(
15
- * (user) => user.age >= 18,
16
- * validateAdultAccount,
17
- * validateMinorAccount
18
- * );
19
- *
20
- * // Without elseRule (passes when predicate is false)
21
- * const adultOnlyRule = branch(
22
- * (user) => user.age >= 18,
23
- * validateAdultAccount
24
- * );
25
- */
26
- export const ifElse = <TInput, TError = string, TContext = unknown>(
27
- predicate: (input: TInput, context?: TContext) => boolean | Promise<boolean>,
28
- ifRule: Rule<TInput, TError, TContext>,
29
- elseRule?: Rule<TInput, TError, TContext>,
30
- ): Rule<TInput, TError, TContext> => {
31
- return async (input: TInput, context?: TContext) => {
32
- const shouldBranch = await predicate(input, context);
33
- return shouldBranch
34
- ? ifRule(input, context)
35
- : elseRule
36
- ? elseRule(input, context)
37
- : pass();
38
- };
39
- };
@@ -1,8 +0,0 @@
1
- export * from "./every";
2
- export * from "./if-else";
3
- export * from "./match";
4
- export * from "./not";
5
- export * from "./one-of";
6
- export * from "./unless";
7
- export * from "./when";
8
- export * from "./with-fallback";
@@ -1,186 +0,0 @@
1
- import { describe, it, expect, vi } from "vitest";
2
- import { match } from "./match";
3
- import type { Rule } from "../../types";
4
-
5
- describe("match combinator", () => {
6
- // Mock rules for testing
7
- const mockPass = vi.fn().mockResolvedValue({ status: "passed" });
8
- const mockFail = vi
9
- .fn()
10
- .mockResolvedValue({ status: "failed", error: "error" });
11
- const mockAsyncPass = vi.fn().mockResolvedValue({ status: "passed" });
12
-
13
- it("should execute the matching rule based on accessor", async () => {
14
- const rules = {
15
- admin: mockPass,
16
- user: mockFail,
17
- };
18
- const matcher = match((user: { role: string }) => user.role, rules);
19
- await matcher({ role: "admin" });
20
-
21
- expect(mockPass).toHaveBeenCalledWith({ role: "admin" }, undefined);
22
- expect(mockFail).not.toHaveBeenCalled();
23
- });
24
-
25
- it("should return the matched rule result", async () => {
26
- const rules = {
27
- admin: mockPass,
28
- user: mockFail,
29
- };
30
- const matcher = match((user: { role: string }) => user.role, rules);
31
- const result = await matcher({ role: "admin" });
32
-
33
- expect(result).toEqual({ status: "passed" });
34
- });
35
-
36
- it("should use default case when no match found", async () => {
37
- const rules = {
38
- admin: mockPass,
39
- };
40
- const matcher = match(
41
- (user: { role: string }) => user.role,
42
- rules,
43
- mockFail,
44
- );
45
- await matcher({ role: "guest" });
46
-
47
- expect(mockFail).toHaveBeenCalledWith({ role: "guest" }, undefined);
48
- });
49
-
50
- it("should use default error when no match and no default rule", async () => {
51
- const rules = {
52
- admin: mockPass,
53
- };
54
- const matcher = match((user: { role: string }) => user.role, rules);
55
- const result = await matcher({ role: "guest" });
56
-
57
- expect(result).toEqual({
58
- status: "failed",
59
- error: "No matching rule for key: guest",
60
- });
61
- });
62
-
63
- it("should work with custom error types", async () => {
64
- interface CustomError {
65
- code: number;
66
- message: string;
67
- }
68
- const customError: CustomError = { code: 404, message: "Not found" };
69
-
70
- const matcher = match<{ id: number }, CustomError>(
71
- (item) => (item.id > 100 ? "special" : "normal"),
72
- {
73
- special: mockPass,
74
- },
75
- customError,
76
- );
77
-
78
- const result = await matcher({ id: 50 });
79
- expect(result).toEqual({
80
- status: "failed",
81
- error: customError,
82
- });
83
- });
84
-
85
- it("should pass context to matched rules", async () => {
86
- const rules = {
87
- admin: mockPass,
88
- };
89
- const context = { auth: true };
90
- const matcher = match((user: { role: string }) => user.role, rules);
91
- await matcher({ role: "admin" }, context);
92
-
93
- expect(mockPass).toHaveBeenCalledWith({ role: "admin" }, context);
94
- });
95
-
96
- it("should handle async accessor functions", async () => {
97
- const rules = {
98
- admin: mockPass,
99
- };
100
- const matcher = match(async (user: { role: string }) => {
101
- await Promise.resolve();
102
- return user.role;
103
- }, rules);
104
- await matcher({ role: "admin" });
105
-
106
- expect(mockPass).toHaveBeenCalled();
107
- });
108
-
109
- it("should work with numeric keys", async () => {
110
- const rules = {
111
- 1: mockPass,
112
- 2: mockFail,
113
- };
114
- const matcher = match((item: { code: number }) => item.code, rules);
115
- await matcher({ code: 1 });
116
-
117
- expect(mockPass).toHaveBeenCalled();
118
- });
119
-
120
- it("should work with symbol keys", async () => {
121
- const TEST_SYMBOL = Symbol("test");
122
- const rules = {
123
- [TEST_SYMBOL]: mockPass,
124
- };
125
- const matcher = match(() => TEST_SYMBOL, rules);
126
- await matcher({});
127
-
128
- expect(mockPass).toHaveBeenCalled();
129
- });
130
-
131
- it("should handle default case as error string", async () => {
132
- const rules = {
133
- admin: mockPass,
134
- };
135
- const matcher = match(
136
- (user: { role: string }) => user.role,
137
- rules,
138
- "Invalid role",
139
- );
140
- const result = await matcher({ role: "guest" });
141
-
142
- expect(result).toEqual({
143
- status: "failed",
144
- error: "Invalid role",
145
- });
146
- });
147
-
148
- it("should handle default case as Rule", async () => {
149
- const rules = {
150
- admin: mockPass,
151
- };
152
- const matcher = match(
153
- (user: { role: string }) => user.role,
154
- rules,
155
- mockAsyncPass,
156
- );
157
- await matcher({ role: "guest" });
158
-
159
- expect(mockAsyncPass).toHaveBeenCalled();
160
- });
161
-
162
- it("should maintain type safety with complex inputs", async () => {
163
- interface ComplexInput {
164
- nested: {
165
- value: string;
166
- items: number[];
167
- };
168
- }
169
-
170
- const complexRule: Rule<ComplexInput> = () =>
171
- Promise.resolve({ status: "passed" });
172
-
173
- const matcher = match((input: ComplexInput) => input.nested.value, {
174
- test: complexRule,
175
- });
176
-
177
- const result = await matcher({
178
- nested: {
179
- value: "test",
180
- items: [1, 2, 3],
181
- },
182
- });
183
-
184
- expect(result.status).toBe("passed");
185
- });
186
- });