ts-rules-composer 1.0.0 → 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 (103) hide show
  1. package/package.json +7 -1
  2. package/.editorconfig +0 -15
  3. package/.github/CONTRIBUTING.md +0 -3
  4. package/.github/ISSUE_TEMPLATE.md +0 -9
  5. package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
  6. package/.github/workflows/docs.yml +0 -29
  7. package/.github/workflows/publish.yml +0 -25
  8. package/.github/workflows/test.yml +0 -37
  9. package/.prettierignore +0 -2
  10. package/.releaserc +0 -11
  11. package/eslint.config.mjs +0 -84
  12. package/examples/financial-transaction.example.ts +0 -188
  13. package/examples/model-deployment.example.ts +0 -136
  14. package/examples/user-registration.example.ts +0 -101
  15. package/src/lib/combinators/index.ts +0 -2
  16. package/src/lib/combinators/logic/every.spec.ts +0 -264
  17. package/src/lib/combinators/logic/every.ts +0 -57
  18. package/src/lib/combinators/logic/if-else.spec.ts +0 -82
  19. package/src/lib/combinators/logic/if-else.ts +0 -64
  20. package/src/lib/combinators/logic/index.ts +0 -8
  21. package/src/lib/combinators/logic/match.spec.ts +0 -186
  22. package/src/lib/combinators/logic/match.ts +0 -106
  23. package/src/lib/combinators/logic/not.spec.ts +0 -64
  24. package/src/lib/combinators/logic/not.ts +0 -34
  25. package/src/lib/combinators/logic/one-of.spec.ts +0 -68
  26. package/src/lib/combinators/logic/one-of.ts +0 -48
  27. package/src/lib/combinators/logic/unless.spec.ts +0 -61
  28. package/src/lib/combinators/logic/unless.ts +0 -50
  29. package/src/lib/combinators/logic/when.spec.ts +0 -119
  30. package/src/lib/combinators/logic/when.ts +0 -50
  31. package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
  32. package/src/lib/combinators/logic/with-fallback.ts +0 -46
  33. package/src/lib/combinators/utility/index.ts +0 -11
  34. package/src/lib/combinators/utility/inject.spec.ts +0 -55
  35. package/src/lib/combinators/utility/inject.ts +0 -25
  36. package/src/lib/combinators/utility/map-error.spec.ts +0 -63
  37. package/src/lib/combinators/utility/map-error.ts +0 -35
  38. package/src/lib/combinators/utility/tap.spec.ts +0 -102
  39. package/src/lib/combinators/utility/tap.ts +0 -28
  40. package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
  41. package/src/lib/combinators/utility/validate-field.ts +0 -66
  42. package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
  43. package/src/lib/combinators/utility/with-debug.ts +0 -55
  44. package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
  45. package/src/lib/combinators/utility/with-memoize.ts +0 -89
  46. package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
  47. package/src/lib/combinators/utility/with-retry.ts +0 -70
  48. package/src/lib/combinators/utility/with-safe-error.spec.ts +0 -137
  49. package/src/lib/combinators/utility/with-safe-error.ts +0 -56
  50. package/src/lib/combinators/utility/with-safe-predicate.spec.ts +0 -176
  51. package/src/lib/combinators/utility/with-safe-predicate.ts +0 -64
  52. package/src/lib/combinators/utility/with-tap.spec.ts +0 -104
  53. package/src/lib/combinators/utility/with-tap.ts +0 -46
  54. package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
  55. package/src/lib/combinators/utility/with-timeout.ts +0 -41
  56. package/src/lib/composition/compose-rules.spec.ts +0 -211
  57. package/src/lib/composition/compose-rules.ts +0 -55
  58. package/src/lib/composition/index.ts +0 -3
  59. package/src/lib/composition/pipe-rules.spec.ts +0 -220
  60. package/src/lib/composition/pipe-rules.ts +0 -52
  61. package/src/lib/composition/pipe.spec.ts +0 -47
  62. package/src/lib/composition/pipe.ts +0 -107
  63. package/src/lib/helpers/clone/clone.ts +0 -12
  64. package/src/lib/helpers/clone/getCloneFn.ts +0 -17
  65. package/src/lib/helpers/clone/shallowClone.ts +0 -12
  66. package/src/lib/helpers/context/has-context.ts +0 -13
  67. package/src/lib/helpers/context/index.ts +0 -3
  68. package/src/lib/helpers/context/require-context.spec.ts +0 -55
  69. package/src/lib/helpers/context/require-context.ts +0 -61
  70. package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
  71. package/src/lib/helpers/context/with-lazy-context.ts +0 -35
  72. package/src/lib/helpers/index.ts +0 -8
  73. package/src/lib/helpers/result/fail.ts +0 -15
  74. package/src/lib/helpers/result/index.ts +0 -2
  75. package/src/lib/helpers/result/pass.ts +0 -14
  76. package/src/lib/helpers/retry/calculate-delay.ts +0 -31
  77. package/src/lib/helpers/safety/get-normalized-rule.spec.ts +0 -209
  78. package/src/lib/helpers/safety/get-normalized-rule.ts +0 -14
  79. package/src/lib/helpers/safety/get-normalized-rules.spec.ts +0 -138
  80. package/src/lib/helpers/safety/get-normalized-rules.ts +0 -14
  81. package/src/lib/index.ts +0 -4
  82. package/src/lib/types/composition-options.ts +0 -32
  83. package/src/lib/types/debug-options.ts +0 -36
  84. package/src/lib/types/index.ts +0 -8
  85. package/src/lib/types/predicate-result.ts +0 -20
  86. package/src/lib/types/predicate-safe.ts +0 -10
  87. package/src/lib/types/predicate-safety-options.ts +0 -27
  88. package/src/lib/types/predicate.ts +0 -8
  89. package/src/lib/types/prettify.ts +0 -3
  90. package/src/lib/types/rule-result.ts +0 -16
  91. package/src/lib/types/rule-safety-options.ts +0 -34
  92. package/src/lib/types/rule.ts +0 -21
  93. package/src/lib/types/safety-options.ts +0 -7
  94. package/src/test/financial-transaction.spec.ts +0 -251
  95. package/src/test/helpers/get-rule-error.ts +0 -23
  96. package/src/test/integration.spec.ts +0 -285
  97. package/src/test/model-deployment.spec.ts +0 -209
  98. package/src/test/user-registration.spec.ts +0 -164
  99. package/tsconfig.json +0 -56
  100. package/tsup.config.ts +0 -36
  101. package/typedoc/tsconfig.typedoc.json +0 -15
  102. package/typedoc/typedoc.json +0 -14
  103. package/vitest.config.ts +0 -16
@@ -1,12 +0,0 @@
1
- export const clone = <T>(obj: T): T => {
2
- if (!obj) return {} as T;
3
- try {
4
- return JSON.parse(JSON.stringify(obj));
5
- } catch (e) {
6
- console.warn(
7
- `Clone failed for ${obj?.constructor?.name}, returning empty object`,
8
- e,
9
- );
10
- return {} as T;
11
- }
12
- };
@@ -1,17 +0,0 @@
1
- import type { CompositionOptions } from "../../types";
2
-
3
- import { clone } from "./clone";
4
- import { shallowClone } from "./shallowClone";
5
-
6
- export const getCloneFn = (opts: CompositionOptions<unknown>) => {
7
- const canUseStructuredClone = typeof structuredClone !== "undefined";
8
-
9
- const cloneFn =
10
- opts.cloneStrategy === "shallow"
11
- ? shallowClone
12
- : opts.cloneStrategy === "structured" && canUseStructuredClone
13
- ? structuredClone
14
- : clone;
15
-
16
- return cloneFn;
17
- };
@@ -1,12 +0,0 @@
1
- export const shallowClone = <T>(obj: T): T => {
2
- if (!obj) return {} as T;
3
- try {
4
- return { ...obj };
5
- } catch (e) {
6
- console.warn(
7
- `Clone failed for ${obj?.constructor?.name}, returning empty object`,
8
- e,
9
- );
10
- return {} as T;
11
- }
12
- };
@@ -1,13 +0,0 @@
1
- /**
2
- * Type guard to check if context exists and is of type T.
3
- * @template T - The expected context type
4
- * @param ctx - The context to check
5
- * @returns Boolean indicating if context exists and matches type
6
- * @example
7
- * if (hasContext<AdminContext>(context)) {
8
- * // context is now typed as AdminContext
9
- * }
10
- */
11
- export const hasContext = <T>(ctx: T | undefined): ctx is T => {
12
- return ctx !== undefined;
13
- };
@@ -1,3 +0,0 @@
1
- export * from "./has-context";
2
- export * from "./require-context";
3
- export * from "./with-lazy-context";
@@ -1,55 +0,0 @@
1
- import { describe, vi, beforeEach, it, expect } from "vitest";
2
- import { fail, pass } from "../result";
3
- import { requireContextRule } from "./require-context";
4
-
5
- describe("requireContextRule", () => {
6
- type UserContext = { userId: string };
7
- type FullContext = UserContext & { db: any };
8
-
9
- const mockRule = vi.fn((_: unknown, _ctx: UserContext) => pass());
10
- const errorMsg = "Context required";
11
-
12
- beforeEach(() => {
13
- vi.clearAllMocks();
14
- });
15
-
16
- it("should pass when context exists", async () => {
17
- const rule = requireContextRule(errorMsg, mockRule);
18
- const context = { userId: "123" };
19
-
20
- await rule({}, context);
21
- expect(mockRule).toHaveBeenCalledWith({}, context);
22
- });
23
-
24
- it("should fail with specified error when context is missing", async () => {
25
- const rule = requireContextRule(errorMsg, mockRule);
26
- const result = await rule({});
27
-
28
- expect(result).toEqual(fail(errorMsg));
29
- expect(mockRule).not.toHaveBeenCalled();
30
- });
31
-
32
- it("should support custom context checks", async () => {
33
- const isFullContext = (ctx: any): ctx is FullContext =>
34
- !!ctx?.userId && !!ctx?.db;
35
-
36
- const rule = requireContextRule(
37
- "DB context required",
38
- (_, ctx) => {
39
- ctx.db.query(); // Safe access
40
- return pass();
41
- },
42
- isFullContext,
43
- );
44
-
45
- // Test with partial context
46
- expect(await rule({}, { userId: "123" })).toEqual(
47
- fail("DB context required"),
48
- );
49
-
50
- // Test with full context
51
- expect(
52
- await rule({}, { userId: "123", db: { query: () => "USER" } }),
53
- ).toEqual({ status: "passed" });
54
- });
55
- });
@@ -1,61 +0,0 @@
1
- import type { Rule, RuleResult } from "../../types";
2
- import { fail } from "../result";
3
-
4
- /**
5
- * Creates a rule that requires specific context to be present.
6
- * @template TInput - The type of the input to validate
7
- * @template TError - The type of the error
8
- * @template TContext - The base context type
9
- * @template TRequiredContext - The required context type
10
- * @param error - Error to return if context is invalid
11
- * @param rule - Rule that requires the specific context
12
- * @param contextCheck - Optional type guard for context validation
13
- * @returns A rule that validates context before execution
14
- * @example
15
- * const adminRule = requireContextRule(
16
- * "Admin context required",
17
- * (input, context: AdminContext) => { ... },
18
- * (ctx): ctx is AdminContext => ctx?.role === "admin"
19
- * );
20
- * @caveats
21
- * - Fails immediately if context check fails
22
- * - Provides type safety for context requirements
23
- */
24
- export const requireContextRule = <
25
- TInput,
26
- TError,
27
- TContext,
28
- TRequiredContext extends TContext,
29
- >(
30
- error: TError,
31
- rule: (
32
- input: TInput,
33
- context: TRequiredContext,
34
- ) => Promise<RuleResult<TError>> | RuleResult<TError>,
35
- contextCheck?: (context: TContext | undefined) => context is TRequiredContext,
36
- ): Rule<TInput, TError, TContext> => {
37
- const defaultCheck = (ctx: TContext | undefined): ctx is TRequiredContext => {
38
- return ctx !== undefined;
39
- };
40
-
41
- const check = contextCheck || defaultCheck;
42
-
43
- return async (input: TInput, context?: TContext) => {
44
- return check(context) ? rule(input, context) : fail(error);
45
- };
46
- };
47
-
48
- /**
49
- * const userRule = requireContextRule(
50
- "User context required",
51
- (input: string, ctx: { userId: string }) => {
52
- return ctx.userId === "admin"
53
- ? pass()
54
- : fail("Unauthorized");
55
- }
56
- );
57
-
58
- await userRule("action"); // fails with "User context required"
59
- await userRule("action", { userId: "user" }); // fails with "Unauthorized"
60
- await userRule("action", { userId: "admin" }); // passes
61
- */
@@ -1,74 +0,0 @@
1
- import { describe, vi, beforeEach, it, expect } from "vitest";
2
- import type { Rule } from "../../types";
3
- import { fail, pass } from "../result";
4
- import { withLazyContext } from "./with-lazy-context";
5
-
6
- describe("withLazyContext", () => {
7
- const mockLoader = vi.fn();
8
- const mockRule = vi.fn(() => pass());
9
-
10
- beforeEach(() => {
11
- vi.clearAllMocks();
12
- mockLoader.mockResolvedValue({ db: {} });
13
- mockRule.mockReturnValue(pass());
14
- });
15
-
16
- it("should load context and pass it to rule", async () => {
17
- const context = { userId: 123 };
18
- const loader = vi.fn().mockResolvedValue(context);
19
- const rule = vi.fn(() => pass());
20
-
21
- const lazyRule = withLazyContext(loader, rule);
22
- await lazyRule({ some: "input" });
23
-
24
- expect(loader).toHaveBeenCalledWith({ some: "input" });
25
- expect(rule).toHaveBeenCalledWith({ some: "input" }, context);
26
- });
27
-
28
- it("should return rule result", async () => {
29
- const expectedResult = fail("Test error");
30
- const rule = vi.fn().mockReturnValue(expectedResult);
31
- const lazyRule = withLazyContext(() => ({}), rule);
32
-
33
- const result = await lazyRule({});
34
- expect(result).toEqual(expectedResult);
35
- });
36
-
37
- it("should handle sync context loading", async () => {
38
- const context = { apiKey: "xyz" };
39
- const lazyRule = withLazyContext(
40
- () => context,
41
- (_, ctx) => (ctx?.apiKey === "xyz" ? pass() : fail("Invalid")),
42
- );
43
-
44
- const result = await lazyRule({});
45
- expect(result.status).toBe("passed");
46
- });
47
-
48
- it("should convert loader errors to failed results", async () => {
49
- const lazyRule = withLazyContext(
50
- () => Promise.reject(new Error("DB down")),
51
- () => pass(),
52
- );
53
-
54
- const result = await lazyRule({});
55
- expect(result).toEqual(fail("DB down"));
56
- });
57
-
58
- it("should preserve input types", async () => {
59
- type StrictInput = { id: string };
60
- type LooseInput = { other: number };
61
-
62
- const typedRule: Rule<StrictInput, string, { db: any }> = () => pass();
63
-
64
- // Valid usage - should pass
65
- const validLoader = (input: StrictInput) => ({ db: input.id });
66
- withLazyContext(validLoader, typedRule);
67
-
68
- // Invalid usage - should fail type check
69
- const invalidLoader = (input: LooseInput) => ({ db: input.other });
70
-
71
- // @ts-expect-error - This should now properly fail
72
- withLazyContext(invalidLoader, typedRule);
73
- });
74
- });
@@ -1,35 +0,0 @@
1
- import type { Rule } from "../../types";
2
- import { fail } from "../result";
3
-
4
- /**
5
- * Creates a rule that loads context lazily before execution.
6
- * @template TInput - The type of the input to validate
7
- * @template TError - The type of the error
8
- * @template TContext - The type of the context object
9
- * @param loader - Function to load context from input
10
- * @param rule - Rule that requires the context
11
- * @returns A rule that loads context before execution
12
- * @example
13
- * const rule = withLazyContext(
14
- * async (userId) => await loadUserContext(userId),
15
- * validateUser
16
- * );
17
- * @caveats
18
- * - Context loading failures are converted to validation failures
19
- * - The loader is called for every rule execution
20
- */
21
- export const withLazyContext = <TInput, TError, TContext>(
22
- loader: (input: TInput) => Promise<TContext> | TContext,
23
- rule: Rule<TInput, TError, TContext>,
24
- ): Rule<TInput, TError> => {
25
- return async (input: TInput) => {
26
- try {
27
- const context = await loader(input);
28
- return rule(input, context);
29
- } catch (error) {
30
- const errorMessage =
31
- error instanceof Error ? error.message : "Context loading failed";
32
- return fail(errorMessage as TError);
33
- }
34
- };
35
- };
@@ -1,8 +0,0 @@
1
- export * from "./context/has-context";
2
- export * from "./context/require-context";
3
- export * from "./context/with-lazy-context";
4
- export * from "./result/fail";
5
- export * from "./result/pass";
6
- export * from "./retry/calculate-delay";
7
- export * from "./safety/get-normalized-rule";
8
- export * from "./safety/get-normalized-rules";
@@ -1,15 +0,0 @@
1
- import type { RuleResult } from "../../types";
2
-
3
- /**
4
- * Creates a failed RuleResult with the provided error.
5
- * @template TError - The type of the error (defaults to string)
6
- * @param error - The error to include in the failed result
7
- * @returns A RuleResult with status "failed" and the provided error
8
- * @example
9
- * const result = fail("Invalid input"); // { status: "failed", error: "Invalid input" }
10
- *
11
- * // Used in rule implementations:
12
- * const alwaysFails: Rule<string> = () => fail("Always fails");
13
- */
14
- export const fail = <TError = string>(error: TError): RuleResult<TError> =>
15
- ({ status: "failed", error }) as const;
@@ -1,2 +0,0 @@
1
- export * from "./fail";
2
- export * from "./pass";
@@ -1,14 +0,0 @@
1
- import type { RuleResult } from "../../types";
2
-
3
- /**
4
- * Creates a successful RuleResult with "passed" status.
5
- * @template TError - The type of the error (defaults to string)
6
- * @returns A RuleResult with status "passed"
7
- * @example
8
- * const result = pass(); // { status: "passed" }
9
- *
10
- * // Used in rule implementations:
11
- * const alwaysPasses: Rule<string> = () => pass();
12
- */
13
- export const pass = <TError = string>(): RuleResult<TError> =>
14
- ({ status: "passed" }) as const;
@@ -1,31 +0,0 @@
1
- import type { RetryStrategy } from "../../combinators";
2
-
3
- export const calculateDelay = (
4
- strategy: RetryStrategy | undefined,
5
- attempt: number,
6
- initialDelayMs: number,
7
- ): number => {
8
- const strategies: Record<string, (attempt: number) => number> = {
9
- fixed: () => initialDelayMs,
10
- linear: (attempt) => initialDelayMs * attempt,
11
- exponential: (attempt) => initialDelayMs * 2 ** (attempt - 1),
12
- };
13
-
14
- if (!strategy) {
15
- return strategies["fixed"](attempt);
16
- }
17
-
18
- // If strategy is one of the predefined strings, use the corresponding function.
19
- if (typeof strategy === "string") {
20
- const strategyFn = strategies[strategy];
21
- return strategyFn ? strategyFn(attempt) : initialDelayMs;
22
- }
23
-
24
- // If the strategy is a custom function, call it.
25
- if (typeof strategy === "function") {
26
- return strategy(attempt);
27
- }
28
-
29
- // If it doesn't match any cases, uses fixed strategy by default
30
- return strategies["fixed"](attempt);
31
- };
@@ -1,209 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { getNormalizedRule } from "./get-normalized-rule";
3
- import type { Rule, RuleSafetyOptions } from "../../types";
4
- import { pass, fail } from "../../helpers";
5
-
6
- describe("getNormalizedRule", () => {
7
- // Mock rules for testing
8
- interface CustomError {
9
- code: number;
10
- message: string;
11
- }
12
-
13
- const passingRule: Rule<string> = vi.fn(() => pass());
14
-
15
- const errorThrowingRuleCustom: Rule<string, CustomError> = vi.fn(() => {
16
- throw new Error("Boom!");
17
- });
18
- const passingRuleCustom: Rule<string, CustomError> = vi.fn(() =>
19
- pass(),
20
- ) as Rule<string, CustomError>;
21
- const failingRuleCustom: Rule<string, CustomError> = vi.fn(() =>
22
- fail({ code: 400, message: "Expected error" }),
23
- );
24
-
25
- const errorThrowingRule: Rule<string> = vi.fn(() => {
26
- throw new Error("Boom!");
27
- });
28
- const objectThrowingRule: Rule<string, { code: number }> = vi.fn(() => {
29
- throw { code: 500 };
30
- });
31
-
32
- beforeEach(() => {
33
- vi.clearAllMocks();
34
- });
35
-
36
- describe("with errorHandlingMode = 'safe' (default)", () => {
37
- const defaultOptions: RuleSafetyOptions = {};
38
-
39
- it("should return original rule when it doesn't throw", async () => {
40
- const normalized = getNormalizedRule(passingRule, defaultOptions);
41
- const result = await normalized("test");
42
-
43
- expect(result).toEqual(pass());
44
- expect(passingRule).toHaveBeenCalledWith("test", undefined);
45
- });
46
-
47
- it("should wrap with withSafeError when rule throws", async () => {
48
- const normalized = getNormalizedRule(errorThrowingRule, defaultOptions);
49
- const result = await normalized("test");
50
-
51
- expect(result.status).toBe("failed");
52
- expect((result as any).error.message).toBe("Boom!");
53
- });
54
- });
55
-
56
- describe("with errorHandlingMode = 'unsafe'", () => {
57
- const unsafeOptions: RuleSafetyOptions = { errorHandlingMode: "unsafe" };
58
-
59
- it("should return original rule when it doesn't throw", async () => {
60
- const normalized = getNormalizedRule(passingRule, unsafeOptions);
61
- const result = await normalized("test");
62
-
63
- expect(result).toEqual(pass());
64
- expect(passingRule).toHaveBeenCalledWith("test");
65
- });
66
-
67
- it("should not catch thrown errors", async () => {
68
- // Create a fresh mock that throws when called
69
- const throwingRule: Rule<string> = vi.fn(() => {
70
- throw new Error("Boom!");
71
- });
72
-
73
- const normalized = getNormalizedRule(throwingRule, unsafeOptions);
74
- expect(async () => await normalized("test")).rejects.toThrow("Boom!");
75
-
76
- expect(throwingRule).toHaveBeenCalledWith("test");
77
- });
78
-
79
- it("should preserve original error throwing behavior", async () => {
80
- const normalized = getNormalizedRule(objectThrowingRule, unsafeOptions);
81
-
82
- expect(async () => await normalized("test")).rejects.toEqual({
83
- code: 500,
84
- });
85
- });
86
- });
87
-
88
- describe("with custom errorTransform", () => {
89
- const customTransform = vi.fn(
90
- (error: unknown): CustomError => ({
91
- code: 500,
92
- message: String(error),
93
- }),
94
- );
95
-
96
- const transformOptions: RuleSafetyOptions<CustomError> = {
97
- errorTransform: customTransform,
98
- };
99
-
100
- it("should use custom transform for thrown errors", async () => {
101
- const normalized = getNormalizedRule(
102
- errorThrowingRuleCustom,
103
- transformOptions,
104
- );
105
- const result = await normalized("test");
106
-
107
- expect(result).toEqual(
108
- fail({
109
- code: 500,
110
- message: "Error: Boom!",
111
- }),
112
- );
113
- expect(customTransform).toHaveBeenCalledWith(expect.any(Error));
114
- });
115
-
116
- it("should not call transform for successful rules", async () => {
117
- const normalized = getNormalizedRule(passingRuleCustom, transformOptions);
118
- await normalized("test");
119
-
120
- expect(customTransform).not.toHaveBeenCalled();
121
- });
122
-
123
- it("should not call transform for explicit failures", async () => {
124
- const normalized = getNormalizedRule(failingRuleCustom, transformOptions);
125
- await normalized("test");
126
-
127
- expect(customTransform).not.toHaveBeenCalled();
128
- });
129
-
130
- it("should use default string error when no transform provided", async () => {
131
- const stringErrorRule: Rule<string> = vi.fn(() => {
132
- throw new Error("Boom!");
133
- });
134
-
135
- const normalized = getNormalizedRule(stringErrorRule, {});
136
- const result = await normalized("test");
137
-
138
- expect(result).toEqual(fail(new Error("Boom!")));
139
- });
140
- });
141
-
142
- describe("edge cases", () => {
143
- it("should handle null/undefined input safely", async () => {
144
- const normalized = getNormalizedRule(passingRule, {});
145
- await expect(normalized(null as any)).resolves.not.toThrow();
146
- await expect(normalized(undefined as any)).resolves.not.toThrow();
147
- });
148
-
149
- it("should handle rules that return invalid results", async () => {
150
- const invalidRule = vi.fn(() => "not a RuleResult" as any);
151
- const normalized = getNormalizedRule(invalidRule, {});
152
- const result = await normalized("test");
153
-
154
- expect(result.status).toBe("failed");
155
- expect((result as any).error.message).toContain(
156
- "Invalid rule - did not return RuleResult",
157
- );
158
- });
159
-
160
- it("should pass context to wrapped rules", async () => {
161
- const context = { userId: 123 };
162
- const contextAwareRule = vi.fn((_: string, ctx: any) =>
163
- ctx?.userId === 123 ? pass() : fail("Wrong user"),
164
- );
165
-
166
- const normalized = getNormalizedRule(contextAwareRule, {});
167
- await normalized("test", context);
168
-
169
- expect(contextAwareRule).toHaveBeenCalledWith("test", context);
170
- });
171
- });
172
-
173
- describe("type safety", () => {
174
- it("should maintain input type safety", () => {
175
- type StrictInput = { id: string };
176
- const typedRule: Rule<StrictInput> = () => pass();
177
-
178
- // Should compile
179
- getNormalizedRule(typedRule, {})({ id: "123" });
180
-
181
- // @ts-expect-error - Should fail if input types don't match
182
- getNormalizedRule(typedRule, {})({ notId: "123" });
183
- });
184
-
185
- it("should maintain error type safety", async () => {
186
- interface CustomError {
187
- code: number;
188
- details: string;
189
- }
190
- const customErrorRule: Rule<string, CustomError> = () => {
191
- throw new Error("Test");
192
- };
193
-
194
- const normalized = getNormalizedRule(customErrorRule, {
195
- errorTransform: (e) => ({
196
- code: 500,
197
- details: String(e),
198
- }),
199
- });
200
-
201
- const result = await normalized("test");
202
- expect(result.status).toBe("failed");
203
- expect((result as any).error).toMatchObject({
204
- code: expect.any(Number),
205
- details: expect.any(String),
206
- });
207
- });
208
- });
209
- });
@@ -1,14 +0,0 @@
1
- import { withSafeError } from "../../combinators";
2
- import type { Rule, RuleSafetyOptions } from "../../types";
3
-
4
- export const getNormalizedRule = <TInput, TError, TContext>(
5
- rule: Rule<TInput, TError, TContext>,
6
- opts?: RuleSafetyOptions<TError>,
7
- ): Rule<TInput, TError, TContext> => {
8
- const normalizedRule =
9
- opts?.errorHandlingMode === "unsafe"
10
- ? rule
11
- : withSafeError(rule, opts?.errorTransform);
12
-
13
- return normalizedRule;
14
- };