@basementuniverse/jsonpad-cli 1.0.0 → 1.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/CHANGELOG.md +77 -1
- package/README.md +252 -27
- package/REFERENCE.md +1292 -3
- package/build/cli.js +8 -0
- package/build/client.js +185 -0
- package/build/commands/config.js +134 -0
- package/build/commands/history.js +205 -0
- package/build/commands/identities.js +372 -0
- package/build/commands/indexes.js +255 -0
- package/build/commands/items.js +329 -0
- package/build/commands/listen.js +173 -0
- package/build/commands/lists.js +237 -0
- package/build/commands/transfer.js +246 -0
- package/build/commands/whoami.js +121 -0
- package/build/completion.js +170 -0
- package/build/config.js +158 -0
- package/build/context.js +24 -8
- package/build/errors.js +56 -0
- package/build/indexes.js +24 -1
- package/build/input.js +167 -0
- package/build/output.js +191 -0
- package/build/program.js +85 -20
- package/build/realtime.js +13 -0
- package/build/reference.js +34 -15
- package/build/resources.js +224 -0
- package/package.json +4 -4
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { Option } from 'commander';
|
|
2
|
+
import { apiError, apiErrorExitCode, CliError } from '../errors.js';
|
|
3
|
+
import { canPrompt, confirm, promptSecret, readStdin } from '../input.js';
|
|
4
|
+
import { addOutputOptions, formatTimestamp, printRecord, renderDetails, resolveOutputFormat, } from '../output.js';
|
|
5
|
+
import { addAllOption, addPagingOptions, addTaggedOption, addTagsOption, nullable, removeUndefined, printPages, request, resolveIdentityId, } from '../resources.js';
|
|
6
|
+
import { JSONPadError } from '../sdk.js';
|
|
7
|
+
import { defineEventCommands, defineStatsCommand } from './history.js';
|
|
8
|
+
const ORDER_FIELDS = [
|
|
9
|
+
'createdAt',
|
|
10
|
+
'updatedAt',
|
|
11
|
+
'name',
|
|
12
|
+
'displayName',
|
|
13
|
+
'group',
|
|
14
|
+
'activated',
|
|
15
|
+
];
|
|
16
|
+
const IDENTITY_ARGUMENT_DESCRIPTION = 'The identity: its id, group/name, or the name of an identity without a group';
|
|
17
|
+
export function identityLabel(identity) {
|
|
18
|
+
return identity.group ? `${identity.group}/${identity.name}` : identity.name;
|
|
19
|
+
}
|
|
20
|
+
function identityOutput(context) {
|
|
21
|
+
const { dim } = context.colours;
|
|
22
|
+
return {
|
|
23
|
+
id: identity => identity.id,
|
|
24
|
+
details: identity => [
|
|
25
|
+
['ID', identity.id],
|
|
26
|
+
['Group', identity.group || dim('(none)')],
|
|
27
|
+
['Name', identity.name],
|
|
28
|
+
['Display name', identity.displayName ?? dim('(none)')],
|
|
29
|
+
[
|
|
30
|
+
'Tags',
|
|
31
|
+
identity.tags?.length ? identity.tags.join(', ') : dim('(none)'),
|
|
32
|
+
],
|
|
33
|
+
[
|
|
34
|
+
'Last login',
|
|
35
|
+
identity.lastLoginAt
|
|
36
|
+
? formatTimestamp(identity.lastLoginAt)
|
|
37
|
+
: dim('never'),
|
|
38
|
+
],
|
|
39
|
+
['Created', formatTimestamp(identity.createdAt)],
|
|
40
|
+
['Updated', formatTimestamp(identity.updatedAt)],
|
|
41
|
+
],
|
|
42
|
+
columns: [
|
|
43
|
+
{ header: 'ID', value: identity => identity.id },
|
|
44
|
+
{ header: 'GROUP', value: identity => identity.group || '-' },
|
|
45
|
+
{ header: 'NAME', value: identity => identity.name },
|
|
46
|
+
{
|
|
47
|
+
header: 'DISPLAY NAME',
|
|
48
|
+
value: identity => identity.displayName ?? '-',
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
header: 'LAST LOGIN',
|
|
52
|
+
value: identity => identity.lastLoginAt ? formatTimestamp(identity.lastLoginAt) : '-',
|
|
53
|
+
},
|
|
54
|
+
],
|
|
55
|
+
empty: 'No identities',
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Read a password: from JSONPAD_IDENTITY_PASSWORD, asked for in a terminal, or
|
|
60
|
+
* from stdin. Passwords are never taken from an option, which would leave them
|
|
61
|
+
* in shell history
|
|
62
|
+
*/
|
|
63
|
+
async function readPassword(context, label) {
|
|
64
|
+
let password = context.env.JSONPAD_IDENTITY_PASSWORD;
|
|
65
|
+
if (password === undefined) {
|
|
66
|
+
password = canPrompt(context)
|
|
67
|
+
? await promptSecret(context, `Password for ${label}: `)
|
|
68
|
+
: (await readStdin(context)).replace(/\r?\n$/, '');
|
|
69
|
+
}
|
|
70
|
+
if (!password) {
|
|
71
|
+
throw new CliError(canPrompt(context)
|
|
72
|
+
? 'A password is needed'
|
|
73
|
+
: 'A password is needed. Pass it on stdin, or set JSONPAD_IDENTITY_PASSWORD');
|
|
74
|
+
}
|
|
75
|
+
return password;
|
|
76
|
+
}
|
|
77
|
+
function addIdentityFieldOptions(command, update) {
|
|
78
|
+
command
|
|
79
|
+
.option('--group <group>', 'The group, which separates identities with the same name')
|
|
80
|
+
.option('--name <name>', 'The name, used to log in')
|
|
81
|
+
.option('--display-name <name>', 'The name to show');
|
|
82
|
+
addTagsOption(command);
|
|
83
|
+
if (update) {
|
|
84
|
+
command
|
|
85
|
+
.option('--no-display-name', 'Remove the display name')
|
|
86
|
+
.option('--password', 'Change the password: asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD');
|
|
87
|
+
}
|
|
88
|
+
return command;
|
|
89
|
+
}
|
|
90
|
+
export function defineIdentities(command, context) {
|
|
91
|
+
command.description('Create, view, change and delete identities');
|
|
92
|
+
const list = command
|
|
93
|
+
.command('list', { isDefault: true })
|
|
94
|
+
.alias('ls')
|
|
95
|
+
.description('List identities (the default when no command is given)')
|
|
96
|
+
.option('--group <group>', 'Only identities whose group contains this')
|
|
97
|
+
.option('--name <name>', 'Only identities whose name contains this')
|
|
98
|
+
.option('--display-name <name>', 'Only identities whose display name contains this');
|
|
99
|
+
addTaggedOption(list);
|
|
100
|
+
addAllOption(list);
|
|
101
|
+
addPagingOptions(list, { choices: ORDER_FIELDS });
|
|
102
|
+
addOutputOptions(list).action(async (options) => {
|
|
103
|
+
const jsonpad = context.createClient();
|
|
104
|
+
await printPages(context, options, paging => jsonpad.fetchIdentities(removeUndefined({
|
|
105
|
+
...paging,
|
|
106
|
+
group: options.group,
|
|
107
|
+
name: options.name,
|
|
108
|
+
displayName: options.displayName,
|
|
109
|
+
tagged: options.tagged,
|
|
110
|
+
})), identityOutput(context));
|
|
111
|
+
});
|
|
112
|
+
addOutputOptions(command
|
|
113
|
+
.command('get')
|
|
114
|
+
.description('Show an identity')
|
|
115
|
+
.argument('<identity>', IDENTITY_ARGUMENT_DESCRIPTION)).action(async (reference, options) => {
|
|
116
|
+
const format = resolveOutputFormat(context, options);
|
|
117
|
+
const jsonpad = context.createClient();
|
|
118
|
+
const id = await resolveIdentityId(context, jsonpad, reference);
|
|
119
|
+
const identity = await request(context, () => jsonpad.fetchIdentity(id));
|
|
120
|
+
printRecord(context, format, identity, identityOutput(context));
|
|
121
|
+
});
|
|
122
|
+
addOutputOptions(addIdentityFieldOptions(command
|
|
123
|
+
.command('create')
|
|
124
|
+
.description('Create an identity. The password is asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD'), false)).action(async (options) => {
|
|
125
|
+
const format = resolveOutputFormat(context, options);
|
|
126
|
+
if (!options.name) {
|
|
127
|
+
throw new CliError('An identity needs a name: pass --name');
|
|
128
|
+
}
|
|
129
|
+
const label = options.group
|
|
130
|
+
? `${options.group}/${options.name}`
|
|
131
|
+
: options.name;
|
|
132
|
+
const password = await readPassword(context, label);
|
|
133
|
+
const jsonpad = context.createClient();
|
|
134
|
+
const identity = await request(context, () => jsonpad.createIdentity(removeUndefined({
|
|
135
|
+
group: options.group || undefined,
|
|
136
|
+
name: options.name,
|
|
137
|
+
displayName: options.displayName || undefined,
|
|
138
|
+
tags: options.tags,
|
|
139
|
+
password,
|
|
140
|
+
})));
|
|
141
|
+
printRecord(context, format, identity, identityOutput(context));
|
|
142
|
+
});
|
|
143
|
+
addOutputOptions(addIdentityFieldOptions(command
|
|
144
|
+
.command('update')
|
|
145
|
+
.description("Change an identity. Fields that aren't given are left as they are")
|
|
146
|
+
.argument('<identity>', IDENTITY_ARGUMENT_DESCRIPTION), true)).action(async (reference, options) => {
|
|
147
|
+
const format = resolveOutputFormat(context, options);
|
|
148
|
+
const jsonpad = context.createClient();
|
|
149
|
+
const id = await resolveIdentityId(context, jsonpad, reference);
|
|
150
|
+
const password = options.password
|
|
151
|
+
? await readPassword(context, reference)
|
|
152
|
+
: undefined;
|
|
153
|
+
const identity = await request(context, () => jsonpad.updateIdentity(id, removeUndefined({
|
|
154
|
+
group: options.group,
|
|
155
|
+
name: options.name,
|
|
156
|
+
displayName: nullable(options.displayName),
|
|
157
|
+
tags: options.tags,
|
|
158
|
+
password,
|
|
159
|
+
})));
|
|
160
|
+
printRecord(context, format, identity, identityOutput(context));
|
|
161
|
+
});
|
|
162
|
+
command
|
|
163
|
+
.command('delete')
|
|
164
|
+
.alias('rm')
|
|
165
|
+
.description('Delete an identity')
|
|
166
|
+
.argument('<identity>', IDENTITY_ARGUMENT_DESCRIPTION)
|
|
167
|
+
.option('-y, --yes', "Don't ask for confirmation")
|
|
168
|
+
.action(async (reference, options) => {
|
|
169
|
+
const jsonpad = context.createClient();
|
|
170
|
+
let question = `Delete the identity ${reference}?`;
|
|
171
|
+
let id;
|
|
172
|
+
// Only look up what's being deleted when there's someone to show it to
|
|
173
|
+
if (!options.yes && canPrompt(context)) {
|
|
174
|
+
id = await resolveIdentityId(context, jsonpad, reference);
|
|
175
|
+
const identity = await request(context, () => jsonpad.fetchIdentity(id));
|
|
176
|
+
question = `Delete the identity ${identityLabel(identity)} (${identity.id})?`;
|
|
177
|
+
}
|
|
178
|
+
await confirm(context, { question, yes: options.yes });
|
|
179
|
+
id ??= await resolveIdentityId(context, jsonpad, reference);
|
|
180
|
+
await request(context, () => jsonpad.deleteIdentity(id));
|
|
181
|
+
context.error(`Deleted the identity ${context.colours.bold(reference)}`);
|
|
182
|
+
});
|
|
183
|
+
defineIdentityModeCommands(command, context);
|
|
184
|
+
const target = {
|
|
185
|
+
arguments: [['<identity>', IDENTITY_ARGUMENT_DESCRIPTION]],
|
|
186
|
+
resolve: async (jsonpad, [reference]) => [
|
|
187
|
+
await resolveIdentityId(context, jsonpad, reference),
|
|
188
|
+
],
|
|
189
|
+
};
|
|
190
|
+
defineStatsCommand(command, context, {
|
|
191
|
+
...target,
|
|
192
|
+
description: "Show an identity's events, by day",
|
|
193
|
+
fetch: (jsonpad, [id], parameters) => jsonpad.fetchIdentityStats(id, parameters),
|
|
194
|
+
});
|
|
195
|
+
defineEventCommands(command, context, {
|
|
196
|
+
...target,
|
|
197
|
+
noun: 'identity',
|
|
198
|
+
types: [
|
|
199
|
+
'identity-created',
|
|
200
|
+
'identity-updated',
|
|
201
|
+
'identity-deleted',
|
|
202
|
+
'identity-registered',
|
|
203
|
+
'identity-logged-in',
|
|
204
|
+
'identity-logged-out',
|
|
205
|
+
'identity-updated-self',
|
|
206
|
+
'identity-deleted-self',
|
|
207
|
+
],
|
|
208
|
+
fetchEvents: (jsonpad, [id], parameters) => jsonpad.fetchIdentityEvents(id, parameters),
|
|
209
|
+
fetchEvent: (jsonpad, [id], eventId, parameters) => jsonpad.fetchIdentityEvent(id, eventId, parameters),
|
|
210
|
+
});
|
|
211
|
+
return command;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Leave out the identity in JSONPAD_IDENTITY_TOKEN, for requests that don't
|
|
215
|
+
* act as it (e.g. logging in as a different identity)
|
|
216
|
+
*/
|
|
217
|
+
const NO_IDENTITY = { ignore: true, token: '' };
|
|
218
|
+
/**
|
|
219
|
+
* Quote a value for a POSIX shell
|
|
220
|
+
*/
|
|
221
|
+
export function shellQuote(value) {
|
|
222
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
223
|
+
}
|
|
224
|
+
function requireIdentity(context) {
|
|
225
|
+
if (!context.identity) {
|
|
226
|
+
throw new CliError('This needs an identity token in JSONPAD_IDENTITY_TOKEN. Log in with: eval "$(jsonpad identities login --name <name> -o env)"');
|
|
227
|
+
}
|
|
228
|
+
return context.identity;
|
|
229
|
+
}
|
|
230
|
+
function defineIdentityModeCommands(command, context) {
|
|
231
|
+
addOutputOptions(addTagsOption(command
|
|
232
|
+
.command('register')
|
|
233
|
+
.summary('Register an identity, as an app would for a new user')
|
|
234
|
+
.description("Register an identity, as an app would for a new user. Unlike create, this needs the token's register permission. The password is asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD")
|
|
235
|
+
.option('--group <group>', 'The group')
|
|
236
|
+
.option('--name <name>', 'The name, used to log in')
|
|
237
|
+
.option('--display-name <name>', 'The name to show'))).action(async (options) => {
|
|
238
|
+
const format = resolveOutputFormat(context, options);
|
|
239
|
+
if (!options.name) {
|
|
240
|
+
throw new CliError('An identity needs a name: pass --name');
|
|
241
|
+
}
|
|
242
|
+
const password = await readPassword(context, options.group ? `${options.group}/${options.name}` : options.name);
|
|
243
|
+
const jsonpad = context.createClient();
|
|
244
|
+
const identity = await request(context, () => jsonpad.registerIdentity(removeUndefined({
|
|
245
|
+
group: options.group || undefined,
|
|
246
|
+
name: options.name,
|
|
247
|
+
displayName: options.displayName || undefined,
|
|
248
|
+
password,
|
|
249
|
+
}), NO_IDENTITY));
|
|
250
|
+
printRecord(context, format, identity, identityOutput(context));
|
|
251
|
+
});
|
|
252
|
+
command
|
|
253
|
+
.command('login')
|
|
254
|
+
.summary('Log in as an identity, to act as it')
|
|
255
|
+
.description('Log in as an identity, and output its identity token. Set JSONPAD_IDENTITY_TOKEN (and JSONPAD_IDENTITY_GROUP) to it to act as the identity when working with items, e.g. eval "$(jsonpad identities login --name ada -o env)". The password is asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD')
|
|
256
|
+
.option('--group <group>', "The identity's group")
|
|
257
|
+
.option('--name <name>', "The identity's name")
|
|
258
|
+
.addOption(new Option('-o, --output <format>', 'Output format: table (the default in a terminal), json (the default otherwise), env (export commands for a POSIX shell), or token (just the token)').choices(['table', 'json', 'env', 'token']))
|
|
259
|
+
.action(async (options) => {
|
|
260
|
+
if (!options.name) {
|
|
261
|
+
throw new CliError("Pass the identity's name with --name");
|
|
262
|
+
}
|
|
263
|
+
const format = options.output ?? (context.stdout.isTTY ? 'table' : 'json');
|
|
264
|
+
const label = options.group
|
|
265
|
+
? `${options.group}/${options.name}`
|
|
266
|
+
: options.name;
|
|
267
|
+
const password = await readPassword(context, label);
|
|
268
|
+
const jsonpad = context.createClient();
|
|
269
|
+
const [identity, token] = await request(context, async () => {
|
|
270
|
+
try {
|
|
271
|
+
return await jsonpad.loginIdentity(removeUndefined({
|
|
272
|
+
group: options.group || undefined,
|
|
273
|
+
name: options.name,
|
|
274
|
+
password,
|
|
275
|
+
}), NO_IDENTITY);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
// Failed logins lock the identity for a while, which isn't worth
|
|
279
|
+
// retrying automatically
|
|
280
|
+
if (error instanceof JSONPadError &&
|
|
281
|
+
error.errorName === 'IDENTITY_TOO_MANY_ATTEMPTS') {
|
|
282
|
+
throw new CliError(`${apiError(error).message}. Wait a few seconds and try again: the wait doubles after each failed attempt`, apiErrorExitCode(error));
|
|
283
|
+
}
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
if (!token) {
|
|
288
|
+
throw new CliError("The API didn't return an identity token");
|
|
289
|
+
}
|
|
290
|
+
const group = identity.group || null;
|
|
291
|
+
switch (format) {
|
|
292
|
+
case 'token':
|
|
293
|
+
context.log(token);
|
|
294
|
+
break;
|
|
295
|
+
case 'env':
|
|
296
|
+
context.log(`export JSONPAD_IDENTITY_TOKEN=${shellQuote(token)}`);
|
|
297
|
+
context.log(group
|
|
298
|
+
? `export JSONPAD_IDENTITY_GROUP=${shellQuote(group)}`
|
|
299
|
+
: 'unset JSONPAD_IDENTITY_GROUP');
|
|
300
|
+
break;
|
|
301
|
+
case 'json':
|
|
302
|
+
context.log(JSON.stringify({ identity, token }, null, 2));
|
|
303
|
+
break;
|
|
304
|
+
case 'table':
|
|
305
|
+
context.log(renderIdentityWithToken(context, identity, token));
|
|
306
|
+
context.error(context.colours.dim(`To act as ${label}, set JSONPAD_IDENTITY_TOKEN${group ? ' and JSONPAD_IDENTITY_GROUP' : ''}, e.g. with: eval "$(jsonpad identities login ${group ? `--group ${shellQuote(group)} ` : ''}--name ${shellQuote(options.name)} -o env)"`));
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
command
|
|
311
|
+
.command('logout')
|
|
312
|
+
.description('Log out the identity in JSONPAD_IDENTITY_TOKEN, so that its token stops working')
|
|
313
|
+
.action(async () => {
|
|
314
|
+
const jsonpad = context.createClient();
|
|
315
|
+
requireIdentity(context);
|
|
316
|
+
await request(context, () => jsonpad.logoutIdentity());
|
|
317
|
+
context.error('Logged out. Unset JSONPAD_IDENTITY_TOKEN and JSONPAD_IDENTITY_GROUP');
|
|
318
|
+
});
|
|
319
|
+
const self = command
|
|
320
|
+
.command('self')
|
|
321
|
+
.description('View, change or delete the identity in JSONPAD_IDENTITY_TOKEN, as the identity itself');
|
|
322
|
+
addOutputOptions(self
|
|
323
|
+
.command('get', { isDefault: true })
|
|
324
|
+
.description('Show the identity in JSONPAD_IDENTITY_TOKEN (the default when no command is given)')).action(async (options) => {
|
|
325
|
+
const format = resolveOutputFormat(context, options);
|
|
326
|
+
const jsonpad = context.createClient();
|
|
327
|
+
requireIdentity(context);
|
|
328
|
+
const identity = await request(context, () => jsonpad.fetchSelfIdentity());
|
|
329
|
+
printRecord(context, format, identity, identityOutput(context));
|
|
330
|
+
});
|
|
331
|
+
addOutputOptions(self
|
|
332
|
+
.command('update')
|
|
333
|
+
.description("Change the identity in JSONPAD_IDENTITY_TOKEN. Fields that aren't given are left as they are")
|
|
334
|
+
.option('--name <name>', 'The name, used to log in')
|
|
335
|
+
.option('--display-name <name>', 'The name to show')
|
|
336
|
+
.option('--no-display-name', 'Remove the display name')
|
|
337
|
+
.option('--password', 'Change the password: asked for in a terminal, or read from stdin or JSONPAD_IDENTITY_PASSWORD')).action(async (options) => {
|
|
338
|
+
const format = resolveOutputFormat(context, options);
|
|
339
|
+
const jsonpad = context.createClient();
|
|
340
|
+
requireIdentity(context);
|
|
341
|
+
const password = options.password
|
|
342
|
+
? await readPassword(context, 'this identity')
|
|
343
|
+
: undefined;
|
|
344
|
+
const identity = await request(context, () => jsonpad.updateSelfIdentity(removeUndefined({
|
|
345
|
+
name: options.name,
|
|
346
|
+
displayName: nullable(options.displayName),
|
|
347
|
+
password,
|
|
348
|
+
})));
|
|
349
|
+
printRecord(context, format, identity, identityOutput(context));
|
|
350
|
+
});
|
|
351
|
+
self
|
|
352
|
+
.command('delete')
|
|
353
|
+
.alias('rm')
|
|
354
|
+
.description('Delete the identity in JSONPAD_IDENTITY_TOKEN')
|
|
355
|
+
.option('-y, --yes', "Don't ask for confirmation")
|
|
356
|
+
.action(async (options) => {
|
|
357
|
+
const jsonpad = context.createClient();
|
|
358
|
+
requireIdentity(context);
|
|
359
|
+
let question = 'Delete the identity in JSONPAD_IDENTITY_TOKEN?';
|
|
360
|
+
if (!options.yes && canPrompt(context)) {
|
|
361
|
+
const identity = await request(context, () => jsonpad.fetchSelfIdentity());
|
|
362
|
+
question = `Delete the identity ${identityLabel(identity)} (${identity.id})?`;
|
|
363
|
+
}
|
|
364
|
+
await confirm(context, { question, yes: options.yes });
|
|
365
|
+
await request(context, () => jsonpad.deleteSelfIdentity());
|
|
366
|
+
context.error('Deleted the identity. Unset JSONPAD_IDENTITY_TOKEN and JSONPAD_IDENTITY_GROUP');
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
function renderIdentityWithToken(context, identity, token) {
|
|
370
|
+
const rows = identityOutput(context).details(identity);
|
|
371
|
+
return renderDetails([...rows, ['Token', token]]);
|
|
372
|
+
}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { Option } from 'commander';
|
|
2
|
+
import { parseTimeout, waitForIndex } from '../indexes.js';
|
|
3
|
+
import { canPrompt, confirm } from '../input.js';
|
|
4
|
+
import { addOutputOptions, formatFlags, formatTimestamp, printRecord, resolveOutputFormat, } from '../output.js';
|
|
5
|
+
import { addBooleanOption, addAllOption, addPagingOptions, addTaggedOption, addTagsOption, readBody, removeUndefined, printPages, request, } from '../resources.js';
|
|
6
|
+
import { defineEventCommands, defineStatsCommand } from './history.js';
|
|
7
|
+
import { defineRebuildIndex } from './rebuild-index.js';
|
|
8
|
+
const FLAGS = ['alias', 'sorting', 'filtering', 'searching', 'guard'];
|
|
9
|
+
const FLAG_DESCRIPTIONS = {
|
|
10
|
+
alias: [
|
|
11
|
+
"Items can be fetched by this index's value, in place of their id",
|
|
12
|
+
'Not an alias',
|
|
13
|
+
],
|
|
14
|
+
sorting: [
|
|
15
|
+
'Items can be ordered by this index',
|
|
16
|
+
"Items can't be ordered by it",
|
|
17
|
+
],
|
|
18
|
+
filtering: [
|
|
19
|
+
'Items can be filtered by this index',
|
|
20
|
+
"Items can't be filtered by it",
|
|
21
|
+
],
|
|
22
|
+
searching: [
|
|
23
|
+
"This index's values are included in searches",
|
|
24
|
+
'Not included in searches',
|
|
25
|
+
],
|
|
26
|
+
guard: [
|
|
27
|
+
'The value is removed from item data returned with a token',
|
|
28
|
+
'Not a guard',
|
|
29
|
+
],
|
|
30
|
+
};
|
|
31
|
+
const VALUE_TYPES = ['string', 'number', 'date'];
|
|
32
|
+
const ORDER_FIELDS = [
|
|
33
|
+
'createdAt',
|
|
34
|
+
'updatedAt',
|
|
35
|
+
'name',
|
|
36
|
+
'pathName',
|
|
37
|
+
'valueType',
|
|
38
|
+
...FLAGS,
|
|
39
|
+
'defaultOrderDirection',
|
|
40
|
+
'activated',
|
|
41
|
+
];
|
|
42
|
+
export function buildStatus(context, index) {
|
|
43
|
+
const { green, yellow, red } = context.colours;
|
|
44
|
+
switch (index.buildStatus) {
|
|
45
|
+
case 'ready':
|
|
46
|
+
return green('ready');
|
|
47
|
+
case 'building':
|
|
48
|
+
return yellow('building');
|
|
49
|
+
case 'failed':
|
|
50
|
+
return red('failed');
|
|
51
|
+
default:
|
|
52
|
+
return String(index.buildStatus);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function indexOutput(context) {
|
|
56
|
+
const { dim } = context.colours;
|
|
57
|
+
return {
|
|
58
|
+
id: index => index.id,
|
|
59
|
+
details: index => [
|
|
60
|
+
['ID', index.id],
|
|
61
|
+
['Path name', index.pathName],
|
|
62
|
+
['Name', index.name || dim('(none)')],
|
|
63
|
+
['Description', index.description || dim('(none)')],
|
|
64
|
+
['Tags', index.tags?.length ? index.tags.join(', ') : dim('(none)')],
|
|
65
|
+
['Pointer', index.pointer],
|
|
66
|
+
['Value type', index.valueType],
|
|
67
|
+
['Flags', formatFlags(index, [...FLAGS])],
|
|
68
|
+
['Order', index.defaultOrderDirection],
|
|
69
|
+
['Status', buildStatus(context, index)],
|
|
70
|
+
['Created', formatTimestamp(index.createdAt)],
|
|
71
|
+
['Updated', formatTimestamp(index.updatedAt)],
|
|
72
|
+
],
|
|
73
|
+
columns: [
|
|
74
|
+
{ header: 'ID', value: index => index.id },
|
|
75
|
+
{ header: 'PATH NAME', value: index => index.pathName },
|
|
76
|
+
{ header: 'POINTER', value: index => index.pointer },
|
|
77
|
+
{ header: 'TYPE', value: index => index.valueType },
|
|
78
|
+
{ header: 'FLAGS', value: index => formatFlags(index, [...FLAGS]) },
|
|
79
|
+
{ header: 'STATUS', value: index => buildStatus(context, index) },
|
|
80
|
+
],
|
|
81
|
+
empty: 'No indexes',
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function addIndexFieldOptions(command) {
|
|
85
|
+
command
|
|
86
|
+
.option('--name <name>', 'The name')
|
|
87
|
+
.option('--path-name <path name>', 'The path name, used to filter and order items, and in place of the id')
|
|
88
|
+
.option('--description <text>', 'The description');
|
|
89
|
+
addTagsOption(command);
|
|
90
|
+
command
|
|
91
|
+
.option('--pointer <pointer>', 'The JSON pointer to the value in item data, e.g. /title')
|
|
92
|
+
.addOption(new Option('--value-type <type>', 'The type of value').choices(VALUE_TYPES))
|
|
93
|
+
.addOption(new Option('--default-order-direction <direction>', 'The direction items are ordered in by default').choices(['asc', 'desc']));
|
|
94
|
+
for (const flag of FLAGS) {
|
|
95
|
+
const [description, negated] = FLAG_DESCRIPTIONS[flag];
|
|
96
|
+
addBooleanOption(command, flag, description, negated);
|
|
97
|
+
}
|
|
98
|
+
return command
|
|
99
|
+
.option('--data <json>', 'The whole index as a JSON object (JSON, @file or - for stdin); the options above take precedence')
|
|
100
|
+
.option('--wait', 'Wait for the index to be built, if it needs building')
|
|
101
|
+
.option('--timeout <seconds>', 'How long --wait waits (default 600)');
|
|
102
|
+
}
|
|
103
|
+
function indexBody(context, options) {
|
|
104
|
+
return readBody(context, options.data, {
|
|
105
|
+
name: options.name,
|
|
106
|
+
pathName: options.pathName,
|
|
107
|
+
description: options.description,
|
|
108
|
+
tags: options.tags,
|
|
109
|
+
pointer: options.pointer,
|
|
110
|
+
valueType: options.valueType,
|
|
111
|
+
defaultOrderDirection: options.defaultOrderDirection,
|
|
112
|
+
...Object.fromEntries(FLAGS.map(flag => [flag, options[flag]])),
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* After creating or changing an index, wait for it to build if asked to
|
|
117
|
+
*/
|
|
118
|
+
async function waitIfBuilding(context, jsonpad, list, index, options) {
|
|
119
|
+
if (!options.wait || index.buildStatus !== 'building') {
|
|
120
|
+
return index;
|
|
121
|
+
}
|
|
122
|
+
return waitForIndex(context, jsonpad, list, index.pathName || index.id, parseTimeout(options.timeout));
|
|
123
|
+
}
|
|
124
|
+
export function defineIndexes(command, context) {
|
|
125
|
+
command.description("Create, view, change and delete a list's indexes");
|
|
126
|
+
const list = command
|
|
127
|
+
.command('list', { isDefault: true })
|
|
128
|
+
.alias('ls')
|
|
129
|
+
.description("List a list's indexes (the default when no command is given)")
|
|
130
|
+
.argument('<list>', 'The list (id or path name)')
|
|
131
|
+
.option('--name <name>', 'Only indexes whose name contains this')
|
|
132
|
+
.option('--path-name <path name>', 'Only indexes whose path name contains this')
|
|
133
|
+
.addOption(new Option('--value-type <type>', 'Only indexes of this type').choices(VALUE_TYPES));
|
|
134
|
+
addBooleanOption(list, 'alias', 'Only the alias index', 'Only other indexes');
|
|
135
|
+
addBooleanOption(list, 'guard', 'Only guard indexes', 'Only other indexes');
|
|
136
|
+
addTaggedOption(list);
|
|
137
|
+
addAllOption(list);
|
|
138
|
+
addPagingOptions(list, { choices: ORDER_FIELDS });
|
|
139
|
+
addOutputOptions(list).action(async (listId, options) => {
|
|
140
|
+
const jsonpad = context.createClient();
|
|
141
|
+
await printPages(context, options, paging => jsonpad.fetchIndexes(listId, removeUndefined({
|
|
142
|
+
...paging,
|
|
143
|
+
name: options.name,
|
|
144
|
+
pathName: options.pathName,
|
|
145
|
+
valueType: options.valueType,
|
|
146
|
+
alias: options.alias,
|
|
147
|
+
guard: options.guard,
|
|
148
|
+
tagged: options.tagged,
|
|
149
|
+
})), indexOutput(context));
|
|
150
|
+
});
|
|
151
|
+
addOutputOptions(command
|
|
152
|
+
.command('get')
|
|
153
|
+
.description('Show an index')
|
|
154
|
+
.argument('<list>', 'The list (id or path name)')
|
|
155
|
+
.argument('<index>', 'The index (id or path name)')).action(async (listId, indexId, options) => {
|
|
156
|
+
const format = resolveOutputFormat(context, options);
|
|
157
|
+
const jsonpad = context.createClient();
|
|
158
|
+
const index = await request(context, () => jsonpad.fetchIndex(listId, indexId));
|
|
159
|
+
printRecord(context, format, index, indexOutput(context));
|
|
160
|
+
});
|
|
161
|
+
addOutputOptions(addIndexFieldOptions(command
|
|
162
|
+
.command('create')
|
|
163
|
+
.description("Create an index. It builds in the background, and until it has built it can't be used to filter, order or search items")
|
|
164
|
+
.argument('<list>', 'The list (id or path name)'))).action(async (listId, options) => {
|
|
165
|
+
const format = resolveOutputFormat(context, options);
|
|
166
|
+
const body = await indexBody(context, options);
|
|
167
|
+
const jsonpad = context.createClient();
|
|
168
|
+
const created = await request(context, () => jsonpad.createIndex(listId, body));
|
|
169
|
+
const index = await waitIfBuilding(context, jsonpad, listId, created, options);
|
|
170
|
+
printRecord(context, format, index, indexOutput(context));
|
|
171
|
+
});
|
|
172
|
+
addOutputOptions(addIndexFieldOptions(command
|
|
173
|
+
.command('update')
|
|
174
|
+
.description("Change an index. Fields that aren't given are left as they are. Changing the pointer rebuilds the index")
|
|
175
|
+
.argument('<list>', 'The list (id or path name)')
|
|
176
|
+
.argument('<index>', 'The index (id or path name)'))).action(async (listId, indexId, options) => {
|
|
177
|
+
const format = resolveOutputFormat(context, options);
|
|
178
|
+
const body = await indexBody(context, options);
|
|
179
|
+
const jsonpad = context.createClient();
|
|
180
|
+
const updated = await request(context, () => jsonpad.updateIndex(listId, indexId, body));
|
|
181
|
+
const index = await waitIfBuilding(context, jsonpad, listId, updated, options);
|
|
182
|
+
printRecord(context, format, index, indexOutput(context));
|
|
183
|
+
});
|
|
184
|
+
command
|
|
185
|
+
.command('delete')
|
|
186
|
+
.alias('rm')
|
|
187
|
+
.description('Delete an index')
|
|
188
|
+
.argument('<list>', 'The list (id or path name)')
|
|
189
|
+
.argument('<index>', 'The index (id or path name)')
|
|
190
|
+
.option('-y, --yes', "Don't ask for confirmation")
|
|
191
|
+
.action(async (listId, indexId, options) => {
|
|
192
|
+
const jsonpad = context.createClient();
|
|
193
|
+
let question = `Delete the index ${listId}/${indexId}?`;
|
|
194
|
+
if (!options.yes && canPrompt(context)) {
|
|
195
|
+
const index = await request(context, () => jsonpad.fetchIndex(listId, indexId));
|
|
196
|
+
const warnings = [
|
|
197
|
+
...(index.alias
|
|
198
|
+
? [
|
|
199
|
+
"It's the list's alias index, so items can't be fetched by alias without it.",
|
|
200
|
+
]
|
|
201
|
+
: []),
|
|
202
|
+
...(index.guard
|
|
203
|
+
? [
|
|
204
|
+
"It's a guard index, so its values will be returned in item data again.",
|
|
205
|
+
]
|
|
206
|
+
: []),
|
|
207
|
+
];
|
|
208
|
+
question = [
|
|
209
|
+
...warnings.map(warning => context.colours.yellow(warning)),
|
|
210
|
+
`Delete the index ${listId}/${index.pathName}?`,
|
|
211
|
+
].join('\n');
|
|
212
|
+
}
|
|
213
|
+
await confirm(context, { question, yes: options.yes });
|
|
214
|
+
await request(context, () => jsonpad.deleteIndex(listId, indexId));
|
|
215
|
+
context.error(`Deleted the index ${context.colours.bold(`${listId}/${indexId}`)}`);
|
|
216
|
+
});
|
|
217
|
+
// The same as jsonpad rebuild-index
|
|
218
|
+
defineRebuildIndex(command.command('rebuild'), context);
|
|
219
|
+
command
|
|
220
|
+
.command('wait')
|
|
221
|
+
.description('Wait for an index to finish building')
|
|
222
|
+
.argument('<list>', 'The list (id or path name)')
|
|
223
|
+
.argument('<index>', 'The index (id or path name)')
|
|
224
|
+
.option('--timeout <seconds>', 'How long to wait (default 600)')
|
|
225
|
+
.action(async (listId, indexId, options) => {
|
|
226
|
+
const jsonpad = context.createClient();
|
|
227
|
+
await waitForIndex(context, jsonpad, listId, indexId, parseTimeout(options.timeout));
|
|
228
|
+
});
|
|
229
|
+
const target = {
|
|
230
|
+
arguments: [
|
|
231
|
+
['<list>', 'The list (id or path name)'],
|
|
232
|
+
['<index>', 'The index (id or path name)'],
|
|
233
|
+
],
|
|
234
|
+
};
|
|
235
|
+
defineStatsCommand(command, context, {
|
|
236
|
+
...target,
|
|
237
|
+
description: "Show an index's events, by day",
|
|
238
|
+
fetch: (jsonpad, [listId, indexId], parameters) => jsonpad.fetchIndexStats(listId, indexId, parameters),
|
|
239
|
+
});
|
|
240
|
+
defineEventCommands(command, context, {
|
|
241
|
+
...target,
|
|
242
|
+
noun: 'index',
|
|
243
|
+
types: [
|
|
244
|
+
'index-created',
|
|
245
|
+
'index-updated',
|
|
246
|
+
'index-deleted',
|
|
247
|
+
'index-built',
|
|
248
|
+
'index-build-failed',
|
|
249
|
+
'index-build-requested',
|
|
250
|
+
],
|
|
251
|
+
fetchEvents: (jsonpad, [listId, indexId], parameters) => jsonpad.fetchIndexEvents(listId, indexId, parameters),
|
|
252
|
+
fetchEvent: (jsonpad, [listId, indexId], eventId, parameters) => jsonpad.fetchIndexEvent(listId, indexId, eventId, parameters),
|
|
253
|
+
});
|
|
254
|
+
return command;
|
|
255
|
+
}
|