@turingcode/cli 0.1.1 → 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 +123 -0
- package/dist/cli/create-cli.js +7 -1
- package/dist/core/bound-error.js +14 -0
- package/dist/{features/table/ast.js → core/exact/expression.js} +22 -14
- package/dist/{features/table → core/exact}/fraction.js +62 -0
- package/dist/core/files.js +26 -0
- package/dist/{features/table/shape.js → core/json-shape.js} +45 -40
- package/dist/core/query.js +226 -0
- package/dist/core/report.js +14 -0
- package/dist/core/tables/csv.js +95 -0
- package/dist/core/tables/markdown.js +107 -0
- package/dist/core/tables/types.js +1 -0
- package/dist/features/contract/check.js +31 -0
- package/dist/features/contract/command.js +79 -0
- package/dist/features/contract/describe.js +86 -0
- package/dist/features/contract/diagnostics.js +109 -0
- package/dist/features/contract/load.js +200 -0
- package/dist/features/contract/model.js +31 -0
- package/dist/features/contract/rules.js +298 -0
- package/dist/features/table/check.js +341 -0
- package/dist/features/table/command.js +22 -75
- package/dist/features/table/read.js +33 -0
- package/package.json +3 -2
- package/dist/features/table/contract.js +0 -487
- package/dist/features/table/contract_check.js +0 -265
- package/dist/features/table/describe.js +0 -200
- package/dist/features/table/diagnostics.js +0 -129
- package/dist/features/table/format.js +0 -75
- package/dist/features/table/primitives.js +0 -268
- package/dist/features/table/source_kinds.js +0 -41
- package/dist/features/table/table_check.js +0 -538
- package/dist/features/table/tables.js +0 -223
package/README.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# @turingcode/cli
|
|
2
|
+
|
|
3
|
+
Check Markdown or CSV tables against a **contract**: a JSON file that declares the tables, their
|
|
4
|
+
columns, value constraints, references and rules. Everything that is checked is written in the
|
|
5
|
+
contract; the checker itself knows no domain.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
npm install -g @turingcode/cli
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
| Command | What it does |
|
|
12
|
+
| --- | --- |
|
|
13
|
+
| `turingcode contract check --contract c.json` | Validates a contract and the contracts it depends on. |
|
|
14
|
+
| `turingcode contract describe --contract c.json` | Prints the tables a contract expects, as Markdown (e.g. for a prompt). |
|
|
15
|
+
| `turingcode table check --contract c.json --tables t.md [--dep alias=file]` | Checks tables against the contract. |
|
|
16
|
+
|
|
17
|
+
Output is compact text: a status line, one line per finding (the same error on several rows is one
|
|
18
|
+
line), and a fix hint per code. `--json` prints the full result. Exit codes: `0` PASS/VALID,
|
|
19
|
+
`1` FAIL/INVALID_CONTRACT, `2` bad input or missing file.
|
|
20
|
+
|
|
21
|
+
## Contract format
|
|
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
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"name": "shop.orders",
|
|
29
|
+
"version": "1.0.0",
|
|
30
|
+
"format": "markdown",
|
|
31
|
+
"missing_values": ["", "-"],
|
|
32
|
+
"depends_on": { "customers": "customers.contract.json" },
|
|
33
|
+
"tables": [
|
|
34
|
+
{
|
|
35
|
+
"name": "Orders",
|
|
36
|
+
"primary_key": "Order_ID",
|
|
37
|
+
"columns": [
|
|
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 } },
|
|
42
|
+
{ "name": "Tracking" },
|
|
43
|
+
{ "name": "Items", "type": "list", "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } } }
|
|
44
|
+
],
|
|
45
|
+
"rules": [
|
|
46
|
+
{ "when": { "Status": "shipped" }, "require": { "Tracking": { "$ne": null } } },
|
|
47
|
+
{ "require": { "$calc": "Total >= 0" } },
|
|
48
|
+
{ "count": { "$gte": 1 } }
|
|
49
|
+
]
|
|
50
|
+
}
|
|
51
|
+
]
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**Contract**: only `tables` is required.
|
|
56
|
+
|
|
57
|
+
| Field | Default | Meaning |
|
|
58
|
+
| --- | --- | --- |
|
|
59
|
+
| `name`, `version`, `description` | | Shown in output and in `describe`. |
|
|
60
|
+
| `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). |
|
|
61
|
+
| `missing_values` | `[""]` | Cell texts that count as empty (`null` in queries). |
|
|
62
|
+
| `allow_extra_tables` | `false` | Allow tables the contract does not declare. |
|
|
63
|
+
| `depends_on` | | `alias -> contract file`; its tables are passed with `--dep alias=<file>`. |
|
|
64
|
+
|
|
65
|
+
**Table**: `name` and `columns` are required.
|
|
66
|
+
|
|
67
|
+
| Field | Default | Meaning |
|
|
68
|
+
| --- | --- | --- |
|
|
69
|
+
| `required` | `true` | The table must be present. |
|
|
70
|
+
| `primary_key` | | Column or columns that identify a row: filled and unique. |
|
|
71
|
+
| `ordered` | `false` | Columns must be in the declared order. |
|
|
72
|
+
| `allow_extra_columns` | `false` | Allow undeclared columns. |
|
|
73
|
+
| `rules` | `[]` | See below. |
|
|
74
|
+
|
|
75
|
+
**Column**: only `name` is required.
|
|
76
|
+
|
|
77
|
+
| Field | Meaning |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `type` | `string` (default), `integer`, `number` (exact decimal), `boolean` (`true`/`false`), `date` (`YYYY-MM-DD`), `list`. |
|
|
80
|
+
| `required` | The cell must not be empty. |
|
|
81
|
+
| `separator` | Item separator for lists (default `,`). |
|
|
82
|
+
| `match` | A condition every filled cell must meet, e.g. `{"$in": ["a", "b"]}`. Empty cells are not tested. |
|
|
83
|
+
| `description` | Shown by `describe`. |
|
|
84
|
+
|
|
85
|
+
**Rule**: exactly one of `require` and `count`.
|
|
86
|
+
|
|
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
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import yargs from "yargs/yargs";
|
|
2
|
+
import contract from "../features/contract/command.js";
|
|
2
3
|
import table from "../features/table/command.js";
|
|
3
4
|
// The clock commands (../features/clock/command.js) are kept but not registered for now.
|
|
4
|
-
const commands = [
|
|
5
|
+
const commands = [contract, table];
|
|
5
6
|
/**
|
|
6
7
|
* Builds the yargs parser with every feature command registered.
|
|
7
8
|
*
|
|
@@ -12,6 +13,11 @@ export function createCli(args) {
|
|
|
12
13
|
const cli = yargs(args)
|
|
13
14
|
.scriptName("turingcode")
|
|
14
15
|
.usage("Usage: $0 <command> [options]; $0 <command> --help for each command's usage")
|
|
16
|
+
.epilogue([
|
|
17
|
+
"Checks tables written in Markdown or CSV against a contract: a JSON file that declares the tables,",
|
|
18
|
+
"their columns, and checks on values and rows as MongoDB-style queries. Contract format: $0 contract --help.",
|
|
19
|
+
"Typical use: `contract describe` shows the tables to write; write them; `table check` until PASS.",
|
|
20
|
+
].join("\n"))
|
|
15
21
|
.command(commands)
|
|
16
22
|
.demandCommand(1)
|
|
17
23
|
.strict()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Raised when a search or size bound is exceeded (maps to SEARCH_BOUND_EXCEEDED). */
|
|
2
|
+
export class BoundError extends Error {
|
|
3
|
+
bound;
|
|
4
|
+
limit;
|
|
5
|
+
/**
|
|
6
|
+
* @param {string} bound - Name of the bound that was exceeded, e.g. `max_table_rows`.
|
|
7
|
+
* @param {number} limit - Its value.
|
|
8
|
+
*/
|
|
9
|
+
constructor(bound, limit) {
|
|
10
|
+
super(`${bound} (${limit}) exceeded`);
|
|
11
|
+
this.bound = bound;
|
|
12
|
+
this.limit = limit;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -1,21 +1,8 @@
|
|
|
1
|
+
import { BoundError } from "../bound-error.js";
|
|
1
2
|
import { ArithmeticError, Fraction } from "./fraction.js";
|
|
2
3
|
/** Raised when an expression cannot be parsed or evaluated. */
|
|
3
4
|
export class AstError extends Error {
|
|
4
5
|
}
|
|
5
|
-
/** Raised when an expression exceeds its node bound (maps to SEARCH_BOUND_EXCEEDED). */
|
|
6
|
-
export class BoundError extends Error {
|
|
7
|
-
bound;
|
|
8
|
-
limit;
|
|
9
|
-
/**
|
|
10
|
-
* @param {string} bound - The `contract.bounds` key that was exceeded.
|
|
11
|
-
* @param {number} limit - Its value.
|
|
12
|
-
*/
|
|
13
|
-
constructor(bound, limit) {
|
|
14
|
-
super(`${bound} (${limit}) exceeded`);
|
|
15
|
-
this.bound = bound;
|
|
16
|
-
this.limit = limit;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
6
|
const TOKEN = new RegExp([
|
|
20
7
|
"\\s+",
|
|
21
8
|
"(0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9][0-9a-fA-F]*[hH](?![0-9A-Za-z_])|[01]+[bB](?![0-9A-Za-z_])"
|
|
@@ -175,3 +162,24 @@ export function evaluate(n, env) {
|
|
|
175
162
|
throw e instanceof ArithmeticError ? new AstError(e.message) : e;
|
|
176
163
|
}
|
|
177
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* The names an expression uses.
|
|
167
|
+
*
|
|
168
|
+
* @param {Node} n - The tree.
|
|
169
|
+
* @returns {Set<string>} Distinct names.
|
|
170
|
+
*/
|
|
171
|
+
export function namesIn(n) {
|
|
172
|
+
const names = new Set();
|
|
173
|
+
const walk = (x) => {
|
|
174
|
+
if (x.k === "name")
|
|
175
|
+
names.add(x.name);
|
|
176
|
+
else if (x.k === "neg")
|
|
177
|
+
walk(x.a);
|
|
178
|
+
else if (x.k === "bin") {
|
|
179
|
+
walk(x.a);
|
|
180
|
+
walk(x.b);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
walk(n);
|
|
184
|
+
return names;
|
|
185
|
+
}
|
|
@@ -73,6 +73,41 @@ export class Fraction {
|
|
|
73
73
|
const digits = BigInt((m[1] ?? "") + frac || "0");
|
|
74
74
|
return exp >= 0 ? new Fraction(digits * 10n ** BigInt(exp)) : new Fraction(digits, 10n ** BigInt(-exp));
|
|
75
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Parses a signed decimal number as written in a table cell: `-3`, `+0.25`, `1.5e3`.
|
|
78
|
+
*
|
|
79
|
+
* @param {string} text - The cell text.
|
|
80
|
+
* @returns {Fraction | null} Its exact value, or null when it is not a decimal number.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* Fraction.parseDecimal("-0.5")?.toString(); // "-1/2"
|
|
84
|
+
*/
|
|
85
|
+
static parseDecimal(text) {
|
|
86
|
+
const m = /^([+-]?)((?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)$/.exec(text.trim());
|
|
87
|
+
if (!m)
|
|
88
|
+
return null;
|
|
89
|
+
try {
|
|
90
|
+
const v = Fraction.parse(m[2]);
|
|
91
|
+
return m[1] === "-" ? v.neg() : v;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Compares with another fraction.
|
|
99
|
+
*
|
|
100
|
+
* @param {Fraction} o - The other value.
|
|
101
|
+
* @returns {number} -1, 0 or 1.
|
|
102
|
+
*/
|
|
103
|
+
cmp(o) {
|
|
104
|
+
const d = this.n * o.d - o.n * this.d;
|
|
105
|
+
return d < 0n ? -1 : d > 0n ? 1 : 0;
|
|
106
|
+
}
|
|
107
|
+
/** @returns {Fraction} |this|. */
|
|
108
|
+
abs() {
|
|
109
|
+
return this.n < 0n ? this.neg() : this;
|
|
110
|
+
}
|
|
76
111
|
/** @returns {boolean} Whether the value is zero. */
|
|
77
112
|
isZero() {
|
|
78
113
|
return this.n === 0n;
|
|
@@ -123,6 +158,33 @@ export class Fraction {
|
|
|
123
158
|
const raised = new Fraction(this.n ** k, this.d ** k);
|
|
124
159
|
return e.n < 0n ? new Fraction(1n).div(raised) : raised;
|
|
125
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* Decimal text: exact when the fraction terminates, else rounded to `places`
|
|
163
|
+
* decimals and prefixed with `~`.
|
|
164
|
+
*
|
|
165
|
+
* @param {number} [places=10] - Decimals for a non-terminating value.
|
|
166
|
+
* @returns {string} e.g. `12.5`, `~0.3333333333`.
|
|
167
|
+
*/
|
|
168
|
+
toDecimal(places = 10) {
|
|
169
|
+
let d = this.d;
|
|
170
|
+
let digits = 0;
|
|
171
|
+
for (const p of [2n, 5n])
|
|
172
|
+
while (d % p === 0n)
|
|
173
|
+
d /= p;
|
|
174
|
+
const exact = d === 1n;
|
|
175
|
+
if (exact) {
|
|
176
|
+
let t = this.d;
|
|
177
|
+
while (t > 1n) {
|
|
178
|
+
t = t % 10n === 0n ? t / 10n : t % 5n === 0n ? (t * 2n) / 10n : (t * 5n) / 10n;
|
|
179
|
+
digits++;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const k = exact ? digits : places;
|
|
183
|
+
const scaled = (abs(this.n) * 10n ** BigInt(k) * 2n + this.d) / (this.d * 2n);
|
|
184
|
+
const s = scaled.toString().padStart(k + 1, "0");
|
|
185
|
+
const text = k ? `${s.slice(0, -k)}.${s.slice(-k)}` : s;
|
|
186
|
+
return `${exact ? "" : "~"}${this.n < 0n ? "-" : ""}${text}`;
|
|
187
|
+
}
|
|
126
188
|
/** @returns {string} `n` or `n/d`. */
|
|
127
189
|
toString() {
|
|
128
190
|
return this.d === 1n ? `${this.n}` : `${this.n}/${this.d}`;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* Reads and parses a UTF-8 JSON file (a leading BOM is ignored).
|
|
4
|
+
*
|
|
5
|
+
* @param {string} path - File path.
|
|
6
|
+
* @returns {JsonFile} The parsed value, or why it could not be read.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* const file = readJsonFile("contract.json");
|
|
10
|
+
* if (file.ok) use(file.data);
|
|
11
|
+
*/
|
|
12
|
+
export function readJsonFile(path) {
|
|
13
|
+
let text;
|
|
14
|
+
try {
|
|
15
|
+
text = readFileSync(path, "utf-8").replace(/^/, "");
|
|
16
|
+
}
|
|
17
|
+
catch (e) {
|
|
18
|
+
return { ok: false, error: "unreadable", message: e.message };
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
return { ok: true, data: JSON.parse(text) };
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
return { ok: false, error: "bad_json", message: e.message };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -1,10 +1,17 @@
|
|
|
1
|
-
import { contractDiag, show } from "./diagnostics.js";
|
|
2
|
-
const VERSION = /^\d+\.\d+\.\d+$/;
|
|
3
|
-
const PIN = /^[^@\s]+@\d+\.\d+\.\d+$/;
|
|
4
1
|
/** @param {unknown} v - Value. @returns {string} Its JSON type name. */
|
|
5
2
|
const typeOf = (v) => (v === null ? "null" : Array.isArray(v) ? "array" : typeof v);
|
|
6
3
|
/**
|
|
7
|
-
*
|
|
4
|
+
* Short, single-line JSON rendering of any value.
|
|
5
|
+
*
|
|
6
|
+
* @param {unknown} v - Value.
|
|
7
|
+
* @returns {string} At most 80 characters.
|
|
8
|
+
*/
|
|
9
|
+
export function show(v) {
|
|
10
|
+
const s = v === undefined ? "(absent)" : JSON.stringify(v);
|
|
11
|
+
return s.length > 80 ? s.slice(0, 77) + "..." : s;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Compiles a regex given as data.
|
|
8
15
|
*
|
|
9
16
|
* @param {string} pattern - The pattern.
|
|
10
17
|
* @returns {RegExp | string} The regex, or the error message.
|
|
@@ -19,9 +26,8 @@ export function compileRegex(pattern) {
|
|
|
19
26
|
}
|
|
20
27
|
/** @param {Shape} shape - A shape. @returns {string} A short description for `expected`. */
|
|
21
28
|
function describe(shape) {
|
|
22
|
-
if (typeof shape === "string")
|
|
23
|
-
return shape
|
|
24
|
-
}
|
|
29
|
+
if (typeof shape === "string")
|
|
30
|
+
return shape.replace(/_/g, " ");
|
|
25
31
|
if ("enum" in shape)
|
|
26
32
|
return `one of ${shape.enum.join(", ")}`;
|
|
27
33
|
if ("literal" in shape)
|
|
@@ -35,86 +41,83 @@ function describe(shape) {
|
|
|
35
41
|
return "object";
|
|
36
42
|
}
|
|
37
43
|
/**
|
|
38
|
-
* Checks a JSON value against a shape
|
|
44
|
+
* Checks a JSON value against a shape.
|
|
39
45
|
*
|
|
40
46
|
* @param {unknown} value - The value.
|
|
41
47
|
* @param {Shape} shape - Its shape.
|
|
42
|
-
* @param {string} path - JSON path for messages, e.g.
|
|
43
|
-
* @
|
|
44
|
-
*
|
|
45
|
-
* @
|
|
46
|
-
*
|
|
48
|
+
* @param {string} path - JSON path for messages, e.g. `$.tables[0]`.
|
|
49
|
+
* @returns {ShapeIssue[]} Every mismatch; empty when the value matches.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* checkShape({ a: 1 }, { obj: { a: "string" } }, "$")[0].message; // "$.a: expected a non-empty string, got number"
|
|
47
53
|
*/
|
|
48
|
-
export function checkShape(value, shape, path
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
const fail = (c, msg, expected = describe(shape)) => out.push(contractDiag(c, `${path}: ${msg}`, where, show(value), expected));
|
|
54
|
+
export function checkShape(value, shape, path) {
|
|
55
|
+
const issues = [];
|
|
56
|
+
const fail = (kind, msg, expected = describe(shape)) => issues.push({ kind, path, message: `${path}: ${msg}`, found: show(value), expected });
|
|
52
57
|
if (typeof shape === "string") {
|
|
53
58
|
switch (shape) {
|
|
54
59
|
case "any":
|
|
55
60
|
break;
|
|
56
61
|
case "string":
|
|
57
62
|
if (typeof value !== "string" || value === "")
|
|
58
|
-
fail(
|
|
63
|
+
fail("type", `expected a non-empty string, got ${typeOf(value)}`);
|
|
59
64
|
break;
|
|
60
65
|
case "bool":
|
|
61
66
|
if (typeof value !== "boolean")
|
|
62
|
-
fail(
|
|
67
|
+
fail("type", `expected a boolean, got ${typeOf(value)}`);
|
|
63
68
|
break;
|
|
64
69
|
case "int":
|
|
65
70
|
case "pos_int":
|
|
66
71
|
if (!Number.isInteger(value) || value < (shape === "int" ? 0 : 1)) {
|
|
67
|
-
fail(
|
|
72
|
+
fail("type", `expected a ${shape === "int" ? "non-negative" : "positive"} integer`);
|
|
68
73
|
}
|
|
69
74
|
break;
|
|
70
75
|
case "regex": {
|
|
71
76
|
const compiled = typeof value === "string" ? compileRegex(value) : "not a string";
|
|
72
77
|
if (typeof compiled === "string")
|
|
73
|
-
fail("
|
|
78
|
+
fail("regex", `invalid regex (${compiled})`);
|
|
74
79
|
break;
|
|
75
80
|
}
|
|
76
|
-
case "
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
fail(typeof value === "string" ? "CONTRACT.BAD_VALUE" : code, "bad version format");
|
|
81
|
+
case "number_or_string":
|
|
82
|
+
if (!(typeof value === "number" && Number.isFinite(value)) && (typeof value !== "string" || value === "")) {
|
|
83
|
+
fail("type", `expected a number or a string, got ${typeOf(value)}`);
|
|
80
84
|
}
|
|
81
85
|
break;
|
|
82
86
|
case "string_or_list":
|
|
83
87
|
if (typeof value !== "string" && !(Array.isArray(value) && value.every(v => typeof v === "string"))) {
|
|
84
|
-
fail(
|
|
88
|
+
fail("type", "expected a string or an array of strings");
|
|
85
89
|
}
|
|
86
90
|
break;
|
|
87
91
|
}
|
|
88
92
|
}
|
|
89
93
|
else if ("enum" in shape) {
|
|
90
|
-
if (typeof value !== "string" || !shape.enum.includes(value))
|
|
91
|
-
fail(typeof value === "string" ? "
|
|
92
|
-
}
|
|
94
|
+
if (typeof value !== "string" || !shape.enum.includes(value))
|
|
95
|
+
fail(typeof value === "string" ? "value" : "type", "value not allowed");
|
|
93
96
|
}
|
|
94
97
|
else if ("literal" in shape) {
|
|
95
98
|
if (value !== shape.literal)
|
|
96
|
-
fail("
|
|
99
|
+
fail("value", "value not allowed");
|
|
97
100
|
}
|
|
98
101
|
else if ("nullable" in shape) {
|
|
99
102
|
if (value !== null)
|
|
100
|
-
checkShape(value, shape.nullable, path
|
|
103
|
+
issues.push(...checkShape(value, shape.nullable, path));
|
|
101
104
|
}
|
|
102
105
|
else if ("list" in shape) {
|
|
103
106
|
if (!Array.isArray(value)) {
|
|
104
|
-
fail(
|
|
107
|
+
fail("type", `expected an array, got ${typeOf(value)}`);
|
|
105
108
|
}
|
|
106
109
|
else {
|
|
107
110
|
if (value.length < (shape.min ?? 0))
|
|
108
|
-
fail("
|
|
109
|
-
value.forEach((v, i) => checkShape(v, shape.list, `${path}[${i}]
|
|
111
|
+
fail("value", `needs at least ${shape.min} entries`);
|
|
112
|
+
value.forEach((v, i) => issues.push(...checkShape(v, shape.list, `${path}[${i}]`)));
|
|
110
113
|
}
|
|
111
114
|
}
|
|
112
115
|
else if (typeOf(value) !== "object") {
|
|
113
|
-
fail(
|
|
116
|
+
fail("type", `expected an object, got ${typeOf(value)}`);
|
|
114
117
|
}
|
|
115
118
|
else if ("map" in shape) {
|
|
116
119
|
for (const [k, v] of Object.entries(value))
|
|
117
|
-
checkShape(v, shape.map, `${path}.${k}
|
|
120
|
+
issues.push(...checkShape(v, shape.map, `${path}.${k}`));
|
|
118
121
|
}
|
|
119
122
|
else {
|
|
120
123
|
const obj = value;
|
|
@@ -122,16 +125,18 @@ export function checkShape(value, shape, path, at, out, code = "CONTRACT.BAD_TYP
|
|
|
122
125
|
for (const [name, key] of keys) {
|
|
123
126
|
if (obj[name] === undefined) {
|
|
124
127
|
if (!key.endsWith("?")) {
|
|
125
|
-
|
|
128
|
+
issues.push({ kind: "missing", path: `${path}.${name}`, message: `${path}: missing required '${name}'`,
|
|
129
|
+
found: "(absent)", expected: describe(shape.obj[key]) });
|
|
126
130
|
}
|
|
127
131
|
}
|
|
128
132
|
else {
|
|
129
|
-
checkShape(obj[name], shape.obj[key], `${path}.${name}
|
|
133
|
+
issues.push(...checkShape(obj[name], shape.obj[key], `${path}.${name}`));
|
|
130
134
|
}
|
|
131
135
|
}
|
|
132
136
|
for (const k of Object.keys(obj).filter(k => !keys.has(k))) {
|
|
133
|
-
|
|
137
|
+
issues.push({ kind: "unknown", path: `${path}.${k}`, message: `${path}: unknown field '${k}'`, found: show(obj[k]),
|
|
138
|
+
expected: `one of ${[...keys.keys()].join(", ")}` });
|
|
134
139
|
}
|
|
135
140
|
}
|
|
136
|
-
return
|
|
141
|
+
return issues;
|
|
137
142
|
}
|