@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/build/output.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { Option } from 'commander';
2
+ import { CliError } from './errors.js';
1
3
  export function createColours(enabled) {
2
4
  const colour = (code) => (text) => enabled ? `\x1b[${code}m${text}\x1b[0m` : text;
3
5
  return {
@@ -9,6 +11,13 @@ export function createColours(enabled) {
9
11
  bold: colour(1),
10
12
  };
11
13
  }
14
+ const ANSI_ESCAPES = /\x1b\[[0-9;]*m/g;
15
+ /**
16
+ * The width of some text as it appears in a terminal, without colour codes
17
+ */
18
+ function visibleLength(text) {
19
+ return text.replace(ANSI_ESCAPES, '').length;
20
+ }
12
21
  /**
13
22
  * Show a value from a change as JSON, shortened to fit on one line
14
23
  */
@@ -21,3 +30,185 @@ export function formatValue(value) {
21
30
  export function plural(count, singular, pluralForm = `${singular}s`) {
22
31
  return `${count} ${count === 1 ? singular : pluralForm}`;
23
32
  }
33
+ export function formatNumber(value) {
34
+ return value.toLocaleString('en-US');
35
+ }
36
+ export function formatBytes(bytes) {
37
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
38
+ let value = bytes;
39
+ let unit = 0;
40
+ while (value >= 1024 && unit < units.length - 1) {
41
+ value /= 1024;
42
+ unit++;
43
+ }
44
+ return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`;
45
+ }
46
+ /**
47
+ * A date as YYYY-MM-DD
48
+ */
49
+ export function formatDate(date) {
50
+ return date.toISOString().slice(0, 10);
51
+ }
52
+ // -----------------------------------------------------------------------------
53
+ // Output formats
54
+ // -----------------------------------------------------------------------------
55
+ export const OUTPUT_FORMATS = ['table', 'json', 'ndjson', 'id'];
56
+ /**
57
+ * Add --output, --json and --quiet to a command
58
+ */
59
+ export function addOutputOptions(command) {
60
+ return command
61
+ .addOption(new Option('-o, --output <format>', 'Output format (default: table in a terminal, otherwise json)').choices(OUTPUT_FORMATS))
62
+ .option('--json', 'Output JSON (the same as --output json)')
63
+ .option('-q, --quiet', 'Only output ids (the same as --output id)');
64
+ }
65
+ /**
66
+ * Work out the output format from --output, --json and --quiet. Without them,
67
+ * it's a table in a terminal, and JSON anywhere else (e.g. piped to jq)
68
+ */
69
+ export function resolveOutputFormat(context, options, defaultFormat) {
70
+ const chosen = new Set([
71
+ ...(options.output ? [options.output] : []),
72
+ ...(options.json ? ['json'] : []),
73
+ ...(options.quiet ? ['id'] : []),
74
+ ]);
75
+ if (chosen.size > 1) {
76
+ throw new CliError('Choose one output format: --output, --json and --quiet disagree');
77
+ }
78
+ return ([...chosen][0] ?? defaultFormat ?? (context.stdout.isTTY ? 'table' : 'json'));
79
+ }
80
+ /**
81
+ * Add --output (json or ndjson only) to a command that outputs JSON data, e.g.
82
+ * an item's data
83
+ */
84
+ export function addDataOutputOptions(command) {
85
+ return command.addOption(new Option('-o, --output <format>', 'Output format: json (the default), or ndjson for one line per value').choices(['json', 'ndjson']));
86
+ }
87
+ /**
88
+ * Output JSON data as it is, e.g. an item's data. A list of values is one per
89
+ * line with ndjson
90
+ */
91
+ export function printData(context, format, data, { list = false } = {}) {
92
+ if (format === 'ndjson') {
93
+ for (const value of list && Array.isArray(data) ? data : [data]) {
94
+ context.log(JSON.stringify(value));
95
+ }
96
+ }
97
+ else {
98
+ context.log(JSON.stringify(data, null, 2));
99
+ }
100
+ }
101
+ /**
102
+ * A date and time, in UTC, to the minute
103
+ */
104
+ export function formatTimestamp(date) {
105
+ return `${date.toISOString().slice(0, 16).replace('T', ' ')}Z`;
106
+ }
107
+ /**
108
+ * Names of the flags that are true, e.g. "pinned, realtime", or "-" for none
109
+ */
110
+ export function formatFlags(record, names) {
111
+ const set = names.filter(name => record[name]);
112
+ return set.length > 0 ? set.join(', ') : '-';
113
+ }
114
+ const MAX_CELL_LENGTH = 60;
115
+ function truncate(text) {
116
+ return visibleLength(text) > MAX_CELL_LENGTH
117
+ ? `${text.replace(ANSI_ESCAPES, '').slice(0, MAX_CELL_LENGTH - 1)}…`
118
+ : text;
119
+ }
120
+ function pad(text, width) {
121
+ return text + ' '.repeat(Math.max(0, width - visibleLength(text)));
122
+ }
123
+ /**
124
+ * Render records as a table with a header row
125
+ */
126
+ export function renderTable(context, columns, records) {
127
+ const rows = records.map(record => columns.map(column => truncate(column.value(record))));
128
+ const widths = columns.map((column, i) => Math.max(column.header.length, ...rows.map(row => visibleLength(row[i]))));
129
+ const line = (cells) => cells
130
+ .map((cell, i) => (i === cells.length - 1 ? cell : pad(cell, widths[i])))
131
+ .join(' ')
132
+ .trimEnd();
133
+ return [
134
+ context.colours.dim(line(columns.map(column => column.header))),
135
+ ...rows.map(line),
136
+ ].join('\n');
137
+ }
138
+ /**
139
+ * Render label and value pairs, one per line, with the values lined up
140
+ */
141
+ export function renderDetails(rows) {
142
+ const width = Math.max(...rows.map(([label]) => label.length));
143
+ // A value with several lines (e.g. JSON) has its later lines indented to
144
+ // line up with the first
145
+ return rows
146
+ .map(([label, value]) => value
147
+ .split('\n')
148
+ .map((line, i) => `${(i === 0 ? label : '').padEnd(width)} ${line}`.trimEnd())
149
+ .join('\n'))
150
+ .join('\n');
151
+ }
152
+ /**
153
+ * Output one record
154
+ */
155
+ export function printRecord(context, format, record, output) {
156
+ const data = output.data ? output.data(record) : record;
157
+ switch (format) {
158
+ case 'table':
159
+ context.log(renderDetails(output.details(record)));
160
+ break;
161
+ case 'json':
162
+ context.log(JSON.stringify(data, null, 2));
163
+ break;
164
+ case 'ndjson':
165
+ context.log(JSON.stringify(data));
166
+ break;
167
+ case 'id':
168
+ context.log(output.id(record));
169
+ break;
170
+ }
171
+ }
172
+ /**
173
+ * Output a list of records
174
+ */
175
+ export function printRecords(context, format, records, output) {
176
+ const data = (record) => (output.data ? output.data(record) : record);
177
+ switch (format) {
178
+ case 'table':
179
+ if (records.length === 0) {
180
+ context.error(context.colours.dim(output.empty));
181
+ }
182
+ else {
183
+ context.log(renderTable(context, output.columns, records));
184
+ }
185
+ break;
186
+ case 'json':
187
+ context.log(JSON.stringify(records.map(data), null, 2));
188
+ break;
189
+ case 'ndjson':
190
+ records.forEach(record => context.log(JSON.stringify(data(record))));
191
+ break;
192
+ case 'id':
193
+ records.forEach(record => context.log(output.id(record)));
194
+ break;
195
+ }
196
+ }
197
+ /**
198
+ * Output a page of records. As JSON, the page keeps its page, limit and total;
199
+ * as a table, they're described on stderr
200
+ */
201
+ export function printPage(context, format, page, output) {
202
+ if (format === 'json') {
203
+ context.log(JSON.stringify({
204
+ ...page,
205
+ data: page.data.map(record => output.data ? output.data(record) : record),
206
+ }, null, 2));
207
+ return;
208
+ }
209
+ printRecords(context, format, page.data, output);
210
+ if (format === 'table' && page.total > 0) {
211
+ const pages = Math.max(1, Math.ceil(page.total / page.limit));
212
+ context.error(context.colours.dim(`page ${page.page} of ${pages} (${formatNumber(page.total)} total)`));
213
+ }
214
+ }
package/build/program.js CHANGED
@@ -1,31 +1,62 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { Command, CommanderError } from 'commander';
3
+ import { describeLimits } from './client.js';
4
+ import { COMPLETE_COMMAND, completions, defineCompletion, } from './completion.js';
5
+ import { defineConfig } from './commands/config.js';
6
+ import { defineIdentities } from './commands/identities.js';
7
+ import { defineIndexes } from './commands/indexes.js';
8
+ import { defineItems } from './commands/items.js';
9
+ import { defineListen } from './commands/listen.js';
10
+ import { defineLists } from './commands/lists.js';
3
11
  import { defineRebuildIndex } from './commands/rebuild-index.js';
4
12
  import { defineExportSchema } from './commands/schema/export.js';
5
13
  import { defineMoveLists } from './commands/schema/move.js';
6
14
  import { defineSyncSchema } from './commands/schema/sync.js';
15
+ import { defineWhoami } from './commands/whoami.js';
7
16
  import { CliError, EXIT_ERROR, EXIT_OK } from './errors.js';
8
17
  export const { version } = createRequire(import.meta.url)('../package.json');
9
18
  export const ENVIRONMENT_HELP = `Environment:
10
- JSONPAD_TOKEN The API token to use (required). The token needs the
11
- sync-schema permission for schema commands, plus
12
- permission for each change a sync makes
19
+ JSONPAD_TOKEN The API token to use, if you don't use a profile. The
20
+ token needs the sync-schema permission for schema
21
+ commands, plus permission for each change a sync makes
13
22
  JSONPAD_API_URL The API's URL (default https://api.jsonpad.io)
14
- NO_COLOR Set to turn off coloured output`;
23
+ JSONPAD_PROFILE The profile to use, like --profile
24
+ JSONPAD_CONFIG The config file, where profiles are saved (see
25
+ jsonpad config path)
26
+ JSONPAD_IDENTITY_TOKEN
27
+ Act as this identity when working with items (see
28
+ jsonpad identities login)
29
+ JSONPAD_IDENTITY_GROUP
30
+ The identity's group, like --identity-group
31
+ JSONPAD_IDENTITY_PASSWORD
32
+ A password for identities create, register and login
33
+ NO_COLOR Set to turn off coloured output
34
+
35
+ A profile chosen with --profile or JSONPAD_PROFILE comes first, then
36
+ JSONPAD_TOKEN, then the default profile.`;
15
37
  export const EXIT_CODES_HELP = `Exit codes:
16
38
  0 Success
17
39
  1 Error, including a sync refused because a change has errors
18
40
  2 A sync was refused because it needs --allow-rebuild
19
41
  3 An index build failed, or didn't finish in time, while waiting
20
- 4 A sync was refused because it needs --allow-destructive`;
42
+ 4 A sync was refused because it needs --allow-destructive
43
+ 5 Refused because it needs confirmation: run again with --yes
44
+ 6 Not found
45
+ 7 The token isn't allowed to do this, or isn't valid
46
+ 8 Rate limited (after retrying), or a plan limit or the monthly quota was
47
+ reached
48
+
49
+ The schema commands and rebuild-index (and indexes rebuild) exit with 1 for
50
+ every API error, as they did in @basementuniverse/jsonpad-sdk.`;
21
51
  /**
22
- * The `jsonpad schema ...` commands, and the top-level commands they're the
23
- * same as
52
+ * Commands that are other names for the commands ported from the SDK, and the
53
+ * commands they're the same as
24
54
  */
25
- export const SCHEMA_ALIASES = {
55
+ export const ALIASES = {
26
56
  'schema sync': 'sync-schema',
27
57
  'schema export': 'export-schema',
28
58
  'schema move': 'move-lists',
59
+ 'indexes rebuild': 'rebuild-index',
29
60
  };
30
61
  /**
31
62
  * Build the jsonpad command, with its output going to the context's streams
@@ -37,14 +68,22 @@ export function createProgram(context) {
37
68
  .version(version, '-v, --version', 'Show the version')
38
69
  .helpOption('-h, --help', 'Show help')
39
70
  .helpCommand('help [command]', 'Show help for a command')
71
+ .option('--profile <name>', 'Use a saved profile (see jsonpad config)')
72
+ .option('--api-url <url>', "The API's URL, e.g. a local server")
73
+ .option('-V, --verbose', 'Log requests, and the rate limit and quota')
74
+ .option('--identity-group <group>', 'The group of the identity in JSONPAD_IDENTITY_TOKEN (for identities in a group)')
40
75
  .showSuggestionAfterError()
76
+ .configureHelp({ showGlobalOptions: true })
41
77
  .exitOverride()
42
78
  .configureOutput({
43
79
  writeOut: text => void context.stdout.write(text),
44
80
  writeErr: text => void context.stderr.write(text),
45
81
  outputError: (text, write) => write(context.colours.red(text)),
46
82
  })
47
- .addHelpText('after', `\n${ENVIRONMENT_HELP}\n\n${EXIT_CODES_HELP}\n`);
83
+ .addHelpText('after', `\n${ENVIRONMENT_HELP}\n\n${EXIT_CODES_HELP}\n`)
84
+ .hook('preAction', (_program, command) => {
85
+ context.globalOptions = command.optsWithGlobals();
86
+ });
48
87
  // Subcommands inherit the settings above (output, exit override, help
49
88
  // option), as long as they're added after them
50
89
  defineSyncSchema(program.command('sync-schema'), context);
@@ -57,6 +96,14 @@ export function createProgram(context) {
57
96
  defineSyncSchema(schema.command('sync'), context);
58
97
  defineExportSchema(schema.command('export'), context);
59
98
  defineMoveLists(schema.command('move'), context);
99
+ defineLists(program.command('lists'), context);
100
+ defineIndexes(program.command('indexes'), context);
101
+ defineItems(program.command('items'), context);
102
+ defineIdentities(program.command('identities'), context);
103
+ defineWhoami(program.command('whoami'), context);
104
+ defineConfig(program.command('config'), context);
105
+ defineListen(program.command('listen'), context);
106
+ defineCompletion(program.command('completion'), context);
60
107
  return program;
61
108
  }
62
109
  /**
@@ -67,22 +114,40 @@ export async function run(argv, context, program = createProgram(context)) {
67
114
  program.outputHelp();
68
115
  return EXIT_OK;
69
116
  }
117
+ // Called by the completion scripts on every Tab, so it skips parsing
118
+ if (argv[0] === COMPLETE_COMMAND) {
119
+ for (const candidate of completions(program, argv.slice(1))) {
120
+ context.log(candidate);
121
+ }
122
+ return EXIT_OK;
123
+ }
70
124
  try {
71
125
  await program.parseAsync(argv, { from: 'user' });
72
126
  return EXIT_OK;
73
127
  }
74
128
  catch (error) {
75
- // Commander has already written its own messages, including help and the
76
- // version, which also end up here
77
- if (error instanceof CommanderError) {
78
- return error.exitCode;
79
- }
80
- const { red } = context.colours;
81
- if (error instanceof CliError) {
82
- context.error(red(error.message));
83
- return error.exitCode;
129
+ return handleError(context, error);
130
+ }
131
+ finally {
132
+ if (context.globalOptions.verbose && context.client) {
133
+ const limits = describeLimits(context.client.lastResponse);
134
+ if (limits) {
135
+ context.error(context.colours.dim(limits));
136
+ }
84
137
  }
85
- context.error(red(`Error: ${error instanceof Error ? error.stack : String(error)}`));
86
- return EXIT_ERROR;
87
138
  }
88
139
  }
140
+ function handleError(context, error) {
141
+ // Commander has already written its own messages, including help and the
142
+ // version, which also end up here
143
+ if (error instanceof CommanderError) {
144
+ return error.exitCode;
145
+ }
146
+ const { red } = context.colours;
147
+ if (error instanceof CliError) {
148
+ context.error(red(error.message));
149
+ return error.exitCode;
150
+ }
151
+ context.error(red(`Error: ${error instanceof Error ? error.stack : String(error)}`));
152
+ return EXIT_ERROR;
153
+ }
@@ -0,0 +1,33 @@
1
+ import { createRequire } from 'node:module';
2
+ import realtime from '@basementuniverse/jsonpad-realtime-sdk';
3
+ // Like the SDK, the realtime SDK is a UMD build, so an ES module only sees its
4
+ // exports object as the default import
5
+ const RealtimeClientClass = realtime.default;
6
+ /**
7
+ * The realtime SDK's build contains socket.io-client's browser build, which
8
+ * connects with XMLHttpRequest. Node doesn't have one, so without this the
9
+ * client never connects (and never says why). xmlhttprequest-ssl is what
10
+ * socket.io-client's own Node build uses
11
+ */
12
+ function provideXMLHttpRequest() {
13
+ if (!('XMLHttpRequest' in globalThis)) {
14
+ const require = createRequire(import.meta.url);
15
+ globalThis.XMLHttpRequest =
16
+ require('xmlhttprequest-ssl').XMLHttpRequest;
17
+ }
18
+ }
19
+ export const JSONPadRealtime = new Proxy(RealtimeClientClass, {
20
+ construct(target, args) {
21
+ provideXMLHttpRequest();
22
+ return Reflect.construct(target, args);
23
+ },
24
+ });
25
+ export const REALTIME_EVENT_TYPES = [
26
+ 'list-created',
27
+ 'list-updated',
28
+ 'list-deleted',
29
+ 'item-created',
30
+ 'item-updated',
31
+ 'item-restored',
32
+ 'item-deleted',
33
+ ];
@@ -1,4 +1,4 @@
1
- import { createProgram, ENVIRONMENT_HELP, EXIT_CODES_HELP, SCHEMA_ALIASES, } from './program.js';
1
+ import { createProgram, ENVIRONMENT_HELP, EXIT_CODES_HELP, ALIASES, } from './program.js';
2
2
  function fullName(command) {
3
3
  const names = [];
4
4
  for (let current = command; current; current = current.parent) {
@@ -13,7 +13,7 @@ function anchor(name) {
13
13
  return name.replace(/\s+/g, '-').toLowerCase();
14
14
  }
15
15
  function describeCommand(command) {
16
- const alias = SCHEMA_ALIASES[fullName(command).replace(/^jsonpad /, '')];
16
+ const alias = ALIASES[fullName(command).replace(/^jsonpad /, '')];
17
17
  if (alias) {
18
18
  return [
19
19
  `### \`${fullName(command)}\``,
@@ -42,13 +42,32 @@ function describeCommand(command) {
42
42
  }
43
43
  const options = command.options.filter(option => option.long !== '--help');
44
44
  if (options.length > 0) {
45
- lines.push('', '| Option | Description |', '| --- | --- |');
46
- for (const option of options) {
47
- lines.push(`| \`${option.flags}\` | ${escapeCell(option.description)} |`);
48
- }
45
+ lines.push('', ...optionsTable(options));
49
46
  }
50
47
  return lines.join('\n');
51
48
  }
49
+ function optionsTable(options) {
50
+ return [
51
+ '| Option | Description |',
52
+ '| --- | --- |',
53
+ ...options.map(option => {
54
+ const choices = option.argChoices
55
+ ? ` (one of: ${option.argChoices.join(', ')})`
56
+ : '';
57
+ return `| \`${option.flags}\` | ${escapeCell(option.description)}${choices} |`;
58
+ }),
59
+ ];
60
+ }
61
+ /**
62
+ * Help text with its heading removed and its indentation undone
63
+ */
64
+ function helpSection(help) {
65
+ return help
66
+ .split('\n')
67
+ .slice(1)
68
+ .map(line => line.replace(/^ /, ''))
69
+ .join('\n');
70
+ }
52
71
  function commandsIn(command) {
53
72
  return command.commands.flatMap(child => child.commands.length > 0 ? commandsIn(child) : [child]);
54
73
  }
@@ -67,25 +86,25 @@ export function generateReference(context) {
67
86
  '',
68
87
  '## Commands',
69
88
  '',
70
- ...commands.map(command => `- [\`${fullName(command)}\`](#${anchor(fullName(command))}): ${command.description()}`),
89
+ ...commands.map(command => `- [\`${fullName(command)}\`](#${anchor(fullName(command))}): ${command.summary() || command.description()}`),
71
90
  '',
72
91
  ...commands.flatMap(command => [describeCommand(command), '']),
92
+ '## Global options',
93
+ '',
94
+ 'Every command accepts these.',
95
+ '',
96
+ ...optionsTable(program.options.filter(option => option.long !== '--help')),
97
+ '',
73
98
  '## Environment',
74
99
  '',
75
100
  '```',
76
- ENVIRONMENT_HELP.split('\n')
77
- .slice(1)
78
- .map(line => line.slice(2))
79
- .join('\n'),
101
+ helpSection(ENVIRONMENT_HELP),
80
102
  '```',
81
103
  '',
82
104
  '## Exit codes',
83
105
  '',
84
106
  '```',
85
- EXIT_CODES_HELP.split('\n')
86
- .slice(1)
87
- .map(line => line.slice(2))
88
- .join('\n'),
107
+ helpSection(EXIT_CODES_HELP),
89
108
  '```',
90
109
  ].join('\n')}\n`;
91
110
  }