@turingcode/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,223 @@
1
+ import { readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { BoundError } from "./ast.js";
4
+ const SEPARATOR = /^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
5
+ const HEADING = /^##\s+(.+?)\s*#*\s*$/;
6
+ /**
7
+ * Splits one Markdown table line into trimmed cells; `\|` is a literal pipe.
8
+ *
9
+ * @param {string} line - A line starting with `|`.
10
+ * @returns {string[]} The cells.
11
+ *
12
+ * @example
13
+ * splitRow("| a | b \\| c |"); // ["a", "b | c"]
14
+ */
15
+ export function splitRow(line) {
16
+ let body = line.trim();
17
+ if (body.startsWith("|"))
18
+ body = body.slice(1);
19
+ if (body.endsWith("|") && !body.endsWith("\\|"))
20
+ body = body.slice(0, -1);
21
+ const cells = [];
22
+ let cell = "";
23
+ for (let i = 0; i < body.length; i++) {
24
+ if (body[i] === "\\" && body[i + 1] === "|") {
25
+ cell += "|";
26
+ i++;
27
+ }
28
+ else if (body[i] === "|") {
29
+ cells.push(cell.trim());
30
+ cell = "";
31
+ }
32
+ else {
33
+ cell += body[i];
34
+ }
35
+ }
36
+ cells.push(cell.trim());
37
+ return cells;
38
+ }
39
+ /**
40
+ * Reads the tables of a Markdown stage output. A table is the first pipe
41
+ * table under a `## <Name>` heading; pipe tables inside fenced code blocks
42
+ * are ignored.
43
+ *
44
+ * @param {string} text - The Markdown text.
45
+ * @param {number} maxRows - `bounds.max_table_rows`.
46
+ * @returns {ParsedOutput} The tables.
47
+ * @throws {BoundError} When a table has more than maxRows rows.
48
+ */
49
+ export function parseMarkdown(text, maxRows) {
50
+ const lines = text.replace(/^/, "").split(/\r?\n/);
51
+ const tables = new Map();
52
+ const duplicates = [];
53
+ const malformed = [];
54
+ /** [section name, first line index, end line index (exclusive)] */
55
+ const sections = [];
56
+ let section = null;
57
+ let fenced = false;
58
+ for (let i = 0; i < lines.length; i++) {
59
+ const line = lines[i];
60
+ if (/^\s*(```|~~~)/.test(line)) {
61
+ fenced = !fenced;
62
+ continue;
63
+ }
64
+ if (fenced)
65
+ continue;
66
+ const heading = HEADING.exec(line);
67
+ if (heading || /^#\s/.test(line)) {
68
+ if (sections.length && sections[sections.length - 1][2] === -1)
69
+ sections[sections.length - 1][2] = i;
70
+ section = heading ? heading[1] : null;
71
+ if (section !== null)
72
+ sections.push([section, i, -1]);
73
+ continue;
74
+ }
75
+ if (section === null || !line.trim().startsWith("|"))
76
+ continue;
77
+ const start = i;
78
+ while (i + 1 < lines.length && lines[i + 1].trim().startsWith("|"))
79
+ i++;
80
+ const block = lines.slice(start, i + 1);
81
+ if (tables.has(section) || malformed.some(([n]) => n === section)) {
82
+ if (!duplicates.includes(section))
83
+ duplicates.push(section);
84
+ continue;
85
+ }
86
+ if (block.length < 2 || !SEPARATOR.test(block[1])) {
87
+ malformed.push([section, `line ${start + 1}: the header row is not followed by a '|---|' separator row`]);
88
+ continue;
89
+ }
90
+ const rows = block.slice(2).map(splitRow);
91
+ if (rows.length > maxRows)
92
+ throw new BoundError("max_table_rows", maxRows);
93
+ tables.set(section, {
94
+ name: section,
95
+ header: splitRow(block[0]),
96
+ rows,
97
+ rowLines: rows.map((_, k) => start + 3 + k),
98
+ });
99
+ }
100
+ if (sections.length && sections[sections.length - 1][2] === -1)
101
+ sections[sections.length - 1][2] = lines.length;
102
+ return {
103
+ tables, duplicates, malformed, text,
104
+ textOutside(names) {
105
+ const skip = new Set();
106
+ for (const [name, from, to] of sections) {
107
+ if (names.includes(name))
108
+ for (let k = from; k < to; k++)
109
+ skip.add(k);
110
+ }
111
+ return lines.filter((l, k) => !skip.has(k) && !/^#/.test(l)).join("\n");
112
+ },
113
+ };
114
+ }
115
+ /**
116
+ * Parses CSV text (RFC 4180: quoted fields, doubled quotes, CRLF).
117
+ *
118
+ * @param {string} text - The CSV text.
119
+ * @returns {string[][]} Records; fields are not trimmed.
120
+ * @throws {Error} On an unterminated quoted field.
121
+ */
122
+ export function parseCsv(text) {
123
+ const records = [];
124
+ let record = [];
125
+ let field = "";
126
+ let quoted = false;
127
+ const src = text.replace(/^/, "");
128
+ for (let i = 0; i < src.length; i++) {
129
+ const ch = src[i];
130
+ if (quoted) {
131
+ if (ch === '"' && src[i + 1] === '"') {
132
+ field += '"';
133
+ i++;
134
+ }
135
+ else if (ch === '"') {
136
+ quoted = false;
137
+ }
138
+ else {
139
+ field += ch;
140
+ }
141
+ }
142
+ else if (ch === '"' && field === "") {
143
+ quoted = true;
144
+ }
145
+ else if (ch === ",") {
146
+ record.push(field);
147
+ field = "";
148
+ }
149
+ else if (ch === "\n" || ch === "\r") {
150
+ if (ch === "\r" && src[i + 1] === "\n")
151
+ i++;
152
+ record.push(field);
153
+ records.push(record);
154
+ record = [];
155
+ field = "";
156
+ }
157
+ else {
158
+ field += ch;
159
+ }
160
+ }
161
+ if (quoted)
162
+ throw new Error("unterminated quoted field");
163
+ if (field !== "" || record.length) {
164
+ record.push(field);
165
+ records.push(record);
166
+ }
167
+ return records.filter(r => !(r.length === 1 && r[0] === ""));
168
+ }
169
+ /**
170
+ * Reads a CSV stage output: a folder holding one `<Table>.csv` per table.
171
+ *
172
+ * @param {string} dir - The folder.
173
+ * @param {number} maxRows - `bounds.max_table_rows`.
174
+ * @returns {ParsedOutput} The tables.
175
+ * @throws {BoundError} When a table has more than maxRows rows.
176
+ */
177
+ export function parseCsvFolder(dir, maxRows) {
178
+ const tables = new Map();
179
+ const malformed = [];
180
+ const texts = new Map();
181
+ for (const file of readdirSync(dir).filter(f => f.toLowerCase().endsWith(".csv")).sort()) {
182
+ const name = basename(file, file.slice(-4));
183
+ const text = readFileSync(join(dir, file), "utf-8");
184
+ texts.set(name, text);
185
+ let records;
186
+ try {
187
+ records = parseCsv(text);
188
+ }
189
+ catch (e) {
190
+ malformed.push([name, `${file}: ${e.message}`]);
191
+ continue;
192
+ }
193
+ if (!records.length) {
194
+ malformed.push([name, `${file}: no header row`]);
195
+ continue;
196
+ }
197
+ const rows = records.slice(1).map(r => r.map(c => c.trim()));
198
+ if (rows.length > maxRows)
199
+ throw new BoundError("max_table_rows", maxRows);
200
+ tables.set(name, { name, header: records[0].map(c => c.trim()), rows, rowLines: rows.map((_, k) => k + 2) });
201
+ }
202
+ return {
203
+ tables, duplicates: [], malformed, text: [...texts.values()].join("\n"),
204
+ textOutside: (names) => [...texts].filter(([n]) => !names.includes(n)).map(([, t]) => t).join("\n"),
205
+ };
206
+ }
207
+ /**
208
+ * Reads a stage output in the contract's input format.
209
+ *
210
+ * @param {string} path - A Markdown file, or a folder of CSV files.
211
+ * @param {"markdown_tables" | "csv"} format - The contract's input_format.
212
+ * @param {number} maxRows - `bounds.max_table_rows`.
213
+ * @returns {ParsedOutput} The tables.
214
+ * @throws {Error} When the path cannot be read; BoundError on too many rows.
215
+ */
216
+ export function readOutput(path, format, maxRows) {
217
+ if (format === "csv") {
218
+ if (!statSync(path).isDirectory())
219
+ throw new Error(`${path} is not a folder of <Table>.csv files`);
220
+ return parseCsvFolder(path, maxRows);
221
+ }
222
+ return parseMarkdown(readFileSync(path, "utf-8"), maxRows);
223
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Turing Code toolkit for AI agents on the command line, e.g. `turingcode clock solve`.",
5
+ "type": "module",
6
+ "bin": {
7
+ "turingcode": "dist/cli/index.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "scripts": {
16
+ "build": "node scripts/build.cjs",
17
+ "typecheck": "tsc --noEmit && tsc --project tsconfig.test.json --noEmit",
18
+ "test": "node scripts/test.cjs",
19
+ "default_publish": "npm publish --access public --tag latest",
20
+ "prepublishOnly": "npm test && npm run build"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "yargs": "17.7.3"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "22.20.5",
30
+ "@types/yargs": "17.0.35",
31
+ "typescript": "7.0.2"
32
+ }
6
33
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.