@basementuniverse/jsonpad-cli 1.0.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 +39 -0
- package/LICENSE +21 -0
- package/README.md +137 -0
- package/REFERENCE.md +123 -0
- package/build/cli.js +4 -0
- package/build/commands/rebuild-index.js +25 -0
- package/build/commands/schema/export.js +46 -0
- package/build/commands/schema/move.js +102 -0
- package/build/commands/schema/sync.js +161 -0
- package/build/context.js +26 -0
- package/build/errors.js +33 -0
- package/build/indexes.js +40 -0
- package/build/output.js +23 -0
- package/build/program.js +88 -0
- package/build/reference.js +91 -0
- package/build/sdk.js +5 -0
- package/package.json +49 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@basementuniverse/jsonpad-cli`.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
Dates are npm publish dates.
|
|
9
|
+
|
|
10
|
+
## [1.0.0] - Unreleased
|
|
11
|
+
|
|
12
|
+
The `jsonpad` command, moved out of `@basementuniverse/jsonpad-sdk` (where
|
|
13
|
+
it's deprecated) into its own package.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- The `sync-schema`, `export-schema`, `move-lists` and `rebuild-index`
|
|
18
|
+
commands. They have the same options, output, exit codes and API requests
|
|
19
|
+
as the SDK's `jsonpad` command in `@basementuniverse/jsonpad-sdk` 1.13.0.
|
|
20
|
+
- `jsonpad schema sync`, `jsonpad schema export` and `jsonpad schema move`, as
|
|
21
|
+
other names for `sync-schema`, `export-schema` and `move-lists`.
|
|
22
|
+
- Help for each command: `jsonpad <command> --help` and
|
|
23
|
+
`jsonpad help <command>`.
|
|
24
|
+
- Suggestions for mistyped commands and options.
|
|
25
|
+
- A command reference, in `REFERENCE.md`.
|
|
26
|
+
|
|
27
|
+
### Changed
|
|
28
|
+
|
|
29
|
+
Compared with the SDK's `jsonpad` command:
|
|
30
|
+
|
|
31
|
+
- Needs Node.js 22.12 or later, instead of 18.3.
|
|
32
|
+
- Help text, and the messages for argument errors like an unknown option or a
|
|
33
|
+
missing argument, come from the new argument parser, so they're worded
|
|
34
|
+
differently. Their exit codes are the same.
|
|
35
|
+
- An option value can start with a dash, e.g. `--timeout -5`. The command then
|
|
36
|
+
checks the value as usual, instead of the argument parser refusing it.
|
|
37
|
+
- Extra arguments are refused, e.g. a second file for `sync-schema`. They used
|
|
38
|
+
to be ignored.
|
|
39
|
+
- `--version` prints this package's version.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gordon Larrigan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# JSONPad CLI
|
|
2
|
+
|
|
3
|
+
The `jsonpad` command line tool for [JSONPad](https://jsonpad.io).
|
|
4
|
+
|
|
5
|
+
It syncs schema documents (lists and their indexes) with your account, for
|
|
6
|
+
example in a deploy script or CI.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
The tool needs Node.js 22.12 or later.
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
# Install the jsonpad command globally
|
|
14
|
+
npm install -g @basementuniverse/jsonpad-cli
|
|
15
|
+
|
|
16
|
+
# Or run it without installing
|
|
17
|
+
npx @basementuniverse/jsonpad-cli sync-schema --dry-run
|
|
18
|
+
|
|
19
|
+
# Or add it to a project, and run it with npx jsonpad
|
|
20
|
+
npm install --save-dev @basementuniverse/jsonpad-cli
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Authentication
|
|
24
|
+
|
|
25
|
+
The tool reads an API token from the `JSONPAD_TOKEN` environment variable.
|
|
26
|
+
Create a token in the JSONPad dashboard.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
export JSONPAD_TOKEN=<your token>
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
For schema commands, the token needs the `sync-schema` permission, plus
|
|
33
|
+
permission for each change a sync makes.
|
|
34
|
+
|
|
35
|
+
Set `JSONPAD_API_URL` to use a different API, e.g. a local server.
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
# See what a sync would change, then apply it
|
|
41
|
+
jsonpad sync-schema --dry-run
|
|
42
|
+
jsonpad sync-schema
|
|
43
|
+
|
|
44
|
+
# Sync a different file, and wait for index builds to finish
|
|
45
|
+
jsonpad sync-schema schemas/recipes.json --wait
|
|
46
|
+
|
|
47
|
+
# Also delete the lists and indexes the document's scope no longer declares
|
|
48
|
+
jsonpad sync-schema --prune --dry-run
|
|
49
|
+
|
|
50
|
+
# Write a schema document for existing lists
|
|
51
|
+
jsonpad export-schema --tagged recipe-app --out jsonpad-schema.json
|
|
52
|
+
|
|
53
|
+
# Move lists to another scope, or rename a scope
|
|
54
|
+
jsonpad move-lists recipes ratings --to cookbook-app
|
|
55
|
+
jsonpad move-lists --from-scope recipe-app --to cookbook-app
|
|
56
|
+
|
|
57
|
+
# Rebuild an index whose last build failed
|
|
58
|
+
jsonpad rebuild-index recipes title --wait
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The schema commands are also available as `jsonpad schema sync`,
|
|
62
|
+
`jsonpad schema export` and `jsonpad schema move`.
|
|
63
|
+
|
|
64
|
+
Run `jsonpad --help`, or `jsonpad <command> --help`, for every option. The full
|
|
65
|
+
command reference is in [REFERENCE.md](REFERENCE.md).
|
|
66
|
+
|
|
67
|
+
## Continuous integration
|
|
68
|
+
|
|
69
|
+
```yaml
|
|
70
|
+
- name: Sync the JSONPad schema
|
|
71
|
+
run: npx @basementuniverse/jsonpad-cli sync-schema --wait
|
|
72
|
+
env:
|
|
73
|
+
JSONPAD_TOKEN: ${{ secrets.JSONPAD_TOKEN }}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Exit codes
|
|
77
|
+
|
|
78
|
+
| Code | Meaning |
|
|
79
|
+
| ---- | -------------------------------------------------------------- |
|
|
80
|
+
| `0` | Success |
|
|
81
|
+
| `1` | Error, including a sync refused because a change has errors |
|
|
82
|
+
| `2` | A sync was refused because it needs `--allow-rebuild` |
|
|
83
|
+
| `3` | An index build failed, or didn't finish in time, while waiting |
|
|
84
|
+
| `4` | A sync was refused because it needs `--allow-destructive` |
|
|
85
|
+
|
|
86
|
+
A dry run exits the same way the real sync would.
|
|
87
|
+
|
|
88
|
+
## Moving from the SDK's `jsonpad` command
|
|
89
|
+
|
|
90
|
+
Versions 1.12 and 1.13 of `@basementuniverse/jsonpad-sdk` include a `jsonpad`
|
|
91
|
+
command. It's deprecated, and it will be removed in SDK 2.0.0. This package has
|
|
92
|
+
the same commands, options, output and exit codes, so to switch, replace
|
|
93
|
+
`npx @basementuniverse/jsonpad-sdk` with `npx @basementuniverse/jsonpad-cli`.
|
|
94
|
+
|
|
95
|
+
If you installed the SDK globally to get the command, uninstall it first.
|
|
96
|
+
Otherwise npm refuses to install this package, because both packages provide a
|
|
97
|
+
`jsonpad` command:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
npm uninstall -g @basementuniverse/jsonpad-sdk
|
|
101
|
+
npm install -g @basementuniverse/jsonpad-cli
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Development
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
npm install
|
|
108
|
+
npm test # builds, then runs the unit and parity tests
|
|
109
|
+
npm run reference # regenerates REFERENCE.md after changing a command
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`npm test` fails when `REFERENCE.md` is out of date.
|
|
113
|
+
|
|
114
|
+
The parity tests check that the commands ported from the SDK behave exactly as
|
|
115
|
+
the SDK's `bin/jsonpad.js` does. They run each scenario against a fake API and
|
|
116
|
+
compare the output, exit code, requests and files against golden files in
|
|
117
|
+
`test/parity/golden`. Those files were recorded from the SDK's command with:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
npm run record-parity -- ../jsonpad-sdk-js/bin/jsonpad.js
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Only re-record them to add scenarios while the SDK still has its command.
|
|
124
|
+
|
|
125
|
+
### Publishing
|
|
126
|
+
|
|
127
|
+
npm lifecycle scripts may be turned off (`ignore-scripts`), so build and test
|
|
128
|
+
explicitly:
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
npm test
|
|
132
|
+
npm publish --access public
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
MIT
|
package/REFERENCE.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# jsonpad command reference
|
|
2
|
+
|
|
3
|
+
<!-- Generated by `npm run reference` from the command definitions. Don't edit this file by hand. -->
|
|
4
|
+
|
|
5
|
+
Run `jsonpad <command> --help` for the same information in a terminal.
|
|
6
|
+
|
|
7
|
+
## Commands
|
|
8
|
+
|
|
9
|
+
- [`jsonpad sync-schema`](#jsonpad-sync-schema): Create and update lists and indexes to match a schema document
|
|
10
|
+
- [`jsonpad export-schema`](#jsonpad-export-schema): Write a schema document for existing lists
|
|
11
|
+
- [`jsonpad move-lists`](#jsonpad-move-lists): Move lists (by id or path name) to a scope, or release them from their scope
|
|
12
|
+
- [`jsonpad rebuild-index`](#jsonpad-rebuild-index): Rebuild an index whose last build failed, once the problem has been fixed
|
|
13
|
+
- [`jsonpad schema sync`](#jsonpad-schema-sync): Create and update lists and indexes to match a schema document
|
|
14
|
+
- [`jsonpad schema export`](#jsonpad-schema-export): Write a schema document for existing lists
|
|
15
|
+
- [`jsonpad schema move`](#jsonpad-schema-move): Move lists (by id or path name) to a scope, or release them from their scope
|
|
16
|
+
|
|
17
|
+
### `jsonpad sync-schema`
|
|
18
|
+
|
|
19
|
+
Create and update lists and indexes to match a schema document
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
jsonpad sync-schema [options] [file]
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
| Argument | Description |
|
|
26
|
+
| --- | --- |
|
|
27
|
+
| `file` (optional) | The schema document (default: `jsonpad-schema.json`) |
|
|
28
|
+
|
|
29
|
+
| Option | Description |
|
|
30
|
+
| --- | --- |
|
|
31
|
+
| `--dry-run` | Show what would change, without changing it |
|
|
32
|
+
| `--allow-rebuild` | Allow changes that rebuild an index in a list with items (the index can't be used until the rebuild finishes) |
|
|
33
|
+
| `--prune` | Also delete the lists and indexes the document's scope manages that it no longer declares |
|
|
34
|
+
| `--allow-destructive` | Allow a prune to delete lists that have items, and guard indexes |
|
|
35
|
+
| `--wait` | Wait for index builds to finish |
|
|
36
|
+
| `--timeout <seconds>` | How long --wait waits for each index (default 600) |
|
|
37
|
+
| `--show-unchanged` | Also list resources that don't change |
|
|
38
|
+
| `--json` | Print the API's response as JSON |
|
|
39
|
+
|
|
40
|
+
### `jsonpad export-schema`
|
|
41
|
+
|
|
42
|
+
Write a schema document for existing lists
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
jsonpad export-schema [options]
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
| Option | Description |
|
|
49
|
+
| --- | --- |
|
|
50
|
+
| `--scope <scope>` | Only lists managed by this scope |
|
|
51
|
+
| `--tagged <tags>` | Only lists with one of these comma-separated tags (repeat the option to require every group) |
|
|
52
|
+
| `--lists <path names>` | Only these comma-separated lists |
|
|
53
|
+
| `--out <file>` | Write the document to a file, not stdout |
|
|
54
|
+
|
|
55
|
+
### `jsonpad move-lists`
|
|
56
|
+
|
|
57
|
+
Move lists (by id or path name) to a scope, or release them from their scope
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
jsonpad move-lists [options] [list...]
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
| Argument | Description |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `list...` (optional) | The lists to move |
|
|
66
|
+
|
|
67
|
+
| Option | Description |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `--to <scope>` | The scope to move the lists to |
|
|
70
|
+
| `--release` | Release the lists from their scope instead |
|
|
71
|
+
| `--from-scope <scope>` | Move every list this scope manages, instead of naming lists (e.g. to rename the scope) |
|
|
72
|
+
| `--dry-run` | Show what would change, without changing it |
|
|
73
|
+
| `--json` | Print the API's response as JSON |
|
|
74
|
+
|
|
75
|
+
### `jsonpad rebuild-index`
|
|
76
|
+
|
|
77
|
+
Rebuild an index whose last build failed, once the problem has been fixed
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
jsonpad rebuild-index [options] <list> <index>
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
| Argument | Description |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `list` | The list (id or path name) |
|
|
86
|
+
| `index` | The index (id or path name) |
|
|
87
|
+
|
|
88
|
+
| Option | Description |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `--wait` | Wait for the build to finish |
|
|
91
|
+
| `--timeout <seconds>` | How long to wait (default 600) |
|
|
92
|
+
|
|
93
|
+
### `jsonpad schema sync`
|
|
94
|
+
|
|
95
|
+
The same as [`jsonpad sync-schema`](#jsonpad-sync-schema), with the same arguments and options.
|
|
96
|
+
|
|
97
|
+
### `jsonpad schema export`
|
|
98
|
+
|
|
99
|
+
The same as [`jsonpad export-schema`](#jsonpad-export-schema), with the same arguments and options.
|
|
100
|
+
|
|
101
|
+
### `jsonpad schema move`
|
|
102
|
+
|
|
103
|
+
The same as [`jsonpad move-lists`](#jsonpad-move-lists), with the same arguments and options.
|
|
104
|
+
|
|
105
|
+
## Environment
|
|
106
|
+
|
|
107
|
+
```
|
|
108
|
+
JSONPAD_TOKEN The API token to use (required). The token needs the
|
|
109
|
+
sync-schema permission for schema commands, plus
|
|
110
|
+
permission for each change a sync makes
|
|
111
|
+
JSONPAD_API_URL The API's URL (default https://api.jsonpad.io)
|
|
112
|
+
NO_COLOR Set to turn off coloured output
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Exit codes
|
|
116
|
+
|
|
117
|
+
```
|
|
118
|
+
0 Success
|
|
119
|
+
1 Error, including a sync refused because a change has errors
|
|
120
|
+
2 A sync was refused because it needs --allow-rebuild
|
|
121
|
+
3 An index build failed, or didn't finish in time, while waiting
|
|
122
|
+
4 A sync was refused because it needs --allow-destructive
|
|
123
|
+
```
|
package/build/cli.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { CliError, describeApiError } from '../errors.js';
|
|
2
|
+
import { parseTimeout, waitForIndexes } from '../indexes.js';
|
|
3
|
+
export function defineRebuildIndex(command, context) {
|
|
4
|
+
return command
|
|
5
|
+
.description('Rebuild an index whose last build failed, once the problem has been fixed')
|
|
6
|
+
.argument('<list>', 'The list (id or path name)')
|
|
7
|
+
.argument('<index>', 'The index (id or path name)')
|
|
8
|
+
.option('--wait', 'Wait for the build to finish')
|
|
9
|
+
.option('--timeout <seconds>', 'How long to wait (default 600)')
|
|
10
|
+
.action((list, index, options) => rebuildIndex(context, list, index, options));
|
|
11
|
+
}
|
|
12
|
+
export async function rebuildIndex(context, list, index, options) {
|
|
13
|
+
const jsonpad = context.createClient();
|
|
14
|
+
let rebuilt;
|
|
15
|
+
try {
|
|
16
|
+
rebuilt = await jsonpad.rebuildIndex(list, index);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
throw new CliError(describeApiError(error));
|
|
20
|
+
}
|
|
21
|
+
context.log(`Rebuilding index ${context.colours.bold(`${list}/${index}`)}`);
|
|
22
|
+
if (options.wait) {
|
|
23
|
+
await waitForIndexes(context, jsonpad, [{ listId: list, indexId: rebuilt.id, label: `${list}/${index}` }], parseTimeout(options.timeout));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError, describeApiError } from '../../errors.js';
|
|
4
|
+
const collect = (value, previous = []) => [
|
|
5
|
+
...previous,
|
|
6
|
+
value,
|
|
7
|
+
];
|
|
8
|
+
export function defineExportSchema(command, context) {
|
|
9
|
+
return command
|
|
10
|
+
.description('Write a schema document for existing lists')
|
|
11
|
+
.option('--scope <scope>', 'Only lists managed by this scope')
|
|
12
|
+
.option('--tagged <tags>', 'Only lists with one of these comma-separated tags (repeat the option to require every group)', collect)
|
|
13
|
+
.option('--lists <path names>', 'Only these comma-separated lists')
|
|
14
|
+
.option('--out <file>', 'Write the document to a file, not stdout')
|
|
15
|
+
.action((options) => exportSchema(context, options));
|
|
16
|
+
}
|
|
17
|
+
export async function exportSchema(context, options) {
|
|
18
|
+
const jsonpad = context.createClient();
|
|
19
|
+
let result;
|
|
20
|
+
try {
|
|
21
|
+
result = await jsonpad.exportSchema({
|
|
22
|
+
scope: options.scope,
|
|
23
|
+
tagged: options.tagged,
|
|
24
|
+
lists: options.lists
|
|
25
|
+
? options.lists
|
|
26
|
+
.split(',')
|
|
27
|
+
.map(pathName => pathName.trim())
|
|
28
|
+
.filter(Boolean)
|
|
29
|
+
: undefined,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
throw new CliError(describeApiError(error));
|
|
34
|
+
}
|
|
35
|
+
for (const warning of result.warnings) {
|
|
36
|
+
context.error(`${context.colours.yellow('warning')}: ${warning}`);
|
|
37
|
+
}
|
|
38
|
+
const json = `${JSON.stringify(result.document, null, 2)}\n`;
|
|
39
|
+
if (options.out) {
|
|
40
|
+
fs.writeFileSync(path.resolve(context.cwd, options.out), json);
|
|
41
|
+
context.error(`Wrote ${Object.keys(result.document.lists).length} lists to ${options.out}`);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
context.stdout.write(json);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { CliError, describeApiError } from '../../errors.js';
|
|
2
|
+
import { formatValue, plural } from '../../output.js';
|
|
3
|
+
export function defineMoveLists(command, context) {
|
|
4
|
+
return command
|
|
5
|
+
.description('Move lists (by id or path name) to a scope, or release them from their scope')
|
|
6
|
+
.argument('[list...]', 'The lists to move')
|
|
7
|
+
.option('--to <scope>', 'The scope to move the lists to')
|
|
8
|
+
.option('--release', 'Release the lists from their scope instead')
|
|
9
|
+
.option('--from-scope <scope>', 'Move every list this scope manages, instead of naming lists (e.g. to rename the scope)')
|
|
10
|
+
.option('--dry-run', 'Show what would change, without changing it')
|
|
11
|
+
.option('--json', "Print the API's response as JSON")
|
|
12
|
+
.action((lists, options) => moveLists(context, lists, options));
|
|
13
|
+
}
|
|
14
|
+
function printMoveChange(context, change) {
|
|
15
|
+
const { green, yellow, red, cyan, dim, bold } = context.colours;
|
|
16
|
+
const symbols = {
|
|
17
|
+
move: cyan('>'),
|
|
18
|
+
assign: green('+'),
|
|
19
|
+
release: yellow('-'),
|
|
20
|
+
'no-change': dim('='),
|
|
21
|
+
error: red('!'),
|
|
22
|
+
};
|
|
23
|
+
const scopeName = (scope) => scope === null ? dim('no scope') : String(scope);
|
|
24
|
+
const action = change.action === 'no-change' ? 'no change' : change.action;
|
|
25
|
+
const scopes = change.from !== undefined && change.action !== 'no-change'
|
|
26
|
+
? ` ${scopeName(change.from)} ${dim('->')} ${scopeName(change.to)}`
|
|
27
|
+
: '';
|
|
28
|
+
const indexes = change.indexes !== undefined
|
|
29
|
+
? dim(` (${plural(change.indexes, 'index', 'indexes')})`)
|
|
30
|
+
: '';
|
|
31
|
+
context.log(`${symbols[change.action]} list ${bold(change.list)} ${dim(action)}${scopes}${indexes}`);
|
|
32
|
+
for (const [field, { from, to }] of Object.entries(change.fields || {})) {
|
|
33
|
+
context.log(` ${field}: ${formatValue(from)} ${dim('->')} ${formatValue(to)}`);
|
|
34
|
+
}
|
|
35
|
+
for (const warning of change.warnings || []) {
|
|
36
|
+
context.log(` ${yellow('warning')}: ${warning}`);
|
|
37
|
+
}
|
|
38
|
+
for (const error of change.errors || []) {
|
|
39
|
+
context.log(` ${red('error')}: ${error.message}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export async function moveLists(context, lists, options) {
|
|
43
|
+
const { green, yellow, red, dim, bold } = context.colours;
|
|
44
|
+
const usage = 'Usage: jsonpad move-lists [list...] (--to <scope> | --release) [--from-scope <scope>]';
|
|
45
|
+
if (!!options.to === !!options.release) {
|
|
46
|
+
throw new CliError(`Pass either --to <scope> or --release. ${usage}`);
|
|
47
|
+
}
|
|
48
|
+
if (lists.length > 0 === !!options.fromScope) {
|
|
49
|
+
throw new CliError(`Name the lists to move, or pass --from-scope, but not both. ${usage}`);
|
|
50
|
+
}
|
|
51
|
+
const jsonpad = context.createClient();
|
|
52
|
+
const selection = options.fromScope
|
|
53
|
+
? { fromScope: options.fromScope }
|
|
54
|
+
: { lists };
|
|
55
|
+
let result;
|
|
56
|
+
try {
|
|
57
|
+
result = await jsonpad.moveLists(selection, options.release ? null : options.to, { dryRun: !!options.dryRun });
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
throw new CliError(describeApiError(error));
|
|
61
|
+
}
|
|
62
|
+
if (options.json) {
|
|
63
|
+
context.log(JSON.stringify(result, null, 2));
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
context.log(bold(result.dryRun ? 'Move lists plan (dry run)' : 'Move lists') +
|
|
67
|
+
dim(result.scope ? ` to scope ${result.scope}` : ' out of their scope'));
|
|
68
|
+
context.log();
|
|
69
|
+
for (const warning of result.warnings) {
|
|
70
|
+
context.log(`${yellow('warning')}: ${warning}`);
|
|
71
|
+
}
|
|
72
|
+
if (result.changes.length === 0 && result.warnings.length === 0) {
|
|
73
|
+
context.log(dim('No lists to move'));
|
|
74
|
+
}
|
|
75
|
+
result.changes.forEach(change => printMoveChange(context, change));
|
|
76
|
+
const { summary } = result;
|
|
77
|
+
const parts = [
|
|
78
|
+
`${summary.move} to move`,
|
|
79
|
+
`${summary.assign} to assign`,
|
|
80
|
+
`${summary.release} to release`,
|
|
81
|
+
`${summary.noChange} unchanged`,
|
|
82
|
+
];
|
|
83
|
+
if (summary.error > 0) {
|
|
84
|
+
parts.push(red(`${summary.error} with errors`));
|
|
85
|
+
}
|
|
86
|
+
context.log(`\n${parts.join(', ')}`);
|
|
87
|
+
}
|
|
88
|
+
if (result.blockedBy) {
|
|
89
|
+
throw new CliError(result.dryRun
|
|
90
|
+
? `A real move would be refused: ${result.blockedBy.message}`
|
|
91
|
+
: result.blockedBy.message);
|
|
92
|
+
}
|
|
93
|
+
if (!options.json) {
|
|
94
|
+
const { move, assign, release } = result.summary;
|
|
95
|
+
if (move + assign + release === 0) {
|
|
96
|
+
context.log(green('Nothing to change'));
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
context.log(result.applied ? green('Applied') : dim('Not applied (dry run)'));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError, describeApiError, EXIT_DESTRUCTIVE_NOT_ALLOWED, EXIT_ERROR, EXIT_REBUILD_NOT_ALLOWED, } from '../../errors.js';
|
|
4
|
+
import { parseTimeout, waitForIndexes } from '../../indexes.js';
|
|
5
|
+
import { formatValue, plural } from '../../output.js';
|
|
6
|
+
export const DEFAULT_SCHEMA_FILE = 'jsonpad-schema.json';
|
|
7
|
+
export function defineSyncSchema(command, context) {
|
|
8
|
+
return command
|
|
9
|
+
.description('Create and update lists and indexes to match a schema document')
|
|
10
|
+
.argument('[file]', 'The schema document', DEFAULT_SCHEMA_FILE)
|
|
11
|
+
.option('--dry-run', 'Show what would change, without changing it')
|
|
12
|
+
.option('--allow-rebuild', "Allow changes that rebuild an index in a list with items (the index can't be used until the rebuild finishes)")
|
|
13
|
+
.option('--prune', "Also delete the lists and indexes the document's scope manages that it no longer declares")
|
|
14
|
+
.option('--allow-destructive', 'Allow a prune to delete lists that have items, and guard indexes')
|
|
15
|
+
.option('--wait', 'Wait for index builds to finish')
|
|
16
|
+
.option('--timeout <seconds>', 'How long --wait waits for each index (default 600)')
|
|
17
|
+
.option('--show-unchanged', "Also list resources that don't change")
|
|
18
|
+
.option('--json', "Print the API's response as JSON")
|
|
19
|
+
.action((file, options) => syncSchema(context, file, options));
|
|
20
|
+
}
|
|
21
|
+
function printChange(context, change) {
|
|
22
|
+
const { green, yellow, red, cyan, dim, bold } = context.colours;
|
|
23
|
+
const symbols = {
|
|
24
|
+
create: green('+'),
|
|
25
|
+
update: yellow('~'),
|
|
26
|
+
adopt: cyan('@'),
|
|
27
|
+
delete: red('-'),
|
|
28
|
+
'no-change': dim('='),
|
|
29
|
+
error: red('!'),
|
|
30
|
+
};
|
|
31
|
+
const name = change.resourceType === 'list'
|
|
32
|
+
? `list ${bold(change.list)}`
|
|
33
|
+
: `index ${bold(`${change.list}/${change.index}`)}`;
|
|
34
|
+
const action = change.action === 'no-change' ? 'no change' : change.action;
|
|
35
|
+
const build = change.build
|
|
36
|
+
? dim(` (${change.build.reason === 'created' ? 'build' : 'rebuild'}: ${change.build.items} ${change.build.items === 1 ? 'item' : 'items'}${change.build.requiresConfirmation ? ', needs --allow-rebuild' : ''})`)
|
|
37
|
+
: '';
|
|
38
|
+
const deleteDetails = change.delete
|
|
39
|
+
? [
|
|
40
|
+
...(change.delete.items !== undefined
|
|
41
|
+
? [plural(change.delete.items, 'item')]
|
|
42
|
+
: []),
|
|
43
|
+
...(change.delete.indexes !== undefined
|
|
44
|
+
? [plural(change.delete.indexes, 'index', 'indexes')]
|
|
45
|
+
: []),
|
|
46
|
+
...(change.delete.destructive ? ['needs --allow-destructive'] : []),
|
|
47
|
+
]
|
|
48
|
+
: [];
|
|
49
|
+
const deleted = deleteDetails.length > 0 ? dim(` (${deleteDetails.join(', ')})`) : '';
|
|
50
|
+
context.log(`${symbols[change.action]} ${name} ${dim(action)}${build}${deleted}`);
|
|
51
|
+
for (const [field, { from, to }] of Object.entries(change.fields || {})) {
|
|
52
|
+
context.log(change.action === 'create'
|
|
53
|
+
? ` ${field}: ${formatValue(to)}`
|
|
54
|
+
: ` ${field}: ${formatValue(from)} ${dim('->')} ${formatValue(to)}`);
|
|
55
|
+
}
|
|
56
|
+
for (const warning of change.warnings || []) {
|
|
57
|
+
context.log(` ${yellow('warning')}: ${warning}`);
|
|
58
|
+
}
|
|
59
|
+
for (const error of change.errors || []) {
|
|
60
|
+
context.log(` ${red('error')}: ${error.message}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function printSummary(context, result) {
|
|
64
|
+
const { summary } = result;
|
|
65
|
+
const parts = [
|
|
66
|
+
`${summary.create} to create`,
|
|
67
|
+
`${summary.update} to update`,
|
|
68
|
+
`${summary.adopt} to adopt`,
|
|
69
|
+
...(result.prune ? [`${summary.delete} to delete`] : []),
|
|
70
|
+
`${summary.noChange} unchanged`,
|
|
71
|
+
];
|
|
72
|
+
if (summary.error > 0) {
|
|
73
|
+
parts.push(context.colours.red(`${summary.error} with errors`));
|
|
74
|
+
}
|
|
75
|
+
context.log(`\n${parts.join(', ')}`);
|
|
76
|
+
}
|
|
77
|
+
export async function syncSchema(context, file, options) {
|
|
78
|
+
const { green, dim, bold } = context.colours;
|
|
79
|
+
let document;
|
|
80
|
+
try {
|
|
81
|
+
document = JSON.parse(fs.readFileSync(path.resolve(context.cwd, file), 'utf8'));
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
throw new CliError(error.code === 'ENOENT'
|
|
85
|
+
? `Can't find ${file}`
|
|
86
|
+
: `Can't read ${file}: ${error.message}`);
|
|
87
|
+
}
|
|
88
|
+
const jsonpad = context.createClient();
|
|
89
|
+
let result;
|
|
90
|
+
try {
|
|
91
|
+
result = await jsonpad.syncSchema(document, {
|
|
92
|
+
dryRun: !!options.dryRun,
|
|
93
|
+
allowRebuild: !!options.allowRebuild,
|
|
94
|
+
prune: !!options.prune,
|
|
95
|
+
allowDestructive: !!options.allowDestructive,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
throw new CliError(describeApiError(error));
|
|
100
|
+
}
|
|
101
|
+
if (options.json) {
|
|
102
|
+
context.log(JSON.stringify(result, null, 2));
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
const heading = result.dryRun
|
|
106
|
+
? 'Schema sync plan (dry run)'
|
|
107
|
+
: 'Schema sync';
|
|
108
|
+
context.log(bold(heading) + (result.scope ? dim(` for scope ${result.scope}`) : ''));
|
|
109
|
+
context.log();
|
|
110
|
+
// Unchanged resources are hidden unless they have something to say, e.g.
|
|
111
|
+
// an index whose last build failed
|
|
112
|
+
const shown = result.changes.filter(change => options.showUnchanged ||
|
|
113
|
+
change.action !== 'no-change' ||
|
|
114
|
+
(change.warnings && change.warnings.length > 0));
|
|
115
|
+
if (shown.length === 0) {
|
|
116
|
+
context.log(dim('Nothing to change'));
|
|
117
|
+
}
|
|
118
|
+
shown.forEach(change => printChange(context, change));
|
|
119
|
+
printSummary(context, result);
|
|
120
|
+
}
|
|
121
|
+
if (result.blockedBy) {
|
|
122
|
+
// The API's message names the query parameter, not the CLI option
|
|
123
|
+
const flags = {
|
|
124
|
+
SCHEMA_SYNC_REBUILD_NOT_ALLOWED: {
|
|
125
|
+
parameter: 'allowRebuild',
|
|
126
|
+
option: '--allow-rebuild',
|
|
127
|
+
exitCode: EXIT_REBUILD_NOT_ALLOWED,
|
|
128
|
+
},
|
|
129
|
+
SCHEMA_SYNC_DESTRUCTIVE_NOT_ALLOWED: {
|
|
130
|
+
parameter: 'allowDestructive',
|
|
131
|
+
option: '--allow-destructive',
|
|
132
|
+
exitCode: EXIT_DESTRUCTIVE_NOT_ALLOWED,
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
const flag = flags[result.blockedBy.name];
|
|
136
|
+
const message = flag
|
|
137
|
+
? `${result.blockedBy.message.replace(` (pass ${flag.parameter}=true to allow this)`, '')}. Run again with ${flag.option} to allow this`
|
|
138
|
+
: result.blockedBy.message;
|
|
139
|
+
throw new CliError(result.dryRun ? `A real sync would be refused: ${message}` : message, flag ? flag.exitCode : EXIT_ERROR);
|
|
140
|
+
}
|
|
141
|
+
if (!options.json) {
|
|
142
|
+
const { create, update, adopt } = result.summary;
|
|
143
|
+
const deletes = result.summary.delete || 0;
|
|
144
|
+
if (create + update + adopt + deletes === 0) {
|
|
145
|
+
context.log(green('Already up to date'));
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
context.log(result.applied ? green('Applied') : dim('Not applied (dry run)'));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (result.applied && options.wait) {
|
|
152
|
+
const building = result.changes
|
|
153
|
+
.filter(change => change.build && change.build.buildStatus === 'building')
|
|
154
|
+
.map(change => ({
|
|
155
|
+
listId: change.listId,
|
|
156
|
+
indexId: change.indexId,
|
|
157
|
+
label: `${change.list}/${change.index}`,
|
|
158
|
+
}));
|
|
159
|
+
await waitForIndexes(context, jsonpad, building, parseTimeout(options.timeout));
|
|
160
|
+
}
|
|
161
|
+
}
|
package/build/context.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { CliError } from './errors.js';
|
|
2
|
+
import { createColours } from './output.js';
|
|
3
|
+
import { JSONPad } from './sdk.js';
|
|
4
|
+
export function createContext(options = {}) {
|
|
5
|
+
const env = options.env ?? process.env;
|
|
6
|
+
const stdout = options.stdout ?? process.stdout;
|
|
7
|
+
const stderr = options.stderr ?? process.stderr;
|
|
8
|
+
return {
|
|
9
|
+
env,
|
|
10
|
+
cwd: options.cwd ?? process.cwd(),
|
|
11
|
+
stdout,
|
|
12
|
+
stderr,
|
|
13
|
+
colours: createColours(!!stdout.isTTY && !('NO_COLOR' in env)),
|
|
14
|
+
log: (text = '') => void stdout.write(`${text}\n`),
|
|
15
|
+
error: (text = '') => void stderr.write(`${text}\n`),
|
|
16
|
+
createClient() {
|
|
17
|
+
const token = env.JSONPAD_TOKEN;
|
|
18
|
+
if (!token) {
|
|
19
|
+
throw new CliError('Set the JSONPAD_TOKEN environment variable to an API token');
|
|
20
|
+
}
|
|
21
|
+
return new JSONPad(token, undefined, undefined, {
|
|
22
|
+
apiUrl: env.JSONPAD_API_URL || undefined,
|
|
23
|
+
});
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
package/build/errors.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { JSONPadError } from './sdk.js';
|
|
2
|
+
export const EXIT_OK = 0;
|
|
3
|
+
export const EXIT_ERROR = 1;
|
|
4
|
+
export const EXIT_REBUILD_NOT_ALLOWED = 2;
|
|
5
|
+
export const EXIT_BUILD_FAILED = 3;
|
|
6
|
+
export const EXIT_DESTRUCTIVE_NOT_ALLOWED = 4;
|
|
7
|
+
/**
|
|
8
|
+
* An error with a message for the user, and the exit code to finish with
|
|
9
|
+
*/
|
|
10
|
+
export class CliError extends Error {
|
|
11
|
+
exitCode;
|
|
12
|
+
constructor(message, exitCode = EXIT_ERROR) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'CliError';
|
|
15
|
+
this.exitCode = exitCode;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Get the message to show for an error thrown by the SDK
|
|
20
|
+
*/
|
|
21
|
+
export function describeApiError(error) {
|
|
22
|
+
if (error instanceof JSONPadError) {
|
|
23
|
+
try {
|
|
24
|
+
return JSON.parse(error.message).message || error.message;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return `The API responded with status ${error.status}`;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return error instanceof Error && error.message
|
|
31
|
+
? error.message
|
|
32
|
+
: String(error);
|
|
33
|
+
}
|
package/build/indexes.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { CliError, describeApiError, EXIT_BUILD_FAILED } from './errors.js';
|
|
2
|
+
import { IndexBuildError } from './sdk.js';
|
|
3
|
+
/**
|
|
4
|
+
* Parse a --timeout option (in seconds) into milliseconds
|
|
5
|
+
*/
|
|
6
|
+
export function parseTimeout(value) {
|
|
7
|
+
if (value === undefined) {
|
|
8
|
+
return 600 * 1000;
|
|
9
|
+
}
|
|
10
|
+
const seconds = Number(value);
|
|
11
|
+
if (!Number.isFinite(seconds) || seconds <= 0) {
|
|
12
|
+
throw new CliError('--timeout must be a number of seconds');
|
|
13
|
+
}
|
|
14
|
+
return seconds * 1000;
|
|
15
|
+
}
|
|
16
|
+
export async function waitForIndexes(context, jsonpad, indexes, timeout) {
|
|
17
|
+
const { green, red } = context.colours;
|
|
18
|
+
let failed = false;
|
|
19
|
+
// Builds for one account run one at a time, so waiting for them in order
|
|
20
|
+
// doesn't slow anything down, and polls less than waiting for all at once
|
|
21
|
+
for (const { listId, indexId, label } of indexes) {
|
|
22
|
+
context.stdout.write(`Waiting for index ${label} to build... `);
|
|
23
|
+
try {
|
|
24
|
+
await jsonpad.waitForIndex(listId, indexId, { timeout });
|
|
25
|
+
context.stdout.write(`${green('ready')}\n`);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
failed = true;
|
|
29
|
+
if (error instanceof IndexBuildError) {
|
|
30
|
+
context.stdout.write(`${red(error.reason === 'failed' ? 'failed' : 'timed out')}\n`);
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
context.stdout.write(`${red('error')}: ${describeApiError(error)}\n`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (failed) {
|
|
38
|
+
throw new CliError('One or more indexes did not build. Fix the problem, then run jsonpad rebuild-index <list> <index>', EXIT_BUILD_FAILED);
|
|
39
|
+
}
|
|
40
|
+
}
|
package/build/output.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export function createColours(enabled) {
|
|
2
|
+
const colour = (code) => (text) => enabled ? `\x1b[${code}m${text}\x1b[0m` : text;
|
|
3
|
+
return {
|
|
4
|
+
green: colour(32),
|
|
5
|
+
yellow: colour(33),
|
|
6
|
+
red: colour(31),
|
|
7
|
+
cyan: colour(36),
|
|
8
|
+
dim: colour(2),
|
|
9
|
+
bold: colour(1),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Show a value from a change as JSON, shortened to fit on one line
|
|
14
|
+
*/
|
|
15
|
+
export function formatValue(value) {
|
|
16
|
+
const json = JSON.stringify(value);
|
|
17
|
+
return json !== undefined && json.length > 60
|
|
18
|
+
? `${json.slice(0, 57)}...`
|
|
19
|
+
: String(json);
|
|
20
|
+
}
|
|
21
|
+
export function plural(count, singular, pluralForm = `${singular}s`) {
|
|
22
|
+
return `${count} ${count === 1 ? singular : pluralForm}`;
|
|
23
|
+
}
|
package/build/program.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { Command, CommanderError } from 'commander';
|
|
3
|
+
import { defineRebuildIndex } from './commands/rebuild-index.js';
|
|
4
|
+
import { defineExportSchema } from './commands/schema/export.js';
|
|
5
|
+
import { defineMoveLists } from './commands/schema/move.js';
|
|
6
|
+
import { defineSyncSchema } from './commands/schema/sync.js';
|
|
7
|
+
import { CliError, EXIT_ERROR, EXIT_OK } from './errors.js';
|
|
8
|
+
export const { version } = createRequire(import.meta.url)('../package.json');
|
|
9
|
+
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
|
|
13
|
+
JSONPAD_API_URL The API's URL (default https://api.jsonpad.io)
|
|
14
|
+
NO_COLOR Set to turn off coloured output`;
|
|
15
|
+
export const EXIT_CODES_HELP = `Exit codes:
|
|
16
|
+
0 Success
|
|
17
|
+
1 Error, including a sync refused because a change has errors
|
|
18
|
+
2 A sync was refused because it needs --allow-rebuild
|
|
19
|
+
3 An index build failed, or didn't finish in time, while waiting
|
|
20
|
+
4 A sync was refused because it needs --allow-destructive`;
|
|
21
|
+
/**
|
|
22
|
+
* The `jsonpad schema ...` commands, and the top-level commands they're the
|
|
23
|
+
* same as
|
|
24
|
+
*/
|
|
25
|
+
export const SCHEMA_ALIASES = {
|
|
26
|
+
'schema sync': 'sync-schema',
|
|
27
|
+
'schema export': 'export-schema',
|
|
28
|
+
'schema move': 'move-lists',
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Build the jsonpad command, with its output going to the context's streams
|
|
32
|
+
*/
|
|
33
|
+
export function createProgram(context) {
|
|
34
|
+
const program = new Command('jsonpad')
|
|
35
|
+
.description('The JSONPad command line tool')
|
|
36
|
+
.usage('<command> [options]')
|
|
37
|
+
.version(version, '-v, --version', 'Show the version')
|
|
38
|
+
.helpOption('-h, --help', 'Show help')
|
|
39
|
+
.helpCommand('help [command]', 'Show help for a command')
|
|
40
|
+
.showSuggestionAfterError()
|
|
41
|
+
.exitOverride()
|
|
42
|
+
.configureOutput({
|
|
43
|
+
writeOut: text => void context.stdout.write(text),
|
|
44
|
+
writeErr: text => void context.stderr.write(text),
|
|
45
|
+
outputError: (text, write) => write(context.colours.red(text)),
|
|
46
|
+
})
|
|
47
|
+
.addHelpText('after', `\n${ENVIRONMENT_HELP}\n\n${EXIT_CODES_HELP}\n`);
|
|
48
|
+
// Subcommands inherit the settings above (output, exit override, help
|
|
49
|
+
// option), as long as they're added after them
|
|
50
|
+
defineSyncSchema(program.command('sync-schema'), context);
|
|
51
|
+
defineExportSchema(program.command('export-schema'), context);
|
|
52
|
+
defineMoveLists(program.command('move-lists'), context);
|
|
53
|
+
defineRebuildIndex(program.command('rebuild-index'), context);
|
|
54
|
+
const schema = program
|
|
55
|
+
.command('schema')
|
|
56
|
+
.description('Schema sync commands (the same as sync-schema, export-schema and move-lists)');
|
|
57
|
+
defineSyncSchema(schema.command('sync'), context);
|
|
58
|
+
defineExportSchema(schema.command('export'), context);
|
|
59
|
+
defineMoveLists(schema.command('move'), context);
|
|
60
|
+
return program;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Run the jsonpad command with some arguments, and return the exit code
|
|
64
|
+
*/
|
|
65
|
+
export async function run(argv, context, program = createProgram(context)) {
|
|
66
|
+
if (argv.length === 0) {
|
|
67
|
+
program.outputHelp();
|
|
68
|
+
return EXIT_OK;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
await program.parseAsync(argv, { from: 'user' });
|
|
72
|
+
return EXIT_OK;
|
|
73
|
+
}
|
|
74
|
+
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;
|
|
84
|
+
}
|
|
85
|
+
context.error(red(`Error: ${error instanceof Error ? error.stack : String(error)}`));
|
|
86
|
+
return EXIT_ERROR;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { createProgram, ENVIRONMENT_HELP, EXIT_CODES_HELP, SCHEMA_ALIASES, } from './program.js';
|
|
2
|
+
function fullName(command) {
|
|
3
|
+
const names = [];
|
|
4
|
+
for (let current = command; current; current = current.parent) {
|
|
5
|
+
names.unshift(current.name());
|
|
6
|
+
}
|
|
7
|
+
return names.join(' ');
|
|
8
|
+
}
|
|
9
|
+
function escapeCell(text) {
|
|
10
|
+
return text.replace(/\|/g, '\\|');
|
|
11
|
+
}
|
|
12
|
+
function anchor(name) {
|
|
13
|
+
return name.replace(/\s+/g, '-').toLowerCase();
|
|
14
|
+
}
|
|
15
|
+
function describeCommand(command) {
|
|
16
|
+
const alias = SCHEMA_ALIASES[fullName(command).replace(/^jsonpad /, '')];
|
|
17
|
+
if (alias) {
|
|
18
|
+
return [
|
|
19
|
+
`### \`${fullName(command)}\``,
|
|
20
|
+
'',
|
|
21
|
+
`The same as [\`jsonpad ${alias}\`](#${anchor(`jsonpad ${alias}`)}), with the same arguments and options.`,
|
|
22
|
+
].join('\n');
|
|
23
|
+
}
|
|
24
|
+
const lines = [
|
|
25
|
+
`### \`${fullName(command)}\``,
|
|
26
|
+
'',
|
|
27
|
+
command.description(),
|
|
28
|
+
'',
|
|
29
|
+
'```',
|
|
30
|
+
`${fullName(command)} ${command.usage()}`,
|
|
31
|
+
'```',
|
|
32
|
+
];
|
|
33
|
+
if (command.registeredArguments.length > 0) {
|
|
34
|
+
lines.push('', '| Argument | Description |', '| --- | --- |');
|
|
35
|
+
for (const argument of command.registeredArguments) {
|
|
36
|
+
const name = `${argument.name()}${argument.variadic ? '...' : ''}`;
|
|
37
|
+
const defaultValue = argument.defaultValue !== undefined
|
|
38
|
+
? ` (default: \`${argument.defaultValue}\`)`
|
|
39
|
+
: '';
|
|
40
|
+
lines.push(`| \`${name}\`${argument.required ? '' : ' (optional)'} | ${escapeCell(argument.description)}${defaultValue} |`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const options = command.options.filter(option => option.long !== '--help');
|
|
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
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return lines.join('\n');
|
|
51
|
+
}
|
|
52
|
+
function commandsIn(command) {
|
|
53
|
+
return command.commands.flatMap(child => child.commands.length > 0 ? commandsIn(child) : [child]);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Generate the command reference as Markdown, from the command definitions
|
|
57
|
+
*/
|
|
58
|
+
export function generateReference(context) {
|
|
59
|
+
const program = createProgram(context);
|
|
60
|
+
const commands = commandsIn(program);
|
|
61
|
+
return `${[
|
|
62
|
+
'# jsonpad command reference',
|
|
63
|
+
'',
|
|
64
|
+
"<!-- Generated by `npm run reference` from the command definitions. Don't edit this file by hand. -->",
|
|
65
|
+
'',
|
|
66
|
+
'Run `jsonpad <command> --help` for the same information in a terminal.',
|
|
67
|
+
'',
|
|
68
|
+
'## Commands',
|
|
69
|
+
'',
|
|
70
|
+
...commands.map(command => `- [\`${fullName(command)}\`](#${anchor(fullName(command))}): ${command.description()}`),
|
|
71
|
+
'',
|
|
72
|
+
...commands.flatMap(command => [describeCommand(command), '']),
|
|
73
|
+
'## Environment',
|
|
74
|
+
'',
|
|
75
|
+
'```',
|
|
76
|
+
ENVIRONMENT_HELP.split('\n')
|
|
77
|
+
.slice(1)
|
|
78
|
+
.map(line => line.slice(2))
|
|
79
|
+
.join('\n'),
|
|
80
|
+
'```',
|
|
81
|
+
'',
|
|
82
|
+
'## Exit codes',
|
|
83
|
+
'',
|
|
84
|
+
'```',
|
|
85
|
+
EXIT_CODES_HELP.split('\n')
|
|
86
|
+
.slice(1)
|
|
87
|
+
.map(line => line.slice(2))
|
|
88
|
+
.join('\n'),
|
|
89
|
+
'```',
|
|
90
|
+
].join('\n')}\n`;
|
|
91
|
+
}
|
package/build/sdk.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import sdk from '@basementuniverse/jsonpad-sdk';
|
|
2
|
+
// The SDK is a UMD build, which Node loads as CommonJS, so an ES module only
|
|
3
|
+
// sees its exports object as the default import
|
|
4
|
+
export const JSONPad = sdk.default;
|
|
5
|
+
export const { IndexBuildError, JSONPadError } = sdk;
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@basementuniverse/jsonpad-cli",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Command line tool for JSONPad",
|
|
5
|
+
"author": "Gordon Larrigan <gordonlarrigan@gmail.com> (https://gordonlarrigan.com)",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/basementuniverse/jsonpad-cli#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/basementuniverse/jsonpad-cli.git"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/basementuniverse/jsonpad-cli/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"jsonpad",
|
|
17
|
+
"cli",
|
|
18
|
+
"json"
|
|
19
|
+
],
|
|
20
|
+
"type": "module",
|
|
21
|
+
"bin": {
|
|
22
|
+
"jsonpad": "build/cli.js"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"build",
|
|
26
|
+
"README.md",
|
|
27
|
+
"REFERENCE.md",
|
|
28
|
+
"CHANGELOG.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=22.12.0"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "rm -rf build && tsc -p tsconfig.build.json && chmod +x build/cli.js",
|
|
36
|
+
"typecheck": "tsc --noEmit",
|
|
37
|
+
"test": "npm run build && node --test \"test/**/*.test.ts\"",
|
|
38
|
+
"reference": "node scripts/generate-reference.ts",
|
|
39
|
+
"record-parity": "npm run build && node scripts/record-parity.ts"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@basementuniverse/jsonpad-sdk": "^1.13.0",
|
|
43
|
+
"commander": "^15.0.0"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/node": "^22.20.3",
|
|
47
|
+
"typescript": "^7.0.2"
|
|
48
|
+
}
|
|
49
|
+
}
|