drawing-axi 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 drawing-axi contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,16 @@
1
+ drawing-axi
2
+ Copyright (c) 2026 drawing-axi contributors. MIT License; see LICENSE.
3
+
4
+ src/cli/parse.ts, src/output/text.ts, src/output/toon.ts and parts of
5
+ src/cli/run.ts and src/output/views.ts are taken from ituran-axi
6
+ (https://github.com/comisai/ituran-axi), MIT License,
7
+ Copyright (c) 2026 ituran-axi contributors: strict argument parsing, text
8
+ safety, TOON rendering with size bounds, and the list and record views.
9
+
10
+ The PDF reader in src/pdf/ is written for this project from the PDF
11
+ specification (ISO 32000). It includes no code from another PDF library.
12
+
13
+ Runtime dependency: @toon-format/toon 4.4.0, MIT License.
14
+
15
+ AutoCAD is a trademark of Autodesk, Inc. This project is not made or endorsed
16
+ by Autodesk.
package/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
1
+ # drawing-axi
2
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.
3
+ [![CI](https://github.com/comisai/drawing-axi/actions/workflows/ci.yml/badge.svg)](https://github.com/comisai/drawing-axi/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/drawing-axi.svg)](https://www.npmjs.com/package/drawing-axi)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ A command-line tool that lets AI agents read CAD drawings saved as PDF: the layers, the labels, the scale, the length of pipe on each layer by size, riser tags, symbols and the legend. It is built for quantity takeoff: turning a plumbing, fire or drainage plan into the rows of a bill of quantities.
8
+
9
+ A PDF plotted from a CAD program keeps much more than a picture. It keeps the drawing's named layers, one per system. It keeps every label as hidden text with its position. A text extractor and a rendered image show neither, so an agent that reads the sheet that way measures by colour and counts by eye. drawing-axi reads what the file really holds.
10
+
11
+ drawing-axi is an AXI, an [agent experience interface](https://axi.md). Every command:
12
+ - prints compact [TOON](https://github.com/toon-format/toon) text on stdout, bounded in size;
13
+ - refuses bad input and says exactly what is wrong;
14
+ - ends with hints for the next command, as a TOON list, so the whole output decodes as one document;
15
+ - reads one local file and never uses the network.
16
+
17
+ It was built to run inside Comis, and it also works on its own.
18
+
19
+ > **Status:** early development (0.x). Checked against eight sheets from one design office, where every measured system was within 10% of a person's takeoff. Drawings from other offices may keep less in the file; `drawing-axi info` says what a sheet holds before you rely on it. A takeoff made with this tool is a draft for a person to check, not a signed bill.
20
+
21
+ ## Requirements
22
+
23
+ - Node.js 22.18 or later.
24
+ - Drawings plotted to PDF from the CAD file (vector PDF). A scan or a photo holds no lines to measure, and the tool says so.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ npm install -g drawing-axi
30
+ ```
31
+
32
+ Each release is published from GitHub Actions with [npm provenance](https://docs.npmjs.com/generating-provenance-statements), so you can check that it was built from this repository. To run from source instead, see [Development](#development).
33
+
34
+ ## Usage
35
+
36
+ ```text
37
+ drawing-axi home view: the PDF drawings in this folder
38
+ drawing-axi info <file.pdf> what a sheet holds: size, scale, layers, labels, what is missing
39
+ drawing-axi scale <file.pdf> the scale and how it was found
40
+ drawing-axi legend <file.pdf> legend lines paired with the layer and colour of their samples
41
+ drawing-axi layers <file.pdf> layers with the length of straight runs drawn on each
42
+ drawing-axi labels <file.pdf> the text on the sheet: legend, notes, sizes
43
+ drawing-axi tags <file.pdf> riser tags with the size written beside each
44
+ drawing-axi runs <file.pdf> --layer L the straight runs on chosen layers, with their ends
45
+ drawing-axi measure <file.pdf> --group name=LAYER[+LAYER]...
46
+ run length by group and pipe size
47
+ drawing-axi symbols <file.pdf> --layer L symbols counted by size and make-up
48
+ drawing-axi render <file.pdf> --out f.svg a picture of chosen layers and area, to look at
49
+ drawing-axi help <command> flags for one command
50
+ ```
51
+
52
+ Positions are `x,y` in points from the top-left corner of the sheet, x to the right and y down. 72 points are one inch on paper.
53
+
54
+ ### A takeoff, step by step
55
+
56
+ These are the outputs for the sample sheet the tests draw (`test/fixtures/sample.ts`).
57
+
58
+ ```sh
59
+ drawing-axi info plan.pdf
60
+ ```
61
+
62
+ ```text
63
+ file: plan.pdf
64
+ page: 1 of 2
65
+ sheet: 494 x 317 mm
66
+ scale: "1:100, 27.78 pt per m (stated ratio, refined by the scale bar)"
67
+ layers: "9 with ink on this page, 9 in the file (1 switched off)"
68
+ geometry: "243 strokes, 2 fills, 0 images"
69
+ labels: "24 stroke-font, 1 font text, 1 notes"
70
+ size_labels: "9 (4 carry a slope or a system code, as a label on a pipe does)"
71
+ ```
72
+
73
+ ```sh
74
+ drawing-axi legend plan.pdf
75
+ ```
76
+
77
+ ```text
78
+ summary: 4 legend lines paired with the layer its sample is drawn on
79
+ box: "1050,93,1360,202"
80
+ legend[4]{text,layer,color,at}:
81
+ צנרת ביוב,SEWER,"#ff00ff","1280,110"
82
+ צנרת ניקוז מי גשם,RAIN,"#00bfff","1280,135"
83
+ צנרת מים כבוי אש (F),FIRE,"#ff0000","1280,160"
84
+ צנרת מים קרים,WATER,"#00ffff","1280,185"
85
+ ```
86
+
87
+ The captions read sewer pipe, rainwater drain pipe, fire water pipe (F) and cold water pipe. The file stores them as `mbr, chuc` and the like: the keys a drafter typed in a Hebrew stroke font.
88
+
89
+ ```sh
90
+ drawing-axi measure plan.pdf --group sewer=SEWER --group rain=RAIN --group fire=FIRE \
91
+ --exclude 1050,93,1360,202 --save takeoff.json
92
+ ```
93
+
94
+ ```text
95
+ summary: "3 groups, 70 m in 6 runs"
96
+ scale: "1:100, 27.78 pt per m (stated ratio, refined by the scale bar)"
97
+ size_labels: "3 of 4 size labels in the area sit on a measured run; the others belong to pipe that is not in these groups, or fit no run"
98
+ groups[3]{group,length_m,runs,sized_m,unsized_m}:
99
+ sewer,43,4,38,5
100
+ rain,12,1,12,0
101
+ fire,15,1,0,15
102
+ sizes[5]{group,size,length_m,labelled_m,runs}:
103
+ sewer,Ø160,30,20,2
104
+ sewer,Ø200,8,8,1
105
+ sewer,unsized,5,null,1
106
+ rain,Ø110,12,12,1
107
+ fire,unsized,15,null,1
108
+ sized_by[3]{group,size,label,labelled_m,runs}:
109
+ sewer,Ø160,Ø160-1%,20,1
110
+ sewer,Ø200,Ø200-1%,8,1
111
+ rain,Ø110,Ø110-2%,12,1
112
+ ```
113
+
114
+ `box` is the legend's own area: the legend holds sample lines on the pipe layers, so a takeoff leaves it out. The fourth size label belongs to the water pipe, which this command did not measure. `sized_by` shows which label sized what, so a label of another system on a row is a wrong pairing to check. `--save` writes every run with its group, size, label and ends as JSON, to a thousandth of a metre, so a program can build the workbook without retyping numbers.
115
+
116
+ ### What the numbers mean
117
+
118
+ - **Runs.** A pipe is plotted as dashes, and broken where a letter or a label sits on it. A run joins pieces that lie on one line and end near each other, and is measured end to end. A break with a linetype letter in it, such as the F of a fire line, is joined up to twice as wide. Curved pipe and runs shorter than 6 mm on paper are left out.
119
+ - **Scale.** The ratio comes from the title block. A plot is often a little off its stated scale, so the factor is refined from the printed scale bar when one is found. `drawing-axi scale` shows both. Pass `--scale 1:N` or `--pt-per-m` when the sheet is wrong or silent.
120
+ - **Sizes.** A run takes the size of a label written along it: just beside the line, or in a break left in the line for it. A line that passes through the middle of a label's text is another pipe, and takes nothing. A run without a label takes the size of the runs of its own group that it touches, when they all agree. `labelled_m` is the part sized by a label of its own.
121
+ - **System codes.** A label such as `F-Ø4"` or `CW1-Ø3"` starts with its system's code. Name a group by that code (`--group F=<layer>`, `--group CW=<layer>`) and it takes only those labels, and no other group takes them. Digits and dots do not count: `C.W.2` is `CW`. A coded label that sits on no run, as one on a leader does, is listed under `labels_apart`: the sheet names that size for the system, and does not say which pipe. It is a size to confirm, not a measured one.
122
+ - **Unsized.** What no label sizes is reported as `unsized`. The tool never guesses a size.
123
+ - **Not on a plan.** Vertical lengths, fittings, hangers and insulation are not drawn to scale on a plan. `tags` and `symbols` count what the sheet marks; the rest needs rules or a person.
124
+
125
+ ### Hebrew and other stroke-font text
126
+
127
+ CAD stroke fonts keep text in the file as the keys the drafter typed. drawing-axi turns `%%C` into Ø, reads Hebrew typed on Latin keys, puts digits stored back to front in reading order, and leaves Latin text alone. `labels --each --full` adds the stored text wherever decoding changed it.
128
+
129
+ ## Exit codes and errors
130
+
131
+ `0` success, `1` an error, `2` a usage error. An error prints `message`, `code` and `usage` on stdout:
132
+
133
+ | Code | Meaning |
134
+ | --- | --- |
135
+ | `usage` | A bad flag or argument |
136
+ | `not_found`, `not_pdf` | No file there, or not a PDF |
137
+ | `encrypted`, `damaged`, `unsupported` | The PDF cannot be read as it is; the message names a `qpdf` command that fixes it |
138
+ | `too_large`, `timed_out` | More than the tool reads at once, or than the caller's deadline allows |
139
+ | `no_page`, `unknown_layer` | The page or layer does not exist; the message lists what does |
140
+ | `scale_unknown` | The sheet states no scale; pass `--scale` |
141
+ | `exists` | `render --out` would replace a file; add `--force` |
142
+
143
+ ## Safety
144
+
145
+ - It reads the file you name and writes only the files you name with `--out` and `--save`. It opens no network connection.
146
+ - A drawing is untrusted input. File size, decoded size, nesting and geometry are bounded, and a damaged file fails with an error.
147
+ - Text from the file is data. Invisible and bidirectional-control characters are shown as escapes, so a label cannot hide or reorder output.
148
+
149
+ ## Development
150
+
151
+ ```sh
152
+ git clone https://github.com/comisai/drawing-axi.git
153
+ cd drawing-axi
154
+ npm ci
155
+ npm run check # type-check, lint, unit, contract and AXI-principle tests
156
+ npm run build # dist/bin/drawing-axi.js
157
+ npm run test:dist # contract and AXI-principle tests against the built CLI
158
+ ```
159
+
160
+ Tests draw their own sample sheet (`test/fixtures/`). No real drawing is in this repository. See [CONTRIBUTING](CONTRIBUTING.md) for the rules and the live test, and [docs/](docs/) for the design, the implementation plan and the master plan.
161
+
162
+ ## License
163
+
164
+ [MIT](LICENSE). See [NOTICE](NOTICE).
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../cli/run.js';
3
+ // A reader that closes early, as in `drawing-axi ... | head`, is a normal end.
4
+ process.stdout.on('error', (error) => {
5
+ if (error.code === 'EPIPE')
6
+ process.exit(0);
7
+ throw error;
8
+ });
9
+ const code = await main(process.argv.slice(2), {
10
+ stdout: (text) => {
11
+ process.stdout.write(text);
12
+ },
13
+ env: process.env,
14
+ now: () => new Date(),
15
+ cwd: process.cwd(),
16
+ });
17
+ // Never end stdout: it may be a socket the caller's shell also writes to, and
18
+ // ending a socket shuts down writing for every process that shares it. An
19
+ // empty write's callback runs only after every earlier write has flushed.
20
+ process.stdout.write('', () => process.exit(code));
@@ -0,0 +1,70 @@
1
+ // Strict parsing with node:util parseArgs, following the Comis AXI fixture:
2
+ // unknown flags, repeated single flags, extra arguments and values on boolean
3
+ // flags are refused. A refusal names the flag, never its value. "--" ends flags.
4
+ import { parseArgs } from 'node:util';
5
+ import { usage } from '../errors.js';
6
+ import { commandName, } from './table.js';
7
+ // An odd flag is not echoed: it may hold a value meant for somewhere else.
8
+ const shownFlag = (raw) => /^--?[A-Za-z0-9][A-Za-z0-9-]{0,40}$/.test(raw) ? ` ${raw}` : '';
9
+ export function parseCommand(spec, argv) {
10
+ const name = commandName(spec);
11
+ const options = {};
12
+ for (const [flag, f] of Object.entries(spec.flags)) {
13
+ options[flag] = f.multiple
14
+ ? { type: f.type, multiple: true }
15
+ : { type: f.type };
16
+ }
17
+ const valid = Object.keys(spec.flags).map((f) => `--${f}`);
18
+ let result;
19
+ try {
20
+ result = parseArgs({
21
+ args: argv,
22
+ options,
23
+ strict: false,
24
+ allowPositionals: true,
25
+ tokens: true,
26
+ });
27
+ }
28
+ catch {
29
+ throw usage(`Invalid arguments for \`${name}\`.`);
30
+ }
31
+ const seen = new Set();
32
+ for (const token of result.tokens) {
33
+ if (token.kind !== 'option')
34
+ continue;
35
+ const f = spec.flags[token.name];
36
+ if (!f) {
37
+ throw usage(`Unknown flag${shownFlag(token.rawName)} for \`${name}\`. ${valid.length ? `Valid flags: ${valid.join(', ')}.` : 'It takes no flags.'}`);
38
+ }
39
+ if (f.type === 'boolean' && token.inlineValue)
40
+ throw usage(`--${token.name} takes no value.`);
41
+ if (f.type === 'string' &&
42
+ (token.value === undefined || token.value === '')) {
43
+ throw usage(`--${token.name} needs a value: --${token.name} ${f.value ?? '<value>'}.`);
44
+ }
45
+ if (!f.multiple && seen.has(token.name))
46
+ throw usage(`--${token.name} is given more than once.`);
47
+ seen.add(token.name);
48
+ }
49
+ const positionals = result.positionals;
50
+ const required = spec.args.filter((a) => a.required);
51
+ if (positionals.length < required.length) {
52
+ throw usage(`Missing ${required[positionals.length]?.name ?? 'argument'} for \`${name}\`.`);
53
+ }
54
+ const variadic = spec.args.at(-1)?.variadic === true;
55
+ if (!variadic && positionals.length > spec.args.length) {
56
+ throw usage(spec.args.length
57
+ ? `\`${name}\` takes ${spec.args.map((a) => a.name).join(' ')}; there is an extra argument.`
58
+ : `\`${name}\` takes no arguments.`);
59
+ }
60
+ const tokens = [];
61
+ for (const token of result.tokens) {
62
+ if (token.kind === 'option') {
63
+ tokens.push({ kind: 'option', name: token.name, value: token.value });
64
+ }
65
+ else if (token.kind === 'positional') {
66
+ tokens.push({ kind: 'positional', value: token.value });
67
+ }
68
+ }
69
+ return { values: result.values, positionals, tokens };
70
+ }
@@ -0,0 +1,353 @@
1
+ // Dispatch: home view with no command, help and version, then one command.
2
+ // Everything goes to stdout. Exit codes: 0 ok, 1 error, 2 usage.
3
+ import { encode } from '@toon-format/toon';
4
+ import { AREA_FLAGS, FULL_FLAG, LIMIT_FLAG, PAGE_FLAG, readerError, SAVE_FLAG, SCALE_FLAGS, } from '../commands/common.js';
5
+ import { DESCRIPTION, home } from '../commands/home.js';
6
+ import { info, scale } from '../commands/info.js';
7
+ import { labels, legend, tags } from '../commands/labels.js';
8
+ import { layers } from '../commands/layers.js';
9
+ import { measure, runs } from '../commands/measure.js';
10
+ import { renderCommand, symbols } from '../commands/symbols.js';
11
+ import { AxiError, usage } from '../errors.js';
12
+ import { errorText, helpBlock } from '../output/toon.js';
13
+ import { VERSION } from '../version.js';
14
+ import { parseCommand } from './parse.js';
15
+ import { BIN, commandName, usageLine, } from './table.js';
16
+ const FILE = [{ name: '<file.pdf>', required: true }];
17
+ const GAP = {
18
+ type: 'string',
19
+ value: '<mm>',
20
+ summary: 'Join pieces up to this far apart on paper, default 8',
21
+ };
22
+ const MIN = {
23
+ type: 'string',
24
+ value: '<mm>',
25
+ summary: 'Leave out runs shorter than this on paper, default 6',
26
+ };
27
+ const LAYER = {
28
+ type: 'string',
29
+ multiple: true,
30
+ value: '<layer>',
31
+ summary: 'A layer by name; LAYER@#rrggbb takes one colour of it',
32
+ };
33
+ const GROUP = {
34
+ type: 'string',
35
+ multiple: true,
36
+ value: '<name>=<layer>',
37
+ summary: 'Layers measured as one system, joined by +: sewer=SEWER+VENT',
38
+ };
39
+ const MATCH = {
40
+ type: 'string',
41
+ value: '<regex>',
42
+ summary: 'Only labels whose text matches, ignoring case',
43
+ };
44
+ const SOURCE = {
45
+ type: 'string',
46
+ value: '<kind>',
47
+ summary: 'shx (stroke-font text), text (font text), note (comments) or all',
48
+ };
49
+ const EACH = {
50
+ type: 'boolean',
51
+ summary: 'One row per item with its place, instead of counts',
52
+ };
53
+ export const COMMANDS = [
54
+ {
55
+ name: '',
56
+ args: [],
57
+ flags: {},
58
+ summary: 'Home view: the PDF drawings in this folder',
59
+ run: home,
60
+ },
61
+ {
62
+ name: 'info',
63
+ args: FILE,
64
+ flags: { page: PAGE_FLAG, ...SCALE_FLAGS, full: FULL_FLAG },
65
+ summary: 'What a sheet holds: size, scale, layers, labels, and what is missing',
66
+ run: info,
67
+ },
68
+ {
69
+ name: 'scale',
70
+ args: FILE,
71
+ flags: { page: PAGE_FLAG, ...SCALE_FLAGS, save: SAVE_FLAG },
72
+ summary: "The sheet's scale and how it was found",
73
+ run: scale,
74
+ },
75
+ {
76
+ name: 'layers',
77
+ args: FILE,
78
+ flags: {
79
+ match: {
80
+ type: 'string',
81
+ value: '<text>',
82
+ summary: 'Only layers whose name contains this',
83
+ },
84
+ split: {
85
+ type: 'boolean',
86
+ summary: 'One row per colour of each layer',
87
+ },
88
+ own: {
89
+ type: 'boolean',
90
+ summary: 'Leave out layers of referenced files, whose names hold a bar',
91
+ },
92
+ gap: GAP,
93
+ min: MIN,
94
+ ...AREA_FLAGS,
95
+ ...SCALE_FLAGS,
96
+ page: PAGE_FLAG,
97
+ limit: LIMIT_FLAG,
98
+ full: FULL_FLAG,
99
+ save: SAVE_FLAG,
100
+ },
101
+ summary: 'Layers with the length of straight runs drawn on each',
102
+ run: layers,
103
+ },
104
+ {
105
+ name: 'legend',
106
+ args: FILE,
107
+ flags: {
108
+ source: SOURCE,
109
+ ...AREA_FLAGS,
110
+ page: PAGE_FLAG,
111
+ limit: { ...LIMIT_FLAG, summary: 'Rows to show, default 40' },
112
+ full: FULL_FLAG,
113
+ save: SAVE_FLAG,
114
+ },
115
+ summary: 'Legend lines paired with the layer and colour of their samples',
116
+ run: legend,
117
+ },
118
+ {
119
+ name: 'labels',
120
+ args: FILE,
121
+ flags: {
122
+ match: MATCH,
123
+ source: SOURCE,
124
+ each: EACH,
125
+ sizes: {
126
+ type: 'boolean',
127
+ summary: 'The pipe sizes the labels name, with counts',
128
+ },
129
+ ...AREA_FLAGS,
130
+ page: PAGE_FLAG,
131
+ limit: LIMIT_FLAG,
132
+ full: FULL_FLAG,
133
+ save: SAVE_FLAG,
134
+ },
135
+ summary: 'The text on the sheet: legend, notes, sizes, tags',
136
+ run: labels,
137
+ },
138
+ {
139
+ name: 'tags',
140
+ args: FILE,
141
+ flags: {
142
+ match: MATCH,
143
+ source: SOURCE,
144
+ each: EACH,
145
+ ...AREA_FLAGS,
146
+ page: PAGE_FLAG,
147
+ limit: LIMIT_FLAG,
148
+ full: FULL_FLAG,
149
+ save: SAVE_FLAG,
150
+ },
151
+ summary: 'Riser tags with the size written beside each, counted by series',
152
+ run: tags,
153
+ },
154
+ {
155
+ name: 'runs',
156
+ args: FILE,
157
+ flags: {
158
+ layer: LAYER,
159
+ group: GROUP,
160
+ gap: GAP,
161
+ min: MIN,
162
+ ...AREA_FLAGS,
163
+ ...SCALE_FLAGS,
164
+ page: PAGE_FLAG,
165
+ limit: LIMIT_FLAG,
166
+ full: FULL_FLAG,
167
+ save: SAVE_FLAG,
168
+ },
169
+ summary: 'The straight runs on chosen layers, each with its length and ends',
170
+ run: runs,
171
+ },
172
+ {
173
+ name: 'measure',
174
+ args: FILE,
175
+ flags: {
176
+ group: GROUP,
177
+ layer: LAYER,
178
+ gap: GAP,
179
+ min: MIN,
180
+ reach: {
181
+ type: 'string',
182
+ value: '<mm>',
183
+ summary: 'A size label may sit this far from its run on paper, default 1.5',
184
+ },
185
+ plain: {
186
+ type: 'boolean',
187
+ summary: 'Also use sizes written alone, without a slope or system prefix',
188
+ },
189
+ ...AREA_FLAGS,
190
+ ...SCALE_FLAGS,
191
+ page: PAGE_FLAG,
192
+ limit: { ...LIMIT_FLAG, summary: 'Size rows to show, default 40' },
193
+ full: FULL_FLAG,
194
+ save: SAVE_FLAG,
195
+ },
196
+ summary: 'Run length by group and pipe size: the table for a bill of quantities',
197
+ run: measure,
198
+ },
199
+ {
200
+ name: 'symbols',
201
+ args: FILE,
202
+ flags: {
203
+ layer: { ...LAYER, required: true },
204
+ join: {
205
+ type: 'string',
206
+ value: '<mm>',
207
+ summary: 'Pieces this close on paper are one symbol, default 1.5',
208
+ },
209
+ 'max-piece': {
210
+ type: 'string',
211
+ value: '<mm>',
212
+ summary: 'Pieces larger than this on paper are lines, default 30',
213
+ },
214
+ ...AREA_FLAGS,
215
+ ...SCALE_FLAGS,
216
+ page: PAGE_FLAG,
217
+ limit: LIMIT_FLAG,
218
+ full: FULL_FLAG,
219
+ save: SAVE_FLAG,
220
+ },
221
+ summary: 'Symbols on chosen layers, counted by size and make-up',
222
+ run: symbols,
223
+ },
224
+ {
225
+ name: 'render',
226
+ args: FILE,
227
+ flags: {
228
+ out: {
229
+ type: 'string',
230
+ required: true,
231
+ value: '<file.svg>',
232
+ summary: 'The picture to write',
233
+ },
234
+ layer: LAYER,
235
+ region: AREA_FLAGS.region,
236
+ labels: { type: 'boolean', summary: 'Draw the labels too' },
237
+ grid: {
238
+ type: 'boolean',
239
+ summary: 'Draw a coordinate grid, in points from the top-left corner',
240
+ },
241
+ width: {
242
+ type: 'string',
243
+ value: '<px>',
244
+ summary: 'Picture width in pixels, default 1600',
245
+ },
246
+ force: {
247
+ type: 'boolean',
248
+ summary: 'Replace the --out file if it exists',
249
+ },
250
+ page: PAGE_FLAG,
251
+ },
252
+ summary: 'Write a picture of chosen layers and area as SVG, to look at',
253
+ run: renderCommand,
254
+ },
255
+ {
256
+ name: 'help',
257
+ args: [{ name: '<command>', required: false }],
258
+ flags: {},
259
+ summary: 'Show help for a command',
260
+ run: async () => '',
261
+ },
262
+ ];
263
+ const HOME = COMMANDS[0];
264
+ const HELP_FLAGS = new Set(['--help', '-h']);
265
+ const VERSION_FLAGS = new Set(['--version', '-v', '-V']);
266
+ export function topHelp() {
267
+ return `${encode({
268
+ description: DESCRIPTION,
269
+ usage: `${BIN} [command] [flags]`,
270
+ commands: COMMANDS.map((c) => ({
271
+ command: commandName(c),
272
+ summary: c.summary,
273
+ })),
274
+ positions: 'x,y in points from the top-left corner of the sheet, x right and y down; 72 points are one inch on paper',
275
+ settings: 'COMIS_DEADLINE (epoch ms): stop reading and say so before this time',
276
+ })}\n${helpBlock([`Run \`${BIN} help <command>\` for its flags`])}`;
277
+ }
278
+ export function commandHelp(spec) {
279
+ const flags = Object.entries(spec.flags).map(([name, f]) => ({
280
+ flag: f.type === 'string' ? `--${name} ${f.value ?? '<value>'}` : `--${name}`,
281
+ summary: f.multiple ? `${f.summary} (repeatable)` : f.summary,
282
+ }));
283
+ return `${encode({
284
+ command: commandName(spec),
285
+ summary: spec.summary,
286
+ usage: usageLine(spec),
287
+ ...(flags.length ? { flags } : {}),
288
+ })}\n`;
289
+ }
290
+ function find(name) {
291
+ return COMMANDS.find((c) => c.name === name && c.name !== '');
292
+ }
293
+ function unknownCommand(name) {
294
+ const shown = /^[a-z][a-z-]{0,30}$/.test(name)
295
+ ? `\`${name}\``
296
+ : 'that command';
297
+ const list = COMMANDS.filter((c) => c.name).map((c) => c.name);
298
+ return usage(`Unknown command ${shown}. Commands: ${list.join(', ')}.`);
299
+ }
300
+ export async function main(argv, io) {
301
+ let spec = HOME;
302
+ let usageText = `${BIN} [command] [flags]`;
303
+ try {
304
+ const first = argv[0];
305
+ if (argv.length === 1 && first && VERSION_FLAGS.has(first)) {
306
+ io.stdout(`${VERSION}\n`);
307
+ return 0;
308
+ }
309
+ if (argv.length === 1 && first && HELP_FLAGS.has(first)) {
310
+ io.stdout(topHelp());
311
+ return 0;
312
+ }
313
+ let rest = argv;
314
+ if (first && !first.startsWith('-')) {
315
+ const found = find(first);
316
+ if (!found)
317
+ throw unknownCommand(first);
318
+ spec = found;
319
+ rest = argv.slice(1);
320
+ }
321
+ usageText = usageLine(spec);
322
+ const beforeTerminator = rest.includes('--')
323
+ ? rest.slice(0, rest.indexOf('--'))
324
+ : rest;
325
+ if (beforeTerminator.some((a) => HELP_FLAGS.has(a))) {
326
+ io.stdout(commandHelp(spec));
327
+ return 0;
328
+ }
329
+ const parsed = parseCommand(spec, rest);
330
+ if (spec.name === 'help') {
331
+ const target = parsed.positionals[0];
332
+ if (!target) {
333
+ io.stdout(topHelp());
334
+ return 0;
335
+ }
336
+ const found = find(target);
337
+ if (!found)
338
+ throw unknownCommand(target);
339
+ io.stdout(commandHelp(found));
340
+ return 0;
341
+ }
342
+ io.stdout(await spec.run({ ...parsed, io }));
343
+ return 0;
344
+ }
345
+ catch (thrown) {
346
+ const error = readerError(thrown);
347
+ const axi = error instanceof AxiError
348
+ ? error
349
+ : new AxiError('internal_error', 'drawing-axi failed unexpectedly. Run the command once more; if it fails again, report it.');
350
+ io.stdout(errorText(axi, usageText));
351
+ return axi.exitCode;
352
+ }
353
+ }
@@ -0,0 +1,17 @@
1
+ // One command table drives parsing, --help and every usage line.
2
+ export const BIN = 'drawing-axi';
3
+ export function commandName(spec) {
4
+ return spec.name ? `${BIN} ${spec.name}` : BIN;
5
+ }
6
+ export function usageLine(spec) {
7
+ const args = spec.args.map((a) => {
8
+ const name = a.variadic ? `${a.name}...` : a.name;
9
+ return a.required ? name : `[${name}]`;
10
+ });
11
+ const flags = Object.entries(spec.flags).map(([name, f]) => {
12
+ const text = f.type === 'string' ? `--${name} ${f.value ?? '<value>'}` : `--${name}`;
13
+ const shown = f.required ? text : `[${text}]`;
14
+ return f.multiple ? `${shown}...` : shown;
15
+ });
16
+ return [commandName(spec), ...args, ...flags].join(' ');
17
+ }