@gheima/cli 0.4.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/dist/client.js ADDED
@@ -0,0 +1,11 @@
1
+ import { GheimaClient } from '@gheima/sdk';
2
+ import { resolveAuth } from './config.js';
3
+ /** Build an SDK client from the resolved auth, or exit with a helpful message. */
4
+ export function makeClient(opts) {
5
+ const auth = resolveAuth(opts);
6
+ if (!auth) {
7
+ process.stderr.write('Not authenticated. Run `gheima login`, set GHEIMA_API_KEY, or pass --key <key>.\n');
8
+ process.exit(1);
9
+ }
10
+ return new GheimaClient({ apiKey: auth.apiKey, baseUrl: auth.url });
11
+ }
@@ -0,0 +1,35 @@
1
+ // Shell-completion scripts. `gheima completion <shell>` prints one for the user to
2
+ // source (e.g. `gheima completion zsh > ~/.gheima-completion.zsh`).
3
+ //
4
+ // The command list is passed in from the program itself rather than duplicated here —
5
+ // a hand-maintained copy silently goes stale every time a command group is added.
6
+ export function completionScript(shell, commands) {
7
+ const names = [...new Set(commands)].filter((c) => /^[\w:-]+$/.test(c)).sort();
8
+ const cmds = names.join(' ');
9
+ switch (shell) {
10
+ case 'zsh':
11
+ return `#compdef gheima
12
+ _gheima() {
13
+ local -a cmds
14
+ cmds=(${cmds})
15
+ _arguments '1: :->cmd' '*: :->args'
16
+ case $state in
17
+ cmd) compadd $cmds ;;
18
+ esac
19
+ }
20
+ _gheima "$@"
21
+ `;
22
+ case 'fish':
23
+ return (names.map((c) => `complete -c gheima -n __fish_use_subcommand -a ${c}`).join('\n') + '\n');
24
+ case 'bash':
25
+ default:
26
+ return `_gheima_completion() {
27
+ local cur="\${COMP_WORDS[COMP_CWORD]}"
28
+ if [ "$COMP_CWORD" -eq 1 ]; then
29
+ COMPREPLY=( $(compgen -W "${cmds}" -- "$cur") )
30
+ fi
31
+ }
32
+ complete -F _gheima_completion gheima
33
+ `;
34
+ }
35
+ }
package/dist/config.js ADDED
@@ -0,0 +1,75 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync } from 'node:fs';
4
+ function configDir() {
5
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
6
+ return join(base, 'gheima');
7
+ }
8
+ export function configPath() {
9
+ return join(configDir(), 'config.json');
10
+ }
11
+ export function loadConfig() {
12
+ const path = configPath();
13
+ if (!existsSync(path))
14
+ return { profiles: {} };
15
+ try {
16
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
17
+ return { current: parsed.current, profiles: parsed.profiles ?? {} };
18
+ }
19
+ catch {
20
+ return { profiles: {} };
21
+ }
22
+ }
23
+ export function saveConfig(config) {
24
+ const dir = configDir();
25
+ // Owner-only from the moment it exists; `mode` is ignored for a directory that is
26
+ // already there, so chmod covers a dir created by an older version.
27
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
28
+ const path = configPath();
29
+ // Secrets live here. `mode` applies only when the file is created, so an existing
30
+ // file keeps whatever it had — chmod after the write covers both cases, and creating
31
+ // it at 0600 closes the window where a fresh file sits world-readable.
32
+ writeFileSync(path, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
33
+ try {
34
+ chmodSync(dir, 0o700);
35
+ chmodSync(path, 0o600);
36
+ }
37
+ catch {
38
+ /* best effort (e.g. Windows) */
39
+ }
40
+ }
41
+ export function setProfile(name, profile, makeCurrent = true) {
42
+ const config = loadConfig();
43
+ config.profiles[name] = profile;
44
+ if (makeCurrent)
45
+ config.current = name;
46
+ saveConfig(config);
47
+ }
48
+ export function removeProfile(name) {
49
+ const config = loadConfig();
50
+ if (!config.profiles[name])
51
+ return false;
52
+ delete config.profiles[name];
53
+ if (config.current === name)
54
+ config.current = Object.keys(config.profiles)[0];
55
+ saveConfig(config);
56
+ return true;
57
+ }
58
+ /**
59
+ * Resolve the API key + base URL, in precedence order:
60
+ * --key flag > GHEIMA_API_KEY env > stored profile (--profile or current).
61
+ * URL precedence: --url > GHEIMA_URL > profile url.
62
+ */
63
+ export function resolveAuth(opts) {
64
+ const config = loadConfig();
65
+ const profileName = opts.profile || config.current || 'default';
66
+ const profile = config.profiles[profileName];
67
+ const url = opts.url || process.env.GHEIMA_URL || profile?.url;
68
+ if (opts.key)
69
+ return { apiKey: opts.key, url, source: 'flag' };
70
+ if (process.env.GHEIMA_API_KEY)
71
+ return { apiKey: process.env.GHEIMA_API_KEY, url, source: 'env' };
72
+ if (profile?.apiKey)
73
+ return { apiKey: profile.apiKey, url, source: 'profile', profile: profileName };
74
+ return null;
75
+ }
@@ -0,0 +1,207 @@
1
+ import { z } from 'zod';
2
+ import { getOp, ops, returnsSecret } from '@gheima/contracts';
3
+ import { Transport } from '@gheima/sdk';
4
+ import { resolveAuth } from './config.js';
5
+ /**
6
+ * Commands built from the contract registry.
7
+ *
8
+ * The hand-written commands own the experience people actually use — they resolve a service
9
+ * by name, print tables, stream logs, prompt before something irreversible. This does not
10
+ * replace them. It FILLS THE GAPS: an operation whose command path is already taken by a
11
+ * hand-written command is skipped, so the generated layer shrinks as the crafted one grows,
12
+ * and the two can never collide.
13
+ *
14
+ * What it buys is that no operation is unreachable from a terminal. A capability added to
15
+ * the platform is callable here the moment it is declared, without waiting for someone to
16
+ * write a command for it.
17
+ */
18
+ /**
19
+ * Every command path already registered, as space-joined strings: `services list`.
20
+ *
21
+ * ALIASES count. `db` is registered with `databases` as an alias, and a walk that recorded
22
+ * only the primary name would happily try to add a second `databases` command — which
23
+ * commander rejects at startup, taking the whole CLI down rather than just that command.
24
+ */
25
+ function existingPaths(program) {
26
+ const paths = new Set();
27
+ const walk = (cmd, prefixes) => {
28
+ for (const child of cmd.commands) {
29
+ const names = [child.name(), ...child.aliases()];
30
+ const here = prefixes.flatMap((prefix) => names.map((n) => [...prefix, n]));
31
+ for (const path of here)
32
+ paths.add(path.join(' '));
33
+ walk(child, here);
34
+ }
35
+ };
36
+ walk(program, [[]]);
37
+ return paths;
38
+ }
39
+ /** A top-level command matching `name`, whether by its own name or an alias. */
40
+ function findGroup(program, name) {
41
+ return program.commands.find((c) => c.name() === name || c.aliases().includes(name));
42
+ }
43
+ /** `services.listEnv` → `['services', 'list-env']`. */
44
+ function commandPath(op) {
45
+ const [resource, action] = op.id.split('.');
46
+ const kebab = (s) => s.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
47
+ return [kebab(resource), kebab(action)];
48
+ }
49
+ /** The JSON Schema for one input part, or null when the op has none. */
50
+ function schemaOf(part) {
51
+ if (!part)
52
+ return null;
53
+ const json = z.toJSONSchema(part, { io: 'input', unrepresentable: 'any' });
54
+ return { properties: json.properties ?? {}, required: json.required ?? [] };
55
+ }
56
+ /** Turn a flag's string value into what the schema expects. */
57
+ function coerce(node, raw) {
58
+ switch (node?.type) {
59
+ case 'integer':
60
+ case 'number': {
61
+ const n = Number(raw);
62
+ return Number.isFinite(n) ? n : raw;
63
+ }
64
+ case 'boolean':
65
+ return raw !== 'false';
66
+ case 'array':
67
+ case 'object':
68
+ // A structured value has to arrive as JSON; anything else could not be expressed.
69
+ try {
70
+ return JSON.parse(raw);
71
+ }
72
+ catch {
73
+ throw new Error(`--${node.type === 'array' ? 'list' : 'object'} value must be JSON: ${raw}`);
74
+ }
75
+ default:
76
+ return raw;
77
+ }
78
+ }
79
+ async function invoke(op, input, opts) {
80
+ const auth = resolveAuth(opts);
81
+ if (!auth) {
82
+ process.stderr.write('Not authenticated. Run `gheima login`, set GHEIMA_API_KEY, or pass --key <key>.\n');
83
+ process.exit(1);
84
+ }
85
+ const transport = new Transport({ apiKey: auth.apiKey, baseUrl: auth.url });
86
+ const params = {};
87
+ const query = {};
88
+ const body = {};
89
+ for (const [key, value] of Object.entries(input)) {
90
+ if (value === undefined)
91
+ continue;
92
+ if (op.input?.params && key in op.input.params.shape)
93
+ params[key] = value;
94
+ else if (op.input?.query && key in op.input.query.shape)
95
+ query[key] = value;
96
+ else
97
+ body[key] = value;
98
+ }
99
+ const path = op.path.replace(/\{(\w+)\}/g, (_m, name) => {
100
+ const value = params[name];
101
+ if (value === undefined)
102
+ throw new Error(`missing <${name}>`);
103
+ return encodeURIComponent(String(value));
104
+ });
105
+ return transport.request(op.method, path, {
106
+ query: query,
107
+ ...(op.method === 'GET' || op.method === 'DELETE' ? {} : { body }),
108
+ });
109
+ }
110
+ /** Operations a terminal can drive: no streaming, no binary, no session-only. */
111
+ export function invocableOps() {
112
+ return ops.filter((op) => op.auth !== 'session' && op.kind !== 'stream' && op.kind !== 'binary');
113
+ }
114
+ /**
115
+ * Register a command for every operation whose path is still free, plus `gheima api` for
116
+ * calling anything by id.
117
+ */
118
+ export function registerGenerated(program, deps) {
119
+ const taken = existingPaths(program);
120
+ const groups = new Map();
121
+ for (const op of invocableOps()) {
122
+ const [group, action] = commandPath(op);
123
+ if (taken.has(`${group} ${action}`))
124
+ continue;
125
+ let parent = groups.get(group);
126
+ if (!parent) {
127
+ const existing = findGroup(program, group);
128
+ parent = existing ?? program.command(group).description(`${group} operations`);
129
+ groups.set(group, parent);
130
+ }
131
+ const paramSchema = schemaOf(op.input?.params);
132
+ const positional = Object.keys(paramSchema?.properties ?? {});
133
+ const signature = [action, ...positional.map((p) => `<${p}>`)].join(' ');
134
+ const cmd = parent.command(signature).description(op.summary);
135
+ const flagSchemas = [schemaOf(op.input?.query), schemaOf(op.input?.body)].filter(Boolean);
136
+ const flagNodes = new Map();
137
+ for (const schema of flagSchemas) {
138
+ for (const [name, node] of Object.entries(schema.properties)) {
139
+ flagNodes.set(name, node);
140
+ const required = schema.required.includes(name);
141
+ const describe = [node.description, required ? '(required)' : null]
142
+ .filter(Boolean)
143
+ .join(' ');
144
+ cmd.option(node.type === 'boolean' ? `--${name}` : `--${name} <value>`, describe || name);
145
+ }
146
+ }
147
+ if (op.mcp?.destructive)
148
+ cmd.option('-y, --yes', 'skip the confirmation');
149
+ cmd.action(async (...args) => {
150
+ // commander hands positionals, then the options object, then the Command.
151
+ const command = args[args.length - 1];
152
+ const options = args[args.length - 2];
153
+ const values = args.slice(0, positional.length);
154
+ const opts = command.optsWithGlobals();
155
+ try {
156
+ if (op.mcp?.destructive) {
157
+ await deps.confirmDestructive(opts.yes, `run ${op.id}`);
158
+ }
159
+ const input = {};
160
+ positional.forEach((name, i) => {
161
+ input[name] = values[i];
162
+ });
163
+ for (const [name, node] of flagNodes) {
164
+ const raw = options[name];
165
+ if (raw === undefined)
166
+ continue;
167
+ input[name] = typeof raw === 'string' ? coerce(node, raw) : raw;
168
+ }
169
+ deps.output(await invoke(op, input, opts), opts);
170
+ }
171
+ catch (e) {
172
+ deps.fail(e);
173
+ }
174
+ });
175
+ }
176
+ program
177
+ .command('api <operation> [input]')
178
+ .description('Call any API operation by id. `gheima api --list` shows them all.')
179
+ .option('--list', 'list every operation and exit')
180
+ .option('-y, --yes', 'skip the confirmation on a destructive operation')
181
+ .action(async (operation, input, _o, command) => {
182
+ const opts = command.optsWithGlobals();
183
+ try {
184
+ if (opts.list) {
185
+ for (const op of invocableOps()) {
186
+ const marks = [
187
+ op.access,
188
+ op.mcp?.destructive ? 'destructive' : null,
189
+ returnsSecret(op) ? 'returns credentials' : null,
190
+ ]
191
+ .filter(Boolean)
192
+ .join(', ');
193
+ process.stdout.write(`${op.id.padEnd(34)} ${op.summary} (${marks})\n`);
194
+ }
195
+ return;
196
+ }
197
+ const op = getOp(operation);
198
+ if (op.mcp?.destructive)
199
+ await deps.confirmDestructive(opts.yes, `run ${op.id}`);
200
+ const parsed = input ? JSON.parse(input) : {};
201
+ deps.output(await invoke(op, parsed, opts), opts);
202
+ }
203
+ catch (e) {
204
+ deps.fail(e);
205
+ }
206
+ });
207
+ }
package/dist/prompt.js ADDED
@@ -0,0 +1,66 @@
1
+ import { createInterface } from 'node:readline';
2
+ /** Prompt for a line of input on the terminal. */
3
+ export function prompt(question) {
4
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
5
+ return new Promise((resolve) => rl.question(question, (a) => {
6
+ rl.close();
7
+ resolve(a.trim());
8
+ }));
9
+ }
10
+ /** Yes/no confirmation (default No). Returns true only on an explicit y/yes. */
11
+ export async function confirm(question) {
12
+ const a = (await prompt(`${question} [y/N] `)).toLowerCase();
13
+ return a === 'y' || a === 'yes';
14
+ }
15
+ /** Prompt for a secret without echoing it to the terminal. */
16
+ export function promptHidden(question) {
17
+ return new Promise((resolve) => {
18
+ const stdin = process.stdin;
19
+ process.stderr.write(question);
20
+ if (!stdin.isTTY) {
21
+ // Non-interactive: read one line from the pipe.
22
+ const rl = createInterface({ input: stdin });
23
+ rl.question('', (a) => {
24
+ rl.close();
25
+ process.stderr.write('\n');
26
+ resolve(a.trim());
27
+ });
28
+ return;
29
+ }
30
+ const wasRaw = stdin.isRaw;
31
+ stdin.setRawMode(true);
32
+ stdin.resume();
33
+ let value = '';
34
+ const onData = (buf) => {
35
+ const code = buf[0];
36
+ if (code === 13 || code === 10) {
37
+ // Enter
38
+ stdin.setRawMode(wasRaw ?? false);
39
+ stdin.pause();
40
+ stdin.removeListener('data', onData);
41
+ process.stderr.write('\n');
42
+ resolve(value.trim());
43
+ }
44
+ else if (code === 3) {
45
+ // Ctrl-C
46
+ process.stderr.write('\n');
47
+ process.exit(130);
48
+ }
49
+ else if (code === 127 || code === 8) {
50
+ // Backspace
51
+ value = value.slice(0, -1);
52
+ }
53
+ else if (code === 27) {
54
+ // An escape sequence (arrow keys, Home/End, a bracketed-paste marker). Dropping
55
+ // it keeps stray control bytes out of the key the user thinks they pasted.
56
+ }
57
+ else {
58
+ // Strip control bytes: a stray one from a paste or a terminal would otherwise be
59
+ // silently baked into the key.
60
+ // eslint-disable-next-line no-control-regex
61
+ value += buf.toString('utf8').replace(/[\u0000-\u001f\u007f]/g, '');
62
+ }
63
+ };
64
+ stdin.on('data', onData);
65
+ });
66
+ }
package/dist/ui.js ADDED
@@ -0,0 +1,61 @@
1
+ // Tiny zero-dependency terminal helpers: colors, tables, spinner, JSON output.
2
+ const ESC = String.fromCharCode(27) + '[';
3
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
4
+ function wrap(code, s) {
5
+ return useColor ? `${ESC}${code}m${s}${ESC}0m` : s;
6
+ }
7
+ export const color = {
8
+ dim: (s) => wrap(2, s),
9
+ bold: (s) => wrap(1, s),
10
+ red: (s) => wrap(31, s),
11
+ green: (s) => wrap(32, s),
12
+ yellow: (s) => wrap(33, s),
13
+ cyan: (s) => wrap(36, s),
14
+ };
15
+ /** Print rows as an aligned text table with a dimmed header. */
16
+ export function table(headers, rows) {
17
+ const cells = rows.map((r) => r.map((c) => (c == null ? '' : String(c))));
18
+ const widths = headers.map((h, i) => Math.max(h.length, ...cells.map((r) => (r[i] ?? '').length), 0));
19
+ const line = (r) => r
20
+ .map((c, i) => c.padEnd(widths[i]))
21
+ .join(' ')
22
+ .trimEnd();
23
+ process.stdout.write(color.dim(line(headers)) + '\n');
24
+ for (const r of cells)
25
+ process.stdout.write(line(r) + '\n');
26
+ if (cells.length === 0)
27
+ process.stdout.write(color.dim('(none)') + '\n');
28
+ }
29
+ export function printJson(value) {
30
+ process.stdout.write(JSON.stringify(value, null, 2) + '\n');
31
+ }
32
+ const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
33
+ /** A minimal spinner; no-ops when stderr isn't a TTY (CI, pipes). */
34
+ export function spinner(text) {
35
+ if (!process.stderr.isTTY) {
36
+ process.stderr.write(text + '\n');
37
+ return { stop: () => { }, update: () => { } };
38
+ }
39
+ let i = 0;
40
+ let label = text;
41
+ const timer = setInterval(() => {
42
+ process.stderr.write(`\r${color.cyan(FRAMES[i++ % FRAMES.length])} ${label} `);
43
+ }, 80);
44
+ return {
45
+ update: (t) => {
46
+ label = t;
47
+ },
48
+ stop: (final) => {
49
+ clearInterval(timer);
50
+ process.stderr.write(`\r${ESC}K`);
51
+ if (final)
52
+ process.stderr.write(final + '\n');
53
+ },
54
+ };
55
+ }
56
+ export function success(msg) {
57
+ process.stderr.write(`${color.green('✓')} ${msg}\n`);
58
+ }
59
+ export function info(msg) {
60
+ process.stderr.write(`${color.dim(msg)}\n`);
61
+ }
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@gheima/cli",
3
+ "version": "0.4.0",
4
+ "description": "Command-line interface for the Gheima platform.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/gheima/gheima.git",
9
+ "directory": "packages/cli"
10
+ },
11
+ "homepage": "https://github.com/gheima/gheima/tree/main/packages/cli#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/gheima/gheima/issues"
14
+ },
15
+ "type": "module",
16
+ "bin": {
17
+ "gheima": "dist/cli.js"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "CHANGELOG.md",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "keywords": [
29
+ "gheima",
30
+ "paas",
31
+ "deploy",
32
+ "cli"
33
+ ],
34
+ "dependencies": {
35
+ "commander": "^12.1.0",
36
+ "zod": "^4.4.3",
37
+ "@gheima/contracts": "0.1.0",
38
+ "@gheima/sdk": "0.2.0"
39
+ },
40
+ "devDependencies": {
41
+ "@arethetypeswrong/cli": "^0.18.5",
42
+ "@types/node": "^22.10.6",
43
+ "eslint": "^9.18.0",
44
+ "publint": "^0.3.22",
45
+ "typescript": "^5.7.3",
46
+ "vitest": "^3.2.6",
47
+ "@gheima/config": "0.0.0"
48
+ },
49
+ "engines": {
50
+ "node": ">=18"
51
+ },
52
+ "scripts": {
53
+ "build": "tsc -p tsconfig.json",
54
+ "check:pack": "pnpm build && publint",
55
+ "typecheck": "tsc -p tsconfig.json --noEmit",
56
+ "test": "vitest run",
57
+ "clean": "rm -rf dist .turbo",
58
+ "lint": "eslint ."
59
+ }
60
+ }