@basementuniverse/jsonpad-cli 1.0.0 → 1.2.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 +69 -1
- package/README.md +242 -15
- 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 +33 -0
- package/build/reference.js +34 -15
- package/build/resources.js +224 -0
- package/package.json +5 -3
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { CliError } from '../errors.js';
|
|
2
|
+
import { canPrompt, confirm, readJsonInput } from '../input.js';
|
|
3
|
+
import { addOutputOptions, formatFlags, formatNumber, formatTimestamp, printRecord, printRecords, resolveOutputFormat, } from '../output.js';
|
|
4
|
+
import { addBooleanOption, addAllOption, addPagingOptions, addTaggedOption, addTagsOption, nullable, readBody, removeUndefined, printPages, request, } from '../resources.js';
|
|
5
|
+
import { defineEventCommands, defineStatsCommand } from './history.js';
|
|
6
|
+
const FLAGS = [
|
|
7
|
+
'pinned',
|
|
8
|
+
'readonly',
|
|
9
|
+
'realtime',
|
|
10
|
+
'protected',
|
|
11
|
+
'indexable',
|
|
12
|
+
'generative',
|
|
13
|
+
];
|
|
14
|
+
const FLAG_DESCRIPTIONS = {
|
|
15
|
+
pinned: ['Pinned in the dashboard', 'Not pinned'],
|
|
16
|
+
readonly: ["Items can't be created, changed or deleted", 'Not readonly'],
|
|
17
|
+
realtime: ['Changes are sent to realtime clients', 'Not realtime'],
|
|
18
|
+
protected: ["The list can't be deleted while it has items", 'Not protected'],
|
|
19
|
+
indexable: [
|
|
20
|
+
'Items can be listed, filtered and searched with a token',
|
|
21
|
+
'Not indexable',
|
|
22
|
+
],
|
|
23
|
+
generative: [
|
|
24
|
+
'Items can be generated from the generative prompt',
|
|
25
|
+
'Not generative',
|
|
26
|
+
],
|
|
27
|
+
};
|
|
28
|
+
const ORDER_FIELDS = [
|
|
29
|
+
'createdAt',
|
|
30
|
+
'updatedAt',
|
|
31
|
+
'name',
|
|
32
|
+
'pathName',
|
|
33
|
+
...FLAGS,
|
|
34
|
+
'activated',
|
|
35
|
+
];
|
|
36
|
+
export function listDetails(context, list) {
|
|
37
|
+
const { dim } = context.colours;
|
|
38
|
+
const rows = [
|
|
39
|
+
['ID', list.id],
|
|
40
|
+
['Path name', list.pathName || dim('(none)')],
|
|
41
|
+
['Name', list.name],
|
|
42
|
+
['Description', list.description || dim('(none)')],
|
|
43
|
+
['Tags', list.tags?.length ? list.tags.join(', ') : dim('(none)')],
|
|
44
|
+
['Items', formatNumber(list.itemCount ?? 0)],
|
|
45
|
+
['Flags', formatFlags(list, [...FLAGS])],
|
|
46
|
+
];
|
|
47
|
+
if (list.generative) {
|
|
48
|
+
rows.push(['Prompt', list.generativePrompt || dim('(none)')]);
|
|
49
|
+
}
|
|
50
|
+
rows.push([
|
|
51
|
+
'Schema',
|
|
52
|
+
list.schema ? JSON.stringify(list.schema, null, 2) : dim('(none)'),
|
|
53
|
+
], ['Created', formatTimestamp(list.createdAt)], ['Updated', formatTimestamp(list.updatedAt)]);
|
|
54
|
+
return rows;
|
|
55
|
+
}
|
|
56
|
+
function listOutput(context) {
|
|
57
|
+
return {
|
|
58
|
+
id: list => list.id,
|
|
59
|
+
details: list => listDetails(context, list),
|
|
60
|
+
columns: [
|
|
61
|
+
{ header: 'ID', value: list => list.id },
|
|
62
|
+
{ header: 'PATH NAME', value: list => list.pathName },
|
|
63
|
+
{ header: 'NAME', value: list => list.name },
|
|
64
|
+
{ header: 'ITEMS', value: list => formatNumber(list.itemCount ?? 0) },
|
|
65
|
+
{ header: 'FLAGS', value: list => formatFlags(list, [...FLAGS]) },
|
|
66
|
+
{ header: 'UPDATED', value: list => formatTimestamp(list.updatedAt) },
|
|
67
|
+
],
|
|
68
|
+
empty: 'No lists',
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The options lists create and update share
|
|
73
|
+
*/
|
|
74
|
+
function addListFieldOptions(command, update) {
|
|
75
|
+
command
|
|
76
|
+
.option('--name <name>', 'The name')
|
|
77
|
+
.option('--path-name <path name>', 'The path name, which can be used in place of the id')
|
|
78
|
+
.option('--description <text>', 'The description');
|
|
79
|
+
addTagsOption(command);
|
|
80
|
+
command
|
|
81
|
+
.option('--schema <json>', 'A JSON schema that items must match: JSON, @file or - for stdin')
|
|
82
|
+
.option('--generative-prompt <text>', 'The prompt used to generate items, for generative lists');
|
|
83
|
+
if (update) {
|
|
84
|
+
command
|
|
85
|
+
.option('--no-schema', 'Remove the schema')
|
|
86
|
+
.option('--no-generative-prompt', 'Remove the generative prompt');
|
|
87
|
+
}
|
|
88
|
+
for (const flag of FLAGS) {
|
|
89
|
+
const [description, negated] = FLAG_DESCRIPTIONS[flag];
|
|
90
|
+
addBooleanOption(command, flag, description, negated);
|
|
91
|
+
}
|
|
92
|
+
return command.option('--data <json>', 'The whole list as a JSON object (JSON, @file or - for stdin); the options above take precedence');
|
|
93
|
+
}
|
|
94
|
+
async function listBody(context, options) {
|
|
95
|
+
const schema = typeof options.schema === 'string'
|
|
96
|
+
? await readJsonInput(context, '--schema', options.schema)
|
|
97
|
+
: nullable(options.schema);
|
|
98
|
+
return readBody(context, options.data, {
|
|
99
|
+
name: options.name,
|
|
100
|
+
pathName: options.pathName,
|
|
101
|
+
description: options.description,
|
|
102
|
+
tags: options.tags,
|
|
103
|
+
schema,
|
|
104
|
+
generativePrompt: nullable(options.generativePrompt),
|
|
105
|
+
...Object.fromEntries(FLAGS.map(flag => [flag, options[flag]])),
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
export function defineLists(command, context) {
|
|
109
|
+
command.description('Create, view, change and delete lists');
|
|
110
|
+
const list = command
|
|
111
|
+
.command('list', { isDefault: true })
|
|
112
|
+
.alias('ls')
|
|
113
|
+
.description('List lists (the default when no command is given)')
|
|
114
|
+
.option('--name <name>', 'Only lists whose name contains this')
|
|
115
|
+
.option('--path-name <path name>', 'Only lists whose path name contains this');
|
|
116
|
+
addTaggedOption(list);
|
|
117
|
+
for (const flag of FLAGS) {
|
|
118
|
+
addBooleanOption(list, flag, `Only ${flag} lists`, `Only lists that aren't ${flag}`);
|
|
119
|
+
}
|
|
120
|
+
addAllOption(list);
|
|
121
|
+
addPagingOptions(list, { choices: ORDER_FIELDS });
|
|
122
|
+
addOutputOptions(list).action(async (options) => {
|
|
123
|
+
const jsonpad = context.createClient();
|
|
124
|
+
await printPages(context, options, paging => jsonpad.fetchLists(removeUndefined({
|
|
125
|
+
...paging,
|
|
126
|
+
name: options.name,
|
|
127
|
+
pathName: options.pathName,
|
|
128
|
+
tagged: options.tagged,
|
|
129
|
+
...Object.fromEntries(FLAGS.map(flag => [flag, options[flag]])),
|
|
130
|
+
})), listOutput(context));
|
|
131
|
+
});
|
|
132
|
+
addOutputOptions(command
|
|
133
|
+
.command('get')
|
|
134
|
+
.description('Show a list')
|
|
135
|
+
.argument('<list>', 'The list (id or path name)')).action(async (listId, options) => {
|
|
136
|
+
const format = resolveOutputFormat(context, options);
|
|
137
|
+
const jsonpad = context.createClient();
|
|
138
|
+
const list = await request(context, () => jsonpad.fetchList(listId));
|
|
139
|
+
printRecord(context, format, list, listOutput(context));
|
|
140
|
+
});
|
|
141
|
+
addOutputOptions(addListFieldOptions(command.command('create').description('Create a list'), false)).action(async (options) => {
|
|
142
|
+
const format = resolveOutputFormat(context, options);
|
|
143
|
+
const body = await listBody(context, options);
|
|
144
|
+
const jsonpad = context.createClient();
|
|
145
|
+
const list = await request(context, () => jsonpad.createList(body));
|
|
146
|
+
printRecord(context, format, list, listOutput(context));
|
|
147
|
+
});
|
|
148
|
+
addOutputOptions(addListFieldOptions(command
|
|
149
|
+
.command('update')
|
|
150
|
+
.description("Change a list. Fields that aren't given are left as they are")
|
|
151
|
+
.argument('<list>', 'The list (id or path name)'), true)).action(async (listId, options) => {
|
|
152
|
+
const format = resolveOutputFormat(context, options);
|
|
153
|
+
const body = await listBody(context, options);
|
|
154
|
+
const jsonpad = context.createClient();
|
|
155
|
+
const list = await request(context, () => jsonpad.updateList(listId, body));
|
|
156
|
+
printRecord(context, format, list, listOutput(context));
|
|
157
|
+
});
|
|
158
|
+
command
|
|
159
|
+
.command('delete')
|
|
160
|
+
.alias('rm')
|
|
161
|
+
.description('Delete a list. Its items and indexes are deleted in the background')
|
|
162
|
+
.argument('<list>', 'The list (id or path name)')
|
|
163
|
+
.option('-y, --yes', "Don't ask for confirmation")
|
|
164
|
+
.action(async (listId, options) => {
|
|
165
|
+
const jsonpad = context.createClient();
|
|
166
|
+
let question = `Delete the list ${listId}?`;
|
|
167
|
+
// Only look up what's being deleted when there's someone to show it to
|
|
168
|
+
if (!options.yes && canPrompt(context)) {
|
|
169
|
+
const [list, indexes] = await request(context, () => Promise.all([
|
|
170
|
+
jsonpad.fetchList(listId),
|
|
171
|
+
jsonpad.fetchIndexes(listId, { limit: 1 }),
|
|
172
|
+
]));
|
|
173
|
+
question = `Delete the list ${list.pathName || list.id}, with ${list.itemCount === 1
|
|
174
|
+
? '1 item'
|
|
175
|
+
: `${formatNumber(list.itemCount ?? 0)} items`} and ${indexes.total === 1 ? '1 index' : `${indexes.total} indexes`}? This can't be undone.`;
|
|
176
|
+
}
|
|
177
|
+
await confirm(context, { question, yes: options.yes });
|
|
178
|
+
await request(context, () => jsonpad.deleteList(listId));
|
|
179
|
+
context.error(`Deleted the list ${context.colours.bold(listId)}. Its items and indexes are being deleted in the background`);
|
|
180
|
+
});
|
|
181
|
+
addOutputOptions(command
|
|
182
|
+
.command('search')
|
|
183
|
+
.description("Search a list's items, using the indexes that allow searching")
|
|
184
|
+
.argument('<list>', 'The list (id or path name)')
|
|
185
|
+
.argument('<query>', 'What to search for, 3 to 100 characters')
|
|
186
|
+
.option('--include-items', 'Include the items, not just their ids')
|
|
187
|
+
.option('--include-data', "With --include-items, include each item's data")
|
|
188
|
+
.option('--include-guarded', 'Include guarded values in the item data, for items the identity making the request owns')).action(async (listId, query, options) => {
|
|
189
|
+
const format = resolveOutputFormat(context, options);
|
|
190
|
+
// The API's own error for this is a raw validation error
|
|
191
|
+
if (query.length < 3 || query.length > 100) {
|
|
192
|
+
throw new CliError('The search query must be from 3 to 100 characters long');
|
|
193
|
+
}
|
|
194
|
+
const jsonpad = context.createClient();
|
|
195
|
+
const results = await request(context, () => jsonpad.searchList(listId, query, removeUndefined({
|
|
196
|
+
includeItems: options.includeItems,
|
|
197
|
+
includeData: options.includeData,
|
|
198
|
+
includeGuarded: options.includeGuarded,
|
|
199
|
+
})));
|
|
200
|
+
const idOf = (result) => 'item' in result ? result.item.id : result.id;
|
|
201
|
+
printRecords(context, format, results, {
|
|
202
|
+
id: idOf,
|
|
203
|
+
columns: [
|
|
204
|
+
{
|
|
205
|
+
header: 'RELEVANCE',
|
|
206
|
+
value: result => result.relevance.toFixed(3),
|
|
207
|
+
},
|
|
208
|
+
{ header: 'ID', value: idOf },
|
|
209
|
+
...(options.includeItems
|
|
210
|
+
? [
|
|
211
|
+
{
|
|
212
|
+
header: 'DESCRIPTION',
|
|
213
|
+
value: (result) => ('item' in result && result.item.description) || '-',
|
|
214
|
+
},
|
|
215
|
+
]
|
|
216
|
+
: []),
|
|
217
|
+
],
|
|
218
|
+
empty: 'Nothing found',
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
const target = {
|
|
222
|
+
arguments: [['<list>', 'The list (id or path name)']],
|
|
223
|
+
};
|
|
224
|
+
defineStatsCommand(command, context, {
|
|
225
|
+
...target,
|
|
226
|
+
description: "Show a list's stats: its items, indexes and events, by day",
|
|
227
|
+
fetch: (jsonpad, [listId], parameters) => jsonpad.fetchListStats(listId, parameters),
|
|
228
|
+
});
|
|
229
|
+
defineEventCommands(command, context, {
|
|
230
|
+
...target,
|
|
231
|
+
noun: 'list',
|
|
232
|
+
types: ['list-created', 'list-updated', 'list-deleted'],
|
|
233
|
+
fetchEvents: (jsonpad, [listId], parameters) => jsonpad.fetchListEvents(listId, parameters),
|
|
234
|
+
fetchEvent: (jsonpad, [listId], eventId, parameters) => jsonpad.fetchListEvent(listId, eventId, parameters),
|
|
235
|
+
});
|
|
236
|
+
return command;
|
|
237
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* items export and items import: copying a list's items to and from NDJSON
|
|
3
|
+
*/
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { installRequestPacing, requestInterval } from '../client.js';
|
|
7
|
+
import { apiError, CliError, EXIT_ERROR } from '../errors.js';
|
|
8
|
+
import { readStdin } from '../input.js';
|
|
9
|
+
import { formatNumber, plural } from '../output.js';
|
|
10
|
+
import { fetchAll, parsePositiveInteger, removeUndefined, request, } from '../resources.js';
|
|
11
|
+
/**
|
|
12
|
+
* The fields of an exported item that importing sets. Everything else (its id,
|
|
13
|
+
* dates, version, size) belongs to the new item
|
|
14
|
+
*/
|
|
15
|
+
const IMPORTED_FIELDS = ['data', 'description', 'tags', 'readonly'];
|
|
16
|
+
/**
|
|
17
|
+
* Show progress on stderr, overwriting the same line, in a terminal only
|
|
18
|
+
*/
|
|
19
|
+
function progress(context, text) {
|
|
20
|
+
if (!context.stderr.isTTY) {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
context.stderr.write(text === null ? '\r\x1b[K' : `\r\x1b[K${text}`);
|
|
24
|
+
}
|
|
25
|
+
export function defineTransferCommands(command, context, whereParameters) {
|
|
26
|
+
command
|
|
27
|
+
.command('export')
|
|
28
|
+
.summary('Output every item in a list as NDJSON, e.g. for a backup')
|
|
29
|
+
.description('Output every item in a list as NDJSON (one item per line), oldest first, e.g. for a backup. Import them again with jsonpad items import')
|
|
30
|
+
.argument('<list>', 'The list (id or path name)')
|
|
31
|
+
.option('--out <file>', 'Write to a file, not stdout')
|
|
32
|
+
.option('--data-only', "Only output each item's data")
|
|
33
|
+
.option('--where <index=value>', 'Only items whose indexed value matches (repeatable)', (value, previous = []) => [...previous, value])
|
|
34
|
+
.option('--tagged <tags>', 'Only items with one of these comma-separated tags (repeat the option to require every group)', (value, previous = []) => [...previous, value])
|
|
35
|
+
.option('--include-guarded', 'Include guarded values, for items the identity making the request owns')
|
|
36
|
+
.option('--max <number>', 'Stop after this many items', parsePositiveInteger)
|
|
37
|
+
.action((listId, options) => exportItems(context, listId, options, whereParameters(options.where)));
|
|
38
|
+
command
|
|
39
|
+
.command('import')
|
|
40
|
+
.summary('Create items from an NDJSON or JSON file')
|
|
41
|
+
.description('Create an item for each record in a file: NDJSON (one record per line), or a JSON array. Records are items, as jsonpad items export outputs them, or with --data-only, item data. Items are created one at a time, at the pace the plan allows')
|
|
42
|
+
.argument('<list>', 'The list (id or path name)')
|
|
43
|
+
.argument('<file>', 'The file to import, or - for stdin')
|
|
44
|
+
.option('--data-only', 'Each record is the data for an item')
|
|
45
|
+
.option('--dry-run', 'Check the records, and say how many items would be created, without creating any')
|
|
46
|
+
.option('--continue-on-error', "Carry on when an item can't be created, instead of stopping")
|
|
47
|
+
.action((listId, file, options) => importItems(context, listId, file, options));
|
|
48
|
+
}
|
|
49
|
+
async function exportItems(context, listId, options, where) {
|
|
50
|
+
const jsonpad = context.createClient();
|
|
51
|
+
const parameters = removeUndefined({
|
|
52
|
+
...where,
|
|
53
|
+
order: 'createdAt',
|
|
54
|
+
direction: 'asc',
|
|
55
|
+
tagged: options.tagged,
|
|
56
|
+
includeGuarded: options.includeGuarded,
|
|
57
|
+
});
|
|
58
|
+
// Oldest first, so that items created during the export are added to the
|
|
59
|
+
// last page rather than moving others onto pages that have been fetched
|
|
60
|
+
const records = options.dataOnly
|
|
61
|
+
? fetchAll(context, paging => jsonpad.fetchItemsData(listId, { ...parameters, ...paging }), options.max)
|
|
62
|
+
: fetchAll(context, paging => jsonpad.fetchItems(listId, {
|
|
63
|
+
...parameters,
|
|
64
|
+
...paging,
|
|
65
|
+
includeData: true,
|
|
66
|
+
}), options.max);
|
|
67
|
+
// A file is written under a temporary name and moved into place at the end,
|
|
68
|
+
// so a failed export never leaves a partial file that looks complete
|
|
69
|
+
const file = options.out ? path.resolve(context.cwd, options.out) : null;
|
|
70
|
+
const partialFile = file ? `${file}.partial` : null;
|
|
71
|
+
const stream = partialFile ? fs.createWriteStream(partialFile) : null;
|
|
72
|
+
const write = (text) => stream
|
|
73
|
+
? new Promise((resolve, reject) => stream.write(text, error => (error ? reject(error) : resolve())))
|
|
74
|
+
: void context.stdout.write(text);
|
|
75
|
+
let count = 0;
|
|
76
|
+
try {
|
|
77
|
+
for await (const record of records) {
|
|
78
|
+
await write(`${JSON.stringify(record)}\n`);
|
|
79
|
+
count++;
|
|
80
|
+
if (stream && count % 100 === 0) {
|
|
81
|
+
progress(context, `Exported ${formatNumber(count)} items...`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (stream) {
|
|
87
|
+
progress(context, null);
|
|
88
|
+
await new Promise(resolve => stream.end(resolve));
|
|
89
|
+
fs.rmSync(partialFile, { force: true });
|
|
90
|
+
}
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
if (stream) {
|
|
94
|
+
await new Promise(resolve => stream.end(resolve));
|
|
95
|
+
fs.renameSync(partialFile, file);
|
|
96
|
+
progress(context, null);
|
|
97
|
+
context.error(`Exported ${plural(count, 'item')} from ${listId} to ${options.out}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Parse an import's records, and turn each one into the body for creating an
|
|
102
|
+
* item. Every problem is found before anything is created
|
|
103
|
+
*/
|
|
104
|
+
export function parseImport(text, dataOnly) {
|
|
105
|
+
const records = [];
|
|
106
|
+
const errors = [];
|
|
107
|
+
let values;
|
|
108
|
+
// A file that's one JSON array is a list of records. Anything else is NDJSON
|
|
109
|
+
let whole;
|
|
110
|
+
let isArray = false;
|
|
111
|
+
try {
|
|
112
|
+
whole = JSON.parse(text);
|
|
113
|
+
isArray = Array.isArray(whole);
|
|
114
|
+
}
|
|
115
|
+
catch { }
|
|
116
|
+
if (isArray) {
|
|
117
|
+
values = whole.map((value, i) => ({
|
|
118
|
+
position: `record ${i + 1}`,
|
|
119
|
+
value,
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
values = [];
|
|
124
|
+
text.split('\n').forEach((line, i) => {
|
|
125
|
+
if (!line.trim()) {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
values.push({
|
|
130
|
+
position: `line ${i + 1}`,
|
|
131
|
+
line: i + 1,
|
|
132
|
+
value: JSON.parse(line),
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
errors.push(`line ${i + 1}: isn't valid JSON (${error.message})`);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
for (const { position, line, value } of values) {
|
|
141
|
+
if (dataOnly) {
|
|
142
|
+
records.push({ position, line, body: { data: value } });
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (!value ||
|
|
146
|
+
typeof value !== 'object' ||
|
|
147
|
+
Array.isArray(value) ||
|
|
148
|
+
!('data' in value)) {
|
|
149
|
+
errors.push(`${position}: isn't an item (an object with data). Use --data-only if each record is an item's data`);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const item = value;
|
|
153
|
+
records.push({
|
|
154
|
+
position,
|
|
155
|
+
line,
|
|
156
|
+
body: Object.fromEntries(IMPORTED_FIELDS.filter(field => item[field] !== undefined).map(field => [field, item[field]])),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
return { records, errors };
|
|
160
|
+
}
|
|
161
|
+
async function readImportFile(context, file) {
|
|
162
|
+
if (file === '-') {
|
|
163
|
+
return readStdin(context);
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
return fs.readFileSync(path.resolve(context.cwd, file), 'utf8');
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
throw new CliError(error.code === 'ENOENT'
|
|
170
|
+
? `Can't find ${file}`
|
|
171
|
+
: `Can't read ${file}: ${error.message}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Pace requests to the plan's limits, and warn if the import is likely to use
|
|
176
|
+
* up the monthly quota or take a long time
|
|
177
|
+
*/
|
|
178
|
+
async function prepareForImport(context, jsonpad, count) {
|
|
179
|
+
const { yellow } = context.colours;
|
|
180
|
+
const { plan, usage } = await request(context, () => jsonpad.fetchSelfToken());
|
|
181
|
+
const interval = requestInterval(plan);
|
|
182
|
+
installRequestPacing(context, interval);
|
|
183
|
+
if (usage.requestsRemaining !== null && count > usage.requestsRemaining) {
|
|
184
|
+
context.error(`${yellow('warning')}: this imports ${formatNumber(count)} items, but the account has ${formatNumber(usage.requestsRemaining)} requests left this month. Creating items will be refused once they run out`);
|
|
185
|
+
}
|
|
186
|
+
const minutes = Math.round((count * interval) / 60_000);
|
|
187
|
+
if (minutes >= 2) {
|
|
188
|
+
context.error(`This will take about ${plural(minutes, 'minute')}, at the pace the ${plan.name} plan allows`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async function importItems(context, listId, file, options) {
|
|
192
|
+
const text = await readImportFile(context, file);
|
|
193
|
+
const { records, errors } = parseImport(text, !!options.dataOnly);
|
|
194
|
+
if (errors.length > 0) {
|
|
195
|
+
const shown = errors.slice(0, 10);
|
|
196
|
+
throw new CliError([
|
|
197
|
+
`Nothing was imported, because ${plural(errors.length, 'record')} ${errors.length === 1 ? "isn't" : "aren't"} valid:`,
|
|
198
|
+
...shown.map(error => ` ${error}`),
|
|
199
|
+
...(errors.length > shown.length
|
|
200
|
+
? [` and ${formatNumber(errors.length - shown.length)} more`]
|
|
201
|
+
: []),
|
|
202
|
+
].join('\n'));
|
|
203
|
+
}
|
|
204
|
+
if (options.dryRun) {
|
|
205
|
+
context.error(`${plural(records.length, 'item')} would be created in ${listId}. Nothing was imported (dry run)`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (records.length === 0) {
|
|
209
|
+
context.error('There are no records to import');
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const jsonpad = context.createClient();
|
|
213
|
+
await prepareForImport(context, jsonpad, records.length);
|
|
214
|
+
let created = 0;
|
|
215
|
+
const failures = [];
|
|
216
|
+
for (const record of records) {
|
|
217
|
+
progress(context, `Importing ${formatNumber(created + failures.length + 1)} of ${formatNumber(records.length)}...`);
|
|
218
|
+
try {
|
|
219
|
+
await jsonpad.createItem(listId, record.body, {
|
|
220
|
+
includeData: false,
|
|
221
|
+
});
|
|
222
|
+
created++;
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
const failure = apiError(error, context.auth?.apiUrl);
|
|
226
|
+
progress(context, null);
|
|
227
|
+
if (!options.continueOnError) {
|
|
228
|
+
const resume = record.line !== undefined && file !== '-'
|
|
229
|
+
? ` To import the rest, fix it and run: tail -n +${record.line} ${file} | jsonpad items import ${listId} -`
|
|
230
|
+
: '';
|
|
231
|
+
throw new CliError(`Stopped at ${record.position}: ${failure.message}\n${created === 0
|
|
232
|
+
? 'No items were created.'
|
|
233
|
+
: `${plural(created, 'item was', 'items were')} created before it.`}${resume}`, failure.exitCode);
|
|
234
|
+
}
|
|
235
|
+
failures.push(record.position);
|
|
236
|
+
context.error(`${record.position}: ${failure.message}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
progress(context, null);
|
|
240
|
+
context.error(`Created ${plural(created, 'item')} in ${listId}${failures.length > 0
|
|
241
|
+
? `. ${plural(failures.length, 'record')} failed: ${failures.join(', ')}`
|
|
242
|
+
: ''}`);
|
|
243
|
+
if (failures.length > 0) {
|
|
244
|
+
throw new CliError(`${plural(failures.length, 'item')} couldn't be created`, EXIT_ERROR);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { apiError } from '../errors.js';
|
|
2
|
+
import { addOutputOptions, formatBytes, formatDate, formatNumber, printRecord, resolveOutputFormat, } from '../output.js';
|
|
3
|
+
export function defineWhoami(command, context) {
|
|
4
|
+
return addOutputOptions(command
|
|
5
|
+
.summary("Show the token you're using, its plan's limits and usage")
|
|
6
|
+
.description("Show the token you're using: what it can do, its plan's limits, and the account's usage this month")
|
|
7
|
+
.action((options) => whoami(context, options)));
|
|
8
|
+
}
|
|
9
|
+
export function describePermission(permission) {
|
|
10
|
+
const scopes = [
|
|
11
|
+
['lists', permission.listIds],
|
|
12
|
+
['items', permission.itemIds],
|
|
13
|
+
['indexes', permission.indexIds],
|
|
14
|
+
['identities', permission.identityIds],
|
|
15
|
+
['groups', permission.groups],
|
|
16
|
+
];
|
|
17
|
+
const scope = scopes
|
|
18
|
+
.filter(([, values]) => values && values.length > 0)
|
|
19
|
+
.map(([name, values]) => `${name}: ${values.join(', ')}`);
|
|
20
|
+
return [
|
|
21
|
+
permission.mode,
|
|
22
|
+
permission.action,
|
|
23
|
+
...(permission.resourceType ? [permission.resourceType] : []),
|
|
24
|
+
...(scope.length > 0 ? [`(${scope.join('; ')})`] : []),
|
|
25
|
+
].join(' ');
|
|
26
|
+
}
|
|
27
|
+
function describeLimit(used, limit, format) {
|
|
28
|
+
return limit === null
|
|
29
|
+
? `${format(used)} (no limit)`
|
|
30
|
+
: `${format(used)} of ${format(limit)}`;
|
|
31
|
+
}
|
|
32
|
+
export function whoamiDetails(context, self, auth, identity = null) {
|
|
33
|
+
const { dim, yellow, red } = context.colours;
|
|
34
|
+
const { token, plan, usage } = self;
|
|
35
|
+
const status = [
|
|
36
|
+
token.locked ? red('locked') : null,
|
|
37
|
+
token.activated ? null : red('deactivated'),
|
|
38
|
+
token.expiresAt
|
|
39
|
+
? token.expiresAt.getTime() < Date.now()
|
|
40
|
+
? red(`expired ${formatDate(token.expiresAt)}`)
|
|
41
|
+
: `expires ${formatDate(token.expiresAt)}`
|
|
42
|
+
: null,
|
|
43
|
+
].filter(Boolean);
|
|
44
|
+
const rate = [
|
|
45
|
+
plan.maxRequestsPerMinute !== null
|
|
46
|
+
? `${formatNumber(plan.maxRequestsPerMinute)} requests per minute`
|
|
47
|
+
: null,
|
|
48
|
+
plan.rateLimit !== null ? `${plan.rateLimit}ms between requests` : null,
|
|
49
|
+
].filter(Boolean);
|
|
50
|
+
const requests = [
|
|
51
|
+
describeLimit(usage.requestCount, usage.requestAllowance, formatNumber),
|
|
52
|
+
...(usage.requestsRemaining !== null
|
|
53
|
+
? [`${formatNumber(usage.requestsRemaining)} left`]
|
|
54
|
+
: []),
|
|
55
|
+
...(usage.credits > 0 ? [`${formatNumber(usage.credits)} credits`] : []),
|
|
56
|
+
];
|
|
57
|
+
const rows = [
|
|
58
|
+
['Token', `${token.name} ${dim(token.id)}`],
|
|
59
|
+
['Status', status.length > 0 ? status.join(', ') : 'active'],
|
|
60
|
+
[
|
|
61
|
+
'Using',
|
|
62
|
+
auth.source.type === 'profile'
|
|
63
|
+
? `profile ${auth.source.name}`
|
|
64
|
+
: 'JSONPAD_TOKEN',
|
|
65
|
+
],
|
|
66
|
+
['API', auth.apiUrl],
|
|
67
|
+
...(identity !== null ? [['Identity', identity]] : []),
|
|
68
|
+
['IPs', token.ips && token.ips.length > 0 ? token.ips.join(', ') : 'any'],
|
|
69
|
+
['Plan', plan.name],
|
|
70
|
+
['Rate limit', rate.length > 0 ? rate.join(', ') : 'none'],
|
|
71
|
+
[
|
|
72
|
+
'Requests',
|
|
73
|
+
`${requests.join(', ')} ${dim(`(${formatDate(usage.periodStart)} to ${formatDate(usage.periodEnd)})`)}`,
|
|
74
|
+
],
|
|
75
|
+
[
|
|
76
|
+
'Storage',
|
|
77
|
+
describeLimit(usage.storageBytes, usage.storageAllowance, formatBytes),
|
|
78
|
+
],
|
|
79
|
+
];
|
|
80
|
+
if (usage.degraded) {
|
|
81
|
+
rows.push([
|
|
82
|
+
'Degraded',
|
|
83
|
+
yellow('yes: the allowance and credits have run out, so writes are refused and reads are slower'),
|
|
84
|
+
]);
|
|
85
|
+
}
|
|
86
|
+
rows.push(['Permissions', '']);
|
|
87
|
+
for (const permission of token.permissions) {
|
|
88
|
+
rows.push(['', describePermission(permission)]);
|
|
89
|
+
}
|
|
90
|
+
if (token.permissions.length === 0) {
|
|
91
|
+
rows.push(['', dim('none')]);
|
|
92
|
+
}
|
|
93
|
+
return rows;
|
|
94
|
+
}
|
|
95
|
+
export async function whoami(context, options) {
|
|
96
|
+
const format = resolveOutputFormat(context, options);
|
|
97
|
+
const jsonpad = context.createClient();
|
|
98
|
+
let self;
|
|
99
|
+
try {
|
|
100
|
+
self = await jsonpad.fetchSelfToken();
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
throw apiError(error, context.auth?.apiUrl);
|
|
104
|
+
}
|
|
105
|
+
// Items commands act as the identity in JSONPAD_IDENTITY_TOKEN, which is
|
|
106
|
+
// easy to forget is set, so a table says which identity that is
|
|
107
|
+
let identity = null;
|
|
108
|
+
if (context.identity && format === 'table') {
|
|
109
|
+
try {
|
|
110
|
+
const found = await jsonpad.fetchSelfIdentity();
|
|
111
|
+
identity = `${found.group ? `${found.group}/` : ''}${found.name} ${context.colours.dim(`${found.id}, from JSONPAD_IDENTITY_TOKEN`)}`;
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
identity = context.colours.red(`JSONPAD_IDENTITY_TOKEN is set, but isn't valid: ${apiError(error).message}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
printRecord(context, format, self, {
|
|
118
|
+
id: record => record.token.id,
|
|
119
|
+
details: record => whoamiDetails(context, record, context.auth, identity),
|
|
120
|
+
});
|
|
121
|
+
}
|