@turingcode/cli 0.2.6 → 0.2.8

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 CHANGED
@@ -66,7 +66,7 @@ plus the operators below for references, exact numbers and checks across rows).
66
66
  | `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). |
67
67
  | `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
68
  | `allow_extra_tables` | `false` | Allow tables the contract does not declare. |
69
- | `depends_on` | | `alias -> contract file`; its tables are passed with `--dep alias=<file>`. |
69
+ | `depends_on` | | `alias -> contract file` (absolute, or relative to this contract); its tables are passed with `--dep alias=<file>`. |
70
70
 
71
71
  **Table**: `name` and `columns` are required.
72
72
 
@@ -114,7 +114,7 @@ is a value or an operator object. As in MongoDB:
114
114
  | --- | --- |
115
115
  | `$eq` `$ne` `$in` `$nin` | Equal / not equal / one of / none of (text, `true`/`false` or `null`). |
116
116
  | `$regex` `$options` | Regex search; anchor with `^...$` to match the whole value. |
117
- | `$gt` `$gte` `$lt` `$lte` | Exact number comparison (`0.1 + 0.2` is `0.3`); text never matches. |
117
+ | `$gt` `$gte` `$lt` `$lte` | Exact number comparison (`0.1 + 0.2` is `0.3`); text never matches. A `YYYY-MM-DD` bound compares dates instead, e.g. `{"$gte": "2026-01-01"}`; a cell that is not a date never matches. |
118
118
  | `$not` | The condition does not hold. |
119
119
  | `$or` `$and` `$nor` | Combine conditions; allowed in a column's condition too. |
120
120
  | `$ref` | The value exists in `Table.Column` or `alias:Table.Column`. |
@@ -0,0 +1,16 @@
1
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
2
+ /**
3
+ * Whether a text is a real calendar date written `YYYY-MM-DD`. Such dates sort
4
+ * correctly as plain text, so they can be compared without parsing.
5
+ *
6
+ * @param {string} v - The text to test.
7
+ * @returns {boolean} True for a valid date, false otherwise (including `2026-02-30`).
8
+ *
9
+ * @example
10
+ * isDate("2026-02-28"); // true
11
+ * isDate("2026-02-30"); // false
12
+ */
13
+ export function isDate(v) {
14
+ const m = DATE.exec(v);
15
+ return !!m && new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])).toISOString().startsWith(v);
16
+ }
@@ -25,14 +25,14 @@ export function readJsonFile(path) {
25
25
  }
26
26
  }
27
27
  /**
28
- * Reads a JSON flag: inline JSON, or a path to a .json file.
28
+ * Reads a JSON flag: inline JSON when it starts with `{` or `[`, otherwise a path to a .json file.
29
29
  *
30
30
  * @param {string} value - Raw flag value.
31
31
  * @returns {unknown} The parsed JSON.
32
32
  * @throws {Error} When the file cannot be read or the JSON is invalid.
33
33
  */
34
34
  export function readJsonArg(value) {
35
- const text = value.trimStart().startsWith("{") ? value : readFileSync(value, "utf-8");
35
+ const text = /^\s*[{[]/.test(value) ? value : readFileSync(value, "utf-8");
36
36
  try {
37
37
  return JSON.parse(text);
38
38
  }
package/dist/core/mcp.js CHANGED
@@ -19,18 +19,25 @@ export const TOKEN_HELP = [
19
19
  * @param {string} token - Bearer token for the gateway.
20
20
  * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
21
21
  * @returns {Promise<any>} The reply's `result`.
22
- * @throws {Error} On HTTP errors or a JSON-RPC error reply.
22
+ * @throws {Error} When the gateway cannot be reached, on HTTP errors, or on a JSON-RPC error reply.
23
23
  */
24
24
  async function postGateway(method, params, token, url = DEFAULT_URL) {
25
- const response = await fetch(url, {
26
- method: "POST",
27
- headers: {
28
- "Authorization": `Bearer ${token}`,
29
- "Content-Type": "application/json",
30
- "Accept": "application/json, text/event-stream",
31
- },
32
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
33
- });
25
+ let response;
26
+ try {
27
+ response = await fetch(url, {
28
+ method: "POST",
29
+ headers: {
30
+ "Authorization": `Bearer ${token}`,
31
+ "Content-Type": "application/json",
32
+ "Accept": "application/json, text/event-stream",
33
+ },
34
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
35
+ });
36
+ }
37
+ catch (e) {
38
+ const cause = e.cause;
39
+ throw new Error(`cannot reach the gateway at ${url}: ${cause?.code ?? cause?.message ?? e.message}`);
40
+ }
34
41
  const body = await response.text();
35
42
  if (!response.ok) {
36
43
  throw new Error(`gateway HTTP ${response.status}: ${body.trim() || response.statusText}`);
@@ -1,4 +1,5 @@
1
1
  import sift from "sift";
2
+ import { isDate } from "./date.js";
2
3
  import { Fraction } from "./exact/fraction.js";
3
4
  const { $and, $eq, $in, $ne, $nin, $nor, $not, $options, $or, $regex, createEqualsOperation, createQueryTester } = sift;
4
5
  /** Operators on one column's value. */
@@ -49,8 +50,9 @@ export function prepareQuery(query) {
49
50
  out[op] = arg;
50
51
  }
51
52
  else if (NUMERIC.has(op)) {
52
- if (!(typeof arg === "number" || typeof arg === "string") || !Fraction.parseDecimal(String(arg)))
53
- problem(here, "must be a number");
53
+ const ok = typeof arg === "number" || (typeof arg === "string" && (!!Fraction.parseDecimal(arg) || isDate(arg)));
54
+ if (!ok)
55
+ problem(here, "must be a number or a date YYYY-MM-DD");
54
56
  out[op] = arg;
55
57
  }
56
58
  else if (op === "$regex") {
@@ -164,8 +166,15 @@ export function prepareQuery(query) {
164
166
  }
165
167
  /** The whole list when sift passes one of its items (it walks arrays item by item), else the value. */
166
168
  const whole = (v, key, owner) => (typeof key === "number" && Array.isArray(owner) ? owner : v);
167
- /** Exact comparison of a number cell with a bound; anything that is not a number does not match. */
168
- const numeric = (holds) => (bound, owner, options) => {
169
+ /**
170
+ * Exact comparison of a cell with a bound: a `YYYY-MM-DD` bound compares date
171
+ * cells as text (such dates sort as text), any other bound compares number
172
+ * cells exactly. A cell of the other kind does not match.
173
+ */
174
+ const ordered = (holds) => (bound, owner, options) => {
175
+ if (typeof bound === "string" && isDate(bound)) {
176
+ return createEqualsOperation((v) => typeof v === "string" && isDate(v) && holds(v < bound ? -1 : v > bound ? 1 : 0), owner, options);
177
+ }
169
178
  const b = Fraction.parseDecimal(String(bound));
170
179
  return createEqualsOperation((v) => {
171
180
  const n = typeof v === "string" ? Fraction.parseDecimal(v) : null;
@@ -188,7 +197,7 @@ export function compileQuery(query, hooks) {
188
197
  const eq = (test) => (owner, options) => createEqualsOperation(test, owner, options);
189
198
  const operations = {
190
199
  $and, $eq, $in, $ne, $nin, $nor, $not, $options, $or, $regex,
191
- $gt: numeric(c => c > 0), $gte: numeric(c => c >= 0), $lt: numeric(c => c < 0), $lte: numeric(c => c <= 0),
200
+ $gt: ordered(c => c > 0), $gte: ordered(c => c >= 0), $lt: ordered(c => c < 0), $lte: ordered(c => c <= 0),
192
201
  $ref: (ref, o, opt) => eq(v => typeof v === "string" && hooks.ref(ref, v))(o, opt),
193
202
  $mentioned: (targets, o, opt) => eq(v => typeof v === "string" && hooks.mentioned(targets, v))(o, opt),
194
203
  $calc: (param, o, opt) => eq(v => hooks.calc(param, v))(o, opt),
@@ -44,7 +44,7 @@ Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an
44
44
  (split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
45
45
  and {"$ne": "x"} means "no item is x"). Operators:
46
46
  $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
47
- $gt $gte $lt $lte exact number comparison
47
+ $gt $gte $lt $lte exact number comparison, or date comparison with a "YYYY-MM-DD" bound
48
48
  $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
49
49
  $every {...} every list item meets the condition
50
50
  $length {...} length (chars, or list items) meets the condition
@@ -1,4 +1,4 @@
1
- import { basename, dirname, join, resolve } from "node:path";
1
+ import { basename, dirname, resolve } from "node:path";
2
2
  import { readJsonFile } from "../../core/files.js";
3
3
  import { checkShape, show } from "../../core/json-shape.js";
4
4
  import { diag } from "./diagnostics.js";
@@ -182,7 +182,7 @@ export function loadContract(path, out, stack = []) {
182
182
  for (const [alias, rel] of Object.entries(dependsOn)) {
183
183
  if (typeof rel !== "string")
184
184
  continue; // reported by the shape check
185
- const depPath = join(dirname(path), rel);
185
+ const depPath = resolve(dirname(path), rel);
186
186
  if ([...stack, full].includes(resolve(depPath))) {
187
187
  own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
188
188
  depsOk = false;
@@ -1,4 +1,5 @@
1
1
  import { BoundError } from "../../core/bound-error.js";
2
+ import { isDate } from "../../core/date.js";
2
3
  import { Fraction } from "../../core/exact/fraction.js";
3
4
  import { compileQuery, prepareQuery } from "../../core/query.js";
4
5
  import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
@@ -6,7 +7,6 @@ import { loadContract, parseRef, parseTableRef } from "../contract/load.js";
6
7
  import { keyColumns } from "../contract/model.js";
7
8
  import { evaluateCalc, explain, listItems, mentions, numberColumns, parseCalc, renderCondition, splitQuery, } from "../contract/rules.js";
8
9
  import { readTables } from "./read.js";
9
- const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
10
10
  const plain = (v) => String(v);
11
11
  /**
12
12
  * Why a value does not fit its column's type, or null when it fits.
@@ -23,11 +23,8 @@ function typeProblem(v, col) {
23
23
  return Fraction.parseDecimal(v) ? null : "a number";
24
24
  case "boolean":
25
25
  return v === "true" || v === "false" ? null : "true or false";
26
- case "date": {
27
- const m = DATE.exec(v);
28
- const ok = m && new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])).toISOString().startsWith(v);
29
- return ok ? null : "a date YYYY-MM-DD";
30
- }
26
+ case "date":
27
+ return isDate(v) ? null : "a date YYYY-MM-DD";
31
28
  default:
32
29
  return null;
33
30
  }
@@ -127,7 +127,7 @@ const call = {
127
127
  .epilogue([
128
128
  "Calls one tool of the Turing Code server. <name> comes from `tool list`, its arguments from",
129
129
  "`tool describe <name>`.",
130
- "--args is a JSON object: inline when it starts with `{`,",
130
+ "--args is a JSON object: inline when it starts with `{` or `[`,",
131
131
  "otherwise a path to a .json file; 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.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "description": "Turing Code toolkit for AI agents: check Markdown/CSV tables against table contracts, e.g. `turingcode table check`.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -31,4 +31,4 @@
31
31
  "@types/yargs": "17.0.35",
32
32
  "typescript": "7.0.2"
33
33
  }
34
- }
34
+ }