ts-rules-composer 1.0.0 → 1.0.2

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 (110) hide show
  1. package/README.md +87 -14
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +148 -176
  5. package/dist/index.d.ts +148 -176
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +1 -1
  8. package/package.json +40 -43
  9. package/.editorconfig +0 -15
  10. package/.github/CONTRIBUTING.md +0 -3
  11. package/.github/ISSUE_TEMPLATE.md +0 -9
  12. package/.github/PULL_REQUEST_TEMPLATE.md +0 -7
  13. package/.github/workflows/docs.yml +0 -29
  14. package/.github/workflows/publish.yml +0 -25
  15. package/.github/workflows/test.yml +0 -37
  16. package/.prettierignore +0 -2
  17. package/.releaserc +0 -11
  18. package/eslint.config.mjs +0 -84
  19. package/examples/financial-transaction.example.ts +0 -188
  20. package/examples/model-deployment.example.ts +0 -136
  21. package/examples/user-registration.example.ts +0 -101
  22. package/src/lib/combinators/index.ts +0 -2
  23. package/src/lib/combinators/logic/every.spec.ts +0 -264
  24. package/src/lib/combinators/logic/every.ts +0 -57
  25. package/src/lib/combinators/logic/if-else.spec.ts +0 -82
  26. package/src/lib/combinators/logic/if-else.ts +0 -64
  27. package/src/lib/combinators/logic/index.ts +0 -8
  28. package/src/lib/combinators/logic/match.spec.ts +0 -186
  29. package/src/lib/combinators/logic/match.ts +0 -106
  30. package/src/lib/combinators/logic/not.spec.ts +0 -64
  31. package/src/lib/combinators/logic/not.ts +0 -34
  32. package/src/lib/combinators/logic/one-of.spec.ts +0 -68
  33. package/src/lib/combinators/logic/one-of.ts +0 -48
  34. package/src/lib/combinators/logic/unless.spec.ts +0 -61
  35. package/src/lib/combinators/logic/unless.ts +0 -50
  36. package/src/lib/combinators/logic/when.spec.ts +0 -119
  37. package/src/lib/combinators/logic/when.ts +0 -50
  38. package/src/lib/combinators/logic/with-fallback.spec.ts +0 -72
  39. package/src/lib/combinators/logic/with-fallback.ts +0 -46
  40. package/src/lib/combinators/utility/index.ts +0 -11
  41. package/src/lib/combinators/utility/inject.spec.ts +0 -55
  42. package/src/lib/combinators/utility/inject.ts +0 -25
  43. package/src/lib/combinators/utility/map-error.spec.ts +0 -63
  44. package/src/lib/combinators/utility/map-error.ts +0 -35
  45. package/src/lib/combinators/utility/tap.spec.ts +0 -102
  46. package/src/lib/combinators/utility/tap.ts +0 -28
  47. package/src/lib/combinators/utility/validate-field.spec.ts +0 -150
  48. package/src/lib/combinators/utility/validate-field.ts +0 -66
  49. package/src/lib/combinators/utility/with-debug.spec.ts +0 -71
  50. package/src/lib/combinators/utility/with-debug.ts +0 -55
  51. package/src/lib/combinators/utility/with-memoize.spec.ts +0 -82
  52. package/src/lib/combinators/utility/with-memoize.ts +0 -89
  53. package/src/lib/combinators/utility/with-retry.spec.ts +0 -220
  54. package/src/lib/combinators/utility/with-retry.ts +0 -70
  55. package/src/lib/combinators/utility/with-safe-error.spec.ts +0 -137
  56. package/src/lib/combinators/utility/with-safe-error.ts +0 -56
  57. package/src/lib/combinators/utility/with-safe-predicate.spec.ts +0 -176
  58. package/src/lib/combinators/utility/with-safe-predicate.ts +0 -64
  59. package/src/lib/combinators/utility/with-tap.spec.ts +0 -104
  60. package/src/lib/combinators/utility/with-tap.ts +0 -46
  61. package/src/lib/combinators/utility/with-timeout.spec.ts +0 -115
  62. package/src/lib/combinators/utility/with-timeout.ts +0 -41
  63. package/src/lib/composition/compose-rules.spec.ts +0 -211
  64. package/src/lib/composition/compose-rules.ts +0 -55
  65. package/src/lib/composition/index.ts +0 -3
  66. package/src/lib/composition/pipe-rules.spec.ts +0 -220
  67. package/src/lib/composition/pipe-rules.ts +0 -52
  68. package/src/lib/composition/pipe.spec.ts +0 -47
  69. package/src/lib/composition/pipe.ts +0 -107
  70. package/src/lib/helpers/clone/clone.ts +0 -12
  71. package/src/lib/helpers/clone/getCloneFn.ts +0 -17
  72. package/src/lib/helpers/clone/shallowClone.ts +0 -12
  73. package/src/lib/helpers/context/has-context.ts +0 -13
  74. package/src/lib/helpers/context/index.ts +0 -3
  75. package/src/lib/helpers/context/require-context.spec.ts +0 -55
  76. package/src/lib/helpers/context/require-context.ts +0 -61
  77. package/src/lib/helpers/context/with-lazy-context.spec.ts +0 -74
  78. package/src/lib/helpers/context/with-lazy-context.ts +0 -35
  79. package/src/lib/helpers/index.ts +0 -8
  80. package/src/lib/helpers/result/fail.ts +0 -15
  81. package/src/lib/helpers/result/index.ts +0 -2
  82. package/src/lib/helpers/result/pass.ts +0 -14
  83. package/src/lib/helpers/retry/calculate-delay.ts +0 -31
  84. package/src/lib/helpers/safety/get-normalized-rule.spec.ts +0 -209
  85. package/src/lib/helpers/safety/get-normalized-rule.ts +0 -14
  86. package/src/lib/helpers/safety/get-normalized-rules.spec.ts +0 -138
  87. package/src/lib/helpers/safety/get-normalized-rules.ts +0 -14
  88. package/src/lib/index.ts +0 -4
  89. package/src/lib/types/composition-options.ts +0 -32
  90. package/src/lib/types/debug-options.ts +0 -36
  91. package/src/lib/types/index.ts +0 -8
  92. package/src/lib/types/predicate-result.ts +0 -20
  93. package/src/lib/types/predicate-safe.ts +0 -10
  94. package/src/lib/types/predicate-safety-options.ts +0 -27
  95. package/src/lib/types/predicate.ts +0 -8
  96. package/src/lib/types/prettify.ts +0 -3
  97. package/src/lib/types/rule-result.ts +0 -16
  98. package/src/lib/types/rule-safety-options.ts +0 -34
  99. package/src/lib/types/rule.ts +0 -21
  100. package/src/lib/types/safety-options.ts +0 -7
  101. package/src/test/financial-transaction.spec.ts +0 -251
  102. package/src/test/helpers/get-rule-error.ts +0 -23
  103. package/src/test/integration.spec.ts +0 -285
  104. package/src/test/model-deployment.spec.ts +0 -209
  105. package/src/test/user-registration.spec.ts +0 -164
  106. package/tsconfig.json +0 -56
  107. package/tsup.config.ts +0 -36
  108. package/typedoc/tsconfig.typedoc.json +0 -15
  109. package/typedoc/typedoc.json +0 -14
  110. package/vitest.config.ts +0 -16
package/eslint.config.mjs DELETED
@@ -1,84 +0,0 @@
1
- import { defineConfig, globalIgnores } from "eslint/config";
2
- import { fixupConfigRules, fixupPluginRules } from "@eslint/compat";
3
- import _import from "eslint-plugin-import";
4
- import eslintComments from "eslint-plugin-eslint-comments";
5
- import tsParser from "@typescript-eslint/parser";
6
- import path from "node:path";
7
- import { fileURLToPath } from "node:url";
8
- import js from "@eslint/js";
9
- import { FlatCompat } from "@eslint/eslintrc";
10
-
11
- const __filename = fileURLToPath(import.meta.url);
12
- const __dirname = path.dirname(__filename);
13
- const compat = new FlatCompat({
14
- baseDirectory: __dirname,
15
- recommendedConfig: js.configs.recommended,
16
- allConfig: js.configs.all
17
- });
18
-
19
- export default defineConfig([
20
- globalIgnores(["**/node_modules", "**/build", "**/coverage", "**/vitest.config.js"]),
21
- {
22
- extends: fixupConfigRules(compat.extends(
23
- "eslint:recommended",
24
- "plugin:eslint-comments/recommended",
25
- "plugin:@typescript-eslint/recommended",
26
- "plugin:import/typescript",
27
- "prettier",
28
- )),
29
-
30
- plugins: {
31
- import: fixupPluginRules(_import),
32
- "eslint-comments": fixupPluginRules(eslintComments),
33
- },
34
-
35
- languageOptions: {
36
- globals: {
37
- BigInt: true,
38
- console: true,
39
- WebAssembly: true,
40
- },
41
- parser: tsParser,
42
- ecmaVersion: 6,
43
- sourceType: "module",
44
- parserOptions: {
45
- project: "./tsconfig.json",
46
- },
47
- },
48
-
49
- rules: {
50
- "@typescript-eslint/explicit-module-boundary-types": "off",
51
- "@typescript-eslint/no-unused-vars": [1, {
52
- argsIgnorePattern: "^_",
53
- varsIgnorePattern: "^_",
54
- }],
55
- "eslint-comments/disable-enable-pair": ["error", {
56
- allowWholeFile: true,
57
- }],
58
- "eslint-comments/no-unused-disable": "error",
59
- "import/order": ["error", {
60
- "newlines-between": "always",
61
- alphabetize: {
62
- order: "asc",
63
- },
64
- }],
65
- quotes: ["error", "double", {
66
- allowTemplateLiterals: true,
67
- avoidEscape: true,
68
- }],
69
- "@typescript-eslint/consistent-type-imports": "error",
70
- "@typescript-eslint/consistent-type-exports": "error"
71
- },
72
- },
73
- {
74
- // Override config for test files
75
- files: ["**/*.spec.ts"],
76
- rules: {
77
- // Add any rules you want to disable or modify for test files
78
- "@typescript-eslint/no-unused-vars": "off",
79
- "import/order": "off",
80
- "@typescript-eslint/no-explicit-any": "off"
81
- // You can add more test-specific rule overrides here
82
- }
83
- }
84
- ]);
@@ -1,188 +0,0 @@
1
- import type { Rule } from "../src/lib";
2
- import {
3
- pipeRules,
4
- match,
5
- withRetry,
6
- withMemoize,
7
- withTimeout,
8
- when,
9
- pass,
10
- fail,
11
- } from "../src/lib";
12
-
13
- // Types
14
- interface Transaction {
15
- amount: number;
16
- currency: string;
17
- userId: string;
18
- recipient: string;
19
- paymentType: string;
20
- accountType: string;
21
- cardNumber?: string;
22
- expiry?: string;
23
- walletAddress?: string;
24
- iban?: string;
25
- }
26
-
27
- const SUPPORTED_CURRENCIES = ["USD", "EUR", "GBP"];
28
-
29
- // Mock services
30
- const fraudService = {
31
- assess: async (_tx: Transaction) => ({ score: 2 }),
32
- };
33
-
34
- const bankService = {
35
- authCheck: async (_cardNumber: string) => true,
36
- };
37
-
38
- // 1. Basic validators
39
- const validateAmount: Rule<Transaction> = (tx: Transaction) =>
40
- tx.amount > 0 ? pass() : fail("Amount must be positive");
41
-
42
- const validateCurrency: Rule<Transaction> = (tx: Transaction) =>
43
- SUPPORTED_CURRENCIES.includes(tx.currency)
44
- ? pass()
45
- : fail(`Unsupported currency: ${tx.currency}`);
46
-
47
- // 2. Payment method specific validators
48
- const validateCardNumber: Rule<Transaction> = (tx: Transaction) => {
49
- if (!tx.cardNumber) return fail("Card number required");
50
- // Simple Luhn check for example purposes
51
- const digits = tx.cardNumber.replace(/\D/g, "").split("").map(Number);
52
- if (digits.length < 13) return fail("Invalid card number");
53
-
54
- let sum = 0;
55
- for (let i = 0; i < digits.length; i++) {
56
- let digit = digits[digits.length - 1 - i];
57
- if (i % 2 === 1) digit *= 2;
58
- if (digit > 9) digit -= 9;
59
- sum += digit;
60
- }
61
-
62
- return sum % 10 === 0 ? pass() : fail("Invalid card number");
63
- };
64
-
65
- const validateExpiry: Rule<Transaction> = (tx: Transaction) => {
66
- if (!tx.expiry) return fail("Expiry required");
67
- const [month, year] = tx.expiry.split("/").map(Number);
68
- const now = new Date();
69
- const currentYear = now.getFullYear() % 100;
70
- const currentMonth = now.getMonth() + 1;
71
-
72
- if (year < currentYear || (year === currentYear && month < currentMonth)) {
73
- return fail("Card expired");
74
- }
75
- return pass();
76
- };
77
-
78
- const bankAuthCheck: Rule<Transaction> = async (tx: Transaction) => {
79
- try {
80
- const isValid = await bankService.authCheck(tx.cardNumber!);
81
- return isValid ? pass() : fail("Bank authorization failed");
82
- } catch (error) {
83
- return fail("Bank service error");
84
- }
85
- };
86
-
87
- const validateWalletAddress: Rule<Transaction> = (tx: Transaction) => {
88
- if (!tx.walletAddress) return fail("Wallet address required");
89
- return /^0x[a-fA-F0-9]{40}$/.test(tx.walletAddress)
90
- ? pass()
91
- : fail("Invalid wallet address");
92
- };
93
-
94
- const validateIBAN: Rule<Transaction> = (tx: Transaction) => {
95
- if (!tx.iban) return fail("IBAN required");
96
- // Simple IBAN format check
97
- return /^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(tx.iban)
98
- ? pass()
99
- : fail("Invalid IBAN");
100
- };
101
-
102
- // 3. Account type specific validators
103
- const validateBusinessTransfer: Rule<Transaction> = (tx: Transaction) => {
104
- return tx.amount <= 100000
105
- ? pass()
106
- : fail("Business transfers limited to $100,000");
107
- };
108
-
109
- const validatePersonalTransfer: Rule<Transaction> = (tx: Transaction) => {
110
- return tx.amount <= 10000
111
- ? pass()
112
- : fail("Personal transfers limited to $10,000");
113
- };
114
-
115
- // 4. Memoized fraud check (cached for 5 minutes)
116
- const checkFraudRisk: Rule<Transaction> = withMemoize(
117
- async (tx: Transaction) => {
118
- const risk = await fraudService.assess(tx);
119
- return risk.score < 5 ? pass() : fail("High fraud risk");
120
- },
121
- (tx) => `${tx.userId}-${tx.amount}-${tx.recipient}`,
122
- { ttl: 300000 },
123
- );
124
-
125
- // 5. Payment method handling
126
- const validatePaymentMethod: Rule<Transaction> = match(
127
- (tx: Transaction) => tx.paymentType,
128
- {
129
- credit_card: pipeRules([
130
- validateCardNumber,
131
- validateExpiry,
132
- withTimeout(bankAuthCheck, 3000, "Bank auth timeout"),
133
- ]),
134
- crypto: validateWalletAddress,
135
- bank_transfer: validateIBAN,
136
- },
137
- );
138
-
139
- // 6. Complete pipeline
140
- const validateTransaction: Rule<Transaction> = pipeRules([
141
- validateAmount,
142
- validateCurrency,
143
-
144
- // Only run fraud check for transactions > $1000
145
- when(
146
- (tx: Transaction) => tx.amount > 1000,
147
- withRetry(checkFraudRisk, { attempts: 2 }),
148
- ),
149
-
150
- validatePaymentMethod,
151
-
152
- // Compliance check (different for business/personal)
153
- match((tx: Transaction) => tx.accountType, {
154
- business: validateBusinessTransfer,
155
- personal: validatePersonalTransfer,
156
- }),
157
- ]);
158
-
159
- // Example usage
160
- (async () => {
161
- const validTransaction = {
162
- amount: 500,
163
- currency: "USD",
164
- userId: "user123",
165
- recipient: "recipient456",
166
- paymentType: "credit_card",
167
- accountType: "personal",
168
- cardNumber: "4111111111111111", // Valid test Visa number
169
- expiry: "12/25",
170
- };
171
-
172
- const validResult = await validateTransaction(validTransaction);
173
- console.log(validResult);
174
-
175
- const invalidTransaction = {
176
- amount: 500,
177
- currency: "XYZ", // Invalid
178
- userId: "user123",
179
- recipient: "recipient456",
180
- paymentType: "credit_card",
181
- accountType: "personal",
182
- cardNumber: "4111111111111111",
183
- expiry: "12/25",
184
- };
185
-
186
- const invalidResult = await validateTransaction(invalidTransaction);
187
- console.log(invalidResult);
188
- })();
@@ -1,136 +0,0 @@
1
- import type { Rule } from "../src/lib";
2
- import {
3
- inject,
4
- withLazyContext,
5
- withMemoize,
6
- pass,
7
- fail,
8
- pipeRules,
9
- tap,
10
- } from "../src/lib";
11
-
12
- // 1. Define types
13
- type Deployment = {
14
- modelId: string;
15
- version: string;
16
- userId: string;
17
- };
18
-
19
- type ModelMetadata = {
20
- modelId: string;
21
- latestVersion: string;
22
- isDeprecated: boolean;
23
- riskScore: number;
24
- };
25
-
26
- type Context = {
27
- modelMeta: ModelMetadata;
28
- };
29
-
30
- type Injected = {
31
- logger: {
32
- log: (msg: string, payload: unknown) => void;
33
- };
34
- riskService: {
35
- assess: (modelId: string) => Promise<number>;
36
- };
37
- modelRegistry: {
38
- getMetadata: (modelId: string) => Promise<ModelMetadata>;
39
- };
40
- };
41
-
42
- // 2. Basic rules
43
- const validateVersionUpToDate: Rule<Deployment, string, Context> = (d, ctx) => {
44
- return d.version === ctx?.modelMeta.latestVersion
45
- ? pass()
46
- : fail("Version is not up to date");
47
- };
48
-
49
- const checkDeprecation: Rule<Deployment, string, Context> = (_, ctx) => {
50
- return ctx?.modelMeta.isDeprecated ? fail("Model is deprecated") : pass();
51
- };
52
-
53
- const checkRisk = (services: Injected["riskService"]): Rule<Deployment> =>
54
- withMemoize(
55
- async (d) => {
56
- const score = await services.assess(d.modelId);
57
- return score < 7 ? pass() : fail("Model risk too high");
58
- },
59
- (d) => d.modelId,
60
- { ttl: 60_000 },
61
- );
62
-
63
- // 3. Factory function with injection
64
- const createDeploymentValidator = (deps: Injected) =>
65
- pipeRules([
66
- tap((input) => deps.logger.log("Deployment started", { input })),
67
-
68
- withLazyContext<Deployment, string, Context>(
69
- async (deployment) => {
70
- const meta = await deps.modelRegistry.getMetadata(deployment.modelId);
71
- return { modelMeta: meta };
72
- },
73
-
74
- pipeRules<Deployment, string, Context>([
75
- validateVersionUpToDate,
76
- checkDeprecation,
77
- ]),
78
- ),
79
-
80
- checkRisk(deps.riskService),
81
-
82
- tap((_, __) => deps.logger.log("Deployment passed", {})),
83
- ]);
84
-
85
- // 4. Setup
86
- const mockLogger = {
87
- log: (msg: string, payload: unknown) =>
88
- console.log(`[LOG] ${msg}:`, JSON.stringify(payload, null, 2)),
89
- };
90
-
91
- const mockRegistry = {
92
- getMetadata: async (id: string): Promise<ModelMetadata> => ({
93
- modelId: id,
94
- latestVersion: "1.2.0",
95
- isDeprecated: false,
96
- riskScore: 4,
97
- }),
98
- };
99
-
100
- const mockRiskService = {
101
- assess: async (modelId: string) => {
102
- console.log(`Assessing risk for ${modelId}...`);
103
- return 5;
104
- },
105
- };
106
-
107
- // 5. Compose final rule
108
- const validateDeployment = inject(
109
- {
110
- logger: mockLogger,
111
- modelRegistry: mockRegistry,
112
- riskService: mockRiskService,
113
- },
114
- createDeploymentValidator,
115
- );
116
-
117
- // 6. Run it
118
- (async () => {
119
- const deployment: Deployment = {
120
- modelId: "gpt-9000",
121
- version: "1.2.0",
122
- userId: "u456",
123
- };
124
-
125
- const result = await validateDeployment(deployment);
126
- console.log("Result:", result);
127
-
128
- const outdatedDeploymenty: Deployment = {
129
- modelId: "gpt-9000",
130
- version: "1.1.0",
131
- userId: "u456",
132
- };
133
-
134
- const outdatedResult = await validateDeployment(outdatedDeploymenty);
135
- console.log("Result 2 (outdated):", outdatedResult);
136
- })();
@@ -1,101 +0,0 @@
1
- import type { Rule } from "../src/lib";
2
- import {
3
- pipeRules,
4
- every,
5
- match,
6
- withMemoize,
7
- pass,
8
- fail,
9
- mapError,
10
- } from "../src/lib";
11
-
12
- // Types
13
- type User = {
14
- username: string;
15
- password: string;
16
- email: string;
17
- role: "admin" | "user" | "unknown";
18
- };
19
-
20
- // Mocked rules
21
- const validateUsernameFormat: Rule<User> = (user) => {
22
- return /^[a-zA-Z0-9_]{3,16}$/.test(user.username)
23
- ? pass()
24
- : fail("Username must be 3-16 characters and alphanumeric");
25
- };
26
-
27
- const checkUsernameAvailability: Rule<User> = async (user) => {
28
- const taken = ["admin", "testuser"];
29
- return taken.includes(user.username)
30
- ? fail("Username is already taken")
31
- : pass();
32
- };
33
-
34
- const validatePasswordStrength: Rule<User> = (user) => {
35
- return user.password.length >= 8
36
- ? pass()
37
- : fail("Password must be at least 8 characters long");
38
- };
39
-
40
- const validateEmailFormat: Rule<User> = (user) => {
41
- return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(user.email)
42
- ? pass()
43
- : fail("Invalid email format");
44
- };
45
-
46
- const checkEmailUnique: Rule<User> = async (user) => {
47
- const usedEmails = ["taken@example.com"];
48
- return usedEmails.includes(user.email)
49
- ? fail("Email is already in use")
50
- : pass();
51
- };
52
-
53
- const validateAdminPrivileges: Rule<User> = (user) =>
54
- user.username === "admin"
55
- ? pass()
56
- : fail("Admin users must use the 'admin' username");
57
-
58
- const validateStandardUser: Rule<User> = () => pass();
59
-
60
- // Compose validator
61
- const validateUser = pipeRules([
62
- validateUsernameFormat,
63
- withMemoize(checkUsernameAvailability, (user) => user.username, {
64
- ttl: 60000,
65
- }),
66
- mapError(
67
- every([validatePasswordStrength, validateEmailFormat, checkEmailUnique]),
68
- (errors) => errors.join(", "),
69
- ),
70
- match<User, string>(
71
- (user) => user.role,
72
- {
73
- admin: validateAdminPrivileges,
74
- user: validateStandardUser,
75
- },
76
- "Unknown role",
77
- ),
78
- ]);
79
-
80
- // Example usage
81
- (async () => {
82
- const validUser: User = {
83
- username: "new_user",
84
- password: "password123",
85
- email: "user@example.com",
86
- role: "user",
87
- };
88
-
89
- const failingUser: User = {
90
- username: "new_user",
91
- password: "psw",
92
- email: "taken@example.com",
93
- role: "user",
94
- };
95
-
96
- const validResult = await validateUser(validUser);
97
- console.log("Validation Result:", validResult);
98
-
99
- const failingResult = await validateUser(failingUser);
100
- console.log("Validation Result 2:", failingResult);
101
- })();
@@ -1,2 +0,0 @@
1
- export * from "./logic";
2
- export * from "./utility";