@jinshuju/cli 0.1.3 → 0.3.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/README.md +80 -1
- package/dist/args.d.ts +47 -0
- package/dist/args.js +185 -0
- package/dist/auth.js +43 -11
- package/dist/cli-bin.js +1 -1
- package/dist/cli.d.ts +2 -20
- package/dist/cli.js +71 -659
- package/dist/commands/account.d.ts +2 -0
- package/dist/commands/account.js +20 -0
- package/dist/commands/comment.d.ts +2 -0
- package/dist/commands/comment.js +66 -0
- package/dist/commands/entry.d.ts +31 -0
- package/dist/commands/entry.js +723 -0
- package/dist/commands/field.d.ts +3 -0
- package/dist/commands/field.js +261 -0
- package/dist/commands/folder.d.ts +2 -0
- package/dist/commands/folder.js +31 -0
- package/dist/commands/form.d.ts +2 -0
- package/dist/commands/form.js +412 -0
- package/dist/commands/index.d.ts +16 -0
- package/dist/commands/index.js +68 -0
- package/dist/commands/local.d.ts +10 -0
- package/dist/commands/local.js +76 -0
- package/dist/commands/opensearch.d.ts +2 -0
- package/dist/commands/opensearch.js +73 -0
- package/dist/commands/shared.d.ts +57 -0
- package/dist/commands/shared.js +122 -0
- package/dist/commands/table.d.ts +2 -0
- package/dist/commands/table.js +101 -0
- package/dist/{commands.d.ts → commands/types.d.ts} +24 -30
- package/dist/commands/types.js +1 -0
- package/dist/commands/upload.d.ts +7 -0
- package/dist/commands/upload.js +40 -0
- package/dist/commands/view.d.ts +2 -0
- package/dist/commands/view.js +81 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.js +45 -5
- package/dist/errors.d.ts +48 -0
- package/dist/errors.js +99 -0
- package/dist/help.d.ts +1 -1
- package/dist/help.js +11 -1
- package/dist/http.d.ts +37 -4
- package/dist/http.js +119 -14
- package/dist/local.d.ts +24 -0
- package/dist/local.js +208 -0
- package/dist/options.d.ts +8 -4
- package/dist/options.js +63 -18
- package/dist/payload.d.ts +14 -8
- package/dist/payload.js +22 -54
- package/dist/render.d.ts +21 -0
- package/dist/render.js +315 -0
- package/dist/result.d.ts +31 -0
- package/dist/result.js +32 -0
- package/dist/values.d.ts +4 -0
- package/dist/values.js +8 -0
- package/dist/version.d.ts +6 -0
- package/dist/version.js +16 -0
- package/package.json +23 -18
- package/dist/commands.js +0 -1690
package/dist/cli.js
CHANGED
|
@@ -1,479 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { bindArgs, bindOptions, leadingWords, readStdin, splitArgs } from './args.js';
|
|
2
|
+
import { findCommand } from './commands/index.js';
|
|
3
|
+
import { defaultConfigPath, loadConfig } from './config.js';
|
|
4
|
+
import { helpFor, rootHelp } from './help.js';
|
|
5
|
+
import { HttpError, JinshujuHttpClient } from './http.js';
|
|
6
|
+
import { runLocal } from './local.js';
|
|
7
|
+
import { GLOBAL_OPTIONS, LOCAL_OPTIONS, UsageError } from './options.js';
|
|
4
8
|
import { progress } from './progress.js';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { GLOBAL_OPTIONS, LOCAL_OPTIONS, UsageError, optionKey, readJsonInput } from './options.js';
|
|
9
|
-
/**
|
|
10
|
-
* Splits the command line before a command is known: `--help` and an unknown
|
|
11
|
-
* command both have to work without one.
|
|
12
|
-
*/
|
|
13
|
-
/**
|
|
14
|
-
* The words that name the command: enough to find it, and no more.
|
|
15
|
-
*
|
|
16
|
-
* A flag may come first — `jinshuju --config local.json form list` is what a
|
|
17
|
-
* shell alias expands to, and what anyone arriving from `git -C` or
|
|
18
|
-
* `kubectl --context` writes — so a flag this CLI knows without a command is
|
|
19
|
-
* stepped over, along with its value. Stopping at it instead reported "Unknown
|
|
20
|
-
* command: jinshuju form list" while offering that very command as a
|
|
21
|
-
* suggestion.
|
|
22
|
-
*
|
|
23
|
-
* An unknown flag still ends the scan. Only a command declares those, so by the
|
|
24
|
-
* time one appears the command has been named already.
|
|
25
|
-
*/
|
|
26
|
-
function leadingWords(argv) {
|
|
27
|
-
const known = new Map();
|
|
28
|
-
for (const spec of [...GLOBAL_OPTIONS, ...LOCAL_OPTIONS]) {
|
|
29
|
-
known.set(spec.name, spec);
|
|
30
|
-
if (spec.short)
|
|
31
|
-
known.set(spec.short, spec);
|
|
32
|
-
}
|
|
33
|
-
const words = [];
|
|
34
|
-
for (let index = 0; index < argv.length; index += 1) {
|
|
35
|
-
const token = argv[index];
|
|
36
|
-
if (!token.startsWith('-') || token === '-') {
|
|
37
|
-
words.push(token);
|
|
38
|
-
continue;
|
|
39
|
-
}
|
|
40
|
-
const equals = token.indexOf('=');
|
|
41
|
-
const spec = known.get(equals === -1 ? token : token.slice(0, equals));
|
|
42
|
-
if (!spec)
|
|
43
|
-
break;
|
|
44
|
-
if (equals === -1 && spec.type !== 'boolean')
|
|
45
|
-
index += 1;
|
|
46
|
-
}
|
|
47
|
-
return words;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Splits the command line, knowing which flags take a value.
|
|
51
|
-
*
|
|
52
|
-
* Guessing from the shape of the next token gets two things wrong that a
|
|
53
|
-
* caller has every right to write: `--json -`, where the value is the very
|
|
54
|
-
* character that looks like a flag, and `--yes 12`, where a boolean must not
|
|
55
|
-
* swallow the argument behind it. Both are decided by the option's own type,
|
|
56
|
-
* so the specs are passed in rather than inferred.
|
|
57
|
-
*/
|
|
58
|
-
function splitArgs(argv, specs = []) {
|
|
59
|
-
const takesValue = new Map();
|
|
60
|
-
for (const spec of specs) {
|
|
61
|
-
takesValue.set(spec.name, spec.type !== 'boolean');
|
|
62
|
-
if (spec.short)
|
|
63
|
-
takesValue.set(spec.short, spec.type !== 'boolean');
|
|
64
|
-
}
|
|
65
|
-
const words = [];
|
|
66
|
-
const flags = {};
|
|
67
|
-
for (let index = 0; index < argv.length; index += 1) {
|
|
68
|
-
const token = argv[index];
|
|
69
|
-
if (token === '--') {
|
|
70
|
-
words.push(...argv.slice(index + 1));
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
|
-
if (!token.startsWith('-') || token === '-') {
|
|
74
|
-
words.push(token);
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
const equals = token.indexOf('=');
|
|
78
|
-
const flag = equals === -1 ? token : token.slice(0, equals);
|
|
79
|
-
const inline = equals === -1 ? undefined : token.slice(equals + 1);
|
|
80
|
-
const next = argv[index + 1];
|
|
81
|
-
// An unknown flag is assumed to take a value, so it reaches bindOptions
|
|
82
|
-
// with whatever followed it and is refused by name rather than by shape.
|
|
83
|
-
const wanted = takesValue.get(flag) ?? true;
|
|
84
|
-
const consumable = wanted && next !== undefined && (next === '-' || !next.startsWith('-'));
|
|
85
|
-
const value = inline ?? (consumable ? (index += 1, next) : true);
|
|
86
|
-
const existing = flags[flag];
|
|
87
|
-
flags[flag] = existing === undefined ? value : [].concat(existing, value);
|
|
88
|
-
}
|
|
89
|
-
return { words, flags };
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Checks the flags against what this command declares. A flag belonging to
|
|
93
|
-
* another command is an error rather than something quietly ignored: that is
|
|
94
|
-
* how a caller learns it asked for something that was never going to happen.
|
|
95
|
-
*/
|
|
96
|
-
function bindOptions(specs, flags, label, stdin) {
|
|
97
|
-
const byFlag = new Map();
|
|
98
|
-
for (const spec of specs) {
|
|
99
|
-
byFlag.set(spec.name, spec);
|
|
100
|
-
if (spec.short)
|
|
101
|
-
byFlag.set(spec.short, spec);
|
|
102
|
-
}
|
|
103
|
-
const bound = {};
|
|
104
|
-
for (const [flag, value] of Object.entries(flags)) {
|
|
105
|
-
const spec = byFlag.get(flag);
|
|
106
|
-
if (!spec)
|
|
107
|
-
throw new UsageError(`${label} does not take ${flag}. Run it with --help to see what it does take.`);
|
|
108
|
-
bound[optionKey(spec)] = coerce(spec, value, stdin);
|
|
109
|
-
}
|
|
110
|
-
return bound;
|
|
111
|
-
}
|
|
112
|
-
function coerce(spec, value, stdin) {
|
|
113
|
-
if (spec.repeatable)
|
|
114
|
-
return [].concat(value).map((item) => coerceOne(spec, item, stdin));
|
|
115
|
-
if (Array.isArray(value))
|
|
116
|
-
throw new UsageError(`${spec.name} takes a single value, but was given more than once`);
|
|
117
|
-
return coerceOne(spec, value, stdin);
|
|
118
|
-
}
|
|
119
|
-
function coerceOne(spec, value, stdin) {
|
|
120
|
-
if (spec.type === 'boolean') {
|
|
121
|
-
if (value === true || value === 'true')
|
|
122
|
-
return true;
|
|
123
|
-
if (value === 'false')
|
|
124
|
-
return false;
|
|
125
|
-
throw new UsageError(`${spec.name} is a flag and takes no value`);
|
|
126
|
-
}
|
|
127
|
-
if (value === true)
|
|
128
|
-
throw new UsageError(`${spec.name} needs a value`);
|
|
129
|
-
const text = String(value);
|
|
130
|
-
if (spec.choices && !spec.choices.includes(text)) {
|
|
131
|
-
throw new UsageError(`${spec.name} must be one of ${spec.choices.join(', ')}, got ${JSON.stringify(text)}`);
|
|
132
|
-
}
|
|
133
|
-
if (spec.type === 'integer') {
|
|
134
|
-
if (!/^\d+$/.test(text))
|
|
135
|
-
throw new UsageError(`${spec.name} must be a whole number, got ${JSON.stringify(text)}`);
|
|
136
|
-
return Number.parseInt(text, 10);
|
|
137
|
-
}
|
|
138
|
-
if (spec.type === 'list')
|
|
139
|
-
return text.split(',').map((item) => item.trim()).filter(Boolean);
|
|
140
|
-
if (spec.type === 'json')
|
|
141
|
-
return readJsonInput(text, stdin);
|
|
142
|
-
return text;
|
|
143
|
-
}
|
|
144
|
-
function bindArgs(command, words) {
|
|
145
|
-
const positionals = words.slice(command.path.length);
|
|
146
|
-
const specs = command.args ?? [];
|
|
147
|
-
const args = {};
|
|
148
|
-
let rest = [];
|
|
149
|
-
specs.forEach((arg, index) => {
|
|
150
|
-
if (arg.variadic) {
|
|
151
|
-
rest = positionals.slice(index);
|
|
152
|
-
if (arg.required && rest.length === 0) {
|
|
153
|
-
throw new UsageError(`jinshuju ${command.path.join(' ')} needs <${arg.name}>: ${arg.description}`);
|
|
154
|
-
}
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
const value = positionals[index];
|
|
158
|
-
if (value === undefined) {
|
|
159
|
-
if (arg.required)
|
|
160
|
-
throw new UsageError(`jinshuju ${command.path.join(' ')} needs <${arg.name}>: ${arg.description}`);
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
args[arg.name] = value;
|
|
164
|
-
});
|
|
165
|
-
if (!specs.some((arg) => arg.variadic)) {
|
|
166
|
-
const extra = positionals.slice(specs.length);
|
|
167
|
-
if (extra.length > 0) {
|
|
168
|
-
throw new UsageError(`jinshuju ${command.path.join(' ')} takes no argument ${JSON.stringify(extra[0])}`);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
return { args, rest };
|
|
172
|
-
}
|
|
173
|
-
function localOptions(flags, stdin) {
|
|
174
|
-
const bound = bindOptions([...GLOBAL_OPTIONS, ...LOCAL_OPTIONS], flags, 'this command', stdin);
|
|
175
|
-
return {
|
|
176
|
-
output: bound.output ?? 'text',
|
|
177
|
-
configPath: bound.config ?? defaultConfigPath,
|
|
178
|
-
apiKey: bound.api_key,
|
|
179
|
-
apiSecret: bound.api_secret,
|
|
180
|
-
host: bound.host,
|
|
181
|
-
authHost: bound.auth_host,
|
|
182
|
-
clientId: bound.client_id,
|
|
183
|
-
scopes: bound.scopes,
|
|
184
|
-
noOpen: Boolean(bound.no_open),
|
|
185
|
-
verify: Boolean(bound.verify),
|
|
186
|
-
showSecret: Boolean(bound.show_secret)
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* Read from package.json, not restated here. A release bumps that file and
|
|
191
|
-
* nothing else, so a constant reports the previous version from the moment it
|
|
192
|
-
* is published — 0.1.1 shipped saying 0.1.0.
|
|
193
|
-
*/
|
|
194
|
-
export const VERSION = readVersion();
|
|
195
|
-
function readVersion() {
|
|
196
|
-
try {
|
|
197
|
-
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
198
|
-
return pkg.version ?? 'unknown';
|
|
199
|
-
}
|
|
200
|
-
catch {
|
|
201
|
-
return 'unknown';
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
function ok(stdout) {
|
|
205
|
-
return { exitCode: 0, stdout: stdout.endsWith('\n') ? stdout : `${stdout}\n`, stderr: '' };
|
|
206
|
-
}
|
|
207
|
-
function fail(message, exitCode = 2) {
|
|
208
|
-
return { exitCode, stdout: '', stderr: `Error: ${message}\n` };
|
|
209
|
-
}
|
|
210
|
-
const MAX_CELL = 120;
|
|
211
|
-
/** What a table is allowed to be wide when nobody is watching it on a screen. */
|
|
212
|
-
const PIPED_WIDTH = 120;
|
|
213
|
-
/** Columns that say which row this is; they earn their place before any value. */
|
|
214
|
-
const LEADING_COLUMNS = ['token', 'api_code', 'serial_number', 'id', 'name', 'title', 'label', 'type', 'state', 'status'];
|
|
215
|
-
/**
|
|
216
|
-
* Timestamps go last, however early they appear in the payload. On a listing of
|
|
217
|
-
* rows they are the least of what the reader came for, and taking them in
|
|
218
|
-
* payload order is what left `entry list` showing two of a form's ten fields.
|
|
219
|
-
*/
|
|
220
|
-
const TRAILING_COLUMNS = ['created_at', 'updated_at'];
|
|
221
|
-
/**
|
|
222
|
-
* A column that names the row rather than saying anything about it. The listed
|
|
223
|
-
* ones plus whatever ends in `_token` or `_id`, because a search answers with
|
|
224
|
-
* `form_token` and a row showing only that has told the reader nothing.
|
|
225
|
-
*/
|
|
226
|
-
function identifies(column) {
|
|
227
|
-
return LEADING_COLUMNS.includes(column) || /(^|_)(token|id)$/.test(column);
|
|
228
|
-
}
|
|
229
|
-
export function terminalWidth(stream = process.stdout) {
|
|
230
|
-
return stream.isTTY && stream.columns > 0 ? stream.columns : PIPED_WIDTH;
|
|
231
|
-
}
|
|
232
|
-
function json(value) {
|
|
233
|
-
return JSON.stringify(value, null, 2);
|
|
234
|
-
}
|
|
235
|
-
function text(value, width) {
|
|
236
|
-
if (typeof value === 'string')
|
|
237
|
-
return value;
|
|
238
|
-
if (value === undefined || value === null)
|
|
239
|
-
return '';
|
|
240
|
-
if (Array.isArray(value))
|
|
241
|
-
return renderList(value, width);
|
|
242
|
-
if (typeof value === 'object')
|
|
243
|
-
return renderObject(value, width);
|
|
244
|
-
return String(value);
|
|
245
|
-
}
|
|
246
|
-
function renderObject(value, width) {
|
|
247
|
-
const listKey = ['data', 'items', 'forms', 'entries', 'views'].find((key) => Array.isArray(value[key]));
|
|
248
|
-
if (listKey) {
|
|
249
|
-
// Everything beside the listing is rendered, not just its scalars. Filtering
|
|
250
|
-
// to scalars here was another way for a payload to lose a key on the way to
|
|
251
|
-
// the page — the warnings an import answers with, say.
|
|
252
|
-
const heading = Object.entries(value)
|
|
253
|
-
.filter(([key]) => key !== listKey)
|
|
254
|
-
.map(([key, fieldValue]) => renderEntry(key, fieldValue, width));
|
|
255
|
-
const listText = renderList(value[listKey], width);
|
|
256
|
-
return [...heading, `${listKey}:`, listText].filter(Boolean).join('\n');
|
|
257
|
-
}
|
|
258
|
-
const entries = Object.entries(value);
|
|
259
|
-
if (entries.length === 0)
|
|
260
|
-
return '{}';
|
|
261
|
-
return entries.map(([key, fieldValue]) => renderEntry(key, fieldValue, width)).join('\n');
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* A setting is an object of objects, and printing it as JSON asks the reader to
|
|
265
|
-
* parse braces to find one flag. Nesting goes one indent deeper instead, so the
|
|
266
|
-
* shape stays visible and every leaf reads as `key: value`.
|
|
267
|
-
*/
|
|
268
|
-
function renderEntry(key, value, width) {
|
|
269
|
-
if (Array.isArray(value)) {
|
|
270
|
-
return value.length === 0 ? `${key}: (empty)` : `${key}:\n${indent(renderList(value, width))}`;
|
|
271
|
-
}
|
|
272
|
-
if (value !== null && typeof value === 'object') {
|
|
273
|
-
const block = renderObject(value, width);
|
|
274
|
-
return block === '{}' ? `${key}: {}` : `${key}:\n${indent(block)}`;
|
|
275
|
-
}
|
|
276
|
-
return `${key}: ${formatCell(value)}`;
|
|
277
|
-
}
|
|
278
|
-
function indent(block) {
|
|
279
|
-
return block.split('\n').map((line) => (line ? ` ${line}` : line)).join('\n');
|
|
280
|
-
}
|
|
281
|
-
function renderList(values, width) {
|
|
282
|
-
if (values.length === 0)
|
|
283
|
-
return '(empty)';
|
|
284
|
-
if (!values.every(isRecord))
|
|
285
|
-
return values.map((item) => formatField(item)).join('\n');
|
|
286
|
-
const { rows, headings } = splitLabels(values.map(unwrapKeyed));
|
|
287
|
-
if (rows.some(hasEssentialList))
|
|
288
|
-
return rows.map((row) => renderObject(row, width)).join('\n\n');
|
|
289
|
-
const heading = (column) => headings.get(column) ?? column;
|
|
290
|
-
const candidates = candidateColumns(rows);
|
|
291
|
-
if (candidates.length === 0)
|
|
292
|
-
return rows.map((row) => json(row)).join('\n');
|
|
293
|
-
const columns = [];
|
|
294
|
-
const widths = [];
|
|
295
|
-
let used = 0;
|
|
296
|
-
for (const column of candidates) {
|
|
297
|
-
const columnWidth = Math.max(displayWidth(heading(column)), ...rows.map((row) => displayWidth(formatCell(row[column]))));
|
|
298
|
-
const next = used + (columns.length === 0 ? 0 : 2) + columnWidth;
|
|
299
|
-
// The first column goes in whatever it costs: a table of nothing is worse
|
|
300
|
-
// than a table too wide.
|
|
301
|
-
if (columns.length > 0 && next > width)
|
|
302
|
-
break;
|
|
303
|
-
columns.push(column);
|
|
304
|
-
widths.push(columnWidth);
|
|
305
|
-
used = next;
|
|
306
|
-
}
|
|
307
|
-
// A row that says nothing but its own name says nothing at all — and the
|
|
308
|
-
// column that would have explained it is exactly the one a narrow terminal
|
|
309
|
-
// drops. `entry search` keeps a form it could not read *with the reason*, and
|
|
310
|
-
// the budget must not be what throws that reason away. A row left with only
|
|
311
|
-
// its identity buys back one column, whatever the width says.
|
|
312
|
-
const told = (row, column) => !identifies(column) && formatCell(row[column]) !== '';
|
|
313
|
-
for (const row of rows) {
|
|
314
|
-
if (columns.some((column) => told(row, column)))
|
|
315
|
-
continue;
|
|
316
|
-
const rescued = candidates.find((column) => !columns.includes(column) && told(row, column));
|
|
317
|
-
if (!rescued)
|
|
318
|
-
continue;
|
|
319
|
-
columns.push(rescued);
|
|
320
|
-
widths.push(Math.max(displayWidth(heading(rescued)), ...rows.map((other) => displayWidth(formatCell(other[rescued])))));
|
|
321
|
-
}
|
|
322
|
-
const header = columns.map((column, index) => pad(heading(column), widths[index])).join(' ');
|
|
323
|
-
const separator = widths.map((columnWidth) => '-'.repeat(columnWidth)).join(' ');
|
|
324
|
-
const body = rows.map((row) => columns.map((column, index) => pad(formatCell(row[column]), widths[index])).join(' '));
|
|
325
|
-
return [header, separator, ...body].join('\n');
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Every column the rows could show, best first. How many of them fit is the
|
|
329
|
-
* caller's question, and it needs their widths to answer it.
|
|
330
|
-
*/
|
|
331
|
-
function candidateColumns(rows) {
|
|
332
|
-
const present = (key) => rows.some((row) => Object.prototype.hasOwnProperty.call(row, key) && isCell(row[key]));
|
|
333
|
-
const seen = new Set(LEADING_COLUMNS.filter(present));
|
|
334
|
-
for (const row of rows) {
|
|
335
|
-
for (const [key, value] of Object.entries(row)) {
|
|
336
|
-
if (isCell(value) && !TRAILING_COLUMNS.includes(key))
|
|
337
|
-
seen.add(key);
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
for (const key of TRAILING_COLUMNS.filter(present))
|
|
341
|
-
seen.add(key);
|
|
342
|
-
return [...seen];
|
|
343
|
-
}
|
|
344
|
-
/**
|
|
345
|
-
* A form's fields arrive as `{ "field_1": { label, type, ... } }`, one key per
|
|
346
|
-
* row. A table of those reads as a column per field and nothing in it, so the
|
|
347
|
-
* key becomes a cell of its own row instead.
|
|
348
|
-
*/
|
|
349
|
-
function unwrapKeyed(row) {
|
|
350
|
-
const entries = Object.entries(row);
|
|
351
|
-
if (entries.length !== 1)
|
|
352
|
-
return row;
|
|
353
|
-
const [key, value] = entries[0];
|
|
354
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
355
|
-
return row;
|
|
356
|
-
return { api_code: key, ...value };
|
|
357
|
-
}
|
|
358
|
-
/**
|
|
359
|
-
* `--labels` answers each field as `{ label, value }`. A cell cannot hold a
|
|
360
|
-
* pair, and a column of pairs is no column at all — which is why the values
|
|
361
|
-
* used to vanish from the table entirely. The pair is split instead: the value
|
|
362
|
-
* becomes the cell, the label becomes the column's heading. Columns stay keyed
|
|
363
|
-
* by api_code, because two fields may carry the same label.
|
|
364
|
-
*/
|
|
365
|
-
function splitLabels(rows) {
|
|
366
|
-
const headings = new Map();
|
|
367
|
-
const split = rows.map((row) => {
|
|
368
|
-
const out = {};
|
|
369
|
-
for (const [key, value] of Object.entries(row)) {
|
|
370
|
-
if (!isLabelled(value)) {
|
|
371
|
-
out[key] = value;
|
|
372
|
-
continue;
|
|
373
|
-
}
|
|
374
|
-
const { label, value: cell } = value;
|
|
375
|
-
if (typeof label === 'string' && label !== '')
|
|
376
|
-
headings.set(key, label);
|
|
377
|
-
out[key] = cell;
|
|
378
|
-
}
|
|
379
|
-
return out;
|
|
380
|
-
});
|
|
381
|
-
return { rows: split, headings };
|
|
382
|
-
}
|
|
383
|
-
function isLabelled(value) {
|
|
384
|
-
if (!isRecord(value))
|
|
385
|
-
return false;
|
|
386
|
-
const keys = Object.keys(value);
|
|
387
|
-
return keys.length === 2 && keys.includes('label') && keys.includes('value');
|
|
388
|
-
}
|
|
389
|
-
/**
|
|
390
|
-
* A row carrying a list of its own has no cell a table could put it in, and the
|
|
391
|
-
* table drops it. Usually that is the right trade — a field's `choices` are
|
|
392
|
-
* detail, and the row still says what the field is. An analysis' buckets are
|
|
393
|
-
* not detail: they are the answer, and a table of `entry summary` without them
|
|
394
|
-
* prints how many people answered and never what they answered.
|
|
395
|
-
*
|
|
396
|
-
* Which is which is not readable off the shape — both are a list of objects
|
|
397
|
-
* beside a handful of scalars — so the lists worth breaking the table for are
|
|
398
|
-
* named, the way `renderObject` names the keys that hold a listing.
|
|
399
|
-
*/
|
|
400
|
-
const ESSENTIAL_LISTS = ['buckets'];
|
|
401
|
-
function hasEssentialList(row) {
|
|
402
|
-
return ESSENTIAL_LISTS.some((key) => {
|
|
403
|
-
const value = row[key];
|
|
404
|
-
return Array.isArray(value) && value.length > 0 && value.every(isRecord);
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
function isRecord(value) {
|
|
408
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
409
|
-
}
|
|
410
|
-
function isScalar(value) {
|
|
411
|
-
return value === null || ['string', 'number', 'boolean'].includes(typeof value);
|
|
412
|
-
}
|
|
413
|
-
/**
|
|
414
|
-
* Whether a value earns its key a column. A list of values does: a
|
|
415
|
-
* multiple-choice answer is a list, and so is the `serial_numbers` a search
|
|
416
|
-
* answers with. Treating those as unprintable dropped the column — which meant
|
|
417
|
-
* `--fields field_6` left out field_6, and `entry search` said how many rows
|
|
418
|
-
* matched without ever saying which.
|
|
419
|
-
*
|
|
420
|
-
* An empty list earns nothing, though. A column that is `[]` in every row is a
|
|
421
|
-
* heading with a blank under it for as far as the table goes.
|
|
422
|
-
*/
|
|
423
|
-
function isCell(value) {
|
|
424
|
-
if (Array.isArray(value))
|
|
425
|
-
return value.length > 0 && value.every(isScalar);
|
|
426
|
-
return isScalar(value);
|
|
427
|
-
}
|
|
428
|
-
function formatField(value) {
|
|
429
|
-
if (isScalar(value))
|
|
430
|
-
return formatCell(value);
|
|
431
|
-
return json(value);
|
|
432
|
-
}
|
|
433
|
-
function formatCell(value) {
|
|
434
|
-
if (value === undefined || value === null)
|
|
435
|
-
return '';
|
|
436
|
-
if (typeof value === 'string')
|
|
437
|
-
return clip(value);
|
|
438
|
-
if (typeof value === 'number' || typeof value === 'boolean')
|
|
439
|
-
return String(value);
|
|
440
|
-
if (Array.isArray(value) && value.every(isScalar))
|
|
441
|
-
return clip(value.map(formatCell).join(', '));
|
|
442
|
-
return clip(JSON.stringify(value));
|
|
443
|
-
}
|
|
444
|
-
/**
|
|
445
|
-
* One rich text field is longer than the rest of a form put together, and it
|
|
446
|
-
* wraps over a screen of terminal. Text is the readable format; whoever wants
|
|
447
|
-
* the whole value asks for --output json.
|
|
448
|
-
*/
|
|
449
|
-
function clip(value) {
|
|
450
|
-
return value.length <= MAX_CELL ? value : `${value.slice(0, MAX_CELL)}… (${value.length} chars)`;
|
|
451
|
-
}
|
|
452
|
-
/**
|
|
453
|
-
* A column is padded to what the terminal shows, not to how many code points
|
|
454
|
-
* the value holds: a Chinese label takes two cells per character, so counting
|
|
455
|
-
* length leaves every table with a Chinese column ragged.
|
|
456
|
-
*/
|
|
457
|
-
function pad(value, width) {
|
|
458
|
-
return value + ' '.repeat(Math.max(0, width - displayWidth(value)));
|
|
459
|
-
}
|
|
460
|
-
function displayWidth(value) {
|
|
461
|
-
let width = 0;
|
|
462
|
-
for (const char of value)
|
|
463
|
-
width += isWide(char.codePointAt(0)) ? 2 : 1;
|
|
464
|
-
return width;
|
|
465
|
-
}
|
|
466
|
-
function isWide(code) {
|
|
467
|
-
return ((code >= 0x1100 && code <= 0x115f) ||
|
|
468
|
-
(code >= 0x2e80 && code <= 0xa4cf) ||
|
|
469
|
-
(code >= 0xac00 && code <= 0xd7a3) ||
|
|
470
|
-
(code >= 0xf900 && code <= 0xfaff) ||
|
|
471
|
-
(code >= 0xfe30 && code <= 0xfe6f) ||
|
|
472
|
-
(code >= 0xff00 && code <= 0xff60) ||
|
|
473
|
-
(code >= 0xffe0 && code <= 0xffe6) ||
|
|
474
|
-
(code >= 0x1f300 && code <= 0x1faff) ||
|
|
475
|
-
(code >= 0x20000 && code <= 0x3fffd));
|
|
476
|
-
}
|
|
9
|
+
import { format, terminalWidth } from './render.js';
|
|
10
|
+
import { fail, ok, outputOf, unknown } from './result.js';
|
|
11
|
+
import { VERSION } from './version.js';
|
|
477
12
|
export async function runCli(args = [], runtime = {}) {
|
|
478
13
|
// The command has to be found before the line can be split, because only it
|
|
479
14
|
// says which flags take a value. Its own words come first and hold no flags,
|
|
@@ -493,11 +28,11 @@ export async function runCli(args = [], runtime = {}) {
|
|
|
493
28
|
if (resource === 'auth' || resource === 'config')
|
|
494
29
|
return await runLocal(words, flags, runtime, stdin);
|
|
495
30
|
if (!command)
|
|
496
|
-
return
|
|
31
|
+
return unknown(words, outputOf(flags));
|
|
497
32
|
return await runRemote(command, words, flags, runtime, stdin);
|
|
498
33
|
}
|
|
499
34
|
catch (error) {
|
|
500
|
-
return fail(error
|
|
35
|
+
return fail(error, outputOf(flags));
|
|
501
36
|
}
|
|
502
37
|
}
|
|
503
38
|
async function runRemote(command, words, flags, runtime, stdin) {
|
|
@@ -507,207 +42,84 @@ async function runRemote(command, words, flags, runtime, stdin) {
|
|
|
507
42
|
const input = { ...bindArgs(command, words), options };
|
|
508
43
|
const output = options.output ?? 'text';
|
|
509
44
|
const width = runtime.width ?? terminalWidth();
|
|
510
|
-
const client = runtime.client ??
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
45
|
+
const client = runtime.client ??
|
|
46
|
+
new JinshujuHttpClient(loadConfig({
|
|
47
|
+
configPath: options.config ?? defaultConfigPath,
|
|
48
|
+
env: runtime.env,
|
|
49
|
+
cli: {
|
|
50
|
+
apiKey: options.api_key,
|
|
51
|
+
apiSecret: options.api_secret,
|
|
52
|
+
host: options.host
|
|
53
|
+
}
|
|
54
|
+
}));
|
|
55
|
+
// A command that needs more than one round trip, or has to decide how many,
|
|
56
|
+
// runs itself and answers with what should be printed.
|
|
57
|
+
const hints = { list: command.text?.list ?? command.paginate?.items, essentialLists: command.text?.essentialLists };
|
|
518
58
|
if (command.run) {
|
|
519
59
|
const payload = await command.run(input, client);
|
|
520
|
-
|
|
521
|
-
return ok(output === 'json' ? json(payload) : text(payload, width));
|
|
60
|
+
return ok(format(payload, output, width, hints));
|
|
522
61
|
}
|
|
523
62
|
const request = command.request?.(input);
|
|
524
63
|
if (!request)
|
|
525
64
|
throw new UsageError(`${label} is not available yet`);
|
|
526
65
|
if (options.all && command.paginate) {
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
66
|
+
// jsonl is the one format that can be written before the end is known,
|
|
67
|
+
// so each page goes out as it arrives and nothing is kept. The other two
|
|
68
|
+
// need the whole listing first: json to close its brackets, text to know
|
|
69
|
+
// how wide its columns are.
|
|
70
|
+
if (output === 'jsonl') {
|
|
71
|
+
let gathered = '';
|
|
72
|
+
const write = runtime.stdout ?? ((chunk) => (gathered += chunk));
|
|
73
|
+
await readAllPages(client, request, command.paginate, progress(), (rows) => {
|
|
74
|
+
for (const row of rows)
|
|
75
|
+
write(`${JSON.stringify(row)}\n`);
|
|
76
|
+
});
|
|
77
|
+
return { exitCode: 0, stdout: gathered, stderr: '' };
|
|
78
|
+
}
|
|
79
|
+
const rows = [];
|
|
80
|
+
await readAllPages(client, request, command.paginate, progress(), (page) => rows.push(...page));
|
|
81
|
+
return ok(format({ count: rows.length, data: rows }, output, width, hints));
|
|
530
82
|
}
|
|
531
|
-
const result = await client.request(
|
|
532
|
-
const selected = command.select ? command.select(result) : result;
|
|
533
|
-
if (output === '
|
|
534
|
-
return ok(
|
|
535
|
-
return ok(
|
|
83
|
+
const result = await client.request(request);
|
|
84
|
+
const selected = command.select ? command.select(result, input) : result;
|
|
85
|
+
if (output === 'text')
|
|
86
|
+
return ok(format(command.render ? command.render(selected) : selected, output, width, hints));
|
|
87
|
+
return ok(format(selected, output, width, hints));
|
|
536
88
|
}
|
|
537
89
|
/**
|
|
538
|
-
*
|
|
90
|
+
* More pages than any listing has. A cursor that never runs out would
|
|
91
|
+
* otherwise read forever; stopping here says so instead, with what was read.
|
|
92
|
+
*/
|
|
93
|
+
const MAX_PAGES = 10_000;
|
|
94
|
+
/**
|
|
95
|
+
* Every page of a listing, handed on a page at a time. A cursor is opaque: it
|
|
96
|
+
* goes back exactly as it came. Answers how many rows there were.
|
|
539
97
|
*/
|
|
540
|
-
async function readAllPages(client, request, paginate, watching
|
|
541
|
-
|
|
98
|
+
async function readAllPages(client, request, paginate, watching, onPage) {
|
|
99
|
+
let count = 0;
|
|
542
100
|
let cursor;
|
|
543
101
|
let page = 0;
|
|
544
102
|
for (;;) {
|
|
545
|
-
const
|
|
546
|
-
|
|
547
|
-
|
|
103
|
+
const body = await client.request({
|
|
104
|
+
...request,
|
|
105
|
+
query: { ...request.query, ...(cursor ? { next: cursor } : {}) }
|
|
106
|
+
});
|
|
107
|
+
const rows = body?.[paginate.items] ?? [];
|
|
108
|
+
count += rows.length;
|
|
109
|
+
onPage(rows);
|
|
548
110
|
page += 1;
|
|
549
|
-
watching.step(`read ${page} page${page === 1 ? '' : 's'}, ${
|
|
111
|
+
watching.step(`read ${page} page${page === 1 ? '' : 's'}, ${count} rows…`);
|
|
550
112
|
const next = body?.[paginate.cursor];
|
|
551
113
|
if (next === undefined || next === null || next === '')
|
|
552
114
|
break;
|
|
115
|
+
// A server answering the cursor it was just given would be read forever.
|
|
116
|
+
if (String(next) === cursor) {
|
|
117
|
+
throw new HttpError(`the server answered page ${page} with the cursor it was asked for; stopping rather than looping`, 200, body);
|
|
118
|
+
}
|
|
119
|
+
if (page >= MAX_PAGES)
|
|
120
|
+
throw new Error(`stopped after ${MAX_PAGES} pages and ${count} rows; the listing has no end`);
|
|
553
121
|
cursor = String(next);
|
|
554
122
|
}
|
|
555
123
|
watching.done();
|
|
556
|
-
return
|
|
557
|
-
}
|
|
558
|
-
/**
|
|
559
|
-
* A list value repeats its parameter as `name[]=a&name[]=b`, which is how Rails
|
|
560
|
-
* reads a list. Joining them with a comma would ask for one keyword containing
|
|
561
|
-
* a comma instead of two keywords.
|
|
562
|
-
*/
|
|
563
|
-
function withQuery(path, query) {
|
|
564
|
-
const params = new URLSearchParams();
|
|
565
|
-
for (const [name, value] of Object.entries(query ?? {})) {
|
|
566
|
-
if (value === undefined)
|
|
567
|
-
continue;
|
|
568
|
-
if (typeof value === 'string') {
|
|
569
|
-
params.set(name, value);
|
|
570
|
-
}
|
|
571
|
-
else {
|
|
572
|
-
for (const item of value)
|
|
573
|
-
params.append(`${name}[]`, item);
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
const search = params.toString();
|
|
577
|
-
return search ? `${path}?${search}` : path;
|
|
578
|
-
}
|
|
579
|
-
function readStdin() {
|
|
580
|
-
try {
|
|
581
|
-
return readFileSync(0, 'utf8');
|
|
582
|
-
}
|
|
583
|
-
catch {
|
|
584
|
-
throw new UsageError('could not read JSON from stdin');
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
async function runLocal(words, flags, runtime, stdin) {
|
|
588
|
-
const options = localOptions(flags, stdin);
|
|
589
|
-
const key = words.slice(0, 2).join(' ');
|
|
590
|
-
switch (key) {
|
|
591
|
-
case 'auth login':
|
|
592
|
-
return await authLogin(options, runtime);
|
|
593
|
-
case 'auth status':
|
|
594
|
-
return await authStatus(options, runtime);
|
|
595
|
-
case 'auth refresh':
|
|
596
|
-
return await authRefresh(options, runtime);
|
|
597
|
-
case 'auth logout':
|
|
598
|
-
return await authLogout(options, runtime);
|
|
599
|
-
case 'config get':
|
|
600
|
-
return configGet(words, options);
|
|
601
|
-
case 'config set':
|
|
602
|
-
return configSet(words, options);
|
|
603
|
-
case 'config unset':
|
|
604
|
-
return configUnset(words, options);
|
|
605
|
-
default:
|
|
606
|
-
return { exitCode: 1, stdout: '', stderr: unknownCommandHelp(words) };
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
function requireArg(value, name) {
|
|
610
|
-
if (!value)
|
|
611
|
-
throw new Error(`Missing argument <${name}>`);
|
|
612
|
-
return value;
|
|
613
|
-
}
|
|
614
|
-
function createClient(options, runtime) {
|
|
615
|
-
return runtime.client ?? new JinshujuHttpClient(loadConfig({ configPath: options.configPath, env: runtime.env, cli: { apiKey: options.apiKey, apiSecret: options.apiSecret, host: options.host } }));
|
|
616
|
-
}
|
|
617
|
-
async function authLogin(options, runtime) {
|
|
618
|
-
const result = await loginWithOAuth({
|
|
619
|
-
configPath: options.configPath,
|
|
620
|
-
env: runtime.env,
|
|
621
|
-
host: options.host,
|
|
622
|
-
authHost: options.authHost,
|
|
623
|
-
clientId: options.clientId,
|
|
624
|
-
scopes: options.scopes,
|
|
625
|
-
openBrowser: !options.noOpen
|
|
626
|
-
});
|
|
627
|
-
const payload = { authenticated: true, mode: 'oauth', auth_host: result.token.auth_host, client_id: result.token.client_id, scope: result.token.scope, expires_at: result.token.expires_at };
|
|
628
|
-
if (options.output === 'json')
|
|
629
|
-
return ok(json(payload));
|
|
630
|
-
return ok(`Authenticated with OAuth.\nConfig: ${options.configPath}`);
|
|
631
|
-
}
|
|
632
|
-
async function authStatus(options, runtime) {
|
|
633
|
-
const config = loadConfig({ configPath: options.configPath, env: runtime.env, cli: { apiKey: options.apiKey, apiSecret: options.apiSecret, host: options.host, authHost: options.authHost, clientId: options.clientId } });
|
|
634
|
-
const authenticated = Boolean(config.accessToken || (config.apiKey && config.apiSecret) || config.auth?.access_token);
|
|
635
|
-
const mode = config.accessToken
|
|
636
|
-
? 'access_token'
|
|
637
|
-
: config.apiKey && config.apiSecret
|
|
638
|
-
? 'api_key_secret'
|
|
639
|
-
: config.auth?.access_token
|
|
640
|
-
? 'oauth'
|
|
641
|
-
: 'none';
|
|
642
|
-
const payload = {
|
|
643
|
-
authenticated,
|
|
644
|
-
mode,
|
|
645
|
-
host: config.host,
|
|
646
|
-
auth_host: config.authHost,
|
|
647
|
-
sources: config.sources,
|
|
648
|
-
source: mode === 'access_token' ? config.sources.accessToken
|
|
649
|
-
: mode === 'api_key_secret' ? config.sources.apiKey
|
|
650
|
-
: mode === 'oauth' ? config.sources.auth : 'missing',
|
|
651
|
-
oauth: config.auth ? { client_id: config.auth.client_id, scope: config.auth.scope, expires_at: config.auth.expires_at, has_refresh_token: Boolean(config.auth.refresh_token) } : undefined
|
|
652
|
-
};
|
|
653
|
-
if (options.verify && authenticated) {
|
|
654
|
-
await createClient(options, runtime).request({ method: 'GET', path: '/api/v1/forms' });
|
|
655
|
-
}
|
|
656
|
-
if (options.output === 'json')
|
|
657
|
-
return ok(json(payload));
|
|
658
|
-
if (mode === 'access_token')
|
|
659
|
-
return ok(`Authenticated with an access token (from ${config.sources.accessToken}).`);
|
|
660
|
-
if (mode === 'oauth')
|
|
661
|
-
return ok('Authenticated with OAuth.');
|
|
662
|
-
if (mode === 'api_key_secret')
|
|
663
|
-
return ok('Authenticated with API Key / Secret.');
|
|
664
|
-
return ok('Missing authentication. Run `jinshuju auth login`, or set an access token, or configure API Key / Secret.');
|
|
665
|
-
}
|
|
666
|
-
async function authRefresh(options, runtime) {
|
|
667
|
-
const config = loadConfig({ configPath: options.configPath, env: runtime.env, cli: { host: options.host, authHost: options.authHost, clientId: options.clientId } });
|
|
668
|
-
const auth = await refreshOAuthToken(config);
|
|
669
|
-
if (options.output === 'json')
|
|
670
|
-
return ok(json({ authenticated: true, mode: 'oauth', expires_at: auth.expires_at, scope: auth.scope }));
|
|
671
|
-
return ok('OAuth token refreshed.');
|
|
672
|
-
}
|
|
673
|
-
async function authLogout(options, runtime) {
|
|
674
|
-
const config = loadConfig({ configPath: options.configPath, env: runtime.env });
|
|
675
|
-
await revokeOAuthToken(config);
|
|
676
|
-
return ok(options.output === 'json' ? json({ authenticated: false }) : 'Logged out.');
|
|
677
|
-
}
|
|
678
|
-
function configGet(positionals, options) {
|
|
679
|
-
const requestedKey = positionals[2];
|
|
680
|
-
if (requestedKey)
|
|
681
|
-
assertConfigKey(requestedKey);
|
|
682
|
-
const config = getConfig(options.configPath);
|
|
683
|
-
const secrets = new Set(['access_token', 'api_key', 'api_secret']);
|
|
684
|
-
const renderValue = (key, value) => options.showSecret || !secrets.has(key) ? value : maskSecret(value);
|
|
685
|
-
let payload;
|
|
686
|
-
if (requestedKey) {
|
|
687
|
-
const configKey = requestedKey;
|
|
688
|
-
payload = { [configKey]: renderValue(configKey, config[configKey]) };
|
|
689
|
-
}
|
|
690
|
-
else {
|
|
691
|
-
payload = {
|
|
692
|
-
access_token: renderValue('access_token', config.access_token),
|
|
693
|
-
api_key: renderValue('api_key', config.api_key),
|
|
694
|
-
api_secret: renderValue('api_secret', config.api_secret)
|
|
695
|
-
};
|
|
696
|
-
}
|
|
697
|
-
if (options.output === 'json')
|
|
698
|
-
return ok(json(payload));
|
|
699
|
-
return ok(Object.entries(payload).map(([k, v]) => `${k}: ${v ?? '(unset)'}`).join('\n'));
|
|
700
|
-
}
|
|
701
|
-
function configSet(positionals, options) {
|
|
702
|
-
const key = requireArg(positionals[2], 'key');
|
|
703
|
-
assertConfigKey(key);
|
|
704
|
-
const value = requireArg(positionals[3], 'value');
|
|
705
|
-
setConfigValue(options.configPath, key, value);
|
|
706
|
-
return ok(`Set ${key}`);
|
|
707
|
-
}
|
|
708
|
-
function configUnset(positionals, options) {
|
|
709
|
-
const key = requireArg(positionals[2], 'key');
|
|
710
|
-
assertConfigKey(key);
|
|
711
|
-
unsetConfigValue(options.configPath, key);
|
|
712
|
-
return ok(`Unset ${key}`);
|
|
124
|
+
return count;
|
|
713
125
|
}
|