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,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 { 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 { 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 { 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,6 +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";
@@ -1,15 +0,0 @@
1
- import { 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 { 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 { 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
- };
package/src/lib/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from "./combinators";
2
- export * from "./composition";
3
- export * from "./helpers";
4
- export * from "./types";
@@ -1,7 +0,0 @@
1
- /**
2
- * Options for rule composition functions.
3
- * @property cloneContext - Whether to clone the context for each rule
4
- */
5
- export type CompositionOptions = {
6
- cloneContext?: boolean;
7
- };
@@ -1,36 +0,0 @@
1
- import { RuleResult } from "./rule-result";
2
-
3
- /**
4
- * Configuration options for debug functionality.
5
- * @template TInput - The type of the input to validate
6
- * @template TError - The type of the error
7
- * @template TContext - The type of the context object
8
- * @property name - Unique identifier for the rule
9
- * @property onStart - Called before rule execution
10
- * @property onEnd - Called after rule completes
11
- * @property onError - Called when rule throws
12
- */
13
- export type DebugOptions<TInput, TError, TContext> = {
14
- /** Unique identifier for the rule */
15
- name?: string;
16
- /** Called before rule execution */
17
- onStart?: (input: TInput, context?: TContext) => void;
18
- /** Called after rule completes */
19
- onEnd?: (
20
- input: TInput,
21
- result: RuleResult<TError>,
22
- context?: TContext,
23
- meta?: {
24
- ruleName: string;
25
- duration: number;
26
- startTime: number;
27
- },
28
- ) => void;
29
- /** Called when rule throws */
30
- onError?: (
31
- error: unknown,
32
- input: TInput,
33
- context?: TContext,
34
- duration?: number,
35
- ) => void;
36
- };
@@ -1,4 +0,0 @@
1
- export * from "./composition-options";
2
- export * from "./debug-options";
3
- export * from "./rule-result";
4
- export * from "./rule";
@@ -1,16 +0,0 @@
1
- /**
2
- * Represents the result of a rule evaluation.
3
- * @template TError - The type of the error (defaults to string)
4
- * @example
5
- * // Passed result
6
- * const passed: RuleResult = { status: "passed" };
7
- *
8
- * // Failed result
9
- * const failed: RuleResult = {
10
- * status: "failed",
11
- * error: "Validation failed"
12
- * };
13
- */
14
- export type RuleResult<TError = string> =
15
- | { readonly status: "passed" }
16
- | { readonly status: "failed"; readonly error: TError };
@@ -1,21 +0,0 @@
1
- import { RuleResult } from "./rule-result";
2
-
3
- /**
4
- * A function that validates an input and returns a RuleResult.
5
- * @template TInput - The type of the input to validate
6
- * @template TError - The type of the error (defaults to string)
7
- * @template TContext - The type of the context object (optional)
8
- * @param input - The input value to validate
9
- * @param context - Optional context object that can be used during validation
10
- * @returns Either a Promise of RuleResult or RuleResult directly
11
- * @example
12
- * const isEven: Rule<number> = (input) => {
13
- * return input % 2 === 0
14
- * ? { status: "passed" }
15
- * : { status: "failed", error: "Number must be even" };
16
- * };
17
- */
18
- export type Rule<TInput, TError = string, TContext = unknown> = (
19
- input: TInput,
20
- context?: TContext,
21
- ) => Promise<RuleResult<TError>> | RuleResult<TError>;
@@ -1,23 +0,0 @@
1
- import { RuleResult } from "../../lib/types";
2
-
3
- /**
4
- * Extracts the error from a failed RuleResult.
5
- * @template TError - The type of the error
6
- * @param result - The RuleResult to inspect
7
- * @returns The error from a failed result
8
- * @throws {Error} When called on a passed result
9
- * @example
10
- * const result = await validate(input);
11
- * if (result.status === "failed") {
12
- * const error = getError(result);
13
- * // Handle error
14
- * }
15
- * @caveats
16
- * - Throws an error if called on a passed result
17
- */
18
- export const getRuleError = <TError>(result: RuleResult<TError>): TError => {
19
- if (result.status !== "failed") {
20
- throw new Error("Cannot get error from passed result");
21
- }
22
- return result.error;
23
- };