@seamapi/cli 0.10.0 → 0.12.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/README.md +118 -0
- package/bin/cli.js +78 -100
- package/bin/cli.js.map +1 -1
- package/completions/seam.bash +11 -0
- package/completions/seam.fish +11 -0
- package/completions/seam.zsh +13 -0
- package/lib/command-spec.d.ts +53 -0
- package/lib/command-spec.js +290 -0
- package/lib/command-spec.js.map +1 -0
- package/lib/completion/describe.d.ts +10 -0
- package/lib/completion/describe.js +16 -0
- package/lib/completion/describe.js.map +1 -0
- package/lib/completion/index.d.ts +20 -0
- package/lib/completion/index.js +65 -0
- package/lib/completion/index.js.map +1 -0
- package/lib/completion/render-bash.d.ts +2 -0
- package/lib/completion/render-bash.js +98 -0
- package/lib/completion/render-bash.js.map +1 -0
- package/lib/completion/render-fish.d.ts +2 -0
- package/lib/completion/render-fish.js +58 -0
- package/lib/completion/render-fish.js.map +1 -0
- package/lib/completion/render-zsh.d.ts +2 -0
- package/lib/completion/render-zsh.js +121 -0
- package/lib/completion/render-zsh.js.map +1 -0
- package/lib/get-response-key.d.ts +9 -0
- package/lib/get-response-key.js +21 -0
- package/lib/get-response-key.js.map +1 -0
- package/lib/interact-for-action-attempt-poll.js +4 -3
- package/lib/interact-for-action-attempt-poll.js.map +1 -1
- package/lib/interact-for-array.js +9 -7
- package/lib/interact-for-array.js.map +1 -1
- package/lib/interact-for-blueprint-object.js +9 -8
- package/lib/interact-for-blueprint-object.js.map +1 -1
- package/lib/interact-for-command-selection.js +2 -2
- package/lib/interact-for-command-selection.js.map +1 -1
- package/lib/interact-for-custom-metadata.js +10 -8
- package/lib/interact-for-custom-metadata.js.map +1 -1
- package/lib/interact-for-login.js +8 -6
- package/lib/interact-for-login.js.map +1 -1
- package/lib/interact-for-resource.js +2 -2
- package/lib/interact-for-resource.js.map +1 -1
- package/lib/interact-for-server-selection.js +7 -5
- package/lib/interact-for-server-selection.js.map +1 -1
- package/lib/interact-for-timestamp.js +2 -2
- package/lib/interact-for-timestamp.js.map +1 -1
- package/lib/interact-for-use-remote-api-defs.js +4 -3
- package/lib/interact-for-use-remote-api-defs.js.map +1 -1
- package/lib/interact-for-workspace-id.js +2 -2
- package/lib/interact-for-workspace-id.js.map +1 -1
- package/lib/output/create-memory-output.d.ts +13 -0
- package/lib/output/create-memory-output.js +22 -0
- package/lib/output/create-memory-output.js.map +1 -0
- package/lib/output/create-output.d.ts +50 -0
- package/lib/output/create-output.js +34 -0
- package/lib/output/create-output.js.map +1 -0
- package/lib/output/get-output.d.ts +12 -0
- package/lib/output/get-output.js +21 -0
- package/lib/output/get-output.js.map +1 -0
- package/lib/output/resolve-output-format.d.ts +16 -0
- package/lib/output/resolve-output-format.js +23 -0
- package/lib/output/resolve-output-format.js.map +1 -0
- package/lib/output/select-response-payload.d.ts +16 -0
- package/lib/output/select-response-payload.js +33 -0
- package/lib/output/select-response-payload.js.map +1 -0
- package/lib/render-help.d.ts +8 -0
- package/lib/render-help.js +150 -0
- package/lib/render-help.js.map +1 -0
- package/lib/util/cli-args.d.ts +16 -1
- package/lib/util/cli-args.js +18 -2
- package/lib/util/cli-args.js.map +1 -1
- package/lib/util/prompt.d.ts +17 -0
- package/lib/util/prompt.js +25 -0
- package/lib/util/prompt.js.map +1 -0
- package/lib/util/read-stdin-json.d.ts +22 -0
- package/lib/util/read-stdin-json.js +42 -0
- package/lib/util/read-stdin-json.js.map +1 -0
- package/lib/util/request-seam-api.d.ts +5 -2
- package/lib/util/request-seam-api.js +13 -15
- package/lib/util/request-seam-api.js.map +1 -1
- package/lib/util/with-loading.js +6 -1
- package/lib/util/with-loading.js.map +1 -1
- package/lib/version.d.ts +1 -1
- package/lib/version.js +1 -1
- package/package.json +2 -1
- package/src/bin/cli.ts +100 -106
- package/src/lib/command-spec.ts +400 -0
- package/src/lib/completion/describe.ts +21 -0
- package/src/lib/completion/index.ts +82 -0
- package/src/lib/completion/render-bash.ts +125 -0
- package/src/lib/completion/render-fish.ts +80 -0
- package/src/lib/completion/render-zsh.ts +157 -0
- package/src/lib/get-response-key.ts +25 -0
- package/src/lib/interact-for-action-attempt-poll.ts +4 -3
- package/src/lib/interact-for-array.ts +9 -7
- package/src/lib/interact-for-blueprint-object.ts +9 -8
- package/src/lib/interact-for-command-selection.ts +2 -3
- package/src/lib/interact-for-custom-metadata.ts +10 -8
- package/src/lib/interact-for-login.ts +8 -6
- package/src/lib/interact-for-resource.ts +2 -3
- package/src/lib/interact-for-server-selection.ts +7 -6
- package/src/lib/interact-for-timestamp.ts +2 -2
- package/src/lib/interact-for-use-remote-api-defs.ts +4 -4
- package/src/lib/interact-for-workspace-id.ts +2 -2
- package/src/lib/output/create-memory-output.ts +39 -0
- package/src/lib/output/create-output.ts +104 -0
- package/src/lib/output/get-output.ts +24 -0
- package/src/lib/output/resolve-output-format.ts +33 -0
- package/src/lib/output/select-response-payload.ts +56 -0
- package/src/lib/render-help.ts +197 -0
- package/src/lib/util/cli-args.ts +32 -2
- package/src/lib/util/prompt.ts +38 -0
- package/src/lib/util/read-stdin-json.ts +59 -0
- package/src/lib/util/request-seam-api.ts +24 -20
- package/src/lib/util/with-loading.ts +9 -1
- package/src/lib/version.ts +1 -1
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { inspect } from 'node:util'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal writable surface needed by {@link Output}.
|
|
5
|
+
*
|
|
6
|
+
* Both `process.stdout` and an in-memory buffer satisfy this,
|
|
7
|
+
* which is what makes output testable.
|
|
8
|
+
*/
|
|
9
|
+
export interface OutputStream {
|
|
10
|
+
write: (chunk: string) => unknown
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* `json` is machine readable: only {@link Output.data} produces output.
|
|
15
|
+
* `text` is human readable: data is pretty printed and may be colorized.
|
|
16
|
+
*/
|
|
17
|
+
export type OutputFormat = 'json' | 'text'
|
|
18
|
+
|
|
19
|
+
export interface Output {
|
|
20
|
+
readonly format: OutputFormat
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The result of a command, e.g., an API response.
|
|
24
|
+
*
|
|
25
|
+
* This is the only thing ever written to stdout,
|
|
26
|
+
* so it is safe to pipe into another program.
|
|
27
|
+
*/
|
|
28
|
+
data: (value: unknown) => void
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A plain text command result, e.g., the version or the help guide.
|
|
32
|
+
*
|
|
33
|
+
* Written to stdout verbatim in every format: these results are already
|
|
34
|
+
* a single value, so encoding them as JSON would only make them harder
|
|
35
|
+
* to consume from a pipe.
|
|
36
|
+
*/
|
|
37
|
+
text: (value: string) => void
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Human facing progress, context, and confirmations.
|
|
41
|
+
*
|
|
42
|
+
* Written to stderr and suppressed entirely in the json format.
|
|
43
|
+
*/
|
|
44
|
+
info: (message?: string) => void
|
|
45
|
+
|
|
46
|
+
/** Human facing warning. Written to stderr in every format. */
|
|
47
|
+
warn: (message: string) => void
|
|
48
|
+
|
|
49
|
+
/** Human facing error. Written to stderr in every format. */
|
|
50
|
+
error: (message: string) => void
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface CreateOutputOptions {
|
|
54
|
+
format?: OutputFormat
|
|
55
|
+
stdout?: OutputStream
|
|
56
|
+
stderr?: OutputStream
|
|
57
|
+
/** Colorize pretty printed data. Never applied to the json format. */
|
|
58
|
+
colors?: boolean
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const createOutput = ({
|
|
62
|
+
format = 'text',
|
|
63
|
+
stdout = process.stdout,
|
|
64
|
+
stderr = process.stderr,
|
|
65
|
+
colors = false,
|
|
66
|
+
}: CreateOutputOptions = {}): Output => {
|
|
67
|
+
const isJson = format === 'json'
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
format,
|
|
71
|
+
|
|
72
|
+
data: (value: unknown): void => {
|
|
73
|
+
if (value === undefined) return
|
|
74
|
+
stdout.write(`${formatData(value, format, colors)}\n`)
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
text: (value: string): void => {
|
|
78
|
+
stdout.write(`${value}\n`)
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
info: (message = ''): void => {
|
|
82
|
+
if (isJson) return
|
|
83
|
+
stderr.write(`${message}\n`)
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
warn: (message: string): void => {
|
|
87
|
+
stderr.write(`${message}\n`)
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
error: (message: string): void => {
|
|
91
|
+
stderr.write(`${message}\n`)
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const formatData = (
|
|
97
|
+
value: unknown,
|
|
98
|
+
format: OutputFormat,
|
|
99
|
+
colors: boolean,
|
|
100
|
+
): string => {
|
|
101
|
+
if (format === 'json') return JSON.stringify(value, null, 2)
|
|
102
|
+
if (typeof value === 'string') return value
|
|
103
|
+
return inspect(value, { depth: null, colors })
|
|
104
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { createOutput, type Output } from './create-output.js'
|
|
2
|
+
|
|
3
|
+
let output: Output | null = null
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The output used by the CLI.
|
|
7
|
+
*
|
|
8
|
+
* Defaults to a `text` output bound to the real process streams,
|
|
9
|
+
* so importing modules never write to stdout by accident.
|
|
10
|
+
*/
|
|
11
|
+
export const getOutput = (): Output => {
|
|
12
|
+
output ??= createOutput()
|
|
13
|
+
return output
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Replace the output, e.g., once flags are parsed, or from a test. */
|
|
17
|
+
export const setOutput = (nextOutput: Output): void => {
|
|
18
|
+
output = nextOutput
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Restore the default output. Intended for tests. */
|
|
22
|
+
export const resetOutput = (): void => {
|
|
23
|
+
output = null
|
|
24
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { OutputFormat } from './create-output.js'
|
|
2
|
+
|
|
3
|
+
export interface ResolveOutputFormatOptions {
|
|
4
|
+
/** Whether stdout is a terminal. */
|
|
5
|
+
isTty?: boolean
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Whether to write machine readable output.
|
|
10
|
+
*
|
|
11
|
+
* An explicit `--json` or `--no-json` wins, otherwise the CLI writes JSON
|
|
12
|
+
* whenever stdout is piped or redirected, and pretty output at a terminal.
|
|
13
|
+
*
|
|
14
|
+
* This reads the arguments rather than the parsed args because `--json` is
|
|
15
|
+
* declared as a boolean flag, so that it never consumes the argument after
|
|
16
|
+
* it, and a boolean cannot tell `--no-json` apart from not passing anything.
|
|
17
|
+
*/
|
|
18
|
+
export const resolveOutputFormat = (
|
|
19
|
+
argv: string[],
|
|
20
|
+
{ isTty = false }: ResolveOutputFormatOptions = {},
|
|
21
|
+
): OutputFormat => {
|
|
22
|
+
const flag = argv.filter((arg) => arg === '--json' || arg === '--no-json')
|
|
23
|
+
|
|
24
|
+
// The last one wins, matching how the argument parser resolves repeats.
|
|
25
|
+
switch (flag[flag.length - 1]) {
|
|
26
|
+
case '--json':
|
|
27
|
+
return 'json'
|
|
28
|
+
case '--no-json':
|
|
29
|
+
return 'text'
|
|
30
|
+
default:
|
|
31
|
+
return isTty ? 'text' : 'json'
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Top level response fields that are transport details,
|
|
3
|
+
* not part of the result the CLI reports.
|
|
4
|
+
*/
|
|
5
|
+
const metaKeys = new Set(['ok'])
|
|
6
|
+
|
|
7
|
+
const paginationKey = 'pagination'
|
|
8
|
+
const errorKey = 'error'
|
|
9
|
+
|
|
10
|
+
export interface SelectResponsePayloadOptions {
|
|
11
|
+
/**
|
|
12
|
+
* The response key for the endpoint, e.g., `devices` for `/devices/list`,
|
|
13
|
+
* usually taken from the API blueprint.
|
|
14
|
+
*
|
|
15
|
+
* When omitted, every top level field except {@link metaKeys} is kept.
|
|
16
|
+
*/
|
|
17
|
+
responseKey?: string | null | undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Reduce an API response body to the response key and pagination.
|
|
22
|
+
*
|
|
23
|
+
* The CLI never reports other top level fields: they are details of the
|
|
24
|
+
* transport, so including them would leak into anything parsing stdout.
|
|
25
|
+
*/
|
|
26
|
+
export const selectResponsePayload = (
|
|
27
|
+
data: unknown,
|
|
28
|
+
{ responseKey }: SelectResponsePayloadOptions = {},
|
|
29
|
+
): unknown => {
|
|
30
|
+
if (!isRecord(data)) return data
|
|
31
|
+
|
|
32
|
+
if (errorKey in data) {
|
|
33
|
+
return { [errorKey]: data[errorKey] }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const keys =
|
|
37
|
+
responseKey != null && responseKey in data
|
|
38
|
+
? [responseKey]
|
|
39
|
+
: Object.keys(data).filter(
|
|
40
|
+
(key) => !metaKeys.has(key) && key !== paginationKey,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
const payload: Record<string, unknown> = {}
|
|
44
|
+
for (const key of keys) {
|
|
45
|
+
payload[key] = data[key]
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (paginationKey in data) {
|
|
49
|
+
payload[paginationKey] = data[paginationKey]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return payload
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
56
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import commandLineUsage, { type Section } from 'command-line-usage'
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
type CommandDefinition,
|
|
5
|
+
type CommandFlag,
|
|
6
|
+
type CommandGroup,
|
|
7
|
+
type CommandSpec,
|
|
8
|
+
findCommand,
|
|
9
|
+
findGroup,
|
|
10
|
+
} from './command-spec.js'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Render the help guide for a command path, or `null` when no command or
|
|
14
|
+
* group goes by that path.
|
|
15
|
+
*
|
|
16
|
+
* An empty path is the guide for `seam` itself.
|
|
17
|
+
*/
|
|
18
|
+
export const renderHelp = (
|
|
19
|
+
path: string[],
|
|
20
|
+
spec: CommandSpec,
|
|
21
|
+
): string | null => {
|
|
22
|
+
const group = findGroup(spec, path)
|
|
23
|
+
if (group != null) return commandLineUsage(groupSections(group, spec))
|
|
24
|
+
|
|
25
|
+
const command = findCommand(spec, path)
|
|
26
|
+
if (command != null) return commandLineUsage(commandSections(command, spec))
|
|
27
|
+
|
|
28
|
+
return null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const overview =
|
|
32
|
+
'Every seam command runs as soon as every required property is given, and otherwise prompts you for what is missing with helpful suggestions. Pass -i to always review properties first, or -y to never be prompted.'
|
|
33
|
+
|
|
34
|
+
const outputSection = {
|
|
35
|
+
header: 'Output',
|
|
36
|
+
content: [
|
|
37
|
+
'Only the response is written to stdout, so it is safe to pipe. Prompts, progress, and other information are written to stderr.',
|
|
38
|
+
'The response is trimmed to the response key and pagination.',
|
|
39
|
+
'Request params may be piped or redirected in as a JSON object. Params given as arguments win over params read from stdin.',
|
|
40
|
+
],
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const examples = [
|
|
44
|
+
{ name: 'seam', summary: 'Interactively select commands to execute.' },
|
|
45
|
+
{ name: 'seam login', summary: 'Login to Seam.' },
|
|
46
|
+
{ name: 'seam wizard', summary: 'Set up Seam in the current project.' },
|
|
47
|
+
{ name: 'seam select workspace', summary: 'Select your workspace.' },
|
|
48
|
+
{
|
|
49
|
+
name: 'seam connect-webviews create',
|
|
50
|
+
summary: 'Create a connect webview to connect devices.',
|
|
51
|
+
},
|
|
52
|
+
{ name: 'seam devices list', summary: 'List devices in your workspace.' },
|
|
53
|
+
{
|
|
54
|
+
name: 'seam devices list {bold --interactive}',
|
|
55
|
+
summary: 'Review and edit filters before listing devices.',
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
name: 'seam devices list {bold --non-interactive}',
|
|
59
|
+
summary: 'List devices, failing instead of prompting.',
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: 'seam locks unlock-door {bold --device-id} $MY_DOOR',
|
|
63
|
+
summary: 'Unlock a lock.',
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
name: "seam access-codes create {bold --code} '1234' {bold --name} 'My Code'",
|
|
67
|
+
summary: 'Create an access code.',
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
name: 'seam devices list > devices.json',
|
|
71
|
+
summary: 'Write the response to a file as JSON.',
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
name: 'cat params.json | seam locks unlock-door',
|
|
75
|
+
summary: 'Pipe request params in as JSON.',
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
name: 'seam completion bash',
|
|
79
|
+
summary: 'Print a shell completion script for bash, fish, or zsh.',
|
|
80
|
+
},
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
const groupSections = (group: CommandGroup, spec: CommandSpec): Section[] => {
|
|
84
|
+
const isRoot = group.path.length === 0
|
|
85
|
+
const name = ['seam', ...group.path].join(' ')
|
|
86
|
+
|
|
87
|
+
return [
|
|
88
|
+
isRoot
|
|
89
|
+
? { header: 'Seam CLI', content: overview }
|
|
90
|
+
: { header: name, content: `Commands under ${name}.` },
|
|
91
|
+
{ header: 'Usage', content: `${name} <command> [options]` },
|
|
92
|
+
...commandSectionsForGroup(group, isRoot),
|
|
93
|
+
optionSection(spec.globalFlags),
|
|
94
|
+
...(isRoot
|
|
95
|
+
? [outputSection, { header: 'Command List Examples', content: examples }]
|
|
96
|
+
: []),
|
|
97
|
+
{ content: `Run '${name} <command> --help' to see a command in detail.` },
|
|
98
|
+
]
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const commandSectionsForGroup = (
|
|
102
|
+
group: CommandGroup,
|
|
103
|
+
isRoot: boolean,
|
|
104
|
+
): Section[] => {
|
|
105
|
+
const content = (subcommands: CommandGroup['subcommands']) =>
|
|
106
|
+
subcommands.map(({ name, description }) => ({ name, summary: description }))
|
|
107
|
+
|
|
108
|
+
// The root guide separates the commands of the CLI itself from the commands
|
|
109
|
+
// that call the Seam API. Anywhere deeper the split adds nothing: a group
|
|
110
|
+
// holds commands of one kind.
|
|
111
|
+
if (!isRoot) {
|
|
112
|
+
return [{ header: 'Commands', content: content(group.subcommands) }]
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const cli = group.subcommands.filter(({ kind }) => kind === 'cli')
|
|
116
|
+
const api = group.subcommands.filter(({ kind }) => kind === 'api')
|
|
117
|
+
|
|
118
|
+
return [
|
|
119
|
+
{ header: 'Commands', content: content(cli) },
|
|
120
|
+
{ header: 'API Commands', content: content(api) },
|
|
121
|
+
].filter((section) => section.content.length > 0)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const commandSections = (
|
|
125
|
+
command: CommandDefinition,
|
|
126
|
+
spec: CommandSpec,
|
|
127
|
+
): Section[] => {
|
|
128
|
+
const name = ['seam', ...command.path].join(' ')
|
|
129
|
+
const hasFlags = command.flags.length > 0
|
|
130
|
+
|
|
131
|
+
return [
|
|
132
|
+
{
|
|
133
|
+
header: name,
|
|
134
|
+
content: [command.title, command.description].filter(
|
|
135
|
+
(line) => line !== '',
|
|
136
|
+
),
|
|
137
|
+
},
|
|
138
|
+
{ header: 'Usage', content: `${name} [options]` },
|
|
139
|
+
// The command's own parameters are what the request is made of, so keep
|
|
140
|
+
// them apart from the options every seam command takes.
|
|
141
|
+
...(hasFlags ? [optionSection(command.flags, 'Parameters')] : []),
|
|
142
|
+
optionSection(spec.globalFlags),
|
|
143
|
+
...(hasFlags
|
|
144
|
+
? [
|
|
145
|
+
{
|
|
146
|
+
content:
|
|
147
|
+
'Any required parameter left out is prompted for interactively.',
|
|
148
|
+
},
|
|
149
|
+
]
|
|
150
|
+
: []),
|
|
151
|
+
]
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const optionSection = (flags: CommandFlag[], header = 'Options'): Section => ({
|
|
155
|
+
header,
|
|
156
|
+
optionList: flags.map(toOptionDefinition),
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
const maxDocumentedValues = 8
|
|
160
|
+
|
|
161
|
+
interface OptionDefinition {
|
|
162
|
+
name: string
|
|
163
|
+
alias?: string
|
|
164
|
+
description: string
|
|
165
|
+
type: typeof Boolean | typeof String
|
|
166
|
+
typeLabel?: string
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const toOptionDefinition = (flag: CommandFlag): OptionDefinition => {
|
|
170
|
+
const description = [
|
|
171
|
+
flag.isRequired ? '{bold [required]}' : '',
|
|
172
|
+
flag.description,
|
|
173
|
+
describeValues(flag),
|
|
174
|
+
]
|
|
175
|
+
.filter((part) => part !== '')
|
|
176
|
+
.join(' ')
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
// command-line-usage renders a nameless option as the short form alone.
|
|
180
|
+
name: flag.long ?? '',
|
|
181
|
+
...(flag.short == null ? {} : { alias: flag.short }),
|
|
182
|
+
// A flag with no value must be typed as a boolean, or the guide labels it
|
|
183
|
+
// as taking a string.
|
|
184
|
+
type: flag.takesValue ? String : Boolean,
|
|
185
|
+
...(flag.takesValue ? { typeLabel: '{underline value}' } : {}),
|
|
186
|
+
description,
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const describeValues = (flag: CommandFlag): string => {
|
|
191
|
+
if (flag.values.length === 0) return ''
|
|
192
|
+
|
|
193
|
+
const shown = flag.values.slice(0, maxDocumentedValues).join(', ')
|
|
194
|
+
const rest = flag.values.length - maxDocumentedValues
|
|
195
|
+
|
|
196
|
+
return rest > 0 ? `One of: ${shown}, and ${rest} more.` : `One of: ${shown}.`
|
|
197
|
+
}
|
package/src/lib/util/cli-args.ts
CHANGED
|
@@ -23,6 +23,20 @@ export const interactivityFlags: string[] = [
|
|
|
23
23
|
'i',
|
|
24
24
|
]
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Argument keys that configure the CLI itself
|
|
28
|
+
* and are therefore never sent as command parameters.
|
|
29
|
+
*/
|
|
30
|
+
export const cliFlags: string[] = [
|
|
31
|
+
...interactivityFlags,
|
|
32
|
+
'h',
|
|
33
|
+
'help',
|
|
34
|
+
'json',
|
|
35
|
+
'remote_api_defs',
|
|
36
|
+
'update',
|
|
37
|
+
'version',
|
|
38
|
+
]
|
|
39
|
+
|
|
26
40
|
/**
|
|
27
41
|
* Thrown when the CLI needs input it cannot prompt for.
|
|
28
42
|
*/
|
|
@@ -33,13 +47,27 @@ export class NonInteractiveError extends Error {
|
|
|
33
47
|
export const parseCliArgs = (argv: string[]): ParsedArgs =>
|
|
34
48
|
parseArgs(argv, {
|
|
35
49
|
string: ['code'],
|
|
36
|
-
boolean: ['non-interactive', 'interactive'],
|
|
50
|
+
boolean: ['non-interactive', 'interactive', 'json'],
|
|
37
51
|
// Deliberately not aliased to -n, which is reserved for a future
|
|
38
52
|
// --dry-run flag.
|
|
39
53
|
alias: { 'non-interactive': 'y', interactive: 'i' },
|
|
40
54
|
})
|
|
41
55
|
|
|
42
|
-
export
|
|
56
|
+
export interface GetInteractivityOptions {
|
|
57
|
+
/**
|
|
58
|
+
* Whether there is a terminal to prompt on.
|
|
59
|
+
*
|
|
60
|
+
* When there is not, the CLI cannot ask for anything, so it behaves as
|
|
61
|
+
* though `--non-interactive` was given rather than waiting on a prompt
|
|
62
|
+
* nobody can answer.
|
|
63
|
+
*/
|
|
64
|
+
canPrompt?: boolean
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const getInteractivity = (
|
|
68
|
+
args: ParsedArgs,
|
|
69
|
+
{ canPrompt = true }: GetInteractivityOptions = {},
|
|
70
|
+
): Interactivity => {
|
|
43
71
|
const isNonInteractive =
|
|
44
72
|
args['non_interactive'] === true || args['y'] === true
|
|
45
73
|
const isInteractive = args['interactive'] === true || args['i'] === true
|
|
@@ -50,7 +78,9 @@ export const getInteractivity = (args: ParsedArgs): Interactivity => {
|
|
|
50
78
|
)
|
|
51
79
|
}
|
|
52
80
|
if (isNonInteractive) return 'non-interactive'
|
|
81
|
+
// An explicit --interactive still asks, and fails loudly if it cannot.
|
|
53
82
|
if (isInteractive) return 'interactive'
|
|
83
|
+
if (!canPrompt) return 'non-interactive'
|
|
54
84
|
return 'auto'
|
|
55
85
|
}
|
|
56
86
|
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import prompts, { type Answers, type Options, type PromptObject } from 'prompts'
|
|
2
|
+
|
|
3
|
+
import { NonInteractiveError } from './cli-args.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Whether the CLI can ask the user a question.
|
|
7
|
+
*
|
|
8
|
+
* Prompts read raw keypresses and render an interface, so they need a
|
|
9
|
+
* terminal on both ends: when stdin is a pipe or a file it holds request
|
|
10
|
+
* params, not answers, and when stderr is redirected nobody sees the
|
|
11
|
+
* question.
|
|
12
|
+
*/
|
|
13
|
+
export const canPrompt = (): boolean =>
|
|
14
|
+
process.stdin.isTTY === true && process.stderr.isTTY === true
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Ask the user a question.
|
|
18
|
+
*
|
|
19
|
+
* Prompts are rendered to stderr: a selection is not a command result,
|
|
20
|
+
* so it must not end up in stdout when the CLI is piped.
|
|
21
|
+
*/
|
|
22
|
+
export const prompt = async <T extends string = string>(
|
|
23
|
+
questions: PromptObject<T> | Array<PromptObject<T>>,
|
|
24
|
+
options?: Options,
|
|
25
|
+
): Promise<Answers<T>> => {
|
|
26
|
+
if (!canPrompt()) {
|
|
27
|
+
throw new NonInteractiveError(
|
|
28
|
+
'Cannot prompt without a terminal: pass the missing arguments, or pipe them in as JSON',
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const questionList = Array.isArray(questions) ? questions : [questions]
|
|
33
|
+
|
|
34
|
+
return await prompts(
|
|
35
|
+
questionList.map((question) => ({ ...question, stdout: process.stderr })),
|
|
36
|
+
options,
|
|
37
|
+
)
|
|
38
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { Readable } from 'node:stream'
|
|
2
|
+
|
|
3
|
+
export interface StdinLike extends AsyncIterable<string | Buffer> {
|
|
4
|
+
isTTY?: boolean | undefined
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Read request params piped into the CLI, e.g.,
|
|
9
|
+
*
|
|
10
|
+
* ```
|
|
11
|
+
* $ echo '{"device_id": "..."}' | seam locks unlock-door --json
|
|
12
|
+
* $ seam locks unlock-door --json < params.json
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* Returns null when stdin is a terminal or is empty,
|
|
16
|
+
* so an interactive session is never blocked waiting for input.
|
|
17
|
+
*/
|
|
18
|
+
export const readStdinJson = async (
|
|
19
|
+
stdin: StdinLike | Readable = process.stdin,
|
|
20
|
+
): Promise<Record<string, unknown> | null> => {
|
|
21
|
+
if ((stdin as StdinLike).isTTY ?? false) return null
|
|
22
|
+
|
|
23
|
+
let raw = ''
|
|
24
|
+
for await (const chunk of stdin) {
|
|
25
|
+
raw += typeof chunk === 'string' ? chunk : chunk.toString('utf8')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return parseJsonParams(raw, 'stdin')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Parse JSON request params, e.g., from stdin or `--json '{"limit": 2}'`.
|
|
33
|
+
*
|
|
34
|
+
* Returns null when there is nothing to parse.
|
|
35
|
+
*/
|
|
36
|
+
export const parseJsonParams = (
|
|
37
|
+
raw: string,
|
|
38
|
+
source: string,
|
|
39
|
+
): Record<string, unknown> | null => {
|
|
40
|
+
const trimmed = raw.trim()
|
|
41
|
+
if (trimmed === '') return null
|
|
42
|
+
|
|
43
|
+
let parsed: unknown
|
|
44
|
+
try {
|
|
45
|
+
parsed = JSON.parse(trimmed)
|
|
46
|
+
} catch (error) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
`Could not parse JSON from ${source}: ${(error as Error).message}`,
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
`Expected a JSON object of request params from ${source}, got ${Array.isArray(parsed) ? 'an array' : typeof parsed}`,
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return parsed as Record<string, unknown>
|
|
59
|
+
}
|
|
@@ -1,19 +1,29 @@
|
|
|
1
1
|
import chalk from 'chalk'
|
|
2
2
|
|
|
3
3
|
import { getSeam } from 'lib/get-seam.js'
|
|
4
|
+
import { getOutput } from 'lib/output/get-output.js'
|
|
5
|
+
import { selectResponsePayload } from 'lib/output/select-response-payload.js'
|
|
4
6
|
|
|
5
7
|
import { withLoading } from './with-loading.js'
|
|
6
8
|
|
|
9
|
+
export interface RequestSeamApiOptions {
|
|
10
|
+
path: string
|
|
11
|
+
params: Record<string, any>
|
|
12
|
+
/** Response key for the endpoint, used to trim the reported payload. */
|
|
13
|
+
responseKey?: string | null | undefined
|
|
14
|
+
}
|
|
15
|
+
|
|
7
16
|
export const RequestSeamApi = async ({
|
|
8
17
|
path,
|
|
9
18
|
params,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
params: Record<string, any>
|
|
13
|
-
}) => {
|
|
19
|
+
responseKey,
|
|
20
|
+
}: RequestSeamApiOptions) => {
|
|
14
21
|
const seam = await getSeam()
|
|
22
|
+
const output = getOutput()
|
|
15
23
|
|
|
16
|
-
|
|
24
|
+
output.info(`\n${chalk.green(path)}`)
|
|
25
|
+
output.info(`Request Params:`)
|
|
26
|
+
output.info(formatParams(params))
|
|
17
27
|
|
|
18
28
|
const response = await withLoading('Making request...', () =>
|
|
19
29
|
seam.client.post(path, params, {
|
|
@@ -21,23 +31,17 @@ export const RequestSeamApi = async ({
|
|
|
21
31
|
}),
|
|
22
32
|
)
|
|
23
33
|
|
|
24
|
-
logResponse(response)
|
|
25
|
-
|
|
26
|
-
return response
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const logResponse = (response: { status: number; data: unknown }) => {
|
|
30
34
|
if (response.status >= 400) {
|
|
31
|
-
|
|
35
|
+
output.warn(chalk.red(`[${response.status}]`))
|
|
36
|
+
process.exitCode = 1
|
|
32
37
|
} else {
|
|
33
|
-
|
|
38
|
+
output.info(chalk.green(`[${response.status}]`))
|
|
34
39
|
}
|
|
35
|
-
console.dir(response.data, { depth: null })
|
|
36
|
-
console.log('\n')
|
|
37
|
-
}
|
|
38
40
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
console.log(params)
|
|
41
|
+
output.data(selectResponsePayload(response.data, { responseKey }))
|
|
42
|
+
|
|
43
|
+
return response
|
|
43
44
|
}
|
|
45
|
+
|
|
46
|
+
const formatParams = (params: Record<string, any>): string =>
|
|
47
|
+
JSON.stringify(params, null, 2)
|
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { createSpinner } from 'nanospinner'
|
|
2
2
|
|
|
3
|
+
import { getOutput } from 'lib/output/get-output.js'
|
|
4
|
+
|
|
3
5
|
export const withLoading = async <T>(
|
|
4
6
|
message: string,
|
|
5
7
|
fn: () => Promise<T>,
|
|
6
8
|
): Promise<T> => {
|
|
7
|
-
|
|
9
|
+
if (!shouldSpin()) return await fn()
|
|
10
|
+
|
|
11
|
+
// Progress is not a command result, so it is rendered to stderr.
|
|
12
|
+
const spinner = createSpinner(message, { stream: process.stderr }).start()
|
|
8
13
|
try {
|
|
9
14
|
const result = await fn()
|
|
10
15
|
spinner.success()
|
|
@@ -14,3 +19,6 @@ export const withLoading = async <T>(
|
|
|
14
19
|
throw error
|
|
15
20
|
}
|
|
16
21
|
}
|
|
22
|
+
|
|
23
|
+
const shouldSpin = (): boolean =>
|
|
24
|
+
getOutput().format === 'text' && process.stderr.isTTY === true
|
package/src/lib/version.ts
CHANGED