nestjs-business-engine 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +277 -0
- package/dist/business-engine.module.d.ts +10 -0
- package/dist/business-engine.module.js +54 -0
- package/dist/business-engine.options.d.ts +31 -0
- package/dist/business-engine.options.js +5 -0
- package/dist/business-engine.service.d.ts +23 -0
- package/dist/business-engine.service.js +223 -0
- package/dist/errors.d.ts +47 -0
- package/dist/errors.js +90 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +25 -0
- package/dist/standard-schema.d.ts +35 -0
- package/dist/standard-schema.js +2 -0
- package/dist/types.d.ts +72 -0
- package/dist/types.js +2 -0
- package/dist/util/formula.util.d.ts +39 -0
- package/dist/util/formula.util.js +134 -0
- package/dist/util/normalize.util.d.ts +8 -0
- package/dist/util/normalize.util.js +49 -0
- package/dist/validation.d.ts +30 -0
- package/dist/validation.js +137 -0
- package/index.d.mts +1 -0
- package/index.mjs +4 -0
- package/llms.txt +82 -0
- package/package.json +141 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.rulesSchema = void 0;
|
|
4
|
+
exports.checkRules = checkRules;
|
|
5
|
+
exports.validateRules = validateRules;
|
|
6
|
+
const formula_util_1 = require("./util/formula.util");
|
|
7
|
+
/**
|
|
8
|
+
* Keys that would change an object's prototype instead of creating a property.
|
|
9
|
+
* Rule ids and transform keys become property names, so they are rejected.
|
|
10
|
+
*/
|
|
11
|
+
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
12
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
13
|
+
const isNonEmptyString = (value) => typeof value === 'string' && value.length > 0;
|
|
14
|
+
/** @internal Structural and safety checks shared by run() and validateRules(). */
|
|
15
|
+
function checkRules(rules, options) {
|
|
16
|
+
if (!Array.isArray(rules)) {
|
|
17
|
+
return [{ message: 'Rules must be an array', path: [] }];
|
|
18
|
+
}
|
|
19
|
+
const issues = [];
|
|
20
|
+
const ids = new Set();
|
|
21
|
+
rules.forEach((rule, index) => {
|
|
22
|
+
if (!isObject(rule)) {
|
|
23
|
+
issues.push({
|
|
24
|
+
message: `Rule at index ${index} must be an object`,
|
|
25
|
+
path: [index],
|
|
26
|
+
});
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const ruleId = isNonEmptyString(rule.id) ? rule.id : undefined;
|
|
30
|
+
const label = ruleId === undefined ? `Rule at index ${index}` : `Rule "${ruleId}"`;
|
|
31
|
+
const add = (message, ...path) => issues.push({ message, path: [index, ...path], ruleId });
|
|
32
|
+
if (ruleId === undefined) {
|
|
33
|
+
add(`${label} must have a non-empty string id`, 'id');
|
|
34
|
+
}
|
|
35
|
+
else if (UNSAFE_KEYS.has(ruleId)) {
|
|
36
|
+
add(`Rule id "${ruleId}" is not allowed`, 'id');
|
|
37
|
+
}
|
|
38
|
+
else if (ids.has(ruleId)) {
|
|
39
|
+
add(`Duplicate rule id "${ruleId}"`, 'id');
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
ids.add(ruleId);
|
|
43
|
+
}
|
|
44
|
+
if (rule.group !== undefined && typeof rule.group !== 'string') {
|
|
45
|
+
add(`${label}: group must be a string`, 'group');
|
|
46
|
+
}
|
|
47
|
+
if (rule.enabled !== undefined && typeof rule.enabled !== 'boolean') {
|
|
48
|
+
add(`${label}: enabled must be a boolean`, 'enabled');
|
|
49
|
+
}
|
|
50
|
+
if (rule.transform !== undefined) {
|
|
51
|
+
if (!Array.isArray(rule.transform)) {
|
|
52
|
+
add(`${label}: transform must be an array`, 'transform');
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
rule.transform.forEach((transform, position) => {
|
|
56
|
+
if (!isObject(transform)) {
|
|
57
|
+
add(`${label}: transform ${position} must be an object`, 'transform', position);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (!isNonEmptyString(transform.key)) {
|
|
61
|
+
add(`${label}: transform ${position} must have a non-empty string key`, 'transform', position, 'key');
|
|
62
|
+
}
|
|
63
|
+
else if (UNSAFE_KEYS.has(transform.key)) {
|
|
64
|
+
add(`${label} uses the forbidden transform key "${transform.key}"`, 'transform', position, 'key');
|
|
65
|
+
}
|
|
66
|
+
checkFormula(transform.formula, options, message => add(`${label}: transform ${position} ${message}`, 'transform', position, 'formula'));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (rule.when !== undefined) {
|
|
71
|
+
if (!isObject(rule.when)) {
|
|
72
|
+
add(`${label}: when must be an object`, 'when');
|
|
73
|
+
}
|
|
74
|
+
else if (options.deep && containsKey(rule.when, '$where')) {
|
|
75
|
+
add(`${label}: the $where operator is not supported`, 'when');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (!isObject(rule.produce)) {
|
|
79
|
+
add(`${label} must have a produce object`, 'produce');
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
checkFormula(rule.produce.formula, options, message => add(`${label}: produce ${message}`, 'produce', 'formula'));
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
return issues;
|
|
86
|
+
}
|
|
87
|
+
function checkFormula(formula, options, report) {
|
|
88
|
+
if (typeof formula !== 'string') {
|
|
89
|
+
report('formula must be a string');
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (!options.deep) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
(0, formula_util_1.parseFormula)(formula);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
const { message, position } = (error ?? {});
|
|
100
|
+
const where = typeof position === 'number' ? ` at position ${position}` : '';
|
|
101
|
+
report(`formula is invalid${where}: ${String(message)}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function containsKey(value, key, seen = new Set()) {
|
|
105
|
+
if (value === null || typeof value !== 'object' || seen.has(value)) {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
seen.add(value);
|
|
109
|
+
if (!Array.isArray(value) &&
|
|
110
|
+
Object.prototype.hasOwnProperty.call(value, key)) {
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
return Object.values(value).some(item => containsKey(item, key, seen));
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Checks a rule set without running it: structure, ids, forbidden keys,
|
|
117
|
+
* formula syntax and unsupported operators. Use it when rules are created or
|
|
118
|
+
* edited (for example before saving them). Returns an empty array when the
|
|
119
|
+
* rules are valid.
|
|
120
|
+
*/
|
|
121
|
+
function validateRules(rules) {
|
|
122
|
+
return checkRules(rules, { deep: true });
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Standard Schema for a rule set, backed by `validateRules()`. Works with any
|
|
126
|
+
* library that accepts a Standard Schema.
|
|
127
|
+
*/
|
|
128
|
+
exports.rulesSchema = {
|
|
129
|
+
'~standard': {
|
|
130
|
+
version: 1,
|
|
131
|
+
vendor: 'nestjs-business-engine',
|
|
132
|
+
validate: value => {
|
|
133
|
+
const issues = validateRules(value);
|
|
134
|
+
return issues.length > 0 ? { issues } : { value: value };
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
};
|
package/index.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './dist/index.js';
|
package/index.mjs
ADDED
package/llms.txt
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# nestjs-business-engine
|
|
2
|
+
|
|
3
|
+
> Business rules engine for NestJS. Rules are plain data: each rule transforms a payload with JSONata, tests a MongoDB-style condition (sift) and produces a result with a JSONata formula. Node.js >= 22.12, NestJS 11 or 12, CommonJS and ESM.
|
|
4
|
+
|
|
5
|
+
Install: `npm install nestjs-business-engine` (peer dependencies: @nestjs/common, reflect-metadata).
|
|
6
|
+
|
|
7
|
+
## Setup
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { Module, Injectable } from '@nestjs/common';
|
|
11
|
+
import { BusinessEngineModule, BusinessEngineService, Rule } from 'nestjs-business-engine';
|
|
12
|
+
|
|
13
|
+
@Module({ imports: [BusinessEngineModule.forRoot({ isGlobal: true, timeout: 100 })] })
|
|
14
|
+
export class AppModule {}
|
|
15
|
+
|
|
16
|
+
const rules: Rule[] = [
|
|
17
|
+
{
|
|
18
|
+
id: 'vip-discount', // unique, results are keyed by it
|
|
19
|
+
group: 'pricing', // optional, filter with { group }
|
|
20
|
+
transform: [{ key: 'total', formula: '$sum(items.(price * quantity))' }], // optional, JSONata, in order
|
|
21
|
+
when: { total: { $gte: 100 }, 'customer.tier': 'vip' }, // optional, MongoDB query, {} = always
|
|
22
|
+
produce: { default: 0, formula: '$round(total * 0.1, 2)' }, // JSONata; default when no match
|
|
23
|
+
},
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
@Injectable()
|
|
27
|
+
export class CheckoutService {
|
|
28
|
+
constructor(private readonly engine: BusinessEngineService) {}
|
|
29
|
+
quote(order: Record<string, unknown>) {
|
|
30
|
+
return this.engine.run(rules, order); // { executionId, results: { 'vip-discount': 12.5 }, matched, errors }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## BusinessEngineService
|
|
36
|
+
|
|
37
|
+
- `run<TResults>(rules: readonly Rule[], payload: Record<string, unknown>, options?: RunOptions): Promise<RunResult<TResults>>`
|
|
38
|
+
- `validate(rules: unknown): RuleIssue[]` (same as `validateRules`)
|
|
39
|
+
- Can be created without Nest: `new BusinessEngineService(options?)`.
|
|
40
|
+
|
|
41
|
+
Rule fields: `id: string`, `group?: string`, `enabled?: boolean` (false skips), `transform?: { key, formula }[]`, `when?: object`, `produce: { formula: string; default?: unknown }`. Each rule runs on its own copy of the payload; rules never see each other's results. The result is `default` when the condition fails or the formula yields undefined.
|
|
42
|
+
|
|
43
|
+
RunOptions:
|
|
44
|
+
- `group?: string | string[]` run only these groups
|
|
45
|
+
- `bindings?: Record<string, unknown>` variables and (async) functions available in formulas as `$name`; merged over module bindings
|
|
46
|
+
- `timeout?: number` max ms per formula; failure code `TIMEOUT` (0 = no limit; a non-number or negative value makes run() throw TypeError)
|
|
47
|
+
- `continueOnError?: boolean` failing rules keep their default and are listed in `errors`
|
|
48
|
+
- `debug?: boolean` return a step-by-step trace in `debug` (contains payload values)
|
|
49
|
+
|
|
50
|
+
RunResult: `executionId: string` (UUID), `results: TResults`, `matched: string[]` (ids whose condition matched), `errors: RuleEvaluationError[]`, `debug?: DebugStep[]` (`{ message, context }`).
|
|
51
|
+
|
|
52
|
+
## Module
|
|
53
|
+
|
|
54
|
+
- `BusinessEngineModule` (defaults), `BusinessEngineModule.forRoot(options)`, `BusinessEngineModule.forRootAsync({ imports?, inject?, useFactory, isGlobal? })`.
|
|
55
|
+
- Options: `isGlobal?`, `bindings?`, `timeout?`, `continueOnError?`, `cacheSize?` (compiled formula LRU size, default 500, 0 disables).
|
|
56
|
+
- Token: `BUSINESS_ENGINE_OPTIONS`.
|
|
57
|
+
|
|
58
|
+
## Validation
|
|
59
|
+
|
|
60
|
+
- `validateRules(rules: unknown): RuleIssue[]` with `RuleIssue = { message: string; path: (string | number)[]; ruleId?: string }`. Checks structure, missing/duplicate ids, forbidden keys (`__proto__`, `constructor`, `prototype`), JSONata syntax, unsafe formulas (redefining `$clone`, using `$eval`) and `$where`. Empty array = valid.
|
|
61
|
+
- `rulesSchema`: Standard Schema v1 (`rulesSchema['~standard'].validate(value)`) backed by validateRules.
|
|
62
|
+
- `run()` checks structure up front and throws `InvalidRuleError`.
|
|
63
|
+
|
|
64
|
+
## Errors (all extend BusinessEngineError, which extends Error)
|
|
65
|
+
|
|
66
|
+
- `InvalidRuleError`: `issues: RuleIssue[]`, `ruleId?`. Thrown before any rule runs.
|
|
67
|
+
- `RuleEvaluationError`: `ruleId`, `stage: 'transform' | 'when' | 'produce'`, `key?` (transform key), `code?` (JSONata code such as `S0207`, `T1006`, or `TIMEOUT` / `UNSAFE_FORMULA`), `position?`, `cause`.
|
|
68
|
+
- `FormulaTimeoutError`: `code: 'TIMEOUT'`, `timeout`. The cause of a RuleEvaluationError on timeout.
|
|
69
|
+
|
|
70
|
+
## Security notes
|
|
71
|
+
|
|
72
|
+
- sift `$where` is disabled (it would run JavaScript). JSONata cannot reach Node.js APIs.
|
|
73
|
+
- Formulas cannot redefine `$clone` or use `$eval` (code `UNSAFE_FORMULA`): the transform operator would otherwise modify the caller's payload and bindings.
|
|
74
|
+
- Set `timeout` when rules come from users or a database: recursive JSONata formulas can run forever. The timeout is checked between formula steps and cannot interrupt one slow operation (catastrophic regex in a formula or a sift `$regex` condition, `$sort` of a huge array); for untrusted rule authors also run the engine in a worker or process you can stop.
|
|
75
|
+
- Bindings are trusted application code.
|
|
76
|
+
|
|
77
|
+
## Links
|
|
78
|
+
|
|
79
|
+
- README: https://github.com/pedrosodre/nestjs-business-engine#readme
|
|
80
|
+
- JSONata: https://docs.jsonata.org
|
|
81
|
+
- Query operators (sift): https://github.com/crcn/sift.js
|
|
82
|
+
- Issues: https://github.com/pedrosodre/nestjs-business-engine/issues
|
package/package.json
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "nestjs-business-engine",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Business rules engine for NestJS: transform payloads with JSONata, match them with MongoDB-style conditions and produce results from rules stored as data.",
|
|
5
|
+
"author": "Pedro Sodré",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/pedrosodre/nestjs-business-engine#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/pedrosodre/nestjs-business-engine.git"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/pedrosodre/nestjs-business-engine/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"nestjs",
|
|
17
|
+
"nest",
|
|
18
|
+
"rules",
|
|
19
|
+
"rules-engine",
|
|
20
|
+
"business-rules",
|
|
21
|
+
"decision-engine",
|
|
22
|
+
"jsonata",
|
|
23
|
+
"mongodb-query",
|
|
24
|
+
"sift",
|
|
25
|
+
"pricing",
|
|
26
|
+
"standard-schema"
|
|
27
|
+
],
|
|
28
|
+
"type": "commonjs",
|
|
29
|
+
"main": "./dist/index.js",
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"import": {
|
|
34
|
+
"types": "./index.d.mts",
|
|
35
|
+
"default": "./index.mjs"
|
|
36
|
+
},
|
|
37
|
+
"require": {
|
|
38
|
+
"types": "./dist/index.d.ts",
|
|
39
|
+
"default": "./dist/index.js"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"./package.json": "./package.json"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"dist",
|
|
46
|
+
"index.mjs",
|
|
47
|
+
"index.d.mts",
|
|
48
|
+
"llms.txt"
|
|
49
|
+
],
|
|
50
|
+
"sideEffects": false,
|
|
51
|
+
"engines": {
|
|
52
|
+
"node": ">=22.12.0"
|
|
53
|
+
},
|
|
54
|
+
"publishConfig": {
|
|
55
|
+
"access": "public",
|
|
56
|
+
"provenance": true
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
|
|
60
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
61
|
+
"lint": "eslint .",
|
|
62
|
+
"format": "prettier --write .",
|
|
63
|
+
"format:check": "prettier --check .",
|
|
64
|
+
"test": "jest --runInBand",
|
|
65
|
+
"test:watch": "jest --watch",
|
|
66
|
+
"test:coverage": "jest --runInBand --coverage",
|
|
67
|
+
"check": "npm run typecheck && npm run lint && npm run format:check && npm run test:coverage && npm run build && npm run api:check && npm run lint:package && npm run test:compat",
|
|
68
|
+
"prepare": "husky",
|
|
69
|
+
"test:compat": "node tests/compat/runtime.cjs && node tests/compat/runtime.mjs",
|
|
70
|
+
"lint:package": "publint --strict && attw --pack .",
|
|
71
|
+
"api:check": "api-extractor run",
|
|
72
|
+
"api:update": "api-extractor run --local"
|
|
73
|
+
},
|
|
74
|
+
"dependencies": {
|
|
75
|
+
"jsonata": "2.2.2",
|
|
76
|
+
"sift": "17.1.4"
|
|
77
|
+
},
|
|
78
|
+
"devDependencies": {
|
|
79
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
80
|
+
"@commitlint/cli": "20.5.3",
|
|
81
|
+
"@commitlint/config-conventional": "20.5.3",
|
|
82
|
+
"@eslint/js": "9.39.5",
|
|
83
|
+
"@microsoft/api-extractor": "7.60.1",
|
|
84
|
+
"@nestjs/common": "11.2.8",
|
|
85
|
+
"@nestjs/core": "11.2.8",
|
|
86
|
+
"@nestjs/testing": "11.2.8",
|
|
87
|
+
"@types/jest": "29.5.14",
|
|
88
|
+
"@types/node": "22.20.5",
|
|
89
|
+
"eslint": "9.39.5",
|
|
90
|
+
"eslint-config-prettier": "10.1.8",
|
|
91
|
+
"husky": "9.1.7",
|
|
92
|
+
"jest": "29.7.0",
|
|
93
|
+
"lint-staged": "16.4.0",
|
|
94
|
+
"prettier": "3.9.10",
|
|
95
|
+
"publint": "0.3.25",
|
|
96
|
+
"reflect-metadata": "0.2.2",
|
|
97
|
+
"rxjs": "7.8.2",
|
|
98
|
+
"semantic-release": "25.0.9",
|
|
99
|
+
"ts-jest": "29.4.15",
|
|
100
|
+
"typescript": "5.9.3",
|
|
101
|
+
"typescript-eslint": "8.72.1"
|
|
102
|
+
},
|
|
103
|
+
"peerDependencies": {
|
|
104
|
+
"@nestjs/common": "^11.0.0 || ^12.0.0",
|
|
105
|
+
"reflect-metadata": "^0.1.12 || ^0.2.0"
|
|
106
|
+
},
|
|
107
|
+
"jest": {
|
|
108
|
+
"collectCoverageFrom": [
|
|
109
|
+
"./lib/**/*.ts"
|
|
110
|
+
],
|
|
111
|
+
"moduleFileExtensions": [
|
|
112
|
+
"js",
|
|
113
|
+
"json",
|
|
114
|
+
"ts"
|
|
115
|
+
],
|
|
116
|
+
"rootDir": ".",
|
|
117
|
+
"roots": [
|
|
118
|
+
"<rootDir>/tests"
|
|
119
|
+
],
|
|
120
|
+
"testEnvironment": "node",
|
|
121
|
+
"testRegex": ".spec.ts$",
|
|
122
|
+
"transform": {
|
|
123
|
+
"^.+\\.(t|j)s$": "ts-jest"
|
|
124
|
+
},
|
|
125
|
+
"coverageThreshold": {
|
|
126
|
+
"global": {
|
|
127
|
+
"statements": 95,
|
|
128
|
+
"branches": 80,
|
|
129
|
+
"functions": 95,
|
|
130
|
+
"lines": 95
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
"lint-staged": {
|
|
135
|
+
"*.{ts,mts,cts,mjs,cjs,js}": [
|
|
136
|
+
"eslint --fix",
|
|
137
|
+
"prettier --write"
|
|
138
|
+
],
|
|
139
|
+
"*.{json,md,yml,yaml}": "prettier --write"
|
|
140
|
+
}
|
|
141
|
+
}
|