@turingcode/cli 0.2.11 → 0.2.13
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 +4 -3
- package/dist/cli/create-cli.js +15 -5
- package/dist/cli/index.js +3 -2
- package/dist/core/files.js +3 -0
- package/dist/core/json-shape.js +0 -43
- package/dist/core/mcp.js +1 -15
- package/dist/core/query.js +11 -0
- package/dist/features/contract/check.js +2 -3
- package/dist/features/contract/command.js +12 -5
- package/dist/features/contract/diagnostics.js +5 -2
- package/dist/features/contract/load.js +25 -18
- package/dist/features/contract/rules.js +11 -12
- package/dist/features/table/check.js +16 -14
- package/dist/features/table/command.js +7 -4
- package/dist/features/table/read.js +23 -3
- package/dist/features/tool/command.js +4 -4
- package/package.json +1 -1
- package/dist/features/clock/command.js +0 -63
package/README.md
CHANGED
|
@@ -22,7 +22,8 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
|
|
|
22
22
|
`1` FAIL/INVALID_CONTRACT, `2` bad input or missing file.
|
|
23
23
|
|
|
24
24
|
`tool` commands need `TURINGCODE_TOKEN` (gateway token); `TURINGCODE_URL` overrides the gateway.
|
|
25
|
-
They exit `0` on success
|
|
25
|
+
They exit `0` on success, `1` on a tool error (printed to stderr) or a failed request, and `2` on bad
|
|
26
|
+
arguments (e.g. `--args` that is not a JSON object), before any request is sent.
|
|
26
27
|
|
|
27
28
|
## Contract format
|
|
28
29
|
|
|
@@ -63,10 +64,10 @@ plus the operators below for references, exact numbers and checks across rows).
|
|
|
63
64
|
| Field | Default | Meaning |
|
|
64
65
|
| --- | --- | --- |
|
|
65
66
|
| `name`, `version`, `description` | | Shown in output and in `describe`. |
|
|
66
|
-
| `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). |
|
|
67
|
+
| `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). The files given with `--tables` and `--dep` must be in their own contract's format; a CSV file for a Markdown contract is reported as `INVALID_INPUT`. |
|
|
67
68
|
| `missing_values` | `[""]` | Cell texts that count as empty (`null` in queries). Leave out a marker like `-` when it is a real value: "`-` allowed, empty forbidden" is `"required": true` with `"match": {"$or": [{"$eq": "-"}, ...]}`. |
|
|
68
69
|
| `allow_extra_tables` | `false` | Allow tables the contract does not declare. |
|
|
69
|
-
| `depends_on` | | `alias -> contract file` (absolute, or relative to this contract); its tables are passed with `--dep alias=<file
|
|
70
|
+
| `depends_on` | | `alias -> contract file` (absolute, or relative to this contract); its tables are passed with `--dep alias=<file>` and referenced as `alias:Table.Column`, e.g. `{"$ref": "customers:Customers.ID"}`. |
|
|
70
71
|
|
|
71
72
|
**Table**: `name` and `columns` are required.
|
|
72
73
|
|
package/dist/cli/create-cli.js
CHANGED
|
@@ -2,19 +2,23 @@ import yargs from "yargs/yargs";
|
|
|
2
2
|
import contract from "../features/contract/command.js";
|
|
3
3
|
import table from "../features/table/command.js";
|
|
4
4
|
import tool from "../features/tool/command.js";
|
|
5
|
-
// The clock commands (../features/clock/command.js) are kept but not registered for now.
|
|
6
5
|
const commands = [contract, table, tool];
|
|
6
|
+
const names = commands.map(c => String(c.command).split(" ")[0]);
|
|
7
|
+
/** Exit code of every argument error, as each command's help documents. */
|
|
8
|
+
const BAD_ARGUMENTS = 2;
|
|
7
9
|
/**
|
|
8
10
|
* Builds the yargs parser with every feature command registered.
|
|
9
11
|
*
|
|
10
12
|
* @param {string[]} args - Arguments after `turingcode`.
|
|
11
13
|
* @returns The parser; call `parseAsync()` to run it.
|
|
12
14
|
* @throws {Error} When the first word is not a command (yargs alone would print help and exit 0 for `<unknown> --help`).
|
|
15
|
+
* It and the argument errors yargs finds (missing option, unknown subcommand, bad flag value) carry
|
|
16
|
+
* `exitCode` 2, so they differ from a failed check or request (1).
|
|
13
17
|
*/
|
|
14
18
|
export function createCli(args) {
|
|
15
19
|
const first = args.find(a => !a.startsWith("-"));
|
|
16
|
-
if (first !== undefined && !
|
|
17
|
-
throw new Error(`Unknown command: ${first}`);
|
|
20
|
+
if (first !== undefined && !names.includes(first)) {
|
|
21
|
+
throw Object.assign(new Error(`Unknown command: ${first}`), { exitCode: BAD_ARGUMENTS });
|
|
18
22
|
}
|
|
19
23
|
const cli = yargs(args)
|
|
20
24
|
.scriptName("turingcode")
|
|
@@ -28,14 +32,20 @@ export function createCli(args) {
|
|
|
28
32
|
" Contract format: $0 contract --help.",
|
|
29
33
|
].join("\n"))
|
|
30
34
|
.command(commands)
|
|
31
|
-
.demandCommand(1)
|
|
35
|
+
.demandCommand(1, `Name a command: ${names.slice(0, -1).join(", ")} or ${names.at(-1)}`)
|
|
32
36
|
.strict()
|
|
33
37
|
.help()
|
|
34
38
|
.hide("help")
|
|
35
39
|
.hide("version")
|
|
36
40
|
.wrap(null)
|
|
37
41
|
.exitProcess(false)
|
|
38
|
-
|
|
42
|
+
// yargs passes a message for argument errors (validation, coerce, check) and none when a
|
|
43
|
+
// command's handler threw; a handler error keeps its own exit code.
|
|
44
|
+
.fail((message, error) => {
|
|
45
|
+
if (!message && error)
|
|
46
|
+
throw error;
|
|
47
|
+
throw Object.assign(error ?? new Error(message), { exitCode: BAD_ARGUMENTS });
|
|
48
|
+
});
|
|
39
49
|
// Type tags such as [string] add tokens without information; the typings lack this yargs 17.7 method.
|
|
40
50
|
return cli.usageConfiguration({ "hide-types": true });
|
|
41
51
|
}
|
package/dist/cli/index.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
import { hideBin } from "yargs/helpers";
|
|
3
3
|
import { createCli } from "./create-cli.js";
|
|
4
4
|
/**
|
|
5
|
-
* Runs the CLI. Errors propagate here, are printed, and exit with code 1
|
|
5
|
+
* Runs the CLI. Errors propagate here, are printed, and exit with code 1, or with the error's
|
|
6
|
+
* own `exitCode` when it has one (e.g. 2 for bad input to a check command).
|
|
6
7
|
*
|
|
7
8
|
* @param {string[]} [args] - Arguments after `turingcode`.
|
|
8
9
|
* @returns {Promise<void>} Resolves when the command finished.
|
|
@@ -13,7 +14,7 @@ export async function main(args = hideBin(process.argv)) {
|
|
|
13
14
|
}
|
|
14
15
|
catch (error) {
|
|
15
16
|
process.stderr.write(`turingcode: ${error.message}\nRun "turingcode <command> --help" for usage.\n`);
|
|
16
|
-
process.exitCode = 1;
|
|
17
|
+
process.exitCode = error.exitCode ?? 1;
|
|
17
18
|
}
|
|
18
19
|
}
|
|
19
20
|
void main();
|
package/dist/core/files.js
CHANGED
|
@@ -40,6 +40,9 @@ export function readJsonArg(value) {
|
|
|
40
40
|
catch (e) {
|
|
41
41
|
if (e.code !== "ENOENT")
|
|
42
42
|
throw e;
|
|
43
|
+
// A value shaped like a path is most likely a mistyped path, so say that instead of talking about JSON.
|
|
44
|
+
if (/\.json$|[/\\]/i.test(value))
|
|
45
|
+
throw new Error(`no such file: '${value}'`);
|
|
43
46
|
throw new Error(`'${value}' is neither inline JSON (starting with {) nor an existing .json file`);
|
|
44
47
|
}
|
|
45
48
|
}
|
package/dist/core/json-shape.js
CHANGED
|
@@ -10,34 +10,16 @@ export function show(v) {
|
|
|
10
10
|
const s = v === undefined ? "(absent)" : JSON.stringify(v);
|
|
11
11
|
return s.length > 80 ? s.slice(0, 77) + "..." : s;
|
|
12
12
|
}
|
|
13
|
-
/**
|
|
14
|
-
* Compiles a regex given as data.
|
|
15
|
-
*
|
|
16
|
-
* @param {string} pattern - The pattern.
|
|
17
|
-
* @returns {RegExp | string} The regex, or the error message.
|
|
18
|
-
*/
|
|
19
|
-
export function compileRegex(pattern) {
|
|
20
|
-
try {
|
|
21
|
-
return new RegExp(pattern);
|
|
22
|
-
}
|
|
23
|
-
catch (e) {
|
|
24
|
-
return e.message;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
13
|
/** @param {Shape} shape - A shape. @returns {string} A short description for `expected`. */
|
|
28
14
|
function describe(shape) {
|
|
29
15
|
if (typeof shape === "string")
|
|
30
16
|
return shape.replace(/_/g, " ");
|
|
31
17
|
if ("enum" in shape)
|
|
32
18
|
return `one of ${shape.enum.join(", ")}`;
|
|
33
|
-
if ("literal" in shape)
|
|
34
|
-
return JSON.stringify(shape.literal);
|
|
35
19
|
if ("list" in shape)
|
|
36
20
|
return `array of ${describe(shape.list)}`;
|
|
37
21
|
if ("map" in shape)
|
|
38
22
|
return `object of ${describe(shape.map)}`;
|
|
39
|
-
if ("nullable" in shape)
|
|
40
|
-
return `${describe(shape.nullable)} or null`;
|
|
41
23
|
return "object";
|
|
42
24
|
}
|
|
43
25
|
/**
|
|
@@ -66,23 +48,6 @@ export function checkShape(value, shape, path) {
|
|
|
66
48
|
if (typeof value !== "boolean")
|
|
67
49
|
fail("type", `expected a boolean, got ${typeOf(value)}`);
|
|
68
50
|
break;
|
|
69
|
-
case "int":
|
|
70
|
-
case "pos_int":
|
|
71
|
-
if (!Number.isInteger(value) || value < (shape === "int" ? 0 : 1)) {
|
|
72
|
-
fail("type", `expected a ${shape === "int" ? "non-negative" : "positive"} integer`);
|
|
73
|
-
}
|
|
74
|
-
break;
|
|
75
|
-
case "regex": {
|
|
76
|
-
const compiled = typeof value === "string" ? compileRegex(value) : "not a string";
|
|
77
|
-
if (typeof compiled === "string")
|
|
78
|
-
fail("regex", `invalid regex (${compiled})`);
|
|
79
|
-
break;
|
|
80
|
-
}
|
|
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)}`);
|
|
84
|
-
}
|
|
85
|
-
break;
|
|
86
51
|
case "string_or_list":
|
|
87
52
|
if (typeof value !== "string" && !(Array.isArray(value) && value.every(v => typeof v === "string"))) {
|
|
88
53
|
fail("type", "expected a string or an array of strings");
|
|
@@ -94,14 +59,6 @@ export function checkShape(value, shape, path) {
|
|
|
94
59
|
if (typeof value !== "string" || !shape.enum.includes(value))
|
|
95
60
|
fail(typeof value === "string" ? "value" : "type", "value not allowed");
|
|
96
61
|
}
|
|
97
|
-
else if ("literal" in shape) {
|
|
98
|
-
if (value !== shape.literal)
|
|
99
|
-
fail("value", "value not allowed");
|
|
100
|
-
}
|
|
101
|
-
else if ("nullable" in shape) {
|
|
102
|
-
if (value !== null)
|
|
103
|
-
issues.push(...checkShape(value, shape.nullable, path));
|
|
104
|
-
}
|
|
105
62
|
else if ("list" in shape) {
|
|
106
63
|
if (!Array.isArray(value)) {
|
|
107
64
|
fail("type", `expected an array, got ${typeOf(value)}`);
|
package/dist/core/mcp.js
CHANGED
|
@@ -97,27 +97,13 @@ export function parseRpcReply(body) {
|
|
|
97
97
|
* @param {any} result - The JSON-RPC result of `tools/call`.
|
|
98
98
|
* @returns {ToolResult} The joined text content and error flag.
|
|
99
99
|
*/
|
|
100
|
-
function toToolResult(result) {
|
|
100
|
+
export function toToolResult(result) {
|
|
101
101
|
const content = result?.content ?? [];
|
|
102
102
|
return {
|
|
103
103
|
text: content.filter(c => c.type === "text").map(c => c.text).join("\n"),
|
|
104
104
|
isError: Boolean(result?.isError),
|
|
105
105
|
};
|
|
106
106
|
}
|
|
107
|
-
/**
|
|
108
|
-
* Turns a gateway `tools/call` reply (plain JSON or an SSE stream) into a ToolResult.
|
|
109
|
-
*
|
|
110
|
-
* @param {string} body - Raw response body.
|
|
111
|
-
* @returns {ToolResult} The joined text content and error flag.
|
|
112
|
-
* @throws {Error} When the reply holds no JSON-RPC response or carries an error.
|
|
113
|
-
*
|
|
114
|
-
* @example
|
|
115
|
-
* parseToolReply('data: {"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"ok"}]}}');
|
|
116
|
-
* // { text: "ok", isError: false }
|
|
117
|
-
*/
|
|
118
|
-
export function parseToolReply(body) {
|
|
119
|
-
return toToolResult(parseRpcReply(body));
|
|
120
|
-
}
|
|
121
107
|
/**
|
|
122
108
|
* Reads the gateway token and endpoint from TURINGCODE_TOKEN and TURINGCODE_URL.
|
|
123
109
|
*
|
package/dist/core/query.js
CHANGED
|
@@ -233,3 +233,14 @@ export function compileQuery(query, hooks) {
|
|
|
233
233
|
};
|
|
234
234
|
return createQueryTester(query, { operations });
|
|
235
235
|
}
|
|
236
|
+
/**
|
|
237
|
+
* Prepares and compiles a query in one step (for queries `contract check` already validated).
|
|
238
|
+
*
|
|
239
|
+
* @param {unknown} query - The query from the contract.
|
|
240
|
+
* @param {QueryHooks} hooks - `$ref`, `$mentioned` and `$calc`.
|
|
241
|
+
* @returns {(doc: Doc) => boolean} Whether a row matches.
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* queryTester({ Qty: { $gte: 1 } }, hooks)({ Qty: "2" }); // true
|
|
245
|
+
*/
|
|
246
|
+
export const queryTester = (query, hooks) => compileQuery(prepareQuery(query).query, hooks);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { formatDiagnostics, sortDiagnostics } from "./diagnostics.js";
|
|
2
|
-
import { loadContract } from "./load.js";
|
|
2
|
+
import { failedLoadStatus, loadContract } from "./load.js";
|
|
3
3
|
/** Labels of a loaded contract and all its dependencies. */
|
|
4
4
|
const labels = (c) => [c.label, ...[...c.deps.values()].flatMap(labels)];
|
|
5
5
|
/**
|
|
@@ -14,8 +14,7 @@ const labels = (c) => [c.label, ...[...c.deps.values()].flatMap(labels)];
|
|
|
14
14
|
export function contractCheck(path) {
|
|
15
15
|
const diags = [];
|
|
16
16
|
const loaded = loadContract(path, diags);
|
|
17
|
-
const status =
|
|
18
|
-
: loaded.contract ? "VALID" : "INVALID_CONTRACT";
|
|
17
|
+
const status = loaded.contract ? "VALID" : failedLoadStatus(diags);
|
|
19
18
|
return { status, contract: loaded.label, checked: [...new Set(labels(loaded))], diagnostics: sortDiagnostics(diags) };
|
|
20
19
|
}
|
|
21
20
|
/**
|
|
@@ -8,14 +8,15 @@ const FORMAT = `Contract JSON. Only "tables" and each table's and column's "name
|
|
|
8
8
|
field is optional. "(default)" marks the value used when a field is left out; other values are examples.
|
|
9
9
|
{
|
|
10
10
|
"name": "shop.orders", "version": "1.0.0", "description": "...", // shown in output
|
|
11
|
-
"format": "markdown", // (default) or "csv": one <table>.csv per table
|
|
11
|
+
"format": "markdown", // (default), or "format": "csv": one <table>.csv per table. The tables
|
|
12
|
+
// given with --tables / --dep must be in their own contract's format
|
|
12
13
|
"missing_values": [""], // (default) cell texts that count as empty (null in queries), e.g. ["", "-"].
|
|
13
14
|
// Keep a marker like "-" out of it when "-" is a real value: "-" allowed
|
|
14
15
|
// but an empty cell forbidden is "required": true plus
|
|
15
16
|
// "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
|
|
16
17
|
"allow_extra_tables": false, // (default) true: tables not declared here are allowed
|
|
17
18
|
"depends_on": { "customers": "customers.contract.json" }, // path absolute or relative to this contract;
|
|
18
|
-
// its tables passed with --dep customers=<file>, referenced as "customers:Table"
|
|
19
|
+
// its tables passed with --dep customers=<file>, referenced as "customers:Table.Column"
|
|
19
20
|
"tables": [{
|
|
20
21
|
"name": "Orders",
|
|
21
22
|
"required": true, // (default) the table must be in the document
|
|
@@ -53,11 +54,17 @@ and {"$ne": "x"} means "no item is x"). Operators:
|
|
|
53
54
|
$mentioned "Table.Column" | [...] | "*" value appears there as a word; "*": anywhere in the
|
|
54
55
|
document outside the value's own table (prose and other tables both count)
|
|
55
56
|
$calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
|
|
57
|
+
Codes: each failing operator reports its own: $eq $in → BAD_VALUE, $regex → PATTERN, $gt.. → OUT_OF_RANGE,
|
|
58
|
+
$length → BAD_LENGTH, $ref → UNKNOWN_REF, $unique → DUPLICATE_KEY, $mentioned → NOT_MENTIONED,
|
|
59
|
+
{"$ne": null} in a rule → REQUIRED_IF, a wrong type → BAD_TYPE, a rule's other queries → MATCH.
|
|
60
|
+
A value failing every branch of an $or reports the branches' code when they agree, else NONE_OF
|
|
61
|
+
(each branch's code in the message, and in --json "alternatives").
|
|
56
62
|
Examples:
|
|
57
63
|
"match": { "$regex": "^O-[0-9]+$" }
|
|
58
64
|
"match": { "$in": ["open", "paid", "shipped"] }
|
|
59
65
|
"match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
|
|
60
66
|
"match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
|
|
67
|
+
"match": { "$ref": "customers:Customers.ID" } // a column of the dependency "customers"
|
|
61
68
|
{ "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
|
|
62
69
|
{ "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
|
|
63
70
|
{ "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
|
|
@@ -67,7 +74,7 @@ const check = {
|
|
|
67
74
|
describe: "Validate a contract and the contracts it depends on",
|
|
68
75
|
builder: cli => cli.options({ contract: CONTRACT, json: JSON_FLAG })
|
|
69
76
|
.example("$0 contract check --contract orders.contract.json", "")
|
|
70
|
-
.epilogue("Contract format: turingcode contract --help.\nExit: 0 VALID, 1 INVALID_CONTRACT, 2 missing file."),
|
|
77
|
+
.epilogue("Contract format: turingcode contract --help.\nExit: 0 VALID, 1 INVALID_CONTRACT, 2 bad input or missing file."),
|
|
71
78
|
handler: args => {
|
|
72
79
|
const result = contractCheck(args.contract);
|
|
73
80
|
report(result, formatContractCheck(result), args.json);
|
|
@@ -78,7 +85,7 @@ const describe = {
|
|
|
78
85
|
describe: "Print the tables a contract expects, their columns and rules, as Markdown",
|
|
79
86
|
builder: cli => cli.options({ contract: CONTRACT, json: JSON_FLAG })
|
|
80
87
|
.example("$0 contract describe --contract orders.contract.json", "")
|
|
81
|
-
.epilogue("Contract format: turingcode contract --help."),
|
|
88
|
+
.epilogue("Contract format: turingcode contract --help.\nExit: 0 described, 1 INVALID_CONTRACT, 2 bad input or missing file."),
|
|
82
89
|
handler: args => {
|
|
83
90
|
const result = describeContract(args.contract);
|
|
84
91
|
report(result, result.markdown ?? formatContractCheck(result), args.json);
|
|
@@ -87,7 +94,7 @@ const describe = {
|
|
|
87
94
|
const contract = {
|
|
88
95
|
command: "contract",
|
|
89
96
|
describe: "Validate a table contract, or print the tables it expects",
|
|
90
|
-
builder: cli => cli.command(check).command(describe).demandCommand(1).epilogue(FORMAT),
|
|
97
|
+
builder: cli => cli.command(check).command(describe).demandCommand(1, "contract needs a subcommand: check or describe").epilogue(FORMAT),
|
|
91
98
|
handler: () => { },
|
|
92
99
|
};
|
|
93
100
|
export default contract;
|
|
@@ -76,6 +76,8 @@ export function sortDiagnostics(list) {
|
|
|
76
76
|
const MAX_ROWS_PER_LINE = 20;
|
|
77
77
|
/** " table row column" without unset parts ("-"), with a leading space when not empty. */
|
|
78
78
|
const place = (...parts) => parts.filter(p => p !== "-").map(p => ` ${p}`).join("");
|
|
79
|
+
/** A NONE_OF diagnostic's branch codes, e.g. "PATTERN, BAD_VALUE"; "" for other diagnostics. */
|
|
80
|
+
const branchCodes = (d) => (d.alternatives ?? []).map(a => a.code).join(", ");
|
|
79
81
|
/**
|
|
80
82
|
* Renders diagnostics as compact text: one line per finding, findings that
|
|
81
83
|
* differ only by row grouped onto one line, then each fix hint once per code.
|
|
@@ -91,7 +93,7 @@ export function formatDiagnostics(diags) {
|
|
|
91
93
|
const lines = [];
|
|
92
94
|
const groups = new Map();
|
|
93
95
|
for (const d of diags) {
|
|
94
|
-
const key = [d.severity, d.code, d.table, d.column, d.expected, d.rule].join("\u0000");
|
|
96
|
+
const key = [d.severity, d.code, d.table, d.column, d.expected, d.rule, branchCodes(d)].join("\u0000");
|
|
95
97
|
groups.set(key, [...(groups.get(key) ?? []), d]);
|
|
96
98
|
}
|
|
97
99
|
for (const [d, ...more] of groups.values()) {
|
|
@@ -103,7 +105,8 @@ export function formatDiagnostics(diags) {
|
|
|
103
105
|
const all = [d, ...more];
|
|
104
106
|
const rows = all.slice(0, MAX_ROWS_PER_LINE).map(x => `${x.row}=${x.found}`).join(", ");
|
|
105
107
|
const extra = all.length > MAX_ROWS_PER_LINE ? ` +${all.length - MAX_ROWS_PER_LINE} more` : "";
|
|
106
|
-
|
|
108
|
+
const branches = d.alternatives ? `; branches failed with ${branchCodes(d)}` : "";
|
|
109
|
+
lines.push(`${d.severity} ${d.code}${place(d.table, d.column)} ×${all.length}: ${rows}${extra}; expected ${d.expected}${branches}${rule}`);
|
|
107
110
|
}
|
|
108
111
|
for (const [code, fix] of new Map(diags.map(d => [d.code, d.fix])))
|
|
109
112
|
lines.push(`fix ${code}: ${fix}`);
|
|
@@ -4,6 +4,16 @@ import { checkShape, show } from "../../core/json-shape.js";
|
|
|
4
4
|
import { diag } from "./diagnostics.js";
|
|
5
5
|
import { CONTRACT_SHAPE, keyColumns } from "./model.js";
|
|
6
6
|
import { checkQuery } from "./rules.js";
|
|
7
|
+
/**
|
|
8
|
+
* Parses a table reference (a rule's `on`).
|
|
9
|
+
*
|
|
10
|
+
* @param {string} ref - `Table` or `alias:Table`.
|
|
11
|
+
* @returns {{alias: string|null, table: string}} Its parts.
|
|
12
|
+
*/
|
|
13
|
+
export function parseTableRef(ref) {
|
|
14
|
+
const colon = ref.indexOf(":");
|
|
15
|
+
return colon > 0 ? { alias: ref.slice(0, colon), table: ref.slice(colon + 1) } : { alias: null, table: ref };
|
|
16
|
+
}
|
|
7
17
|
/**
|
|
8
18
|
* Parses a column reference.
|
|
9
19
|
*
|
|
@@ -11,22 +21,18 @@ import { checkQuery } from "./rules.js";
|
|
|
11
21
|
* @returns {{alias: string|null, table: string|null, column: string}} Its parts.
|
|
12
22
|
*/
|
|
13
23
|
export function parseRef(ref) {
|
|
14
|
-
const
|
|
15
|
-
const alias = colon > 0 ? ref.slice(0, colon) : null;
|
|
16
|
-
const rest = colon > 0 ? ref.slice(colon + 1) : ref;
|
|
24
|
+
const { alias, table: rest } = parseTableRef(ref);
|
|
17
25
|
const dot = rest.indexOf(".");
|
|
18
26
|
return dot > 0 ? { alias, table: rest.slice(0, dot), column: rest.slice(dot + 1) } : { alias, table: null, column: rest };
|
|
19
27
|
}
|
|
20
28
|
/**
|
|
21
|
-
*
|
|
29
|
+
* The status of a check whose contract did not load: MISSING_DATA when a contract file
|
|
30
|
+
* could not be read, else INVALID_CONTRACT.
|
|
22
31
|
*
|
|
23
|
-
* @param {
|
|
24
|
-
* @returns {
|
|
32
|
+
* @param {Diagnostic[]} diags - The loading diagnostics.
|
|
33
|
+
* @returns {"MISSING_DATA" | "INVALID_CONTRACT"} The status.
|
|
25
34
|
*/
|
|
26
|
-
export
|
|
27
|
-
const colon = ref.indexOf(":");
|
|
28
|
-
return colon > 0 ? { alias: ref.slice(0, colon), table: ref.slice(colon + 1) } : { alias: null, table: ref };
|
|
29
|
-
}
|
|
35
|
+
export const failedLoadStatus = (diags) => (diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT");
|
|
30
36
|
/** A shape message without its leading JSON path, which the diagnostic already shows as its column. */
|
|
31
37
|
const stripPath = (message, path) => message.replace(/^[^:]*: /, "") || path;
|
|
32
38
|
/** Pushes CONTRACT.DUPLICATE for repeated names. */
|
|
@@ -49,12 +55,12 @@ export function validateContract(data, deps) {
|
|
|
49
55
|
const out = [];
|
|
50
56
|
const shapeIssues = checkShape(data, CONTRACT_SHAPE, "$");
|
|
51
57
|
for (const i of shapeIssues) {
|
|
52
|
-
out.push(diag(
|
|
58
|
+
out.push(diag("CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { column: i.path }, i.found, i.expected));
|
|
53
59
|
}
|
|
54
|
-
|
|
55
|
-
if (shapeIssues.some(i => i.kind !== "regex"))
|
|
60
|
+
if (shapeIssues.length)
|
|
56
61
|
return out;
|
|
57
62
|
const c = data;
|
|
63
|
+
// Checked here, not by the shape: the "string" shape rejects "", the most common missing value.
|
|
58
64
|
for (const v of c.missing_values ?? []) {
|
|
59
65
|
if (typeof v !== "string")
|
|
60
66
|
out.push(diag("CONTRACT.BAD_FIELD", "missing_values must be strings", { column: "missing_values" }, show(v), "a string"));
|
|
@@ -94,7 +100,7 @@ export function validateContract(data, deps) {
|
|
|
94
100
|
return table;
|
|
95
101
|
const owner = alias ? undefined : [...deps].find(([, dep]) => dep.contract?.tables.some(t => t.name === name))?.[0];
|
|
96
102
|
if (owner) {
|
|
97
|
-
report("CONTRACT.UNKNOWN_TABLE", `'${name}' is a table of dependency '${owner}': write ${owner}:${
|
|
103
|
+
report("CONTRACT.UNKNOWN_TABLE", `'${name}' is a table of dependency '${owner}': write ${owner}:${text}`, text, `${owner}:${text}`);
|
|
98
104
|
}
|
|
99
105
|
else {
|
|
100
106
|
report("CONTRACT.UNKNOWN_TABLE", `table '${name}' does not exist`, text, target.tables.map(t => t.name).join(", "));
|
|
@@ -172,12 +178,14 @@ export function loadContract(path, out, stack = []) {
|
|
|
172
178
|
const full = resolve(path);
|
|
173
179
|
const loaded = { path, label: basename(path), contract: null, deps: new Map() };
|
|
174
180
|
const own = [];
|
|
181
|
+
// Findings in a dependency name it; findings in the checked contract need no prefix.
|
|
182
|
+
const publish = () => out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
175
183
|
const file = readJsonFile(path);
|
|
176
184
|
if (!file.ok) {
|
|
177
185
|
own.push(file.error === "unreadable"
|
|
178
186
|
? diag("CONTRACT.MISSING_FILE", `cannot read ${path}: ${file.message}`, {}, path, "a readable file")
|
|
179
187
|
: diag("CONTRACT.BAD_JSON", `${path}: ${file.message}`, {}, path, "valid JSON"));
|
|
180
|
-
|
|
188
|
+
publish();
|
|
181
189
|
return loaded;
|
|
182
190
|
}
|
|
183
191
|
const data = file.data;
|
|
@@ -190,7 +198,7 @@ export function loadContract(path, out, stack = []) {
|
|
|
190
198
|
if (typeof rel !== "string")
|
|
191
199
|
continue; // reported by the shape check
|
|
192
200
|
const depPath = resolve(dirname(path), rel);
|
|
193
|
-
if ([...stack, full].includes(
|
|
201
|
+
if ([...stack, full].includes(depPath)) {
|
|
194
202
|
own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
|
|
195
203
|
depsOk = false;
|
|
196
204
|
continue;
|
|
@@ -200,8 +208,7 @@ export function loadContract(path, out, stack = []) {
|
|
|
200
208
|
depsOk &&= dep.contract !== null;
|
|
201
209
|
}
|
|
202
210
|
own.push(...validateContract(data, loaded.deps));
|
|
203
|
-
|
|
204
|
-
out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
211
|
+
publish();
|
|
205
212
|
loaded.contract = depsOk && !own.some(d => d.severity === "FAIL") ? data : null;
|
|
206
213
|
return loaded;
|
|
207
214
|
}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { BoundError } from "../../core/bound-error.js";
|
|
2
2
|
import { AstError, evaluate, namesIn, parseExpression } from "../../core/exact/expression.js";
|
|
3
3
|
import { Fraction } from "../../core/exact/fraction.js";
|
|
4
|
-
import { compileQuery, prepareQuery } from "../../core/query.js";
|
|
4
|
+
import { compileQuery, prepareQuery, queryTester } from "../../core/query.js";
|
|
5
5
|
/** Largest expression a `$calc` may use. */
|
|
6
6
|
const MAX_EXPRESSION_NODES = 256;
|
|
7
7
|
const CALC_OPS = ["<=", ">=", "==", "!=", "<", ">"];
|
|
8
8
|
const code = (v) => `\`${String(v)}\``;
|
|
9
|
-
const plain = (v) => String(v);
|
|
10
9
|
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
11
10
|
const NUMERIC_TEXT = { $gt: ">", $gte: ">=", $lt: "<", $lte: "<=" };
|
|
12
11
|
/** Splits a list cell into trimmed, non-empty items. */
|
|
@@ -154,7 +153,7 @@ export function splitQuery(q) {
|
|
|
154
153
|
*/
|
|
155
154
|
export function explain(part, doc, hooks) {
|
|
156
155
|
const [key, arg] = Object.entries(part)[0];
|
|
157
|
-
const match = { code: "MATCH", message: "row does not match", column: "-", found: "-", expected: renderQuery(part,
|
|
156
|
+
const match = { code: "MATCH", message: "row does not match", column: "-", found: "-", expected: renderQuery(part, String) };
|
|
158
157
|
if (key === "$calc") {
|
|
159
158
|
const values = hooks.calcValues(arg, doc);
|
|
160
159
|
const text = isObject(arg) ? String(arg.expr) : String(arg);
|
|
@@ -169,7 +168,7 @@ export function explain(part, doc, hooks) {
|
|
|
169
168
|
if (key === "$or" || key === "$and") {
|
|
170
169
|
// The first failing part of each branch: all of them for $or, the first failing branch for $and.
|
|
171
170
|
const failures = arg.flatMap(branch => {
|
|
172
|
-
const failing = splitQuery(branch).find(p => !
|
|
171
|
+
const failing = splitQuery(branch).find(p => !queryTester(p, hooks)(doc));
|
|
173
172
|
return failing ? [explain(failing, doc, hooks)] : [];
|
|
174
173
|
});
|
|
175
174
|
if (key === "$and")
|
|
@@ -191,7 +190,7 @@ export function explain(part, doc, hooks) {
|
|
|
191
190
|
*/
|
|
192
191
|
function explainFirst(column, cond, value, hooks) {
|
|
193
192
|
const parts = splitCondition("_", cond);
|
|
194
|
-
const failing = parts.find(p => !
|
|
193
|
+
const failing = parts.find(p => !queryTester(p, hooks)({ _: value })) ?? parts[0];
|
|
195
194
|
return explainCondition(column, failing._, value, hooks);
|
|
196
195
|
}
|
|
197
196
|
/**
|
|
@@ -212,13 +211,13 @@ function explainFirst(column, cond, value, hooks) {
|
|
|
212
211
|
*/
|
|
213
212
|
function explainOr(column, alternatives, value, hooks) {
|
|
214
213
|
const text = valueText(value);
|
|
215
|
-
const expected = renderCondition({ $or: alternatives },
|
|
214
|
+
const expected = renderCondition({ $or: alternatives }, String);
|
|
216
215
|
const failures = alternatives.map(alt => explainFirst(column, alt, value, hooks));
|
|
217
216
|
const narrowed = failures.filter(f => f.code !== "MATCH" && f.found !== text && f.found !== "");
|
|
218
217
|
if (narrowed.length === 1)
|
|
219
218
|
return { ...narrowed[0], expected };
|
|
220
219
|
const shared = failures.every(f => f.code === failures[0].code) ? failures[0].code : null;
|
|
221
|
-
const names = alternatives.map((alt, i) => `(${renderCondition(alt,
|
|
220
|
+
const names = alternatives.map((alt, i) => `(${renderCondition(alt, String)})${shared ? "" : ` [${failures[i].code}]`}`);
|
|
222
221
|
const none = names.length === 2 ? `neither ${names[0]} nor ${names[1]}` : `none of ${names.join(", ")}`;
|
|
223
222
|
const failure = { code: shared ?? "NONE_OF", message: `'${text}' is ${none}`, column, found: text, expected };
|
|
224
223
|
return shared ? failure : { ...failure, alternatives: failures.map(f => ({ code: f.code, message: f.message })) };
|
|
@@ -227,14 +226,14 @@ function explainOr(column, alternatives, value, hooks) {
|
|
|
227
226
|
* Explains why one column's value fails a single-operator condition.
|
|
228
227
|
*
|
|
229
228
|
* @param {string} column - The column.
|
|
230
|
-
* @param {unknown} cond - The condition (one operator, or a
|
|
229
|
+
* @param {unknown} cond - The condition (one operator, or a String value).
|
|
231
230
|
* @param {Value} value - The value.
|
|
232
231
|
* @param {CheckHooks} hooks - The hooks the query ran with.
|
|
233
232
|
* @returns {Failure} The explanation.
|
|
234
233
|
*/
|
|
235
234
|
function explainCondition(column, cond, value, hooks) {
|
|
236
235
|
const text = valueText(value);
|
|
237
|
-
const expected = renderCondition(cond,
|
|
236
|
+
const expected = renderCondition(cond, String);
|
|
238
237
|
const fail = (c, message, found = text, exp = expected) => ({ code: c, message, column, found, expected: exp });
|
|
239
238
|
if (cond === null || (isObject(cond) && "$eq" in cond && cond.$eq === null))
|
|
240
239
|
return fail("EMPTY_IF", `${column} must be empty`, text, "empty");
|
|
@@ -273,7 +272,7 @@ function explainCondition(column, cond, value, hooks) {
|
|
|
273
272
|
case "$or":
|
|
274
273
|
return explainOr(column, arg, value, hooks);
|
|
275
274
|
case "$and": {
|
|
276
|
-
const sub = arg.find(c => !
|
|
275
|
+
const sub = arg.find(c => !queryTester({ _: c }, hooks)({ _: value }));
|
|
277
276
|
if (sub !== undefined)
|
|
278
277
|
return explainFirst(column, sub, value, hooks);
|
|
279
278
|
break;
|
|
@@ -283,7 +282,7 @@ function explainCondition(column, cond, value, hooks) {
|
|
|
283
282
|
const inner = isObject(arg) && Object.keys(arg).length === 1 ? arg : null;
|
|
284
283
|
if (!inner)
|
|
285
284
|
break;
|
|
286
|
-
const test =
|
|
285
|
+
const test = queryTester({ _: arg }, hooks);
|
|
287
286
|
const badItems = items.filter(x => !test({ _: x }));
|
|
288
287
|
const f = explainCondition(column, inner, badItems.length === 1 ? badItems[0] : badItems, hooks);
|
|
289
288
|
return { ...f, expected: `every item ${f.expected}` };
|
|
@@ -295,7 +294,7 @@ function explainCondition(column, cond, value, hooks) {
|
|
|
295
294
|
* One column condition in words, e.g. "one of `a`, `b`".
|
|
296
295
|
*
|
|
297
296
|
* @param {unknown} cond - The condition.
|
|
298
|
-
* @param {(v: unknown) => string} c - Formats a value (backticks for describe,
|
|
297
|
+
* @param {(v: unknown) => string} c - Formats a value (backticks for describe, String for diagnostics).
|
|
299
298
|
* @returns {string} The text.
|
|
300
299
|
*/
|
|
301
300
|
export function renderCondition(cond, c = code) {
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { BoundError } from "../../core/bound-error.js";
|
|
2
2
|
import { isDate } from "../../core/date.js";
|
|
3
3
|
import { Fraction } from "../../core/exact/fraction.js";
|
|
4
|
-
import {
|
|
4
|
+
import { queryTester } from "../../core/query.js";
|
|
5
5
|
import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
|
|
6
|
-
import { loadContract, parseRef, parseTableRef } from "../contract/load.js";
|
|
6
|
+
import { failedLoadStatus, loadContract, parseRef, parseTableRef } from "../contract/load.js";
|
|
7
7
|
import { keyColumns } from "../contract/model.js";
|
|
8
8
|
import { evaluateCalc, explain, listItems, mentions, numberColumns, parseCalc, renderCondition, splitQuery, } from "../contract/rules.js";
|
|
9
|
-
import { readTables } from "./read.js";
|
|
10
|
-
const plain = (v) => String(v);
|
|
9
|
+
import { FORMAT_FILES, formatMismatch, readTables } from "./read.js";
|
|
11
10
|
/**
|
|
12
11
|
* Why a value does not fit its column's type, or null when it fits.
|
|
13
12
|
*
|
|
@@ -54,9 +53,9 @@ function rowsOf(t, table, name, missing) {
|
|
|
54
53
|
const parsed = t.tables.get(name);
|
|
55
54
|
const key = table ? keyColumns(table) : [];
|
|
56
55
|
const columns = new Map((table?.columns ?? []).map(c => [c.name, c]));
|
|
56
|
+
const names = new Set([...parsed.header, ...columns.keys()]);
|
|
57
57
|
return parsed.rows.map((r, k) => {
|
|
58
58
|
const cells = Object.fromEntries(parsed.header.flatMap((h, i) => (r[i] === undefined ? [] : [[h, r[i]]])));
|
|
59
|
-
const names = new Set([...parsed.header, ...columns.keys()]);
|
|
60
59
|
const doc = Object.fromEntries([...names].map(n => [n, valueOf(cells[n], columns.get(n), missing)]));
|
|
61
60
|
const keyValues = key.map(c => cells[c] ?? "");
|
|
62
61
|
const label = key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`;
|
|
@@ -89,9 +88,8 @@ export function tableCheck(input) {
|
|
|
89
88
|
};
|
|
90
89
|
const loaded = loadContract(input.contract, diags);
|
|
91
90
|
label = loaded.label;
|
|
92
|
-
if (!loaded.contract)
|
|
93
|
-
return finish(diags
|
|
94
|
-
}
|
|
91
|
+
if (!loaded.contract)
|
|
92
|
+
return finish(failedLoadStatus(diags));
|
|
95
93
|
const contract = loaded.contract;
|
|
96
94
|
const extra = Object.keys(input.deps ?? {}).filter(a => !contract.depends_on?.[a]);
|
|
97
95
|
if (extra.length) {
|
|
@@ -99,13 +97,17 @@ export function tableCheck(input) {
|
|
|
99
97
|
}
|
|
100
98
|
/** Reads one tables file; failures become a status. */
|
|
101
99
|
const read = (path, c) => {
|
|
100
|
+
const format = c.format ?? "markdown";
|
|
101
|
+
const mismatch = formatMismatch(path, format);
|
|
102
|
+
if (mismatch)
|
|
103
|
+
return stop("INVALID_INPUT", "INVALID_INPUT", mismatch, path, FORMAT_FILES[format]);
|
|
102
104
|
try {
|
|
103
|
-
return readTables(path,
|
|
105
|
+
return readTables(path, format);
|
|
104
106
|
}
|
|
105
107
|
catch (e) {
|
|
106
108
|
if (e instanceof BoundError)
|
|
107
109
|
return stop("INVALID_INPUT", "TOO_LARGE", `${path}: ${e.message}`, path, `<= ${e.limit} rows`);
|
|
108
|
-
return stop("MISSING_DATA", "MISSING_FILE", `cannot read ${path}: ${e.message}`, path,
|
|
110
|
+
return stop("MISSING_DATA", "MISSING_FILE", `cannot read ${path}: ${e.message}`, path, FORMAT_FILES[format]);
|
|
109
111
|
}
|
|
110
112
|
};
|
|
111
113
|
const missingOf = (c) => {
|
|
@@ -206,7 +208,7 @@ export function tableCheck(input) {
|
|
|
206
208
|
*/
|
|
207
209
|
const runParts = (q, tableRows, hooks, skip, report) => {
|
|
208
210
|
for (const part of splitQuery(q)) {
|
|
209
|
-
const test =
|
|
211
|
+
const test = queryTester(part, hooks);
|
|
210
212
|
for (const r of tableRows.filter(row => !skip(row) && !test(row.doc)))
|
|
211
213
|
report(explain(part, r.doc, hooks), r);
|
|
212
214
|
}
|
|
@@ -237,14 +239,14 @@ export function tableCheck(input) {
|
|
|
237
239
|
if (!scope || !scopeRows)
|
|
238
240
|
return; // the table is missing: reported as MISSING_TABLE
|
|
239
241
|
const hooks = hooksFor(scope, !on.alias);
|
|
240
|
-
const when =
|
|
242
|
+
const when = queryTester(rule.when ?? {}, hooks);
|
|
241
243
|
const matching = scopeRows.filter(r => when(r.doc));
|
|
242
244
|
const where = { table: rule.on ?? owner.name, rule: rule.id ?? fallbackId };
|
|
243
245
|
const severity = rule.severity === "warning" ? "WARN" : "FAIL";
|
|
244
246
|
if (rule.count) {
|
|
245
|
-
const test =
|
|
247
|
+
const test = queryTester({ _: rule.count }, hooks);
|
|
246
248
|
if (!test({ _: String(matching.length) })) {
|
|
247
|
-
diags.push(diag("ROW_COUNT", `${matching.length} matching rows`, where, String(matching.length), renderCondition(rule.count,
|
|
249
|
+
diags.push(diag("ROW_COUNT", `${matching.length} matching rows`, where, String(matching.length), renderCondition(rule.count, String), severity));
|
|
248
250
|
}
|
|
249
251
|
return;
|
|
250
252
|
}
|
|
@@ -6,7 +6,7 @@ import { formatTableCheck, tableCheck } from "./check.js";
|
|
|
6
6
|
*
|
|
7
7
|
* @param {string[]} values - Raw flag values.
|
|
8
8
|
* @returns {Record<string, string>} alias -> tables file.
|
|
9
|
-
* @throws {Error} When a value has no
|
|
9
|
+
* @throws {Error} When a value has no `=` (an argument error: exit 2).
|
|
10
10
|
*/
|
|
11
11
|
function parseDeps(values) {
|
|
12
12
|
return Object.fromEntries(values.map(v => {
|
|
@@ -21,10 +21,13 @@ const check = {
|
|
|
21
21
|
describe: "Verify tables against an existing contract, e.g. many tables in one run",
|
|
22
22
|
builder: cli => cli.options({
|
|
23
23
|
contract: CONTRACT,
|
|
24
|
-
tables: {
|
|
24
|
+
tables: {
|
|
25
|
+
type: "string", demandOption: true,
|
|
26
|
+
describe: "Markdown file, or .csv file / folder of <Table>.csv when the contract has \"format\": \"csv\" (required)",
|
|
27
|
+
},
|
|
25
28
|
dep: {
|
|
26
29
|
type: "string", array: true, coerce: parseDeps,
|
|
27
|
-
describe: "<alias>=<tables file> for each alias in the contract's depends_on",
|
|
30
|
+
describe: "<alias>=<tables file> for each alias in the contract's depends_on, in that dependency contract's format",
|
|
28
31
|
},
|
|
29
32
|
json: JSON_FLAG,
|
|
30
33
|
})
|
|
@@ -47,7 +50,7 @@ const check = {
|
|
|
47
50
|
const table = {
|
|
48
51
|
command: "table",
|
|
49
52
|
describe: "Check Markdown/CSV tables against a contract",
|
|
50
|
-
builder: cli => cli.command(check).demandCommand(1),
|
|
53
|
+
builder: cli => cli.command(check).demandCommand(1, "table needs a subcommand: check"),
|
|
51
54
|
handler: () => { },
|
|
52
55
|
};
|
|
53
56
|
export default table;
|
|
@@ -1,9 +1,31 @@
|
|
|
1
|
-
import { readFileSync, statSync } from "node:fs";
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
2
|
import { basename, dirname } from "node:path";
|
|
3
3
|
import { parseCsvFolder } from "../../core/tables/csv.js";
|
|
4
4
|
import { parseMarkdown } from "../../core/tables/markdown.js";
|
|
5
5
|
/** Most rows read from one table. */
|
|
6
6
|
export const MAX_TABLE_ROWS = 100_000;
|
|
7
|
+
/** The files a format reads, for `expected`. */
|
|
8
|
+
export const FORMAT_FILES = { markdown: "a Markdown file", csv: "a .csv file or a folder of them" };
|
|
9
|
+
/**
|
|
10
|
+
* Why a path is in the wrong format for its contract, or null when it fits (or does not exist,
|
|
11
|
+
* which reading reports). Markdown parsing of CSV text finds no tables, so this must be checked
|
|
12
|
+
* first or a CSV dependency would silently look empty.
|
|
13
|
+
*
|
|
14
|
+
* @param {string} path - The file or folder.
|
|
15
|
+
* @param {"markdown" | "csv"} format - The contract's format.
|
|
16
|
+
* @returns {string | null} The problem, or null.
|
|
17
|
+
*/
|
|
18
|
+
export function formatMismatch(path, format) {
|
|
19
|
+
const csv = /\.csv$/i.test(path) || (existsSync(path) && statSync(path).isDirectory());
|
|
20
|
+
if (format === "markdown" && csv) {
|
|
21
|
+
return `${path} is CSV, but its contract reads Markdown: set "format": "csv" in that contract, or pass a Markdown file`;
|
|
22
|
+
}
|
|
23
|
+
if (format === "csv" && !csv && existsSync(path)) {
|
|
24
|
+
return `${path} is not CSV, but its contract reads CSV ("format": "csv"): pass a .csv file or a folder of them, `
|
|
25
|
+
+ `or remove "format" from that contract`;
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
7
29
|
/**
|
|
8
30
|
* Reads tables in a contract's format: a Markdown file, a folder of
|
|
9
31
|
* `<Table>.csv` files, or one `<Table>.csv` file.
|
|
@@ -21,8 +43,6 @@ export function readTables(path, format) {
|
|
|
21
43
|
const doc = parseCsvFolder(dirname(path), MAX_TABLE_ROWS);
|
|
22
44
|
const name = basename(path).replace(/\.csv$/i, "");
|
|
23
45
|
const only = doc.tables.get(name);
|
|
24
|
-
if (!only && !doc.malformed.some(([n]) => n === name))
|
|
25
|
-
throw new Error(`${path} is not a .csv file`);
|
|
26
46
|
return {
|
|
27
47
|
...doc,
|
|
28
48
|
tables: only ? new Map([[name, only]]) : new Map(),
|
|
@@ -81,7 +81,7 @@ const list = {
|
|
|
81
81
|
"Prints the tools of the Turing Code server that your token may call, one line each: the name",
|
|
82
82
|
"and the first line of its description. The list comes from the server, so it is always current.",
|
|
83
83
|
"`tool describe <name>` shows a tool's full description and arguments, before `tool call`.",
|
|
84
|
-
"Exit: 0 ok, 1 failed request.",
|
|
84
|
+
"Exit: 0 ok, 1 failed request, 2 bad arguments.",
|
|
85
85
|
TOKEN_HELP,
|
|
86
86
|
].join("\n")),
|
|
87
87
|
handler: async () => {
|
|
@@ -100,7 +100,7 @@ const describe = {
|
|
|
100
100
|
.epilogue([
|
|
101
101
|
"Prints each named tool as a `## <name>` section: its full description and its arguments",
|
|
102
102
|
"(type, required, default, description), which go in `tool call <name> --args`.",
|
|
103
|
-
"Exit: 0 ok, 1 unknown tool name or failed request.",
|
|
103
|
+
"Exit: 0 ok, 1 unknown tool name or failed request, 2 bad arguments.",
|
|
104
104
|
TOKEN_HELP,
|
|
105
105
|
].join("\n")),
|
|
106
106
|
handler: async (args) => {
|
|
@@ -131,7 +131,7 @@ const call = {
|
|
|
131
131
|
"leave it out for a tool without arguments.",
|
|
132
132
|
"The tool's text result goes to stdout: redirect it (`> file`) to save a large result without",
|
|
133
133
|
"reading it. A tool error is printed to stderr.",
|
|
134
|
-
"Exit: 0 ok, 1 tool error or failed request.",
|
|
134
|
+
"Exit: 0 ok, 1 tool error or failed request, 2 bad arguments (e.g. --args not a JSON object).",
|
|
135
135
|
TOKEN_HELP,
|
|
136
136
|
].join("\n")),
|
|
137
137
|
handler: args => runServerTool(args.name, (args.args ?? {})),
|
|
@@ -139,7 +139,7 @@ const call = {
|
|
|
139
139
|
const command = {
|
|
140
140
|
command: "tool",
|
|
141
141
|
describe: "List, describe or call tools on the Turing Code server",
|
|
142
|
-
builder: cli => cli.command(list).command(describe).command(call).demandCommand(1)
|
|
142
|
+
builder: cli => cli.command(list).command(describe).command(call).demandCommand(1, "tool needs a subcommand: list, describe or call")
|
|
143
143
|
.epilogue([
|
|
144
144
|
"Typical use: `tool list` to find a tool, `tool describe <name>` for its arguments, then",
|
|
145
145
|
"`tool call <name> --args ... > file` to save its result.",
|
package/package.json
CHANGED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { readJsonArg } from "../../core/files.js";
|
|
2
|
-
import { runServerTool } from "../../core/mcp.js";
|
|
3
|
-
/**
|
|
4
|
-
* Rejects number flags that yargs parsed to NaN.
|
|
5
|
-
*
|
|
6
|
-
* @param {number} value - Parsed flag value.
|
|
7
|
-
* @returns {number} The value.
|
|
8
|
-
* @throws {Error} When it is not a finite number.
|
|
9
|
-
*/
|
|
10
|
-
const finite = (value) => {
|
|
11
|
-
if (!Number.isFinite(value)) {
|
|
12
|
-
throw new Error(`expected a number, got '${value}'`);
|
|
13
|
-
}
|
|
14
|
-
return value;
|
|
15
|
-
};
|
|
16
|
-
const sharedOptions = {
|
|
17
|
-
project: { type: "string", describe: "Project folder name on the server" },
|
|
18
|
-
format: { choices: ["markdown", "json"], describe: "markdown | json (default markdown)" },
|
|
19
|
-
"hse-ppm": { type: "number", coerce: finite, describe: "HSE tolerance in ppm, for the worst case (default 0)" },
|
|
20
|
-
vdd: { type: "number", coerce: finite, describe: "Supply voltage in V, for SPI limits (default 3.3)" },
|
|
21
|
-
};
|
|
22
|
-
const solve = {
|
|
23
|
-
command: "solve",
|
|
24
|
-
describe: "Solve a clock tree for a target SYSCLK; prints a .ioc patch for stm32_cubetools_set_params",
|
|
25
|
-
builder: cli => cli.options({
|
|
26
|
-
...sharedOptions,
|
|
27
|
-
config: { type: "string", coerce: readJsonArg, describe: "Design (before a project exists), inline JSON or .json path" },
|
|
28
|
-
target: { type: "number", coerce: finite, describe: "Target SYSCLK in Hz (with --project)" },
|
|
29
|
-
objective: {
|
|
30
|
-
choices: ["exact_target", "min_error", "max_clock"],
|
|
31
|
-
describe: "exact_target | min_error | max_clock (default exact_target; with --project)",
|
|
32
|
-
},
|
|
33
|
-
})
|
|
34
|
-
.example(`$0 clock solve --config '{"part":"STM32G474RETx","sources":{"hse":{"hz":8000000,"ppm":50}},`
|
|
35
|
-
+ `"system":{"objective":"exact_target","target_sysclk_hz":170000000}}'`, "")
|
|
36
|
-
.example("$0 clock solve --project my_board --target 170000000", "")
|
|
37
|
-
.epilogue("Give --project, --config or both. With --config, put target, objective, ppm and vdd inside it "
|
|
38
|
-
+ "(system, sources, conditions)."),
|
|
39
|
-
handler: args => runServerTool("stm32_cubetools_clock_solve", {
|
|
40
|
-
project_name: args.project, config: args.config, target_sysclk_hz: args.target, objective: args.objective,
|
|
41
|
-
output_format: args.format, hse_ppm: args["hse-ppm"], vdd: args.vdd,
|
|
42
|
-
}),
|
|
43
|
-
};
|
|
44
|
-
const audit = {
|
|
45
|
-
command: "audit",
|
|
46
|
-
describe: "Audit a project's clocks and peripheral timing against the datasheet limits",
|
|
47
|
-
builder: cli => cli.options({
|
|
48
|
-
...sharedOptions,
|
|
49
|
-
project: { ...sharedOptions.project, demandOption: true, describe: "Project folder name on the server (required)" },
|
|
50
|
-
})
|
|
51
|
-
.example("$0 clock audit --project my_board", ""),
|
|
52
|
-
handler: args => runServerTool("stm32_cubetools_clock_audit", {
|
|
53
|
-
project_name: args.project, output_format: args.format, hse_ppm: args["hse-ppm"], vdd: args.vdd,
|
|
54
|
-
}),
|
|
55
|
-
};
|
|
56
|
-
const command = {
|
|
57
|
-
command: "clock",
|
|
58
|
-
describe: "Solve or audit an STM32 clock tree on the Turing Code server",
|
|
59
|
-
builder: cli => cli.command(solve).command(audit).demandCommand(1)
|
|
60
|
-
.epilogue("Needs TURINGCODE_TOKEN (gateway token); TURINGCODE_URL overrides the gateway."),
|
|
61
|
-
handler: () => { },
|
|
62
|
-
};
|
|
63
|
-
export default command;
|