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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ts-rules-composer",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Typescript rules engine by composition",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -9,6 +9,12 @@
9
9
  "license": "MIT",
10
10
  "sideEffects": false,
11
11
  "type": "module",
12
+ "files": [
13
+ "dist/**",
14
+ "README.md",
15
+ "LICENSE",
16
+ "package.json"
17
+ ],
12
18
  "exports": {
13
19
  "import": {
14
20
  "types": "./dist/index.d.ts",
package/.editorconfig DELETED
@@ -1,15 +0,0 @@
1
- # http://editorconfig.org
2
- root = true
3
-
4
- [*]
5
- charset = utf-8
6
- end_of_line = lf
7
- indent_size = 2
8
- indent_style = space
9
- insert_final_newline = true
10
- max_line_length = 80
11
- trim_trailing_whitespace = true
12
-
13
- [*.md]
14
- max_line_length = 0
15
- trim_trailing_whitespace = false
@@ -1,3 +0,0 @@
1
- # Example Contributing Guidelines
2
-
3
- This is an example of GitHub's contributing guidelines file. Check out GitHub's [CONTRIBUTING.md help center article](https://help.github.com/articles/setting-guidelines-for-repository-contributors/) for more information.
@@ -1,9 +0,0 @@
1
- - **I'm submitting a ...**
2
- [ ] bug report
3
- [ ] feature request
4
- [ ] question about the decisions made in the repository
5
- [ ] question about how to use this project
6
-
7
- - **Summary**
8
-
9
- - **Other information** (e.g. detailed explanation, stack traces, related issues, suggestions how to fix, links for us to have context, eg. StackOverflow, personal fork, etc.)
@@ -1,7 +0,0 @@
1
- - **What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...)
2
-
3
- - **What is the current behavior?** (You can also link to an open issue here)
4
-
5
- - **What is the new behavior (if this is a feature change)?**
6
-
7
- - **Other information**:
@@ -1,29 +0,0 @@
1
- name: docs
2
-
3
- on:
4
- push:
5
- branches:
6
- - main
7
-
8
- jobs:
9
- test:
10
- runs-on: ubuntu-latest
11
- strategy:
12
- matrix:
13
- node-version: [22.x]
14
- steps:
15
- - uses: actions/checkout@v2
16
- - name: Build on Node.js ${{ matrix.node-version }}
17
- uses: actions/setup-node@v3
18
- with:
19
- node-version: ${{ matrix.node-version }}
20
- - run: npm ci --ignore-scripts
21
-
22
- - name: Run typedoc to generate html documentation
23
- run: npm run generate-docs
24
-
25
- - name: Deploy 🚀
26
- uses: JamesIves/github-pages-deploy-action@4.1.4
27
- with:
28
- branch: gh-pages
29
- folder: genDocs
@@ -1,25 +0,0 @@
1
- name: publish
2
-
3
- on:
4
- workflow_run:
5
- workflows: ["test"]
6
- branches: [main]
7
- types:
8
- - completed
9
-
10
- jobs:
11
- publish:
12
- if: ${{ github.event.workflow_run.conclusion == 'success' }} && github.ref == 'refs/heads/main'
13
- runs-on: ubuntu-latest
14
- steps:
15
- - uses: actions/checkout@v4
16
- - uses: actions/setup-node@v4
17
- with:
18
- node-version: 22
19
- registry-url: 'https://registry.npmjs.org'
20
- - run: npm ci --ignore-scripts
21
- - run: npm run build --if-present
22
- - name: Publish
23
- run: npm run release
24
- env:
25
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -1,37 +0,0 @@
1
- name: test
2
-
3
- on:
4
- push:
5
- branches:
6
- - main
7
- - dev
8
-
9
- pull_request:
10
- types:
11
- - opened
12
- - synchronize
13
-
14
- jobs:
15
- test:
16
- runs-on: ubuntu-latest
17
- strategy:
18
- matrix:
19
- node-version: [22.x]
20
- steps:
21
- - uses: actions/checkout@v2
22
- - name: Build on Node.js ${{ matrix.node-version }}
23
- uses: actions/setup-node@v1
24
- with:
25
- node-version: ${{ matrix.node-version }}
26
- - run: npm ci --ignore-scripts
27
- - run: npm run build --if-present
28
- name: Build
29
- - run: npm test
30
- env:
31
- CI: true
32
- - run: npm run lint
33
- env:
34
- CI: true
35
- - run: npm run format
36
- env:
37
- CI: true
package/.prettierignore DELETED
@@ -1,2 +0,0 @@
1
- # package.json is formatted by package managers, so we ignore it here
2
- package.json
package/.releaserc DELETED
@@ -1,11 +0,0 @@
1
- branches:
2
- - main
3
- - name: alpha
4
- prerelease: true
5
- debug: true
6
- ci: true
7
- dryRun: false
8
- plugins:
9
- - ["@semantic-release/commit-analyzer", { "preset": "conventionalcommits" }]
10
- - "@semantic-release/release-notes-generator"
11
- - "@semantic-release/npm"
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";