@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/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,13 @@
1
+ import realtime from '@basementuniverse/jsonpad-realtime-sdk';
2
+ // The realtime SDK's Node build is CommonJS, so an ES module only sees its
3
+ // exports object as the default import
4
+ export const JSONPadRealtime = realtime.default;
5
+ export const REALTIME_EVENT_TYPES = [
6
+ 'list-created',
7
+ 'list-updated',
8
+ 'list-deleted',
9
+ 'item-created',
10
+ 'item-updated',
11
+ 'item-restored',
12
+ 'item-deleted',
13
+ ];
@@ -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
  }
@@ -0,0 +1,224 @@
1
+ import { InvalidArgumentError, Option } from 'commander';
2
+ import { apiError, CliError, EXIT_NOT_FOUND } from './errors.js';
3
+ import { collectList, readJsonInput } from './input.js';
4
+ import { formatNumber, printPage, printRecords, resolveOutputFormat, } from './output.js';
5
+ export const MAX_PAGE_SIZE = 100;
6
+ function parsePositiveInteger(value) {
7
+ const number = Number(value);
8
+ if (!Number.isInteger(number) || number < 1) {
9
+ throw new InvalidArgumentError('Must be a whole number, 1 or more.');
10
+ }
11
+ return number;
12
+ }
13
+ function parseLimit(value) {
14
+ const number = parsePositiveInteger(value);
15
+ if (number > MAX_PAGE_SIZE) {
16
+ throw new InvalidArgumentError(`Must be ${MAX_PAGE_SIZE} or less.`);
17
+ }
18
+ return number;
19
+ }
20
+ /**
21
+ * Add --page, --limit, --order and --direction to a command that fetches a
22
+ * page of records
23
+ */
24
+ export function addPagingOptions(command, order = {}) {
25
+ const orderOption = new Option('--order <field>', order.description ?? 'The field to order by');
26
+ if (order.choices) {
27
+ orderOption.choices(order.choices);
28
+ }
29
+ return command
30
+ .option('--page <number>', 'The page to fetch (default 1)', parsePositiveInteger)
31
+ .option('--limit <number>', `How many to fetch per page, up to ${MAX_PAGE_SIZE} (default 20)`, parseLimit)
32
+ .addOption(orderOption)
33
+ .addOption(new Option('--direction <direction>', 'The order direction').choices([
34
+ 'asc',
35
+ 'desc',
36
+ ]));
37
+ }
38
+ export function pagingParameters(options) {
39
+ return removeUndefined({
40
+ page: options.page,
41
+ limit: options.limit,
42
+ order: options.order,
43
+ direction: options.direction,
44
+ });
45
+ }
46
+ /**
47
+ * Add --name and --no-name for a boolean, so that leaving both out means
48
+ * "don't change it" or "don't filter by it"
49
+ */
50
+ export function addBooleanOption(command, flag, description, negatedDescription) {
51
+ return command
52
+ .option(`--${flag}`, description)
53
+ .option(`--no-${flag}`, negatedDescription);
54
+ }
55
+ /**
56
+ * Add --tags, which replaces a resource's tags
57
+ */
58
+ export function addTagsOption(command) {
59
+ return command.option('--tags <tags>', 'Comma-separated tags, replacing any it has (repeatable; pass "" to remove them all)', collectList);
60
+ }
61
+ /**
62
+ * Add --tagged, which filters by tags
63
+ */
64
+ export function addTaggedOption(command) {
65
+ return command.option('--tagged <tags>', 'Only those with one of these comma-separated tags (repeat the option to require every group)', (value, previous = []) => [...previous, value]);
66
+ }
67
+ export function removeUndefined(object) {
68
+ return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
69
+ }
70
+ /**
71
+ * A nullable field set with --field <value> and cleared with --no-field, which
72
+ * commander gives as false
73
+ */
74
+ export function nullable(value) {
75
+ return value === false ? null : value;
76
+ }
77
+ /**
78
+ * Build a request body from --data (a JSON object) and field options, which
79
+ * take precedence over the same fields in --data
80
+ */
81
+ export async function readBody(context, data, fields) {
82
+ let body = {};
83
+ if (data !== undefined) {
84
+ const parsed = await readJsonInput(context, '--data', data);
85
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
86
+ throw new CliError('--data must be a JSON object');
87
+ }
88
+ body = parsed;
89
+ }
90
+ return { ...body, ...removeUndefined(fields) };
91
+ }
92
+ /**
93
+ * Make a request, turning an API error into a CliError with the right exit
94
+ * code
95
+ */
96
+ export async function request(context, send) {
97
+ try {
98
+ return await send();
99
+ }
100
+ catch (error) {
101
+ throw apiError(error, context.auth?.apiUrl);
102
+ }
103
+ }
104
+ /**
105
+ * A JSON pointer as the SDK wants it: without its leading slash, since the SDK
106
+ * adds one
107
+ */
108
+ export function sdkPointer(pointer) {
109
+ return pointer === undefined ? undefined : pointer.replace(/^\/+/, '');
110
+ }
111
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
112
+ /**
113
+ * Find an identity's id from what was passed on the command line: its id,
114
+ * group/name, or the name of an identity with no group
115
+ *
116
+ * The API only looks identities up by id, and its name and group filters
117
+ * match partially, so the matches are narrowed down to exact ones here
118
+ */
119
+ export async function resolveIdentityId(context, jsonpad, reference) {
120
+ if (UUID.test(reference)) {
121
+ return reference;
122
+ }
123
+ // Names can't contain a slash, but groups can
124
+ const slash = reference.lastIndexOf('/');
125
+ const group = slash === -1 ? null : reference.slice(0, slash);
126
+ const name = reference.slice(slash + 1);
127
+ const page = await request(context, () => jsonpad.fetchIdentities({
128
+ name,
129
+ ...(group ? { group } : {}),
130
+ limit: MAX_PAGE_SIZE,
131
+ }));
132
+ const matches = page.data.filter((identity) => identity.name === name && (identity.group || null) === group);
133
+ if (matches.length === 0) {
134
+ throw new CliError(group
135
+ ? `There's no identity named "${name}" in the group "${group}"`
136
+ : `There's no identity named "${name}" without a group. Use group/name for an identity in a group, or its id`, EXIT_NOT_FOUND);
137
+ }
138
+ return matches[0].id;
139
+ }
140
+ /**
141
+ * Add --all and --max to a command that fetches a page of records
142
+ */
143
+ export function addAllOption(command) {
144
+ return command
145
+ .option('--all', 'Fetch every page, not just one. The output is NDJSON unless --output says otherwise')
146
+ .option('--max <number>', 'With --all, stop after this many', parsePositiveInteger);
147
+ }
148
+ /**
149
+ * Fetch every page of records, a page at a time, with the most records a page
150
+ * can have. Stops after max records, if given
151
+ *
152
+ * Pages are fetched by number, so records added or deleted while this runs
153
+ * can be skipped or repeated. Order by creation date for the most stable
154
+ * results
155
+ */
156
+ export async function* fetchAll(context, fetchPage, max) {
157
+ let fetched = 0;
158
+ for (let page = 1;; page++) {
159
+ const response = await request(context, () => fetchPage({ page, limit: MAX_PAGE_SIZE }));
160
+ for (const record of response.data) {
161
+ if (max !== undefined && fetched >= max) {
162
+ return;
163
+ }
164
+ fetched++;
165
+ yield record;
166
+ }
167
+ if (response.data.length < MAX_PAGE_SIZE ||
168
+ page * MAX_PAGE_SIZE >= response.total ||
169
+ (max !== undefined && fetched >= max)) {
170
+ return;
171
+ }
172
+ }
173
+ }
174
+ export function checkAllOptions(options) {
175
+ if (options.all &&
176
+ (options.page !== undefined || options.limit !== undefined)) {
177
+ throw new CliError("--page and --limit fetch one page, so they can't be used with --all. Use --max to limit how many are fetched");
178
+ }
179
+ if (!options.all && options.max !== undefined) {
180
+ throw new CliError('--max only works with --all');
181
+ }
182
+ }
183
+ /**
184
+ * Fetch and output a page of records, or with --all, every page
185
+ *
186
+ * With --all, NDJSON and ids are output as each page arrives. JSON and tables
187
+ * are output once everything has been fetched
188
+ */
189
+ export async function printPages(context, options, fetchPage, output) {
190
+ checkAllOptions(options);
191
+ if (!options.all) {
192
+ const format = resolveOutputFormat(context, options);
193
+ const page = await request(context, () => fetchPage(pagingParameters(options)));
194
+ printPage(context, format, page, output);
195
+ return;
196
+ }
197
+ const format = resolveOutputFormat(context, options, 'ndjson');
198
+ const records = fetchAll(context, parameters => fetchPage({ ...pagingParameters(options), ...parameters }), options.max);
199
+ if (format === 'ndjson' || format === 'id') {
200
+ for await (const record of records) {
201
+ printRecords(context, format, [record], output);
202
+ }
203
+ return;
204
+ }
205
+ const all = [];
206
+ for await (const record of records) {
207
+ all.push(record);
208
+ }
209
+ printRecords(context, format, all, output);
210
+ if (format === 'table' && all.length > 0) {
211
+ context.error(context.colours.dim(`${formatNumber(all.length)} total`));
212
+ }
213
+ }
214
+ /**
215
+ * Parse a date option, e.g. --start-at, into an ISO 8601 string
216
+ */
217
+ export function parseDate(value) {
218
+ const date = new Date(value);
219
+ if (Number.isNaN(date.getTime())) {
220
+ throw new InvalidArgumentError('Must be a date, e.g. 2026-09-01 or 2026-09-01T12:00:00Z.');
221
+ }
222
+ return date.toISOString();
223
+ }
224
+ export { parsePositiveInteger };