ts-rules-composer 0.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 (83) hide show
  1. package/.editorconfig +15 -0
  2. package/.eslintrc.json +66 -0
  3. package/.github/CONTRIBUTING.md +3 -0
  4. package/.github/ISSUE_TEMPLATE.md +9 -0
  5. package/.github/PULL_REQUEST_TEMPLATE.md +7 -0
  6. package/.github/workflows/docs.yml +29 -0
  7. package/.github/workflows/publish.yml +25 -0
  8. package/.github/workflows/test.yml +37 -0
  9. package/.prettierignore +2 -0
  10. package/.releaserc +11 -0
  11. package/LICENSE +21 -0
  12. package/README.md +625 -0
  13. package/dist/index.cjs +2 -0
  14. package/dist/index.cjs.map +1 -0
  15. package/dist/index.d.cts +634 -0
  16. package/dist/index.d.ts +634 -0
  17. package/dist/index.js +2 -0
  18. package/dist/index.js.map +1 -0
  19. package/package.json +64 -0
  20. package/src/lib/combinators/index.ts +2 -0
  21. package/src/lib/combinators/logic/every.spec.ts +264 -0
  22. package/src/lib/combinators/logic/every.ts +47 -0
  23. package/src/lib/combinators/logic/if-else.spec.ts +72 -0
  24. package/src/lib/combinators/logic/if-else.ts +39 -0
  25. package/src/lib/combinators/logic/index.ts +8 -0
  26. package/src/lib/combinators/logic/match.spec.ts +186 -0
  27. package/src/lib/combinators/logic/match.ts +92 -0
  28. package/src/lib/combinators/logic/not.spec.ts +62 -0
  29. package/src/lib/combinators/logic/not.ts +25 -0
  30. package/src/lib/combinators/logic/one-of.spec.ts +68 -0
  31. package/src/lib/combinators/logic/one-of.ts +41 -0
  32. package/src/lib/combinators/logic/unless.spec.ts +61 -0
  33. package/src/lib/combinators/logic/unless.ts +27 -0
  34. package/src/lib/combinators/logic/when.spec.ts +123 -0
  35. package/src/lib/combinators/logic/when.ts +29 -0
  36. package/src/lib/combinators/logic/with-fallback.spec.ts +72 -0
  37. package/src/lib/combinators/logic/with-fallback.ts +37 -0
  38. package/src/lib/combinators/utility/index.ts +8 -0
  39. package/src/lib/combinators/utility/inject.spec.ts +55 -0
  40. package/src/lib/combinators/utility/inject.ts +25 -0
  41. package/src/lib/combinators/utility/map-error.spec.ts +63 -0
  42. package/src/lib/combinators/utility/map-error.ts +35 -0
  43. package/src/lib/combinators/utility/tap.spec.ts +102 -0
  44. package/src/lib/combinators/utility/tap.ts +38 -0
  45. package/src/lib/combinators/utility/validate-field.spec.ts +150 -0
  46. package/src/lib/combinators/utility/validate-field.ts +59 -0
  47. package/src/lib/combinators/utility/with-debug.spec.ts +71 -0
  48. package/src/lib/combinators/utility/with-debug.ts +55 -0
  49. package/src/lib/combinators/utility/with-memoize.spec.ts +82 -0
  50. package/src/lib/combinators/utility/with-memoize.ts +81 -0
  51. package/src/lib/combinators/utility/with-retry.spec.ts +220 -0
  52. package/src/lib/combinators/utility/with-retry.ts +68 -0
  53. package/src/lib/combinators/utility/with-timeout.spec.ts +115 -0
  54. package/src/lib/combinators/utility/with-timeout.ts +34 -0
  55. package/src/lib/composition/compose-rules.spec.ts +211 -0
  56. package/src/lib/composition/compose-rules.ts +47 -0
  57. package/src/lib/composition/index.ts +3 -0
  58. package/src/lib/composition/pipe-rules.spec.ts +220 -0
  59. package/src/lib/composition/pipe-rules.ts +44 -0
  60. package/src/lib/composition/pipe.spec.ts +47 -0
  61. package/src/lib/composition/pipe.ts +106 -0
  62. package/src/lib/helpers/context/has-context.ts +13 -0
  63. package/src/lib/helpers/context/index.ts +3 -0
  64. package/src/lib/helpers/context/require-context.spec.ts +55 -0
  65. package/src/lib/helpers/context/require-context.ts +61 -0
  66. package/src/lib/helpers/context/with-lazy-context.spec.ts +74 -0
  67. package/src/lib/helpers/context/with-lazy-context.ts +35 -0
  68. package/src/lib/helpers/index.ts +6 -0
  69. package/src/lib/helpers/result/fail.ts +15 -0
  70. package/src/lib/helpers/result/index.ts +2 -0
  71. package/src/lib/helpers/result/pass.ts +14 -0
  72. package/src/lib/helpers/retry/calculate-delay.ts +31 -0
  73. package/src/lib/index.ts +4 -0
  74. package/src/lib/types/composition-options.ts +7 -0
  75. package/src/lib/types/debug-options.ts +36 -0
  76. package/src/lib/types/index.ts +4 -0
  77. package/src/lib/types/rule-result.ts +16 -0
  78. package/src/lib/types/rule.ts +21 -0
  79. package/src/test/helpers/get-rule-error.ts +23 -0
  80. package/src/test/integration.spec.ts +285 -0
  81. package/tsconfig.json +55 -0
  82. package/tsup.config.ts +36 -0
  83. package/vitest.config.ts +16 -0
@@ -0,0 +1,285 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import {
3
+ withFallback,
4
+ withRetry,
5
+ withTimeout,
6
+ every,
7
+ unless,
8
+ withMemoize,
9
+ mapError,
10
+ when,
11
+ oneOf,
12
+ not,
13
+ withDebug,
14
+ match,
15
+ } from "../lib/combinators";
16
+ import { pipeRules } from "../lib/composition";
17
+ import { pass, fail } from "../lib/helpers";
18
+ import { getRuleError } from "./helpers/get-rule-error";
19
+ import { validateField } from "../lib/combinators/utility/validate-field";
20
+
21
+ describe("Full Integration Test", () => {
22
+ type User = {
23
+ email?: string;
24
+ username?: string;
25
+ age?: number;
26
+ payment: {
27
+ method?: string;
28
+ paymentId?: string;
29
+ };
30
+ profile?: {
31
+ bio?: string;
32
+ avatar?: string;
33
+ };
34
+ id: string;
35
+ };
36
+
37
+ // Mock services
38
+ const mockDb = {
39
+ checkEmail: vi.fn(),
40
+ checkUsername: vi.fn(),
41
+ getProfile: vi.fn(),
42
+ };
43
+
44
+ const mockPaymentService = {
45
+ validateCard: vi.fn(),
46
+ validatePaypal: vi.fn(),
47
+ };
48
+
49
+ beforeEach(() => {
50
+ vi.resetAllMocks();
51
+ mockDb.checkEmail.mockResolvedValue(false);
52
+ mockDb.checkUsername.mockResolvedValue(true);
53
+ mockDb.getProfile.mockResolvedValue({ verified: true });
54
+ mockPaymentService.validateCard.mockResolvedValue(true);
55
+ mockPaymentService.validatePaypal.mockResolvedValue(true);
56
+ });
57
+
58
+ // 1. Define individual rules
59
+ const validateEmailFormat = (email: string) =>
60
+ /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
61
+ ? pass()
62
+ : fail("Invalid email format");
63
+
64
+ const checkEmailUnique = async (email: string) =>
65
+ (await mockDb.checkEmail(email)) ? fail("Email already in use") : pass();
66
+
67
+ const validateUserEmail = validateField<User, string>(
68
+ (user) => user.email,
69
+ pipeRules([validateEmailFormat, checkEmailUnique]),
70
+ );
71
+
72
+ const validateUsername = pipeRules([
73
+ (username: string) => (username.length >= 3 ? pass() : fail("Too short")),
74
+ async (username: string) =>
75
+ (await mockDb.checkUsername(username)) ? pass() : fail("Username taken"),
76
+ ]);
77
+
78
+ const validateUserUsername = validateField<User, string>(
79
+ (user) => user.username,
80
+ validateUsername,
81
+ );
82
+
83
+ const validateAge = (age: number) =>
84
+ age >= 18 ? pass() : fail("Must be 18+");
85
+
86
+ const validateUserAge = validateField<User, number>(
87
+ (user) => user.age,
88
+ validateAge,
89
+ );
90
+
91
+ // 2. Payment validation with fallback
92
+ const validateCreditCard = withFallback(
93
+ withRetry(
94
+ async (card: User["payment"]) => {
95
+ const valid = await mockPaymentService.validateCard(card.paymentId);
96
+ return valid ? pass() : fail("Card declined");
97
+ },
98
+ { attempts: 2 },
99
+ ),
100
+ () => fail("Payment system unavailable"),
101
+ );
102
+
103
+ const validatePaypal = withTimeout(
104
+ async (paypalAccount: User["payment"]) => {
105
+ const valid = await mockPaymentService.validatePaypal(
106
+ paypalAccount.paymentId,
107
+ );
108
+ return valid ? pass() : fail("Paypal error");
109
+ },
110
+ 3000,
111
+ "Paypal timeout",
112
+ );
113
+
114
+ // 3. Profile validation (parallel)
115
+ const validateProfile = mapError(
116
+ every([
117
+ (profile: User["profile"]) =>
118
+ !profile?.bio || profile.bio.length <= 500
119
+ ? pass()
120
+ : fail("Bio too long"),
121
+ unless(
122
+ (profile) => !profile?.avatar,
123
+ () => fail("Avatar required"),
124
+ ),
125
+ ]),
126
+ (errors) => errors.join(", "),
127
+ );
128
+
129
+ const validateUserProfile = validateField<User, User["profile"]>(
130
+ (user) => user.profile,
131
+ validateProfile,
132
+ );
133
+
134
+ pipeRules<User>([
135
+ withMemoize(
136
+ validateField((user) => user.email, validateEmailFormat),
137
+ (user) => user.id,
138
+ ),
139
+ validateField((user) => user.email, checkEmailUnique),
140
+ validateField((user) => user.username, validateUsername),
141
+ mapError(
142
+ validateField((user) => user.age, validateAge),
143
+ (err) => `Age: ${err}`,
144
+ ),
145
+ ]);
146
+
147
+ // 4. Main pipeline
148
+ const validateUserRegistration = pipeRules<User>([
149
+ // Account basics
150
+ withMemoize(validateUserEmail, (user) => user.id + user.email),
151
+ validateUserUsername,
152
+ mapError(validateUserAge, (err) => `Age: ${err}`),
153
+ // Payment method branch
154
+ match(
155
+ (user: User) => user.payment.method || "",
156
+ {
157
+ credit: validateField((user) => user.payment, validateCreditCard),
158
+ paypal: validateField((user) => user.payment, validatePaypal),
159
+ },
160
+ "Invalid payment method",
161
+ ),
162
+
163
+ // Conditional profile check
164
+ when(
165
+ (user) => user.profile !== undefined,
166
+ mapError(
167
+ oneOf(
168
+ validateUserProfile,
169
+ not(() => fail("Profile blocked"), "Profile must be valid"),
170
+ ),
171
+ (errors) => errors.join(", "),
172
+ ),
173
+ ),
174
+
175
+ // Final verification
176
+ withDebug(
177
+ async (user, _ctx) => {
178
+ const profile = await mockDb.getProfile(user.id);
179
+ return profile?.verified ? pass() : fail("Unverified");
180
+ },
181
+ { name: "FinalVerification" },
182
+ ),
183
+ ]);
184
+
185
+ it("should successfully validate complete registration", async () => {
186
+ const user = {
187
+ email: "test@example.com",
188
+ username: "testuser",
189
+ age: 25,
190
+ payment: { method: "credit", paymentId: "4111111111111111" },
191
+ profile: { bio: "Hello", avatar: "image.jpg" },
192
+ id: "123",
193
+ };
194
+
195
+ const result = await validateUserRegistration(user);
196
+
197
+ expect(result).toEqual(pass());
198
+ expect(mockDb.checkEmail).toHaveBeenCalledWith("test@example.com");
199
+ expect(mockPaymentService.validateCard).toHaveBeenCalledWith(
200
+ "4111111111111111",
201
+ );
202
+ });
203
+
204
+ it("should collect multiple errors from parallel rules", async () => {
205
+ const user = {
206
+ email: "test@example.com",
207
+ username: "testuser",
208
+ age: 25,
209
+ payment: { method: "credit", number: "4111111111111111" },
210
+ profile: { bio: "a".repeat(600) }, // Invalid bio
211
+ id: "123",
212
+ };
213
+
214
+ mockDb.getProfile.mockResolvedValue({ verified: false });
215
+
216
+ const result = await validateUserRegistration(user);
217
+
218
+ if (result.status === "failed") {
219
+ const error = getRuleError(result);
220
+ console.log(error);
221
+ expect(error).toMatch("Unverified");
222
+ } else {
223
+ expect.fail("Expected validation to fail");
224
+ }
225
+ });
226
+
227
+ it("should handle payment fallback", async () => {
228
+ const user = {
229
+ email: "test@example.com",
230
+ username: "testuser",
231
+ age: 25,
232
+ payment: { method: "credit", number: "4111111111111111" },
233
+ id: "123",
234
+ };
235
+
236
+ mockPaymentService.validateCard.mockRejectedValue(new Error("API down"));
237
+
238
+ const result = await validateUserRegistration(user);
239
+
240
+ if (result.status === "failed") {
241
+ expect(getRuleError(result)).toBe("Payment system unavailable");
242
+ } else {
243
+ expect.fail("Expected fallback to trigger");
244
+ }
245
+ });
246
+
247
+ it("should timeout slow payments", async () => {
248
+ const user = {
249
+ email: "test@example.com",
250
+ username: "testuser",
251
+ age: 25,
252
+ payment: { method: "paypal", email: "test@paypal.com" },
253
+ id: "123",
254
+ };
255
+
256
+ mockPaymentService.validatePaypal.mockImplementation(
257
+ () => new Promise((resolve) => setTimeout(() => resolve(true), 4000)),
258
+ );
259
+
260
+ const result = await validateUserRegistration(user);
261
+
262
+ if (result.status === "failed") {
263
+ expect(getRuleError(result)).toBe("Paypal timeout");
264
+ } else {
265
+ expect.fail("Expected timeout to trigger");
266
+ }
267
+ });
268
+
269
+ it("should memoize expensive validations", async () => {
270
+ const user = {
271
+ email: "memo@test.com",
272
+ username: "memo_user",
273
+ age: 30,
274
+ payment: { method: "credit", number: "5555555555554444" },
275
+ id: "456",
276
+ };
277
+
278
+ // First call
279
+ await validateUserRegistration(user);
280
+ // Second call with same email
281
+ await validateUserRegistration(user);
282
+
283
+ expect(mockDb.checkEmail).toHaveBeenCalledTimes(1);
284
+ });
285
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "compilerOptions": {
3
+ "incremental": false,
4
+ "target": "ES2018",
5
+ "outDir": "dist",
6
+ "rootDir": "src",
7
+ "sourceRoot": "src",
8
+ "moduleResolution": "node",
9
+ "module": "ES6",
10
+ "declaration": true,
11
+ "sourceMap": true,
12
+ "mapRoot": "./",
13
+ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
14
+ "resolveJsonModule": true /* Include modules imported with .json extension. */,
15
+ "strict": true /* Enable all strict type-checking options. */,
16
+ /* Strict Type-Checking Options */
17
+ // "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
18
+ // "strictNullChecks": true /* Enable strict null checks. */,
19
+ // "strictFunctionTypes": true /* Enable strict checking of function types. */,
20
+ // "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */,
21
+ // "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
22
+ // "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,
23
+ /* Additional Checks */
24
+ "noUnusedLocals": true /* Report errors on unused locals. */,
25
+ "noUnusedParameters": true /* Report errors on unused parameters. */,
26
+ "noImplicitReturns": false /* Report error when not all code paths in function return a value. */,
27
+ "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
28
+ /* Debugging Options */
29
+ "traceResolution": false /* Report module resolution log messages. */,
30
+ "listEmittedFiles": false /* Print names of generated files part of the compilation. */,
31
+ "listFiles": false /* Print names of files part of the compilation. */,
32
+ "pretty": true /* Stylize errors and messages using color and context. */,
33
+ /* Experimental Options */
34
+ "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
35
+ "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
36
+ "lib": [
37
+ "ES2022",
38
+ "DOM"
39
+ ],
40
+ "types": [],
41
+ "typeRoots": [
42
+ "node_modules/@types",
43
+ "src/types"
44
+ ]
45
+ },
46
+ "include": [
47
+ "src/**/*.ts"
48
+ ],
49
+ "exclude": [
50
+ "dist/**",
51
+ "build/**",
52
+ "node_modules/**"
53
+ ],
54
+ "compileOnSave": false
55
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,36 @@
1
+ // tsup.config.ts
2
+ import { defineConfig } from 'tsup'
3
+
4
+ export default defineConfig({
5
+ // Entry file(s)
6
+ entry: ['src/lib/index.ts'],
7
+
8
+ // Output formats
9
+ format: ['cjs', 'esm'],
10
+
11
+ // Generate declaration files
12
+ dts: true,
13
+
14
+ // Clean dist folder before build
15
+ clean: true,
16
+
17
+ // Target ES2018 for good balance
18
+ target: 'es2018',
19
+
20
+ // Bundle dependencies (adjust based on your needs)
21
+ noExternal: [], // Bundle all dependencies
22
+ // or
23
+ // external: ['some-package'], // Mark specific packages as external
24
+
25
+ // Enable sourcemaps
26
+ sourcemap: true,
27
+
28
+ // Optional: Splitting for ESM
29
+ splitting: true,
30
+
31
+ // Optional: Minification
32
+ minify: true,
33
+
34
+ // Optional: Tree-shaking
35
+ treeshake: true,
36
+ })
@@ -0,0 +1,16 @@
1
+ /// <reference types="vitest" />
2
+
3
+ // Configure Vitest (https://vitest.dev/config/)
4
+
5
+ import { defineConfig } from 'vite';
6
+
7
+ export default defineConfig({
8
+ test: {
9
+ coverage: {
10
+ reporter: ['html', 'json'],
11
+ },
12
+ include: ['src/**/*.{test,spec}.ts'],
13
+ /* for example, use global to avoid globals imports (describe, test, expect): */
14
+ // globals: true,
15
+ },
16
+ });