@turingcode/cli 0.2.0 → 0.2.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.
- package/README.md +51 -24
- package/dist/cli/create-cli.js +1 -1
- package/dist/core/query.js +226 -0
- package/dist/features/contract/command.js +28 -9
- package/dist/features/contract/describe.js +11 -18
- package/dist/features/contract/diagnostics.js +1 -0
- package/dist/features/contract/load.js +74 -86
- package/dist/features/contract/model.js +8 -10
- package/dist/features/contract/rules.js +273 -172
- package/dist/features/table/check.js +130 -84
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -20,6 +20,9 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
|
|
|
20
20
|
|
|
21
21
|
## Contract format
|
|
22
22
|
|
|
23
|
+
Every check on cell values is a MongoDB-style query (run with [sift](https://github.com/crcn/sift.js),
|
|
24
|
+
plus the operators below for references, exact numbers and checks across rows).
|
|
25
|
+
|
|
23
26
|
```json
|
|
24
27
|
{
|
|
25
28
|
"name": "shop.orders",
|
|
@@ -32,15 +35,17 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
|
|
|
32
35
|
"name": "Orders",
|
|
33
36
|
"primary_key": "Order_ID",
|
|
34
37
|
"columns": [
|
|
35
|
-
{ "name": "Order_ID", "
|
|
36
|
-
{ "name": "Customer", "required": true, "
|
|
37
|
-
{ "name": "Status", "
|
|
38
|
-
{ "name": "Total", "type": "number", "
|
|
38
|
+
{ "name": "Order_ID", "match": { "$regex": "^O-[0-9]+$" } },
|
|
39
|
+
{ "name": "Customer", "required": true, "match": { "$ref": "customers:Customers.Customer_ID" } },
|
|
40
|
+
{ "name": "Status", "required": true, "match": { "$in": ["open", "paid", "shipped"] } },
|
|
41
|
+
{ "name": "Total", "type": "number", "match": { "$gte": 0 } },
|
|
39
42
|
{ "name": "Tracking" },
|
|
40
|
-
{ "name": "Items", "type": "list", "
|
|
43
|
+
{ "name": "Items", "type": "list", "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } } }
|
|
41
44
|
],
|
|
42
45
|
"rules": [
|
|
43
|
-
{ "
|
|
46
|
+
{ "when": { "Status": "shipped" }, "require": { "Tracking": { "$ne": null } } },
|
|
47
|
+
{ "require": { "$calc": "Total >= 0" } },
|
|
48
|
+
{ "count": { "$gte": 1 } }
|
|
44
49
|
]
|
|
45
50
|
}
|
|
46
51
|
]
|
|
@@ -53,7 +58,7 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
|
|
|
53
58
|
| --- | --- | --- |
|
|
54
59
|
| `name`, `version`, `description` | | Shown in output and in `describe`. |
|
|
55
60
|
| `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). |
|
|
56
|
-
| `missing_values` | `[""]` | Cell texts that count as empty. |
|
|
61
|
+
| `missing_values` | `[""]` | Cell texts that count as empty (`null` in queries). |
|
|
57
62
|
| `allow_extra_tables` | `false` | Allow tables the contract does not declare. |
|
|
58
63
|
| `depends_on` | | `alias -> contract file`; its tables are passed with `--dep alias=<file>`. |
|
|
59
64
|
|
|
@@ -73,24 +78,46 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
|
|
|
73
78
|
| --- | --- |
|
|
74
79
|
| `type` | `string` (default), `integer`, `number` (exact decimal), `boolean` (`true`/`false`), `date` (`YYYY-MM-DD`), `list`. |
|
|
75
80
|
| `required` | The cell must not be empty. |
|
|
76
|
-
| `unique` | No two rows share the value. |
|
|
77
|
-
| `pattern` | Regex the whole value must match (each item for lists). |
|
|
78
|
-
| `enum` | Allowed values (each item for lists). |
|
|
79
|
-
| `minimum`, `maximum` | Bounds for `integer`/`number`, compared exactly. |
|
|
80
|
-
| `min_length`, `max_length` | Characters for strings, items for lists. |
|
|
81
81
|
| `separator` | Item separator for lists (default `,`). |
|
|
82
|
-
| `
|
|
82
|
+
| `match` | A condition every filled cell must meet, e.g. `{"$in": ["a", "b"]}`. Empty cells are not tested. |
|
|
83
83
|
| `description` | Shown by `describe`. |
|
|
84
84
|
|
|
85
|
-
**
|
|
86
|
-
`{"Column": ["a", "b"]}`, which limits the rule to matching rows) and `severity` (`error`, the default,
|
|
87
|
-
or `warning`).
|
|
85
|
+
**Rule**: exactly one of `require` and `count`.
|
|
88
86
|
|
|
89
|
-
|
|
|
90
|
-
| --- | --- |
|
|
91
|
-
| `
|
|
92
|
-
| `
|
|
93
|
-
| `
|
|
94
|
-
| `
|
|
95
|
-
| `
|
|
96
|
-
| `
|
|
87
|
+
| Field | Meaning |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| `require` | A row query every applicable row must match. |
|
|
90
|
+
| `count` | A condition on the number of applicable rows, e.g. `{"$gte": 1, "$lte": 10}`. |
|
|
91
|
+
| `when` | A row query: the rule applies only to matching rows. |
|
|
92
|
+
| `on` | `Table` or `alias:Table` whose rows the rule tests (default: the table it is in), e.g. "every BOM part has a stock row". |
|
|
93
|
+
| `id`, `description` | Shown in findings; `description` replaces the generated `expected` text. |
|
|
94
|
+
| `severity` | `error` (default) or `warning`. |
|
|
95
|
+
|
|
96
|
+
### Queries
|
|
97
|
+
|
|
98
|
+
A **row query** maps column names to conditions, e.g. `{"Status": "open", "Qty": {"$gte": 1}}`, and may use
|
|
99
|
+
`$or`, `$and`, `$nor`, `$calc` and `$unique`. A **condition** (a column's `match`, or a column in a row query)
|
|
100
|
+
is a value or an operator object. As in MongoDB:
|
|
101
|
+
|
|
102
|
+
- Cells are text; boolean columns are `true`/`false`; an empty cell is `null` (`{"Col": null}` = empty,
|
|
103
|
+
`{"Col": {"$ne": null}}` = filled).
|
|
104
|
+
- A list cell is an array of its items, and an operator matches when **any** item does
|
|
105
|
+
(`{"Tags": "x"}` = contains `x`). Use `$every` to require all items.
|
|
106
|
+
|
|
107
|
+
| Operator | Meaning |
|
|
108
|
+
| --- | --- |
|
|
109
|
+
| `$eq` `$ne` `$in` `$nin` | Equal / not equal / one of / none of (text, `true`/`false` or `null`). |
|
|
110
|
+
| `$regex` `$options` | Regex search; anchor with `^...$` to match the whole value. |
|
|
111
|
+
| `$gt` `$gte` `$lt` `$lte` | Exact number comparison (`0.1 + 0.2` is `0.3`); text never matches. |
|
|
112
|
+
| `$not` | The condition does not hold. |
|
|
113
|
+
| `$or` `$and` `$nor` | Combine conditions; allowed in a column's condition too. |
|
|
114
|
+
| `$ref` | The value exists in `Table.Column` or `alias:Table.Column`. |
|
|
115
|
+
| `$every` | Every list item meets the condition, e.g. `{"$every": {"$ref": "Lines.Line_ID"}}`. |
|
|
116
|
+
| `$length` | The length (characters, or items of a list) meets a condition, e.g. `{"$length": {"$lte": 3}}`. |
|
|
117
|
+
| `$unique` | `true`: no two rows share the value. In a row query, `["A", "B"]`: no two rows share the combination. Empty cells are skipped. |
|
|
118
|
+
| `$mentioned` | The value appears as a word in `Table.Column` (or a list of them), or with `"*"` anywhere in the document outside its own table. |
|
|
119
|
+
| `$calc` | Row query only: exact arithmetic over number columns, `"Qty * Price == Total"`, or `{"expr": ..., "tolerance": 0.01}`; ops `<` `<=` `==` `!=` `>=` `>`. Skipped when a value is empty. |
|
|
120
|
+
|
|
121
|
+
Other operators (`$where`, `$exists`, ...) are rejected by `contract check`. Each top-level operator is
|
|
122
|
+
checked and reported on its own, with a specific code (`$ref` → `UNKNOWN_REF`, `$regex` → `PATTERN`,
|
|
123
|
+
`$gte` → `OUT_OF_RANGE`, `{"$ne": null}` → `REQUIRED_IF`, ...); a failing `$or` reports `MATCH`.
|
package/dist/cli/create-cli.js
CHANGED
|
@@ -15,7 +15,7 @@ export function createCli(args) {
|
|
|
15
15
|
.usage("Usage: $0 <command> [options]; $0 <command> --help for each command's usage")
|
|
16
16
|
.epilogue([
|
|
17
17
|
"Checks tables written in Markdown or CSV against a contract: a JSON file that declares the tables,",
|
|
18
|
-
"their columns,
|
|
18
|
+
"their columns, and checks on values and rows as MongoDB-style queries. Contract format: $0 contract --help.",
|
|
19
19
|
"Typical use: `contract describe` shows the tables to write; write them; `table check` until PASS.",
|
|
20
20
|
].join("\n"))
|
|
21
21
|
.command(commands)
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import sift from "sift";
|
|
2
|
+
import { Fraction } from "./exact/fraction.js";
|
|
3
|
+
const { $and, $eq, $in, $ne, $nin, $nor, $not, $options, $or, $regex, createEqualsOperation, createQueryTester } = sift;
|
|
4
|
+
/** Operators on one column's value. */
|
|
5
|
+
export const FIELD_OPERATORS = [
|
|
6
|
+
"$eq", "$ne", "$in", "$nin", "$regex", "$options", "$not", "$gt", "$gte", "$lt", "$lte",
|
|
7
|
+
"$ref", "$every", "$length", "$unique", "$mentioned",
|
|
8
|
+
];
|
|
9
|
+
/** Operators on a whole row (besides column names). */
|
|
10
|
+
export const ROW_OPERATORS = ["$or", "$and", "$nor", "$calc", "$unique"];
|
|
11
|
+
/** The placeholder column that `$every` and `$length` sub-queries test. */
|
|
12
|
+
const ITEM = "_";
|
|
13
|
+
const LOGICAL = new Set(["$or", "$and", "$nor"]);
|
|
14
|
+
const NUMERIC = new Set(["$gt", "$gte", "$lt", "$lte"]);
|
|
15
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
16
|
+
const isScalar = (v) => typeof v === "string" || typeof v === "boolean" || v === null;
|
|
17
|
+
const isStrings = (v) => Array.isArray(v) && v.length > 0 && v.every(x => typeof x === "string");
|
|
18
|
+
/**
|
|
19
|
+
* Checks a row query and rewrites it for sift: a column's `$or`/`$and`/`$nor`
|
|
20
|
+
* is lifted to the row (sift allows them only there), and `$every`/`$length`
|
|
21
|
+
* sub-queries are prepared too.
|
|
22
|
+
*
|
|
23
|
+
* @param {unknown} query - The query from the contract.
|
|
24
|
+
* @returns {PreparedQuery} The rewritten query, what it uses and its problems.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* prepareQuery({ Kind: { $in: ["a", "b"] }, Qty: { $gte: 1 } }).fields; // ["Kind", "Qty"]
|
|
28
|
+
*/
|
|
29
|
+
export function prepareQuery(query) {
|
|
30
|
+
const p = { query: {}, fields: [], refs: [], mentions: [], calcs: [], problems: [] };
|
|
31
|
+
const fields = new Set();
|
|
32
|
+
const problem = (at, message) => p.problems.push(`${at}: ${message}`);
|
|
33
|
+
/** Field-level operators of one column (no logical operators). */
|
|
34
|
+
const ops = (cond, at) => {
|
|
35
|
+
const out = {};
|
|
36
|
+
for (const [op, arg] of Object.entries(cond)) {
|
|
37
|
+
const here = `${at}.${op}`;
|
|
38
|
+
if (!FIELD_OPERATORS.includes(op)) {
|
|
39
|
+
problem(here, `unknown operator; use ${FIELD_OPERATORS.join(", ")}`);
|
|
40
|
+
}
|
|
41
|
+
else if (op === "$eq" || op === "$ne") {
|
|
42
|
+
if (!isScalar(arg))
|
|
43
|
+
problem(here, "must be a string, true, false or null (cells are text)");
|
|
44
|
+
out[op] = arg;
|
|
45
|
+
}
|
|
46
|
+
else if (op === "$in" || op === "$nin") {
|
|
47
|
+
if (!Array.isArray(arg) || !arg.length || !arg.every(isScalar))
|
|
48
|
+
problem(here, "must be a non-empty list of strings, true, false or null");
|
|
49
|
+
out[op] = arg;
|
|
50
|
+
}
|
|
51
|
+
else if (NUMERIC.has(op)) {
|
|
52
|
+
if (!(typeof arg === "number" || typeof arg === "string") || !Fraction.parseDecimal(String(arg)))
|
|
53
|
+
problem(here, "must be a number");
|
|
54
|
+
out[op] = arg;
|
|
55
|
+
}
|
|
56
|
+
else if (op === "$regex") {
|
|
57
|
+
if (typeof arg !== "string")
|
|
58
|
+
problem(here, "must be a string");
|
|
59
|
+
out[op] = arg;
|
|
60
|
+
}
|
|
61
|
+
else if (op === "$options") {
|
|
62
|
+
if (typeof arg !== "string" || !/^[imsu]*$/.test(arg))
|
|
63
|
+
problem(here, "must be letters from imsu");
|
|
64
|
+
out[op] = arg;
|
|
65
|
+
}
|
|
66
|
+
else if (op === "$ref") {
|
|
67
|
+
if (typeof arg !== "string")
|
|
68
|
+
problem(here, "must be Table.Column or alias:Table.Column");
|
|
69
|
+
else
|
|
70
|
+
p.refs.push(arg);
|
|
71
|
+
out[op] = arg;
|
|
72
|
+
}
|
|
73
|
+
else if (op === "$mentioned") {
|
|
74
|
+
const targets = typeof arg === "string" ? [arg] : arg;
|
|
75
|
+
if (!isStrings(targets))
|
|
76
|
+
problem(here, "must be \"*\", Table.Column, or a list of them");
|
|
77
|
+
else
|
|
78
|
+
p.mentions.push(...targets);
|
|
79
|
+
out[op] = targets;
|
|
80
|
+
}
|
|
81
|
+
else if (op === "$unique") {
|
|
82
|
+
if (arg !== true)
|
|
83
|
+
problem(here, "must be true");
|
|
84
|
+
out[op] = arg;
|
|
85
|
+
}
|
|
86
|
+
else if (op === "$not") {
|
|
87
|
+
if (!isObject(arg))
|
|
88
|
+
problem(here, "must be an operator object");
|
|
89
|
+
else
|
|
90
|
+
out[op] = ops(arg, here);
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
// $every, $length: a query on each item / on the length, tested on the placeholder column.
|
|
94
|
+
out[op] = field(ITEM, arg, here);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
};
|
|
99
|
+
/** One column's condition as a row query; logical operators are lifted. */
|
|
100
|
+
const field = (name, cond, at) => {
|
|
101
|
+
if (name !== ITEM)
|
|
102
|
+
fields.add(name);
|
|
103
|
+
if (isScalar(cond))
|
|
104
|
+
return { [name]: cond };
|
|
105
|
+
if (!isObject(cond)) {
|
|
106
|
+
problem(at, Array.isArray(cond) ? "use {\"$in\": [...]} for one of several values" : "must be a string, true, false, null or an operator object");
|
|
107
|
+
return {};
|
|
108
|
+
}
|
|
109
|
+
const parts = [];
|
|
110
|
+
const plain = {};
|
|
111
|
+
for (const [op, arg] of Object.entries(cond)) {
|
|
112
|
+
if (LOGICAL.has(op)) {
|
|
113
|
+
if (!Array.isArray(arg) || !arg.length)
|
|
114
|
+
problem(`${at}.${op}`, "must be a non-empty list");
|
|
115
|
+
else
|
|
116
|
+
parts.push({ [op]: arg.map((c, i) => field(name, c, `${at}.${op}[${i}]`)) });
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
plain[op] = cond[op];
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (Object.keys(plain).length)
|
|
123
|
+
parts.unshift({ [name]: ops(plain, at) });
|
|
124
|
+
return parts.length === 1 ? parts[0] : { $and: parts };
|
|
125
|
+
};
|
|
126
|
+
/** A row query. */
|
|
127
|
+
const row = (q, at) => {
|
|
128
|
+
if (!isObject(q)) {
|
|
129
|
+
problem(at, "must be an object");
|
|
130
|
+
return {};
|
|
131
|
+
}
|
|
132
|
+
const parts = [];
|
|
133
|
+
for (const [key, v] of Object.entries(q)) {
|
|
134
|
+
const here = `${at}.${key}`;
|
|
135
|
+
if (LOGICAL.has(key)) {
|
|
136
|
+
if (!Array.isArray(v) || !v.length)
|
|
137
|
+
problem(here, "must be a non-empty list of queries");
|
|
138
|
+
else
|
|
139
|
+
parts.push({ [key]: v.map((x, i) => row(x, `${here}[${i}]`)) });
|
|
140
|
+
}
|
|
141
|
+
else if (key === "$calc") {
|
|
142
|
+
p.calcs.push(v);
|
|
143
|
+
parts.push({ $calc: v });
|
|
144
|
+
}
|
|
145
|
+
else if (key === "$unique") {
|
|
146
|
+
if (!isStrings(v))
|
|
147
|
+
problem(here, "must be a list of column names");
|
|
148
|
+
else
|
|
149
|
+
v.forEach(f => fields.add(f));
|
|
150
|
+
parts.push({ $unique: v });
|
|
151
|
+
}
|
|
152
|
+
else if (key.startsWith("$")) {
|
|
153
|
+
problem(here, `not a row operator; use ${ROW_OPERATORS.join(", ")} or a column name`);
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
parts.push(field(key, v, here));
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return parts.length === 0 ? {} : parts.length === 1 ? parts[0] : { $and: parts };
|
|
160
|
+
};
|
|
161
|
+
p.query = row(query, "$");
|
|
162
|
+
p.fields = [...fields];
|
|
163
|
+
return p;
|
|
164
|
+
}
|
|
165
|
+
/** The whole list when sift passes one of its items (it walks arrays item by item), else the value. */
|
|
166
|
+
const whole = (v, key, owner) => (typeof key === "number" && Array.isArray(owner) ? owner : v);
|
|
167
|
+
/** Exact comparison of a number cell with a bound; anything that is not a number does not match. */
|
|
168
|
+
const numeric = (holds) => (bound, owner, options) => {
|
|
169
|
+
const b = Fraction.parseDecimal(String(bound));
|
|
170
|
+
return createEqualsOperation((v) => {
|
|
171
|
+
const n = typeof v === "string" ? Fraction.parseDecimal(v) : null;
|
|
172
|
+
return !!n && holds(n.cmp(b));
|
|
173
|
+
}, owner, options);
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Compiles a prepared query into a row tester. `$unique` remembers the values
|
|
177
|
+
* it has seen, so run one tester over the rows in order.
|
|
178
|
+
*
|
|
179
|
+
* @param {Query} query - `prepareQuery(...).query` with no problems.
|
|
180
|
+
* @param {QueryHooks} hooks - `$ref`, `$mentioned` and `$calc`.
|
|
181
|
+
* @returns {(doc: Doc) => boolean} Whether a row matches.
|
|
182
|
+
* @throws {Error} When sift rejects the query, e.g. an invalid `$regex`.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* compileQuery(prepareQuery({ Qty: { $gte: 1 } }).query, hooks)({ Qty: "2" }); // true
|
|
186
|
+
*/
|
|
187
|
+
export function compileQuery(query, hooks) {
|
|
188
|
+
const eq = (test) => (owner, options) => createEqualsOperation(test, owner, options);
|
|
189
|
+
const operations = {
|
|
190
|
+
$and, $eq, $in, $ne, $nin, $nor, $not, $options, $or, $regex,
|
|
191
|
+
$gt: numeric(c => c > 0), $gte: numeric(c => c >= 0), $lt: numeric(c => c < 0), $lte: numeric(c => c <= 0),
|
|
192
|
+
$ref: (ref, o, opt) => eq(v => typeof v === "string" && hooks.ref(ref, v))(o, opt),
|
|
193
|
+
$mentioned: (targets, o, opt) => eq(v => typeof v === "string" && hooks.mentioned(targets, v))(o, opt),
|
|
194
|
+
$calc: (param, o, opt) => eq(v => hooks.calc(param, v))(o, opt),
|
|
195
|
+
$every: (q, o, opt) => {
|
|
196
|
+
const test = compileQuery(q, hooks);
|
|
197
|
+
return eq((v, k, own) => {
|
|
198
|
+
const w = whole(v, k, own);
|
|
199
|
+
return (Array.isArray(w) ? w : w === null ? [] : [w]).every(x => test({ [ITEM]: x }));
|
|
200
|
+
})(o, opt);
|
|
201
|
+
},
|
|
202
|
+
$length: (q, o, opt) => {
|
|
203
|
+
const test = compileQuery(q, hooks);
|
|
204
|
+
return eq((v, k, own) => {
|
|
205
|
+
const w = whole(v, k, own);
|
|
206
|
+
const n = Array.isArray(w) ? w.length : typeof w === "string" ? [...w].length : null;
|
|
207
|
+
return n !== null && test({ [ITEM]: String(n) });
|
|
208
|
+
})(o, opt);
|
|
209
|
+
},
|
|
210
|
+
// ponytail: remembers every value it has seen; fine for one pass over a table's rows.
|
|
211
|
+
$unique: (param, o, opt) => {
|
|
212
|
+
const seen = new Set();
|
|
213
|
+
return eq((v, k, own) => {
|
|
214
|
+
const values = param === true ? [whole(v, k, own)] : param.map(c => v[c]);
|
|
215
|
+
if (values.some(x => x === null || x === undefined))
|
|
216
|
+
return true;
|
|
217
|
+
const key = JSON.stringify(values);
|
|
218
|
+
if (seen.has(key))
|
|
219
|
+
return false;
|
|
220
|
+
seen.add(key);
|
|
221
|
+
return true;
|
|
222
|
+
})(o, opt);
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
return createQueryTester(query, { operations });
|
|
226
|
+
}
|
|
@@ -17,18 +17,37 @@ const FORMAT = `Contract JSON (only "tables" and each table's and column's "name
|
|
|
17
17
|
"columns": [{
|
|
18
18
|
"name": "Total",
|
|
19
19
|
"type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
|
|
20
|
-
"required": false,
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"references": "Table.Column" // or "alias:Table.Column" of a dependency
|
|
20
|
+
"required": false,
|
|
21
|
+
"separator": ",", // list items
|
|
22
|
+
"match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query)
|
|
24
23
|
}],
|
|
25
|
-
"rules": [{
|
|
24
|
+
"rules": [{ // exactly one of require, count
|
|
25
|
+
"id": "...", "description": "...", "severity": "error", // or "warning"
|
|
26
|
+
"on": "Table", // or "alias:Table"; default: this table
|
|
27
|
+
"when": { "Status": "shipped" }, // rows the rule applies to
|
|
28
|
+
"require": { "Tracking": { "$ne": null } }, // row query each of them matches
|
|
29
|
+
"count": { "$gte": 1 } // or: condition on how many there are
|
|
30
|
+
}]
|
|
26
31
|
}]
|
|
27
32
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
33
|
+
Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
|
|
34
|
+
(an operator matches if any item does). Operators:
|
|
35
|
+
$eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
|
|
36
|
+
$gt $gte $lt $lte exact number comparison
|
|
37
|
+
$ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
|
|
38
|
+
$every {...} every list item meets the condition
|
|
39
|
+
$length {...} length (chars, or list items) meets the condition
|
|
40
|
+
$unique true no two rows share the value; in a row query ["A", "B"]: the combination
|
|
41
|
+
$mentioned "Table.Column" | [...] | "*" value appears there, or anywhere else in the document
|
|
42
|
+
$calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
|
|
43
|
+
Examples:
|
|
44
|
+
"match": { "$regex": "^O-[0-9]+$" }
|
|
45
|
+
"match": { "$in": ["open", "paid", "shipped"] }
|
|
46
|
+
"match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
|
|
47
|
+
"match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
|
|
48
|
+
{ "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
|
|
49
|
+
{ "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
|
|
50
|
+
{ "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }`;
|
|
32
51
|
const check = {
|
|
33
52
|
command: "check",
|
|
34
53
|
describe: "Validate a contract and the contracts it depends on",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { sortDiagnostics } from "./diagnostics.js";
|
|
2
2
|
import { loadContract } from "./load.js";
|
|
3
3
|
import { keyColumns } from "./model.js";
|
|
4
|
-
import {
|
|
4
|
+
import { renderCondition, renderQuery } from "./rules.js";
|
|
5
5
|
const code = (v) => `\`${String(v)}\``;
|
|
6
6
|
const list = (vs) => vs.map(code).join(", ");
|
|
7
7
|
/** Escapes a cell for a Markdown table. */
|
|
@@ -9,25 +9,19 @@ const cell = (s) => s.replace(/\|/g, "\\|");
|
|
|
9
9
|
/** The constraints of a column, in words. */
|
|
10
10
|
function constraints(col) {
|
|
11
11
|
const parts = [];
|
|
12
|
-
if (col.
|
|
13
|
-
parts.push(
|
|
14
|
-
if (col.enum)
|
|
15
|
-
parts.push(`one of ${list(col.enum)}`);
|
|
16
|
-
if (col.pattern)
|
|
17
|
-
parts.push(`matches ${code(col.pattern)}`);
|
|
18
|
-
if (col.minimum !== undefined)
|
|
19
|
-
parts.push(`>= ${col.minimum}`);
|
|
20
|
-
if (col.maximum !== undefined)
|
|
21
|
-
parts.push(`<= ${col.maximum}`);
|
|
22
|
-
if (col.min_length !== undefined || col.max_length !== undefined) {
|
|
23
|
-
parts.push(`length ${col.min_length ?? 0}..${col.max_length ?? "any"}`);
|
|
24
|
-
}
|
|
12
|
+
if (col.match)
|
|
13
|
+
parts.push(renderCondition(col.match));
|
|
25
14
|
if (col.type === "list")
|
|
26
15
|
parts.push(`items separated by ${code(col.separator ?? ",")}`);
|
|
27
|
-
if (col.references)
|
|
28
|
-
parts.push(`values of ${code(col.references)}`);
|
|
29
16
|
return parts.join("; ");
|
|
30
17
|
}
|
|
18
|
+
/** One rule in words, e.g. "When `Status` = `shipped`: `Tracking` filled." */
|
|
19
|
+
function ruleText(r) {
|
|
20
|
+
const on = r.on ? `On ${code(r.on)}: ` : "";
|
|
21
|
+
const when = r.when ? `When ${renderQuery(r.when)}: ` : "";
|
|
22
|
+
const what = r.require ? renderQuery(r.require) : `${on || when ? "the" : "The"} number of rows is ${renderCondition(r.count)}`;
|
|
23
|
+
return `${on}${when}${what}.` + (r.severity === "warning" ? " (warning)" : "") + (r.description ? ` ${r.description}` : "");
|
|
24
|
+
}
|
|
31
25
|
/** Markdown lines for one table. */
|
|
32
26
|
function tableSection(t) {
|
|
33
27
|
const key = keyColumns(t);
|
|
@@ -44,8 +38,7 @@ function tableSection(t) {
|
|
|
44
38
|
const required = col.required || key.includes(col.name) ? "yes" : "no";
|
|
45
39
|
lines.push(`| ${col.name} | ${col.type ?? "string"} | ${required} | ${cell(constraints(col))} | ${cell(col.description ?? "")} |`);
|
|
46
40
|
}
|
|
47
|
-
const rules = (t.rules ?? []).map(r => `- ${
|
|
48
|
-
+ (r.severity === "warning" ? " (warning)" : "") + (r.description ? ` ${r.description}` : ""));
|
|
41
|
+
const rules = (t.rules ?? []).map(r => `- ${ruleText(r)}`);
|
|
49
42
|
if (rules.length)
|
|
50
43
|
lines.push("", "Rules:", ...rules);
|
|
51
44
|
lines.push("");
|
|
@@ -36,6 +36,7 @@ const HINTS = {
|
|
|
36
36
|
"UNIQUE_TOGETHER": "Make the combination of values unique.",
|
|
37
37
|
"ROW_COUNT": "Add or remove rows so the count fits.",
|
|
38
38
|
"NOT_MENTIONED": "Mention the value where the rule says.",
|
|
39
|
+
"MATCH": "Correct the row so it matches the rule's query (shown in 'expected').",
|
|
39
40
|
// Inputs.
|
|
40
41
|
"MISSING_FILE": "Check the path; the file must exist and be readable.",
|
|
41
42
|
"MISSING_DEPENDENCY": "Pass the dependency's tables with --dep <alias>=<file>.",
|