@turingcode/cli 0.2.13 → 0.3.5

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.
Files changed (185) hide show
  1. package/README.md +2 -0
  2. package/dist/cli/create-cli.d.ts +10 -0
  3. package/dist/cli/create-cli.js +17 -4
  4. package/dist/cli/index.d.ts +9 -0
  5. package/dist/cli/index.js +5 -1
  6. package/dist/core/bound-error.d.ts +10 -0
  7. package/dist/core/date.d.ts +12 -0
  8. package/dist/core/exact/expression.d.ts +49 -0
  9. package/dist/core/exact/fraction.d.ts +85 -0
  10. package/dist/core/exact/fraction.js +2 -0
  11. package/dist/core/files.d.ts +44 -0
  12. package/dist/core/files.js +48 -3
  13. package/dist/core/json-shape.d.ts +45 -0
  14. package/dist/core/json-shape.js +1 -0
  15. package/dist/core/mcp.d.ts +92 -0
  16. package/dist/core/mcp.js +56 -15
  17. package/dist/core/query.d.ts +69 -0
  18. package/dist/core/query.js +2 -2
  19. package/dist/core/report.d.ts +11 -0
  20. package/dist/core/tables/csv.d.ts +29 -0
  21. package/dist/core/tables/csv.js +54 -25
  22. package/dist/core/tables/markdown.d.ts +22 -0
  23. package/dist/core/tables/markdown.js +8 -2
  24. package/dist/core/tables/types.d.ts +25 -0
  25. package/dist/features/contract/check.d.ts +30 -0
  26. package/dist/features/contract/command.d.ts +12 -0
  27. package/dist/features/contract/command.js +64 -64
  28. package/dist/features/contract/describe.d.ts +22 -0
  29. package/dist/features/contract/diagnostics.d.ts +111 -0
  30. package/dist/features/contract/diagnostics.js +7 -4
  31. package/dist/features/contract/load.d.ts +58 -0
  32. package/dist/features/contract/load.js +4 -4
  33. package/dist/features/contract/model.d.ts +67 -0
  34. package/dist/features/contract/rules.d.ts +149 -0
  35. package/dist/features/contract/rules.js +31 -4
  36. package/dist/features/debug/clear_breakpoint.d.ts +3 -0
  37. package/dist/features/debug/clear_breakpoint.js +24 -0
  38. package/dist/features/debug/command.d.ts +5 -0
  39. package/dist/features/debug/command.js +66 -0
  40. package/dist/features/debug/continue.d.ts +3 -0
  41. package/dist/features/debug/continue.js +22 -0
  42. package/dist/features/debug/debug_start.d.ts +3 -0
  43. package/dist/features/debug/debug_start.js +22 -0
  44. package/dist/features/debug/debug_stop.d.ts +3 -0
  45. package/dist/features/debug/debug_stop.js +11 -0
  46. package/dist/features/debug/evaluate.d.ts +3 -0
  47. package/dist/features/debug/evaluate.js +48 -0
  48. package/dist/features/debug/get_stack.d.ts +3 -0
  49. package/dist/features/debug/get_stack.js +14 -0
  50. package/dist/features/debug/get_variables.d.ts +3 -0
  51. package/dist/features/debug/get_variables.js +26 -0
  52. package/dist/features/debug/halt.d.ts +3 -0
  53. package/dist/features/debug/halt.js +16 -0
  54. package/dist/features/debug/set_breakpoint.d.ts +3 -0
  55. package/dist/features/debug/set_breakpoint.js +30 -0
  56. package/dist/features/debug/step.d.ts +3 -0
  57. package/dist/features/debug/step.js +23 -0
  58. package/dist/features/install-mods/command.d.ts +6 -0
  59. package/dist/features/install-mods/command.js +18 -0
  60. package/dist/features/install-mods/install.d.ts +23 -0
  61. package/dist/features/install-mods/install.js +49 -0
  62. package/dist/features/install-skills/command.d.ts +7 -0
  63. package/dist/features/install-skills/command.js +22 -0
  64. package/dist/features/install-skills/install.d.ts +14 -0
  65. package/dist/features/install-skills/install.js +29 -0
  66. package/dist/features/probe/command.d.ts +5 -0
  67. package/dist/features/probe/command.js +112 -0
  68. package/dist/features/probe/kill_all_debuggers.d.ts +3 -0
  69. package/dist/features/probe/kill_all_debuggers.js +50 -0
  70. package/dist/features/probe/list_probes.d.ts +3 -0
  71. package/dist/features/probe/list_probes.js +8 -0
  72. package/dist/features/probe/program_project.d.ts +3 -0
  73. package/dist/features/probe/program_project.js +29 -0
  74. package/dist/features/probe/read_fault_status.d.ts +3 -0
  75. package/dist/features/probe/read_fault_status.js +19 -0
  76. package/dist/features/probe/read_memory.d.ts +3 -0
  77. package/dist/features/probe/read_memory.js +36 -0
  78. package/dist/features/probe/read_peripheral.d.ts +3 -0
  79. package/dist/features/probe/read_peripheral.js +60 -0
  80. package/dist/features/probe/reset_probe_usb.d.ts +3 -0
  81. package/dist/features/probe/reset_probe_usb.js +17 -0
  82. package/dist/features/probe/reset_target.d.ts +3 -0
  83. package/dist/features/probe/reset_target.js +16 -0
  84. package/dist/features/probe/target_info.d.ts +3 -0
  85. package/dist/features/probe/target_info.js +34 -0
  86. package/dist/features/project/analysis_static.d.ts +3 -0
  87. package/dist/features/project/analysis_static.js +19 -0
  88. package/dist/features/project/analysis_syntax_check.d.ts +3 -0
  89. package/dist/features/project/analysis_syntax_check.js +21 -0
  90. package/dist/features/project/command.d.ts +5 -0
  91. package/dist/features/project/command.js +64 -0
  92. package/dist/features/project/project_build.d.ts +3 -0
  93. package/dist/features/project/project_build.js +22 -0
  94. package/dist/features/project/project_download_template.d.ts +3 -0
  95. package/dist/features/project/project_download_template.js +34 -0
  96. package/dist/features/project/project_regenerate.d.ts +2 -0
  97. package/dist/features/project/project_regenerate.js +20 -0
  98. package/dist/features/project/project_sync_from_server.d.ts +2 -0
  99. package/dist/features/project/project_sync_from_server.js +13 -0
  100. package/dist/features/project/project_sync_to_server.d.ts +2 -0
  101. package/dist/features/project/project_sync_to_server.js +51 -0
  102. package/dist/features/project/stm32_cubetools_download_drivers.d.ts +3 -0
  103. package/dist/features/project/stm32_cubetools_download_drivers.js +19 -0
  104. package/dist/features/status/command.d.ts +2 -0
  105. package/dist/features/status/command.js +6 -0
  106. package/dist/features/status/get_status.d.ts +3 -0
  107. package/dist/features/status/get_status.js +44 -0
  108. package/dist/features/table/check.d.ts +38 -0
  109. package/dist/features/table/check.js +5 -5
  110. package/dist/features/table/command.d.ts +3 -0
  111. package/dist/features/table/read.d.ts +28 -0
  112. package/dist/features/table/read.js +9 -9
  113. package/dist/features/tool/command.d.ts +35 -0
  114. package/dist/features/tool/command.js +95 -66
  115. package/dist/lib.d.ts +15 -0
  116. package/dist/lib.js +11 -0
  117. package/dist/stm32/actions/DebugAction.d.ts +65 -0
  118. package/dist/stm32/actions/DebugAction.js +106 -0
  119. package/dist/stm32/actions/DebugActionInfo.d.ts +11 -0
  120. package/dist/stm32/actions/DebugActionInfo.js +11 -0
  121. package/dist/stm32/actions/DebugActionListProbes.d.ts +10 -0
  122. package/dist/stm32/actions/DebugActionListProbes.js +10 -0
  123. package/dist/stm32/actions/DebugActionProgram.d.ts +34 -0
  124. package/dist/stm32/actions/DebugActionProgram.js +81 -0
  125. package/dist/stm32/actions/DebugActionRead.d.ts +39 -0
  126. package/dist/stm32/actions/DebugActionRead.js +61 -0
  127. package/dist/stm32/actions/DebugActionReset.d.ts +12 -0
  128. package/dist/stm32/actions/DebugActionReset.js +9 -0
  129. package/dist/stm32/actions/DebugActionServer.d.ts +11 -0
  130. package/dist/stm32/actions/DebugActionServer.js +11 -0
  131. package/dist/stm32/analysis.d.ts +20 -0
  132. package/dist/stm32/analysis.js +21 -0
  133. package/dist/stm32/build.d.ts +34 -0
  134. package/dist/stm32/build.js +79 -0
  135. package/dist/stm32/context.d.ts +23 -0
  136. package/dist/stm32/context.js +42 -0
  137. package/dist/stm32/daemon.d.ts +65 -0
  138. package/dist/stm32/daemon.js +209 -0
  139. package/dist/stm32/regen.d.ts +68 -0
  140. package/dist/stm32/regen.js +231 -0
  141. package/dist/stm32/session.d.ts +137 -0
  142. package/dist/stm32/session.js +375 -0
  143. package/dist/stm32/sync.d.ts +25 -0
  144. package/dist/stm32/sync.js +74 -0
  145. package/dist/stm32/tool.d.ts +45 -0
  146. package/dist/stm32/tool.js +20 -0
  147. package/dist/stm32/toolCommand.d.ts +50 -0
  148. package/dist/stm32/toolCommand.js +100 -0
  149. package/dist/stm32/utils/discover_tools.d.ts +25 -0
  150. package/dist/stm32/utils/discover_tools.js +121 -0
  151. package/dist/stm32/utils/downloadzip_utils.d.ts +57 -0
  152. package/dist/stm32/utils/downloadzip_utils.js +180 -0
  153. package/dist/stm32/utils/faultUtils.d.ts +15 -0
  154. package/dist/stm32/utils/faultUtils.js +69 -0
  155. package/dist/stm32/utils/findElf.d.ts +9 -0
  156. package/dist/stm32/utils/findElf.js +19 -0
  157. package/dist/stm32/utils/hash_utils.d.ts +19 -0
  158. package/dist/stm32/utils/hash_utils.js +28 -0
  159. package/dist/stm32/utils/listSyncFiles.d.ts +9 -0
  160. package/dist/stm32/utils/listSyncFiles.js +100 -0
  161. package/dist/stm32/utils/mcu_utils.d.ts +58 -0
  162. package/dist/stm32/utils/mcu_utils.js +100 -0
  163. package/dist/stm32/utils/project_utils.d.ts +54 -0
  164. package/dist/stm32/utils/project_utils.js +104 -0
  165. package/dist/stm32/utils/svdUtils.d.ts +31 -0
  166. package/dist/stm32/utils/svdUtils.js +30 -0
  167. package/dist/stm32/utils/truncate.d.ts +7 -0
  168. package/dist/stm32/utils/truncate.js +9 -0
  169. package/dist/stm32/utils/usb_utils.d.ts +5 -0
  170. package/dist/stm32/utils/usb_utils.js +23 -0
  171. package/dist/stm32/utils/user_code.d.ts +17 -0
  172. package/dist/stm32/utils/user_code.js +45 -0
  173. package/dist/stm32/utils/utils_mutex.d.ts +15 -0
  174. package/dist/stm32/utils/utils_mutex.js +113 -0
  175. package/dist/stm32/validate.d.ts +17 -0
  176. package/dist/stm32/validate.js +46 -0
  177. package/mods/claude/.claude-plugin/marketplace.json +8 -0
  178. package/mods/claude/turingcode-skills/.claude-plugin/plugin.json +5 -0
  179. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +44 -0
  180. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +47 -0
  181. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +42 -0
  182. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +35 -0
  183. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +21 -0
  184. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +35 -0
  185. package/package.json +11 -3
@@ -0,0 +1,69 @@
1
+ /** A MongoDB-style query. */
2
+ export type Query = Record<string, unknown>;
3
+ /** A cell as a query sees it: text, `true`/`false` for booleans, items for lists, null when missing. */
4
+ export type Value = string | boolean | string[] | null;
5
+ /** A row as a query sees it: column name -> value. */
6
+ export type Doc = Record<string, Value>;
7
+ /** Operators that need the caller's data (other tables, the document text, exact arithmetic over the row). */
8
+ export interface QueryHooks {
9
+ /** `$ref`: whether the value exists in the referenced column. */
10
+ ref(ref: string, value: string): boolean;
11
+ /** `$mentioned`: whether the value is mentioned in the targets. */
12
+ mentioned(targets: string[], value: string): boolean;
13
+ /** `$calc`: whether the comparison holds for the row (true when it cannot be evaluated). */
14
+ calc(param: unknown, doc: Doc): boolean;
15
+ }
16
+ /** A query rewritten for sift, with what it uses and what is wrong with it. */
17
+ export interface PreparedQuery {
18
+ query: Query;
19
+ /** Column names the query reads. */
20
+ fields: string[];
21
+ /** Every `$ref` value. */
22
+ refs: string[];
23
+ /** Every `$mentioned` target. */
24
+ mentions: string[];
25
+ /** Every `$calc` parameter. */
26
+ calcs: unknown[];
27
+ /** Readable problems; the query must not be run when there are any. */
28
+ problems: string[];
29
+ }
30
+ /** Operators on one column's value. */
31
+ export declare const FIELD_OPERATORS: string[];
32
+ /** Operators on a whole row (besides column names). */
33
+ export declare const ROW_OPERATORS: string[];
34
+ /**
35
+ * Checks a row query and rewrites it for sift: a column's `$or`/`$and`/`$nor`
36
+ * is lifted to the row (sift allows them only there), and `$every`/`$length`
37
+ * sub-queries are prepared too.
38
+ *
39
+ * @param {unknown} query - The query from the contract.
40
+ * @returns {PreparedQuery} The rewritten query, what it uses and its problems.
41
+ *
42
+ * @example
43
+ * prepareQuery({ Kind: { $in: ["a", "b"] }, Qty: { $gte: 1 } }).fields; // ["Kind", "Qty"]
44
+ */
45
+ export declare function prepareQuery(query: unknown): PreparedQuery;
46
+ /**
47
+ * Compiles a prepared query into a row tester. `$unique` remembers the values
48
+ * it has seen, so run one tester over the rows in order.
49
+ *
50
+ * @param {Query} query - `prepareQuery(...).query` with no problems.
51
+ * @param {QueryHooks} hooks - `$ref`, `$mentioned` and `$calc`.
52
+ * @returns {(doc: Doc) => boolean} Whether a row matches.
53
+ * @throws {Error} When sift rejects the query, e.g. an invalid `$regex`.
54
+ *
55
+ * @example
56
+ * compileQuery(prepareQuery({ Qty: { $gte: 1 } }).query, hooks)({ Qty: "2" }); // true
57
+ */
58
+ export declare function compileQuery(query: Query, hooks: QueryHooks): (doc: Doc) => boolean;
59
+ /**
60
+ * Prepares and compiles a query in one step (for queries `contract check` already validated).
61
+ *
62
+ * @param {unknown} query - The query from the contract.
63
+ * @param {QueryHooks} hooks - `$ref`, `$mentioned` and `$calc`.
64
+ * @returns {(doc: Doc) => boolean} Whether a row matches.
65
+ *
66
+ * @example
67
+ * queryTester({ Qty: { $gte: 1 } }, hooks)({ Qty: "2" }); // true
68
+ */
69
+ export declare const queryTester: (query: unknown, hooks: QueryHooks) => ((doc: Doc) => boolean);
@@ -92,7 +92,7 @@ export function prepareQuery(query) {
92
92
  out[op] = ops(arg, here);
93
93
  }
94
94
  else {
95
- // $every, $length: a query on each item / on the length, tested on the placeholder column.
95
+ /** $every, $length: a query on each item / on the length, tested on the placeholder column. */
96
96
  out[op] = field(ITEM, arg, here);
97
97
  }
98
98
  }
@@ -216,7 +216,7 @@ export function compileQuery(query, hooks) {
216
216
  return n !== null && test({ [ITEM]: String(n) });
217
217
  })(o, opt);
218
218
  },
219
- // ponytail: remembers every value it has seen; fine for one pass over a table's rows.
219
+ /** ponytail: remembers every value it has seen; fine for one pass over a table's rows. */
220
220
  $unique: (param, o, opt) => {
221
221
  const seen = new Set();
222
222
  return eq((v, k, own) => {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Prints a tool result, as compact text or (with json) as one-line JSON,
3
+ * and sets the process exit code from its status.
4
+ *
5
+ * @param {{status: string}} result - The tool result.
6
+ * @param {string} text - Its compact text form.
7
+ * @param {boolean} [json] - Print the full JSON object instead.
8
+ */
9
+ export declare function report(result: {
10
+ status: string;
11
+ }, text: string, json?: boolean): void;
@@ -0,0 +1,29 @@
1
+ import { ParsedTable, TablesDoc } from "./types.js";
2
+ /**
3
+ * Parses CSV text (RFC 4180: quoted fields, doubled quotes, CRLF).
4
+ *
5
+ * @param {string} text - The CSV text.
6
+ * @param {number[]} [lines] - Filled with each returned record's 1-based starting line.
7
+ * @returns {string[][]} Records; fields are not trimmed.
8
+ * @throws {Error} On an unterminated quoted field.
9
+ */
10
+ export declare function parseCsv(text: string, lines?: number[]): string[][];
11
+ /**
12
+ * Reads one `<Table>.csv` file's text as a table named after the file.
13
+ *
14
+ * @param {string} file - The file name, for the table name and messages.
15
+ * @param {string} text - The file's text.
16
+ * @param {number} maxRows - `bounds.max_table_rows`.
17
+ * @returns {ParsedTable | string} The table, or why it is malformed.
18
+ * @throws {BoundError} When the table has more than maxRows rows.
19
+ */
20
+ export declare function parseCsvTable(file: string, text: string, maxRows: number): ParsedTable | string;
21
+ /**
22
+ * Reads a folder of CSV tables: holding one `<Table>.csv` per table.
23
+ *
24
+ * @param {string} dir - The folder.
25
+ * @param {number} maxRows - `bounds.max_table_rows`.
26
+ * @returns {TablesDoc} The tables.
27
+ * @throws {BoundError} When a table has more than maxRows rows.
28
+ */
29
+ export declare function parseCsvFolder(dir: string, maxRows: number): TablesDoc;
@@ -5,14 +5,29 @@ import { BoundError } from "../bound-error.js";
5
5
  * Parses CSV text (RFC 4180: quoted fields, doubled quotes, CRLF).
6
6
  *
7
7
  * @param {string} text - The CSV text.
8
+ * @param {number[]} [lines] - Filled with each returned record's 1-based starting line.
8
9
  * @returns {string[][]} Records; fields are not trimmed.
9
10
  * @throws {Error} On an unterminated quoted field.
10
11
  */
11
- export function parseCsv(text) {
12
+ export function parseCsv(text, lines = []) {
12
13
  const records = [];
13
14
  let record = [];
14
15
  let field = "";
15
16
  let quoted = false;
17
+ let hadQuote = false;
18
+ let line = 1;
19
+ let start = 1;
20
+ /** Ends the record; a blank line (one empty unquoted field) is dropped. */
21
+ const endRecord = () => {
22
+ record.push(field);
23
+ if (hadQuote || record.length > 1 || field !== "") {
24
+ records.push(record);
25
+ lines.push(start);
26
+ }
27
+ record = [];
28
+ field = "";
29
+ hadQuote = false;
30
+ };
16
31
  const src = text.replace(/^/, "");
17
32
  for (let i = 0; i < src.length; i++) {
18
33
  const ch = src[i];
@@ -25,11 +40,14 @@ export function parseCsv(text) {
25
40
  quoted = false;
26
41
  }
27
42
  else {
43
+ if (ch === "\n" || (ch === "\r" && src[i + 1] !== "\n"))
44
+ line++;
28
45
  field += ch;
29
46
  }
30
47
  }
31
48
  else if (ch === '"' && field === "") {
32
49
  quoted = true;
50
+ hadQuote = true;
33
51
  }
34
52
  else if (ch === ",") {
35
53
  record.push(field);
@@ -38,10 +56,8 @@ export function parseCsv(text) {
38
56
  else if (ch === "\n" || ch === "\r") {
39
57
  if (ch === "\r" && src[i + 1] === "\n")
40
58
  i++;
41
- record.push(field);
42
- records.push(record);
43
- record = [];
44
- field = "";
59
+ endRecord();
60
+ start = ++line;
45
61
  }
46
62
  else {
47
63
  field += ch;
@@ -49,11 +65,35 @@ export function parseCsv(text) {
49
65
  }
50
66
  if (quoted)
51
67
  throw new Error("unterminated quoted field");
52
- if (field !== "" || record.length) {
53
- record.push(field);
54
- records.push(record);
68
+ if (field !== "" || record.length || hadQuote)
69
+ endRecord();
70
+ return records;
71
+ }
72
+ /**
73
+ * Reads one `<Table>.csv` file's text as a table named after the file.
74
+ *
75
+ * @param {string} file - The file name, for the table name and messages.
76
+ * @param {string} text - The file's text.
77
+ * @param {number} maxRows - `bounds.max_table_rows`.
78
+ * @returns {ParsedTable | string} The table, or why it is malformed.
79
+ * @throws {BoundError} When the table has more than maxRows rows.
80
+ */
81
+ export function parseCsvTable(file, text, maxRows) {
82
+ const name = basename(file, file.slice(-4));
83
+ const lines = [];
84
+ let records;
85
+ try {
86
+ records = parseCsv(text, lines);
55
87
  }
56
- return records.filter(r => !(r.length === 1 && r[0] === ""));
88
+ catch (e) {
89
+ return `${file}: ${e.message}`;
90
+ }
91
+ if (!records.length)
92
+ return `${file}: no header row`;
93
+ const rows = records.slice(1).map(r => r.map(c => c.trim()));
94
+ if (rows.length > maxRows)
95
+ throw new BoundError("max_table_rows", maxRows);
96
+ return { name, header: records[0].map(c => c.trim()), rows, rowLines: lines.slice(1) };
57
97
  }
58
98
  /**
59
99
  * Reads a folder of CSV tables: holding one `<Table>.csv` per table.
@@ -71,22 +111,11 @@ export function parseCsvFolder(dir, maxRows) {
71
111
  const name = basename(file, file.slice(-4));
72
112
  const text = readFileSync(join(dir, file), "utf-8");
73
113
  texts.set(name, text);
74
- let records;
75
- try {
76
- records = parseCsv(text);
77
- }
78
- catch (e) {
79
- malformed.push([name, `${file}: ${e.message}`]);
80
- continue;
81
- }
82
- if (!records.length) {
83
- malformed.push([name, `${file}: no header row`]);
84
- continue;
85
- }
86
- const rows = records.slice(1).map(r => r.map(c => c.trim()));
87
- if (rows.length > maxRows)
88
- throw new BoundError("max_table_rows", maxRows);
89
- tables.set(name, { name, header: records[0].map(c => c.trim()), rows, rowLines: rows.map((_, k) => k + 2) });
114
+ const table = parseCsvTable(file, text, maxRows);
115
+ if (typeof table === "string")
116
+ malformed.push([name, table]);
117
+ else
118
+ tables.set(name, table);
90
119
  }
91
120
  return {
92
121
  tables, duplicates: [], malformed, text: [...texts.values()].join("\n"),
@@ -0,0 +1,22 @@
1
+ import { TablesDoc } from "./types.js";
2
+ /**
3
+ * Splits one Markdown table line into trimmed cells; `\|` is a literal pipe.
4
+ *
5
+ * @param {string} line - A line starting with `|`.
6
+ * @returns {string[]} The cells.
7
+ *
8
+ * @example
9
+ * splitRow("| a | b \\| c |"); // ["a", "b | c"]
10
+ */
11
+ export declare function splitRow(line: string): string[];
12
+ /**
13
+ * Reads the tables of a Markdown document. A table is the first pipe
14
+ * table under a `## <Name>` heading; pipe tables inside fenced code blocks
15
+ * are ignored.
16
+ *
17
+ * @param {string} text - The Markdown text.
18
+ * @param {number} maxRows - `bounds.max_table_rows`.
19
+ * @returns {TablesDoc} The tables.
20
+ * @throws {BoundError} When a table has more than maxRows rows.
21
+ */
22
+ export declare function parseMarkdown(text: string, maxRows: number): TablesDoc;
@@ -1,6 +1,6 @@
1
1
  import { BoundError } from "../bound-error.js";
2
2
  const SEPARATOR = /^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
3
- const HEADING = /^##\s+(.+?)\s*#*\s*$/;
3
+ const HEADING = /^##\s+(.+?)(?:\s+#+)?\s*$/;
4
4
  /**
5
5
  * Splits one Markdown table line into trimmed cells; `\|` is a literal pipe.
6
6
  *
@@ -49,9 +49,11 @@ export function parseMarkdown(text, maxRows) {
49
49
  const tables = new Map();
50
50
  const duplicates = [];
51
51
  const malformed = [];
52
- /** [table name, first line index, end line index (exclusive)] of every pipe-table block. */
52
+ /** [table name, first line index, end line index (exclusive)] of each section's pipe-table block. */
53
53
  const blocks = [];
54
54
  let section = null;
55
+ /** The current section already had its pipe table; later ones are ignored. */
56
+ let taken = false;
55
57
  let fenced = false;
56
58
  for (let i = 0; i < lines.length; i++) {
57
59
  const line = lines[i];
@@ -64,6 +66,7 @@ export function parseMarkdown(text, maxRows) {
64
66
  const heading = HEADING.exec(line);
65
67
  if (heading || /^#\s/.test(line)) {
66
68
  section = heading ? heading[1] : null;
69
+ taken = false;
67
70
  continue;
68
71
  }
69
72
  if (section === null || !line.trim().startsWith("|"))
@@ -71,6 +74,9 @@ export function parseMarkdown(text, maxRows) {
71
74
  const start = i;
72
75
  while (i + 1 < lines.length && lines[i + 1].trim().startsWith("|"))
73
76
  i++;
77
+ if (taken)
78
+ continue;
79
+ taken = true;
74
80
  const block = lines.slice(start, i + 1);
75
81
  blocks.push([section, start, i + 1]);
76
82
  if (tables.has(section) || malformed.some(([n]) => n === section)) {
@@ -0,0 +1,25 @@
1
+ /** One table read from a Markdown or CSV document. */
2
+ export interface ParsedTable {
3
+ name: string;
4
+ header: string[];
5
+ rows: string[][];
6
+ /** 1-based source line of each row, for messages. */
7
+ rowLines: number[];
8
+ }
9
+ /** A document of tables, plus the problems found while reading it. */
10
+ export interface TablesDoc {
11
+ tables: Map<string, ParsedTable>;
12
+ /** Table names that appear more than once. */
13
+ duplicates: string[];
14
+ /** `[table, message]` for tables whose layout could not be read. */
15
+ malformed: [string, string][];
16
+ /** Full text, for citation checks. */
17
+ text: string;
18
+ /**
19
+ * The text without the named tables (their header, separator and rows).
20
+ *
21
+ * @param {string[]} sections - Table names to leave out.
22
+ * @returns {string} The remaining text.
23
+ */
24
+ textOutside(sections: string[]): string;
25
+ }
@@ -0,0 +1,30 @@
1
+ import { Diagnostic } from "./diagnostics.js";
2
+ export interface ContractCheckResult {
3
+ status: "VALID" | "INVALID_CONTRACT" | "MISSING_DATA";
4
+ contract: string;
5
+ /** Labels of the contract and every dependency that was checked. */
6
+ checked: string[];
7
+ diagnostics: Diagnostic[];
8
+ }
9
+ /**
10
+ * contract check: validates a contract and the contracts it depends on.
11
+ *
12
+ * @param {string} path - Contract file.
13
+ * @returns {ContractCheckResult} Status and diagnostics.
14
+ *
15
+ * @example
16
+ * contractCheck("orders.contract.json").status; // "VALID"
17
+ */
18
+ export declare function contractCheck(path: string): ContractCheckResult;
19
+ /**
20
+ * Compact text for a contract check (or describe) result.
21
+ *
22
+ * @param {{status: string, contract: string, diagnostics: Diagnostic[], checked?: string[]}} r - The result.
23
+ * @returns {string} Status line, then the diagnostics.
24
+ */
25
+ export declare function formatContractCheck(r: {
26
+ status: string;
27
+ contract: string;
28
+ diagnostics: Diagnostic[];
29
+ checked?: string[];
30
+ }): string;
@@ -0,0 +1,12 @@
1
+ import { CommandModule } from "yargs";
2
+ export declare const CONTRACT: {
3
+ readonly type: "string";
4
+ readonly demandOption: true;
5
+ readonly describe: "Contract JSON (required)";
6
+ };
7
+ export declare const JSON_FLAG: {
8
+ readonly type: "boolean";
9
+ readonly describe: "Full result as one-line JSON";
10
+ };
11
+ declare const contract: CommandModule;
12
+ export default contract;
@@ -4,70 +4,70 @@ import { describeContract } from "./describe.js";
4
4
  export const CONTRACT = { type: "string", demandOption: true, describe: "Contract JSON (required)" };
5
5
  export const JSON_FLAG = { type: "boolean", describe: "Full result as one-line JSON" };
6
6
  /** The contract format in brief, for `contract --help`. Only tables, and each table's and column's name, are required. */
7
- const FORMAT = `Contract JSON. Only "tables" and each table's and column's "name" are required; every other
8
- field is optional. "(default)" marks the value used when a field is left out; other values are examples.
9
- {
10
- "name": "shop.orders", "version": "1.0.0", "description": "...", // shown in output
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
13
- "missing_values": [""], // (default) cell texts that count as empty (null in queries), e.g. ["", "-"].
14
- // Keep a marker like "-" out of it when "-" is a real value: "-" allowed
15
- // but an empty cell forbidden is "required": true plus
16
- // "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
17
- "allow_extra_tables": false, // (default) true: tables not declared here are allowed
18
- "depends_on": { "customers": "customers.contract.json" }, // path absolute or relative to this contract;
19
- // its tables passed with --dep customers=<file>, referenced as "customers:Table.Column"
20
- "tables": [{
21
- "name": "Orders",
22
- "required": true, // (default) the table must be in the document
23
- "primary_key": "Order_ID", // or ["A", "B"]; always filled and unique, no "required" needed
24
- "ordered": false, // (default) true: columns must be in the declared order
25
- "allow_extra_columns": false, // (default) true: columns not declared here are allowed
26
- "columns": [{
27
- "name": "Total",
28
- "type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
29
- "required": false, // (default) true: every cell must be filled (an empty cell fails
30
- // MISSING_VALUE); the column itself must always be in the header
31
- "separator": ",", // (default) list item separator
32
- "match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query);
33
- // empty cells are skipped: use "required" to forbid them
34
- }],
35
- "rules": [{ // exactly one of require, count
36
- "id": "...", "description": "...", // shown in findings; description replaces the "expected" text
37
- "severity": "error", // (default) or "warning": reported as WARN, does not fail the check
38
- "on": "Table", // or "alias:Table"; default: the table the rule is in
39
- "when": { "Status": "shipped" }, // rows the rule applies to; default: all rows
40
- "require": { "Tracking": { "$ne": null } }, // row query each of them matches
41
- "count": { "$gte": 1 } // or: condition on how many there are
42
- }]
43
- }]
44
- }
45
- Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
46
- (split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
47
- and {"$ne": "x"} means "no item is x"). Operators:
48
- $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
49
- $gt $gte $lt $lte exact number comparison, or date comparison with a "YYYY-MM-DD" bound
50
- $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
51
- $every {...} every list item meets the condition
52
- $length {...} length (chars, or list items) meets the condition
53
- $unique true no two rows share the value; in a row query ["A", "B"]: the combination
54
- $mentioned "Table.Column" | [...] | "*" value appears there as a word; "*": anywhere in the
55
- document outside the value's own table (prose and other tables both count)
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").
62
- Examples:
63
- "match": { "$regex": "^O-[0-9]+$" }
64
- "match": { "$in": ["open", "paid", "shipped"] }
65
- "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
66
- "match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
67
- "match": { "$ref": "customers:Customers.ID" } // a column of the dependency "customers"
68
- { "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
69
- { "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
70
- { "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
7
+ const FORMAT = `Contract JSON. Only "tables" and each table's and column's "name" are required; every other
8
+ field is optional. "(default)" marks the value used when a field is left out; other values are examples.
9
+ {
10
+ "name": "shop.orders", "version": "1.0.0", "description": "...", // shown in output
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
13
+ "missing_values": [""], // (default) cell texts that count as empty (null in queries), e.g. ["", "-"].
14
+ // Keep a marker like "-" out of it when "-" is a real value: "-" allowed
15
+ // but an empty cell forbidden is "required": true plus
16
+ // "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
17
+ "allow_extra_tables": false, // (default) true: tables not declared here are allowed
18
+ "depends_on": { "customers": "customers.contract.json" }, // path absolute or relative to this contract;
19
+ // its tables passed with --dep customers=<file>, referenced as "customers:Table.Column"
20
+ "tables": [{
21
+ "name": "Orders",
22
+ "required": true, // (default) the table must be in the document
23
+ "primary_key": "Order_ID", // or ["A", "B"]; always filled and unique, no "required" needed
24
+ "ordered": false, // (default) true: columns must be in the declared order
25
+ "allow_extra_columns": false, // (default) true: columns not declared here are allowed
26
+ "columns": [{
27
+ "name": "Total",
28
+ "type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
29
+ "required": false, // (default) true: every cell must be filled (an empty cell fails
30
+ // MISSING_VALUE); the column itself must always be in the header
31
+ "separator": ",", // (default) list item separator
32
+ "match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query);
33
+ // empty cells are skipped: use "required" to forbid them
34
+ }],
35
+ "rules": [{ // exactly one of require, count
36
+ "id": "...", "description": "...", // shown in findings; description replaces the "expected" text
37
+ "severity": "error", // (default) or "warning": reported as WARN, does not fail the check
38
+ "on": "Table", // or "alias:Table"; default: the table the rule is in
39
+ "when": { "Status": "shipped" }, // rows the rule applies to; default: all rows
40
+ "require": { "Tracking": { "$ne": null } }, // row query each of them matches
41
+ "count": { "$gte": 1 } // or: condition on how many there are
42
+ }]
43
+ }]
44
+ }
45
+ Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
46
+ (split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
47
+ and {"$ne": "x"} means "no item is x"). Operators:
48
+ $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
49
+ $gt $gte $lt $lte exact number comparison, or date comparison with a "YYYY-MM-DD" bound
50
+ $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
51
+ $every {...} every list item meets the condition
52
+ $length {...} length (chars, or list items) meets the condition
53
+ $unique true no two rows share the value; in a row query ["A", "B"]: the combination
54
+ $mentioned "Table.Column" | [...] | "*" value appears there as a word; "*": anywhere in the
55
+ document outside the value's own table (prose and other tables both count)
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").
62
+ Examples:
63
+ "match": { "$regex": "^O-[0-9]+$" }
64
+ "match": { "$in": ["open", "paid", "shipped"] }
65
+ "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
66
+ "match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
67
+ "match": { "$ref": "customers:Customers.ID" } // a column of the dependency "customers"
68
+ { "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
69
+ { "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
70
+ { "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
71
71
  { "severity": "warning", "require": { "ID": { "$mentioned": "*" } } }`;
72
72
  const check = {
73
73
  command: "check",
@@ -0,0 +1,22 @@
1
+ import { Diagnostic } from "./diagnostics.js";
2
+ import { Contract } from "./model.js";
3
+ export interface DescribeResult {
4
+ status: "OK" | "INVALID_CONTRACT" | "MISSING_DATA";
5
+ contract: string;
6
+ markdown?: string;
7
+ diagnostics: Diagnostic[];
8
+ }
9
+ /**
10
+ * Renders a valid contract as a Markdown guide to the tables it expects.
11
+ *
12
+ * @param {Contract} c - The contract.
13
+ * @returns {string} The guide.
14
+ */
15
+ export declare function renderGuide(c: Contract): string;
16
+ /**
17
+ * contract describe: validates the contract, then renders its guide.
18
+ *
19
+ * @param {string} path - Contract file.
20
+ * @returns {DescribeResult} OK with the Markdown, or the contract's problems.
21
+ */
22
+ export declare function describeContract(path: string): DescribeResult;