@turingcode/cli 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,197 @@
1
+ import { BoundError } from "../../core/bound-error.js";
2
+ import { AstError, evaluate, namesIn, parseExpression } from "../../core/exact/expression.js";
3
+ import { Fraction } from "../../core/exact/fraction.js";
4
+ /** Largest expression a `compare` rule may use. */
5
+ const MAX_EXPRESSION_NODES = 256;
6
+ const code = (v) => `\`${String(v)}\``;
7
+ const list = (vs) => vs.map(code).join(", ");
8
+ const SL = { list: "string", min: 1 };
9
+ const OPS = ["<", "<=", "==", "!=", ">=", ">"];
10
+ /** Number columns of a table: the names a `compare` expression may use. */
11
+ const numberColumns = (t) => new Set(t.columns.filter(c => c.type === "integer" || c.type === "number").map(c => c.name));
12
+ /**
13
+ * Parses a compare expression, reporting syntax errors and names that are not number columns.
14
+ *
15
+ * @param {string} text - The expression.
16
+ * @param {string} field - Rule parameter, for the report.
17
+ * @param {ValidateContext} v - Validation context.
18
+ * @returns {Node | null} The tree, or null when invalid.
19
+ */
20
+ function parseSide(text, field, v) {
21
+ const allowed = numberColumns(v.table);
22
+ try {
23
+ // Parse with every identifier allowed, then say which ones are not number columns.
24
+ const names = new Set(text.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? []);
25
+ const node = parseExpression(text, MAX_EXPRESSION_NODES, names);
26
+ const bad = [...namesIn(node)].filter(n => !allowed.has(n));
27
+ if (bad.length) {
28
+ v.problem("CONTRACT.BAD_EXPRESSION", `uses ${bad.join(", ")}, which ${bad.length > 1 ? "are" : "is"} not an integer/number column`, field, text, [...allowed].join(", ") || "(no number columns)");
29
+ return null;
30
+ }
31
+ return node;
32
+ }
33
+ catch (e) {
34
+ if (!(e instanceof AstError || e instanceof BoundError))
35
+ throw e;
36
+ v.problem("CONTRACT.BAD_EXPRESSION", e.message, field, text, "an arithmetic expression");
37
+ return null;
38
+ }
39
+ }
40
+ /** Splits a list cell into trimmed, non-empty items. */
41
+ export const listItems = (cell, separator = ",") => cell.split(separator).map(s => s.trim()).filter(Boolean);
42
+ /**
43
+ * Whether `word` occurs in `text` as a whole token (not inside a longer word or ID).
44
+ *
45
+ * @param {string} text - Text to search.
46
+ * @param {string} word - The value.
47
+ * @returns {boolean} True when mentioned.
48
+ */
49
+ export function mentions(text, word) {
50
+ const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
51
+ return new RegExp(`(?<![A-Za-z0-9_])${escaped}(?![A-Za-z0-9_]|-\\d)`).test(text);
52
+ }
53
+ /** `required_if` and `empty_if` share everything but the condition. */
54
+ function presenceRule(mustBeFilled) {
55
+ return {
56
+ params: { columns: SL },
57
+ validate: (rule, v) => v.requireColumns(rule.columns, "columns"),
58
+ check: ({ rule, rows, missing, fail }) => {
59
+ for (const r of rows) {
60
+ for (const col of rule.columns) {
61
+ if (missing(r.cells[col]) === mustBeFilled) {
62
+ fail(mustBeFilled ? "REQUIRED_IF" : "EMPTY_IF", mustBeFilled ? `${col} is empty` : `${col} must be empty`, r.label, col, r.cells[col] ?? "", mustBeFilled ? "a value" : "empty");
63
+ }
64
+ }
65
+ }
66
+ },
67
+ describe: rule => `${list(rule.columns)} must be ${mustBeFilled ? "filled" : "empty"}.`,
68
+ };
69
+ }
70
+ /** The rule kinds. A rule's `kind` picks one; its other fields are that kind's parameters. */
71
+ export const RULE_KINDS = {
72
+ required_if: presenceRule(true),
73
+ empty_if: presenceRule(false),
74
+ compare: {
75
+ params: { left: "string", op: { enum: OPS }, right: "string", "tolerance?": "number_or_string" },
76
+ validate: (rule, v) => {
77
+ parseSide(String(rule.left), "left", v);
78
+ parseSide(String(rule.right), "right", v);
79
+ if (rule.tolerance !== undefined) {
80
+ const t = Fraction.parseDecimal(String(rule.tolerance));
81
+ if (!t || t.cmp(new Fraction(0n)) < 0) {
82
+ v.problem("CONTRACT.BAD_FIELD", "tolerance must be a number >= 0", "tolerance", String(rule.tolerance), ">= 0");
83
+ }
84
+ }
85
+ },
86
+ check: ({ rule, table, rows, missing, fail }) => {
87
+ const allowed = numberColumns(table);
88
+ const left = parseExpression(String(rule.left), MAX_EXPRESSION_NODES, allowed);
89
+ const right = parseExpression(String(rule.right), MAX_EXPRESSION_NODES, allowed);
90
+ const tol = rule.tolerance === undefined ? new Fraction(0n) : Fraction.parseDecimal(String(rule.tolerance));
91
+ for (const r of rows) {
92
+ const env = {};
93
+ for (const n of allowed)
94
+ env[n] = missing(r.cells[n]) ? null : Fraction.parseDecimal(r.cells[n] ?? "");
95
+ let l;
96
+ let rv;
97
+ try {
98
+ l = evaluate(left, env);
99
+ rv = evaluate(right, env);
100
+ }
101
+ catch {
102
+ continue; // e.g. division by zero with these values: nothing to compare
103
+ }
104
+ if (!l || !rv)
105
+ continue; // a missing or non-number value is reported by the column check
106
+ const diff = l.sub(rv).abs().cmp(tol);
107
+ const c = l.cmp(rv);
108
+ const holds = { "<": c < 0, "<=": c <= 0, "==": diff <= 0, "!=": diff > 0, ">=": c >= 0, ">": c > 0 }[rule.op];
109
+ if (!holds) {
110
+ fail("COMPARE", `${rule.left} ${rule.op} ${rule.right} is false (${l.toDecimal()} vs ${rv.toDecimal()})`, r.label, "-", `${l.toDecimal()} ${rule.op} ${rv.toDecimal()}`, `${rule.left} ${rule.op} ${rule.right}`);
111
+ }
112
+ }
113
+ },
114
+ describe: rule => `${code(`${rule.left} ${rule.op} ${rule.right}`)} must hold`
115
+ + (rule.tolerance !== undefined ? ` (within ${rule.tolerance})` : "") + ".",
116
+ },
117
+ unique_together: {
118
+ params: { columns: SL },
119
+ validate: (rule, v) => v.requireColumns(rule.columns, "columns"),
120
+ check: ({ rule, rows, missing, fail }) => {
121
+ const cols = rule.columns;
122
+ const seen = new Set();
123
+ for (const r of rows) {
124
+ const values = cols.map(c => r.cells[c] ?? "");
125
+ if (values.some(v => missing(v)))
126
+ continue;
127
+ const key = values.join("\u0000");
128
+ if (seen.has(key)) {
129
+ fail("UNIQUE_TOGETHER", `${cols.join(" + ")} is used twice`, r.label, cols.join("+"), values.join(" / "), "a unique combination");
130
+ }
131
+ seen.add(key);
132
+ }
133
+ },
134
+ describe: rule => `The combination of ${list(rule.columns)} must be unique.`,
135
+ },
136
+ row_count: {
137
+ params: { "min?": "int", "max?": "int" },
138
+ validate: (rule, v) => {
139
+ if (rule.min === undefined && rule.max === undefined) {
140
+ v.problem("CONTRACT.BAD_FIELD", "row_count needs min, max or both", "min", "(absent)", "min and/or max");
141
+ }
142
+ else if (rule.min !== undefined && rule.max !== undefined && rule.min > rule.max) {
143
+ v.problem("CONTRACT.CONFLICT", "min is greater than max", "min", `${rule.min} > ${rule.max}`, "min <= max");
144
+ }
145
+ },
146
+ check: ({ rule, rows, fail }) => {
147
+ const n = rows.length;
148
+ if ((rule.min !== undefined && n < rule.min) || (rule.max !== undefined && n > rule.max)) {
149
+ fail("ROW_COUNT", `${n} matching rows`, "-", "-", String(n), rule.min === undefined ? `<= ${rule.max}` : rule.max === undefined ? `>= ${rule.min}` : `${rule.min}..${rule.max}`);
150
+ }
151
+ },
152
+ describe: rule => (rule.min !== undefined && rule.max !== undefined
153
+ ? rule.min === rule.max ? `Exactly ${rule.min} row(s).` : `${rule.min} to ${rule.max} rows.`
154
+ : rule.min !== undefined ? `At least ${rule.min} row(s).` : `At most ${rule.max} row(s).`),
155
+ },
156
+ mentioned: {
157
+ params: { values_of: "string", in: "string_or_list" },
158
+ validate: (rule, v) => {
159
+ const ref = v.resolve(String(rule.values_of), "values_of", true);
160
+ if (ref && (ref.alias || ref.table !== v.table) && rule.when) {
161
+ v.problem("CONTRACT.CONFLICT", "when filters this table's rows, but values_of is another table's column", "when", JSON.stringify(rule.when), "no when, or values_of in this table");
162
+ }
163
+ for (const target of [rule.in].flat()) {
164
+ if (target !== "*")
165
+ v.resolve(target, "in", false);
166
+ }
167
+ },
168
+ check: ({ rule, table, rows, missing, refRows, columnText, textOutside, fail }) => {
169
+ const source = refRows(String(rule.values_of));
170
+ if (!source)
171
+ return; // dependency tables not read: reported as missing input
172
+ // `when` filters the rule's own table, so its rows are used when values_of is one of its columns.
173
+ const sourceRows = source.own && source.table === table.name ? rows : source.rows;
174
+ const targets = [rule.in].flat();
175
+ const text = targets.map(t => (t === "*" ? textOutside(source.own ? [source.table] : []) : columnText(t))).join("\n");
176
+ for (const r of sourceRows) {
177
+ const cell = r.cells[source.column.name] ?? "";
178
+ if (missing(cell))
179
+ continue;
180
+ const values = source.column.type === "list" ? listItems(cell, source.column.separator) : [cell];
181
+ for (const value of values.filter(x => !mentions(text, x))) {
182
+ fail("NOT_MENTIONED", `${value} is not mentioned in ${targets.join(", ")}`, source.own ? r.label : "-", source.column.name, value, targets.includes("*") ? "a mention in the document" : `a mention in ${targets.join(", ")}`);
183
+ }
184
+ }
185
+ },
186
+ describe: rule => {
187
+ const targets = [rule.in].flat();
188
+ return `Every value of ${code(rule.values_of)} must be mentioned `
189
+ + (targets.includes("*") ? "elsewhere in the document." : `in ${list(targets)}.`);
190
+ },
191
+ },
192
+ };
193
+ /** One plain-language line for a rule's `when`, e.g. "When `Kind` is `EXTRACTED`: ". */
194
+ export function whenText(rule) {
195
+ const parts = Object.entries(rule.when ?? {}).map(([col, v]) => `${code(col)} is ${Array.isArray(v) ? `one of ${list(v)}` : code(v)}`);
196
+ return parts.length ? `When ${parts.join(" and ")}: ` : "";
197
+ }
@@ -0,0 +1,295 @@
1
+ import { BoundError } from "../../core/bound-error.js";
2
+ import { Fraction } from "../../core/exact/fraction.js";
3
+ import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
4
+ import { loadContract, parseRef } from "../contract/load.js";
5
+ import { keyColumns } from "../contract/model.js";
6
+ import { listItems, RULE_KINDS } from "../contract/rules.js";
7
+ import { readTables } from "./read.js";
8
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
9
+ /**
10
+ * Why a value does not fit its column's type, or null when it fits.
11
+ *
12
+ * @param {string} v - The cell (not missing).
13
+ * @param {Column} col - Its column.
14
+ * @returns {string | null} The expected type, or null.
15
+ */
16
+ function typeProblem(v, col) {
17
+ switch (col.type ?? "string") {
18
+ case "integer":
19
+ return /^[+-]?\d+$/.test(v) ? null : "an integer";
20
+ case "number":
21
+ return Fraction.parseDecimal(v) ? null : "a number";
22
+ case "boolean":
23
+ return v === "true" || v === "false" ? null : "true or false";
24
+ case "date": {
25
+ const m = DATE.exec(v);
26
+ const ok = m && new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])).toISOString().startsWith(v);
27
+ return ok ? null : "a date YYYY-MM-DD";
28
+ }
29
+ default:
30
+ return null;
31
+ }
32
+ }
33
+ /** Rows of a table keyed by its header; the label is the primary key, or `#n`. */
34
+ function rowsOf(t, table, name, missing) {
35
+ const parsed = t.tables.get(name);
36
+ const key = table ? keyColumns(table) : [];
37
+ return parsed.rows.filter(r => r.length === parsed.header.length).map((r, k) => {
38
+ const cells = Object.fromEntries(parsed.header.map((h, i) => [h, r[i]]));
39
+ const keyValues = key.map(c => cells[c] ?? "");
40
+ return { label: key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`, cells };
41
+ });
42
+ }
43
+ /**
44
+ * Checks tables against a contract: tables and columns, every cell against
45
+ * its column, references, then the rules.
46
+ *
47
+ * @param {TableCheckInput} input - Contract, tables and dependency tables.
48
+ * @returns {TableCheckResult} Status, summary and diagnostics.
49
+ *
50
+ * @example
51
+ * tableCheck({ contract: "orders.contract.json", tables: "orders.md" }).status; // "PASS"
52
+ */
53
+ export function tableCheck(input) {
54
+ const diags = [];
55
+ let label = input.contract;
56
+ const summary = { tables: 0, rows: 0, fails: 0, warnings: 0 };
57
+ const finish = (status) => {
58
+ const all = sortDiagnostics(diags);
59
+ summary.fails = all.filter(d => d.severity === "FAIL").length;
60
+ summary.warnings = all.length - summary.fails;
61
+ return { status: status ?? (summary.fails ? "FAIL" : "PASS"), contract: label, summary, diagnostics: all };
62
+ };
63
+ const stop = (status, code, message, found, expected) => {
64
+ diags.push(diag(code, message, {}, found, expected));
65
+ return finish(status);
66
+ };
67
+ const loaded = loadContract(input.contract, diags);
68
+ label = loaded.label;
69
+ if (!loaded.contract) {
70
+ return finish(diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT");
71
+ }
72
+ const contract = loaded.contract;
73
+ const extra = Object.keys(input.deps ?? {}).filter(a => !contract.depends_on?.[a]);
74
+ if (extra.length) {
75
+ return stop("INVALID_INPUT", "INVALID_INPUT", `--dep ${extra.join(", ")} is not in the contract's depends_on`, extra.join(", "), Object.keys(contract.depends_on ?? {}).join(", ") || "(no depends_on)");
76
+ }
77
+ /** Reads one tables file; failures become a status. */
78
+ const read = (path, c) => {
79
+ try {
80
+ return readTables(path, c.format ?? "markdown");
81
+ }
82
+ catch (e) {
83
+ if (e instanceof BoundError)
84
+ return stop("INVALID_INPUT", "TOO_LARGE", `${path}: ${e.message}`, path, `<= ${e.limit} rows`);
85
+ return stop("MISSING_DATA", "MISSING_FILE", `cannot read ${path}: ${e.message}`, path, c.format === "csv" ? "a .csv file or a folder of them" : "a Markdown file");
86
+ }
87
+ };
88
+ const missingOf = (c) => {
89
+ const values = new Set(c.missing_values ?? [""]);
90
+ return (v) => v === undefined || values.has(v);
91
+ };
92
+ const deps = new Map();
93
+ for (const [alias, dep] of loaded.deps) {
94
+ const path = input.deps?.[alias];
95
+ if (!path) {
96
+ return stop("MISSING_DATA", "MISSING_DEPENDENCY", `no tables given for dependency '${alias}'`, "(absent)", `--dep ${alias}=<its tables>`);
97
+ }
98
+ const text = read(path, dep.contract);
99
+ if ("status" in text)
100
+ return text;
101
+ const depMissing = missingOf(dep.contract);
102
+ const rows = new Map([...text.tables.keys()].map(n => [n, rowsOf(text, dep.contract.tables.find(t => t.name === n), n, depMissing)]));
103
+ deps.set(alias, { contract: dep.contract, text, rows });
104
+ }
105
+ const text = read(input.tables, contract);
106
+ if ("status" in text)
107
+ return text;
108
+ const missing = missingOf(contract);
109
+ const rows = checkStructure(contract, text, missing, diags);
110
+ summary.tables = rows.size;
111
+ summary.rows = [...rows.values()].reduce((n, r) => n + r.length, 0);
112
+ const self = { contract, text, rows };
113
+ /** Rows, column and owner of a reference. */
114
+ const refRows = (ref, owner) => {
115
+ const p = parseRef(ref);
116
+ const doc = p.alias ? deps.get(p.alias) : self;
117
+ const tableName = p.table ?? owner.name;
118
+ const table = doc?.contract.tables.find(t => t.name === tableName);
119
+ const column = table?.columns.find(c => c.name === p.column);
120
+ const tableRows = doc?.rows.get(tableName);
121
+ return doc && column && tableRows ? { rows: tableRows, column, table: tableName, own: !p.alias } : null;
122
+ };
123
+ /** Non-missing values (list items split) of a reference. */
124
+ const refValues = (ref, owner) => {
125
+ const r = refRows(ref, owner);
126
+ if (!r)
127
+ return null;
128
+ const docMissing = parseRef(ref).alias ? missingOf(deps.get(parseRef(ref).alias).contract) : missing;
129
+ return new Set(r.rows.flatMap(row => {
130
+ const v = row.cells[r.column.name];
131
+ return docMissing(v) ? [] : r.column.type === "list" ? listItems(v, r.column.separator) : [v];
132
+ }));
133
+ };
134
+ for (const t of contract.tables) {
135
+ const tableRows = rows.get(t.name);
136
+ if (!tableRows)
137
+ continue;
138
+ for (const col of t.columns.filter(c => c.references)) {
139
+ const known = refValues(col.references, t);
140
+ if (!known)
141
+ continue; // the referenced table is missing: reported as MISSING_TABLE
142
+ for (const r of tableRows) {
143
+ const v = r.cells[col.name];
144
+ if (missing(v))
145
+ continue;
146
+ for (const item of (col.type === "list" ? listItems(v, col.separator) : [v]).filter(x => !known.has(x))) {
147
+ diags.push(diag("UNKNOWN_REF", `${item} is not a value of ${col.references}`, { table: t.name, row: r.label, column: col.name }, item, `a value of ${col.references}`));
148
+ }
149
+ }
150
+ }
151
+ (t.rules ?? []).forEach((rule, i) => {
152
+ const when = Object.entries(rule.when ?? {});
153
+ const matching = tableRows.filter(r => when.every(([c, v]) => (Array.isArray(v) ? v.includes(r.cells[c]) : r.cells[c] === v)));
154
+ const ruleId = rule.id ?? `${t.name}.rules[${i}]`;
155
+ const ctx = {
156
+ rule, table: t, rows: matching, missing,
157
+ refRows: ref => refRows(ref, t),
158
+ columnText: ref => {
159
+ const r = refRows(ref, t);
160
+ return r ? r.rows.map(row => row.cells[r.column.name] ?? "").join("\n") : "";
161
+ },
162
+ textOutside: names => text.textOutside(names),
163
+ fail: (code, message, row, column, found, expected) => diags.push(diag(code, message, { table: t.name, row, column, rule: ruleId }, found, expected, rule.severity === "warning" ? "WARN" : "FAIL")),
164
+ };
165
+ RULE_KINDS[rule.kind].check(ctx);
166
+ });
167
+ }
168
+ return finish();
169
+ }
170
+ /**
171
+ * Checks tables, columns and every cell against the contract's declarations.
172
+ *
173
+ * @param {Contract} c - The contract.
174
+ * @param {TablesDoc} doc - The tables.
175
+ * @param {(v: string | undefined) => boolean} missing - Missing-value test.
176
+ * @param {Diagnostic[]} out - Receives diagnostics.
177
+ * @returns {Map<string, Row[]>} Rows of every declared table that could be read.
178
+ */
179
+ function checkStructure(c, doc, missing, out) {
180
+ const rows = new Map();
181
+ for (const name of doc.duplicates) {
182
+ out.push(diag("DUPLICATE_TABLE", `table ${name} appears more than once`, { table: name }, name, "one table"));
183
+ }
184
+ for (const [name, message] of doc.malformed) {
185
+ out.push(diag("BAD_TABLE", message, { table: name }, name, "header, separator, rows"));
186
+ }
187
+ const declared = new Set(c.tables.map(t => t.name));
188
+ for (const name of doc.tables.keys()) {
189
+ if (!declared.has(name) && !c.allow_extra_tables) {
190
+ out.push(diag("EXTRA_TABLE", `table ${name} is not in the contract`, { table: name }, name, [...declared].join(", ")));
191
+ }
192
+ }
193
+ for (const t of c.tables) {
194
+ const parsed = doc.tables.get(t.name);
195
+ if (!parsed) {
196
+ if (t.required !== false && !doc.malformed.some(([n]) => n === t.name)) {
197
+ out.push(diag("MISSING_TABLE", `table ${t.name} is missing`, { table: t.name }, "(absent)", t.name));
198
+ }
199
+ continue;
200
+ }
201
+ const header = parsed.header;
202
+ const dupes = header.filter((h, i) => header.indexOf(h) !== i);
203
+ if (dupes.length) {
204
+ out.push(diag("DUPLICATE_COLUMN", `column ${dupes[0]} appears twice`, { table: t.name, column: dupes[0] }, header.join(" | "), "each column once"));
205
+ continue;
206
+ }
207
+ const names = t.columns.map(col => col.name);
208
+ for (const col of names.filter(n => !header.includes(n))) {
209
+ out.push(diag("MISSING_COLUMN", `column ${col} is missing`, { table: t.name, column: col }, header.join(" | "), names.join(" | ")));
210
+ }
211
+ if (!t.allow_extra_columns) {
212
+ for (const h of header.filter(h => !names.includes(h))) {
213
+ out.push(diag("EXTRA_COLUMN", `column ${h} is not in the contract`, { table: t.name, column: h }, h, names.join(" | ")));
214
+ }
215
+ }
216
+ const present = header.filter(h => names.includes(h));
217
+ if (t.ordered && present.join("\n") !== names.filter(n => header.includes(n)).join("\n")) {
218
+ out.push(diag("COLUMN_ORDER", "columns are not in the declared order", { table: t.name }, header.join(" | "), names.join(" | ")));
219
+ }
220
+ parsed.rows.forEach((cells, k) => {
221
+ if (cells.length !== header.length) {
222
+ out.push(diag("ROW_SHAPE", `line ${parsed.rowLines[k]} has ${cells.length} cells`, { table: t.name, row: `#${k + 1}` }, String(cells.length), `${header.length} cells`));
223
+ }
224
+ });
225
+ const tableRows = rowsOf(doc, t, t.name, missing);
226
+ const key = keyColumns(t);
227
+ const seen = new Map();
228
+ const seenKeys = new Set();
229
+ for (const r of tableRows) {
230
+ const at = (column) => ({ table: t.name, row: r.label, column });
231
+ for (const col of t.columns.filter(col => header.includes(col.name))) {
232
+ const v = r.cells[col.name];
233
+ if (missing(v)) {
234
+ if (col.required || key.includes(col.name))
235
+ out.push(diag("MISSING_VALUE", `${col.name} is empty`, at(col.name), v, "a value"));
236
+ continue;
237
+ }
238
+ const typeIssue = typeProblem(v, col);
239
+ if (typeIssue) {
240
+ out.push(diag("BAD_TYPE", `'${v}' is not ${typeIssue}`, at(col.name), v, typeIssue));
241
+ continue;
242
+ }
243
+ const items = col.type === "list" ? listItems(v, col.separator) : [v];
244
+ for (const item of items) {
245
+ if (col.enum && !col.enum.includes(item)) {
246
+ out.push(diag("BAD_VALUE", `'${item}' is not allowed`, at(col.name), item, col.enum.join(", ")));
247
+ }
248
+ if (col.pattern && !new RegExp(`^(?:${col.pattern})$`).test(item)) {
249
+ out.push(diag("PATTERN", `'${item}' does not match the pattern`, at(col.name), item, col.pattern));
250
+ }
251
+ }
252
+ if (col.type === "integer" || col.type === "number") {
253
+ const n = Fraction.parseDecimal(v);
254
+ const min = col.minimum !== undefined ? Fraction.parseDecimal(String(col.minimum)) : null;
255
+ const max = col.maximum !== undefined ? Fraction.parseDecimal(String(col.maximum)) : null;
256
+ if ((min && n.cmp(min) < 0) || (max && n.cmp(max) > 0)) {
257
+ out.push(diag("OUT_OF_RANGE", `${v} is out of range`, at(col.name), v, min && max ? `${col.minimum}..${col.maximum}` : min ? `>= ${col.minimum}` : `<= ${col.maximum}`));
258
+ }
259
+ }
260
+ const length = col.type === "list" ? items.length : [...v].length;
261
+ if ((col.min_length !== undefined && length < col.min_length) || (col.max_length !== undefined && length > col.max_length)) {
262
+ out.push(diag("BAD_LENGTH", `length ${length} is out of range`, at(col.name), String(length), `${col.min_length ?? 0}..${col.max_length ?? "any"}`));
263
+ }
264
+ if (col.unique) {
265
+ const values = seen.get(col.name) ?? new Set();
266
+ if (values.has(v))
267
+ out.push(diag("DUPLICATE_KEY", `${col.name} '${v}' is used twice`, at(col.name), v, "a unique value"));
268
+ seen.set(col.name, values.add(v));
269
+ }
270
+ }
271
+ if (key.length && key.every(k => header.includes(k) && !missing(r.cells[k]))) {
272
+ const k = key.map(c => r.cells[c]).join("\u0000");
273
+ if (seenKeys.has(k)) {
274
+ out.push(diag("DUPLICATE_KEY", `primary key ${r.label} is used twice`, at(key.join("+")), r.label, "a unique primary key"));
275
+ }
276
+ seenKeys.add(k);
277
+ }
278
+ }
279
+ rows.set(t.name, tableRows);
280
+ }
281
+ return rows;
282
+ }
283
+ /**
284
+ * Compact text for a table check result.
285
+ *
286
+ * @param {TableCheckResult} r - The result.
287
+ * @returns {string} Status line, then the diagnostics.
288
+ */
289
+ export function formatTableCheck(r) {
290
+ const s = r.summary;
291
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
292
+ const head = `${r.status} ${r.contract}: ${plural(s.tables, "table")}, ${plural(s.rows, "row")}, ${s.fails} FAIL`
293
+ + (s.warnings ? `, ${s.warnings} WARN` : "");
294
+ return [head, ...formatDiagnostics(r.diagnostics)].join("\n") + "\n";
295
+ }
@@ -1,106 +1,53 @@
1
- import { contractCheck } from "./contract_check.js";
2
- import { describeContract } from "./describe.js";
3
- import { formatContractCheck, formatTableCheck } from "./format.js";
4
- import { tableCheck } from "./table_check.js";
5
- const EXIT_CODES = { VALID: 0, OK: 0, PASS: 0, INVALID_CONTRACT: 1, FAIL: 1 };
1
+ import { report } from "../../core/report.js";
2
+ import { CONTRACT, JSON_FLAG } from "../contract/command.js";
3
+ import { formatTableCheck, tableCheck } from "./check.js";
6
4
  /**
7
- * Prints a tool result, as compact text or (with --json) as one-line JSON,
8
- * and sets the exit code from its status (0 ok, 1 invalid/fail, 2 otherwise).
9
- *
10
- * @param {{status: string}} result - The tool result.
11
- * @param {string} text - Its compact text form.
12
- * @param {boolean} [json] - Print the full JSON object instead.
13
- */
14
- const report = (result, text, json) => {
15
- process.stdout.write(json ? JSON.stringify(result) + "\n" : text);
16
- process.exitCode = EXIT_CODES[result.status] ?? 2;
17
- };
18
- const CONTRACT = { type: "string", demandOption: true, describe: "Contract JSON (required)" };
19
- const SOURCE_KINDS = { type: "string", demandOption: true, describe: "source_kinds registry JSON the contract pins (required)" };
20
- const JSON_FLAG = { type: "boolean", describe: "Full result as one-line JSON" };
21
- const check = {
22
- command: "check",
23
- describe: "Validate a contract",
24
- builder: cli => cli.options({
25
- contract: { ...CONTRACT, demandOption: false, describe: "Contract JSON (required unless --kit-manifest)" },
26
- "source-kinds": SOURCE_KINDS,
27
- kit: { type: "boolean", describe: "Also validate the contracts it depends on (found next to it) and the references between them" },
28
- "kit-manifest": { type: "string", describe: "With --kit: JSON {\"contracts\": {\"<id>@<version>\": \"<path>\"}} to validate" },
29
- json: JSON_FLAG,
30
- })
31
- .example("$0 contract check --contract orders.json --source-kinds source_kinds.json --kit", "")
32
- .epilogue("Exit: 0 VALID, 1 INVALID_CONTRACT, 2 bad input or missing file."),
33
- handler: args => {
34
- const result = contractCheck({
35
- contract_path: args.contract, source_kinds_path: args["source-kinds"], kit: args.kit,
36
- kit_manifest_path: args["kit-manifest"],
37
- });
38
- report(result, formatContractCheck(result), args.json);
39
- },
40
- };
41
- const describe = {
42
- command: "describe",
43
- describe: "Print the tables a contract expects, their columns and rules, as Markdown",
44
- builder: cli => cli.options({ contract: CONTRACT, "source-kinds": SOURCE_KINDS, json: JSON_FLAG })
45
- .example("$0 contract describe --contract orders.json --source-kinds source_kinds.json", ""),
46
- handler: args => {
47
- const result = describeContract({ contract_path: args.contract, source_kinds_path: args["source-kinds"] });
48
- report(result, result.markdown ?? formatContractCheck(result), args.json);
49
- },
50
- };
51
- /**
52
- * Parses `--dep <contract_id@version>=<tables file>` flags.
5
+ * Parses `--dep <alias>=<tables file>` flags.
53
6
  *
54
7
  * @param {string[]} values - Raw flag values.
55
- * @returns {Record<string, {output_path: string}>} pin -> tables file.
8
+ * @returns {Record<string, string>} alias -> tables file.
56
9
  * @throws {Error} When a value has no `=`.
57
10
  */
58
11
  function parseDeps(values) {
59
12
  return Object.fromEntries(values.map(v => {
60
13
  const at = v.indexOf("=");
61
14
  if (at < 1)
62
- throw new Error(`--dep expects <contract_id@version>=<tables file>, got '${v}'`);
63
- return [v.slice(0, at), { output_path: v.slice(at + 1) }];
15
+ throw new Error(`--dep expects <alias>=<tables file>, got '${v}'`);
16
+ return [v.slice(0, at), v.slice(at + 1)];
64
17
  }));
65
18
  }
66
- const tableCheckCommand = {
19
+ const check = {
67
20
  command: "check",
68
- describe: "Check tables against a contract",
21
+ describe: "Verify tables against an existing contract, e.g. many tables in one run",
69
22
  builder: cli => cli.options({
70
23
  contract: CONTRACT,
71
- "source-kinds": SOURCE_KINDS,
72
- tables: { type: "string", demandOption: true, describe: "Markdown file of tables, or folder of <Table>.csv (required)" },
24
+ tables: { type: "string", demandOption: true, describe: "Markdown file, or .csv file / folder of <Table>.csv (required)" },
73
25
  dep: {
74
26
  type: "string", array: true, coerce: parseDeps,
75
- describe: "<pin>=<tables file> for each contract this one depends on (`contract describe` lists them)",
27
+ describe: "<alias>=<tables file> for each alias in the contract's depends_on",
76
28
  },
77
- "contract-id": { type: "string", describe: "Expected <contract_id>@<version> of --contract" },
78
29
  json: JSON_FLAG,
79
30
  })
80
- .example("$0 table check --contract orders.json --source-kinds source_kinds.json --tables orders.md", "")
31
+ .example("$0 table check --contract orders.contract.json --tables orders.md", "")
32
+ .example("$0 table check --contract shop.contract.json --tables exports/", "every <table>.csv in a folder, in one run")
81
33
  .epilogue([
82
- "Prints PASS or FAIL, then each failing item with how to fix it; after fixing, run it again to confirm.",
83
- "Rules listed as \"not checked yet\" are not verified by this version. `contract describe` shows the tables a contract expects.",
34
+ "Use it to verify many tables at once against a contract you already have: all tables of one",
35
+ "Markdown file, or a folder of CSV files, in one run.",
36
+ "Tables file: Markdown with each table under a `## <table name>` heading: a header row, a `|---|` row,",
37
+ "then one row per line (write \\| for a | inside a cell). Or CSV: one <table name>.csv per table.",
38
+ "Prints PASS or FAIL, then each failing item (table, row, column, found, expected) and how to fix it;",
39
+ "after fixing, run it again to confirm. `contract describe` shows the tables a contract expects.",
84
40
  "Exit: 0 PASS, 1 FAIL or invalid contract, 2 bad input or missing file.",
85
41
  ].join("\n")),
86
42
  handler: args => {
87
- const result = tableCheck({
88
- contract_path: args.contract, source_kinds_path: args["source-kinds"], output_path: args.tables,
89
- contract_id: args["contract-id"], upstream_outputs: args.dep,
90
- });
43
+ const result = tableCheck({ contract: args.contract, tables: args.tables, deps: args.dep });
91
44
  report(result, formatTableCheck(result), args.json);
92
45
  },
93
46
  };
94
- const contract = {
95
- command: "contract",
96
- describe: "Validate a table contract, or print the tables it expects",
97
- builder: cli => cli.command(check).command(describe).demandCommand(1),
98
- handler: () => { },
99
- };
100
47
  const table = {
101
48
  command: "table",
102
49
  describe: "Check Markdown/CSV tables against a contract",
103
- builder: cli => cli.command(tableCheckCommand).demandCommand(1),
50
+ builder: cli => cli.command(check).demandCommand(1),
104
51
  handler: () => { },
105
52
  };
106
- export default [contract, table];
53
+ export default table;
@@ -0,0 +1,33 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { basename, dirname } from "node:path";
3
+ import { parseCsvFolder } from "../../core/tables/csv.js";
4
+ import { parseMarkdown } from "../../core/tables/markdown.js";
5
+ /** Most rows read from one table. */
6
+ export const MAX_TABLE_ROWS = 100_000;
7
+ /**
8
+ * Reads tables in a contract's format: a Markdown file, a folder of
9
+ * `<Table>.csv` files, or one `<Table>.csv` file.
10
+ *
11
+ * @param {string} path - The file or folder.
12
+ * @param {"markdown" | "csv"} format - The contract's format.
13
+ * @returns {TablesDoc} The tables.
14
+ * @throws {Error} When the path cannot be read; BoundError when a table has too many rows.
15
+ */
16
+ export function readTables(path, format) {
17
+ if (format === "markdown")
18
+ return parseMarkdown(readFileSync(path, "utf-8"), MAX_TABLE_ROWS);
19
+ if (statSync(path).isDirectory())
20
+ return parseCsvFolder(path, MAX_TABLE_ROWS);
21
+ const doc = parseCsvFolder(dirname(path), MAX_TABLE_ROWS);
22
+ const name = basename(path).replace(/\.csv$/i, "");
23
+ 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
+ return {
27
+ ...doc,
28
+ tables: only ? new Map([[name, only]]) : new Map(),
29
+ malformed: doc.malformed.filter(([n]) => n === name),
30
+ text: only ? readFileSync(path, "utf-8") : "",
31
+ textOutside: names => (names.includes(name) ? "" : readFileSync(path, "utf-8")),
32
+ };
33
+ }