@gheima/cli 0.5.0 → 0.6.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 +56 -0
- package/README.md +72 -26
- package/dist/bin.js +6 -0
- package/dist/cli.js +401 -82
- package/dist/client.js +18 -7
- package/dist/config.js +1 -1
- package/dist/device-login.js +8 -7
- package/dist/exit.js +49 -0
- package/dist/generated.js +44 -14
- package/dist/link.js +68 -0
- package/dist/prompt.js +11 -3
- package/dist/proxy.js +18 -0
- package/dist/ui.js +63 -4
- package/dist/update-check.js +107 -0
- package/dist/version.js +2 -0
- package/package.json +8 -6
package/dist/client.js
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
1
|
import { GheimaClient } from '@gheima/sdk';
|
|
2
2
|
import { resolveAuth } from './config.js';
|
|
3
|
-
|
|
4
|
-
export
|
|
3
|
+
import { NotAuthenticatedError } from './exit.js';
|
|
4
|
+
export { VERSION } from './version.js';
|
|
5
|
+
import { VERSION } from './version.js';
|
|
6
|
+
/** The platform records a request with this agent as the audit surface `CLI`, not `API`. */
|
|
7
|
+
export const USER_AGENT = `gheima-cli/${VERSION}`;
|
|
8
|
+
/** The resolved credential, or a NotAuthenticatedError (exit code 3). */
|
|
9
|
+
export function requireAuth(opts) {
|
|
5
10
|
const auth = resolveAuth(opts);
|
|
6
|
-
if (!auth)
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
+
if (!auth)
|
|
12
|
+
throw new NotAuthenticatedError();
|
|
13
|
+
return auth;
|
|
14
|
+
}
|
|
15
|
+
/** Transport settings every command shares, generated or hand-written. */
|
|
16
|
+
export function transportOptions(auth) {
|
|
17
|
+
return { apiKey: auth.apiKey, baseUrl: auth.url, headers: { 'user-agent': USER_AGENT } };
|
|
18
|
+
}
|
|
19
|
+
/** Build an SDK client from the resolved auth. */
|
|
20
|
+
export function makeClient(opts) {
|
|
21
|
+
return new GheimaClient(transportOptions(requireAuth(opts)));
|
|
11
22
|
}
|
package/dist/config.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { homedir } from 'node:os';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync } from 'node:fs';
|
|
4
|
-
function configDir() {
|
|
4
|
+
export function configDir() {
|
|
5
5
|
const base = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
|
|
6
6
|
return join(base, 'gheima');
|
|
7
7
|
}
|
package/dist/device-login.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { hostname, userInfo } from 'node:os';
|
|
3
|
+
import { apiBaseUrl } from '@gheima/sdk';
|
|
3
4
|
/** A name the approver will recognise as their own machine — or not, if it is not theirs. */
|
|
4
5
|
export function defaultClientName() {
|
|
5
6
|
let who = 'cli';
|
|
@@ -51,10 +52,10 @@ async function postJson(url, body, signal) {
|
|
|
51
52
|
});
|
|
52
53
|
}
|
|
53
54
|
export async function startDeviceLogin(baseUrl, clientName) {
|
|
54
|
-
const res = await postJson(`${baseUrl}/
|
|
55
|
+
const res = await postJson(`${apiBaseUrl(baseUrl)}/device/start`, { client_name: clientName });
|
|
55
56
|
if (!res.ok) {
|
|
56
57
|
const body = (await res.json().catch(() => ({})));
|
|
57
|
-
throw new Error(body.error?.message ?? `Could not start a
|
|
58
|
+
throw new Error(body.error?.message ?? `Could not start a sign-in (HTTP ${res.status}). Try again.`);
|
|
58
59
|
}
|
|
59
60
|
return (await res.json());
|
|
60
61
|
}
|
|
@@ -73,10 +74,10 @@ export async function pollForApproval(baseUrl, start, opts = {}) {
|
|
|
73
74
|
let intervalMs = Math.max(1, start.interval) * 1000;
|
|
74
75
|
for (;;) {
|
|
75
76
|
if (now() >= deadline) {
|
|
76
|
-
throw new Error('This
|
|
77
|
+
throw new Error('This sign-in expired before it was approved. Run `gheima login` again.');
|
|
77
78
|
}
|
|
78
79
|
await sleep(intervalMs);
|
|
79
|
-
const res = await postJson(`${baseUrl}/
|
|
80
|
+
const res = await postJson(`${apiBaseUrl(baseUrl)}/device/token`, {
|
|
80
81
|
device_code: start.device_code,
|
|
81
82
|
});
|
|
82
83
|
if (res.ok) {
|
|
@@ -92,11 +93,11 @@ export async function pollForApproval(baseUrl, start, opts = {}) {
|
|
|
92
93
|
opts.onSlowDown?.(Math.round(intervalMs / 1000));
|
|
93
94
|
break;
|
|
94
95
|
case 'access_denied':
|
|
95
|
-
throw new Error('The
|
|
96
|
+
throw new Error('The sign-in was denied in the dashboard.');
|
|
96
97
|
case 'expired_token':
|
|
97
|
-
throw new Error('This
|
|
98
|
+
throw new Error('This sign-in expired or was already used. Run `gheima login` again.');
|
|
98
99
|
default:
|
|
99
|
-
throw new Error(body.error?.message ?? `
|
|
100
|
+
throw new Error(body.error?.message ?? `Sign-in failed (HTTP ${res.status}). Run \`gheima login\` again.`);
|
|
100
101
|
}
|
|
101
102
|
}
|
|
102
103
|
}
|
package/dist/exit.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { GheimaError } from '@gheima/sdk';
|
|
2
|
+
/**
|
|
3
|
+
* The CLI's exit codes. Stable: scripts branch on them, so a code is never reused for a
|
|
4
|
+
* different meaning. Documented in the README.
|
|
5
|
+
*/
|
|
6
|
+
export const EXIT = {
|
|
7
|
+
ok: 0,
|
|
8
|
+
error: 1,
|
|
9
|
+
usage: 2,
|
|
10
|
+
auth: 3,
|
|
11
|
+
notFound: 4,
|
|
12
|
+
conflict: 5,
|
|
13
|
+
rateLimited: 6,
|
|
14
|
+
network: 7,
|
|
15
|
+
/** `gheima deploy` waited, and the deployment did not go live. */
|
|
16
|
+
deployFailed: 8,
|
|
17
|
+
};
|
|
18
|
+
/** The command was invoked wrongly: a missing flag, or a prompt with nobody to answer it. */
|
|
19
|
+
export class UsageError extends Error {
|
|
20
|
+
name = 'UsageError';
|
|
21
|
+
}
|
|
22
|
+
/** Map a failure to its exit code, from the API envelope's status. */
|
|
23
|
+
export function exitCodeFor(err) {
|
|
24
|
+
if (err instanceof UsageError)
|
|
25
|
+
return EXIT.usage;
|
|
26
|
+
if (err instanceof NotAuthenticatedError)
|
|
27
|
+
return EXIT.auth;
|
|
28
|
+
if (!(err instanceof GheimaError))
|
|
29
|
+
return EXIT.error;
|
|
30
|
+
// status 0 is the SDK's "no response at all": a dropped connection or a timeout.
|
|
31
|
+
if (err.status === 0 || err.status === 408 || err.status === 504)
|
|
32
|
+
return EXIT.network;
|
|
33
|
+
if (err.status === 401 || err.status === 403)
|
|
34
|
+
return EXIT.auth;
|
|
35
|
+
if (err.status === 404)
|
|
36
|
+
return EXIT.notFound;
|
|
37
|
+
if ([400, 409, 412, 422, 428].includes(err.status))
|
|
38
|
+
return EXIT.conflict;
|
|
39
|
+
if (err.status === 429)
|
|
40
|
+
return EXIT.rateLimited;
|
|
41
|
+
return EXIT.error;
|
|
42
|
+
}
|
|
43
|
+
/** No credential from `--key`, `GHEIMA_API_KEY` or a stored profile. */
|
|
44
|
+
export class NotAuthenticatedError extends Error {
|
|
45
|
+
name = 'NotAuthenticatedError';
|
|
46
|
+
constructor() {
|
|
47
|
+
super('Not authenticated. Run `gheima login`, set GHEIMA_API_KEY, or pass --key <key>.');
|
|
48
|
+
}
|
|
49
|
+
}
|
package/dist/generated.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { getOp, ops, returnsSecret } from '@gheima/contracts';
|
|
2
|
+
import { getOp, isDestructive, ops, returnsSecret } from '@gheima/contracts';
|
|
3
3
|
import { Transport } from '@gheima/sdk';
|
|
4
|
-
import {
|
|
4
|
+
import { requireAuth, transportOptions } from './client.js';
|
|
5
|
+
import { isJsonMode, printJson } from './ui.js';
|
|
5
6
|
/**
|
|
6
7
|
* Commands built from the contract registry.
|
|
7
8
|
*
|
|
@@ -76,13 +77,17 @@ function coerce(node, raw) {
|
|
|
76
77
|
return raw;
|
|
77
78
|
}
|
|
78
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* Call a declared operation by id. Hand-written commands use this for operations the SDK's
|
|
82
|
+
* resource classes do not wrap, so nothing gets a second, hand-written copy of an endpoint.
|
|
83
|
+
*/
|
|
84
|
+
export function callOp(id, input, opts) {
|
|
85
|
+
return invoke(getOp(id), input, opts);
|
|
86
|
+
}
|
|
79
87
|
async function invoke(op, input, opts) {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
process.exit(1);
|
|
84
|
-
}
|
|
85
|
-
const transport = new Transport({ apiKey: auth.apiKey, baseUrl: auth.url });
|
|
88
|
+
// Retries and Idempotency-Key come from the transport, which knows from the spec which
|
|
89
|
+
// operations dedupe a repeated key — the same rules the SDK applies for everyone.
|
|
90
|
+
const transport = new Transport(transportOptions(requireAuth(opts)));
|
|
86
91
|
const params = {};
|
|
87
92
|
const query = {};
|
|
88
93
|
const body = {};
|
|
@@ -125,7 +130,13 @@ export function registerGenerated(program, deps) {
|
|
|
125
130
|
let parent = groups.get(group);
|
|
126
131
|
if (!parent) {
|
|
127
132
|
const existing = findGroup(program, group);
|
|
128
|
-
|
|
133
|
+
// Derived from the contract rather than hard-coded: a group with any write operation
|
|
134
|
+
// is something you manage, one with only reads is something you inspect. The old
|
|
135
|
+
// `${group} operations` sat in the top-level help next to hand-written entries like
|
|
136
|
+
// "Manage services" and read like a placeholder, because it was one.
|
|
137
|
+
const writes = invocableOps().some((o) => commandPath(o)[0] === group && o.method !== 'GET');
|
|
138
|
+
parent =
|
|
139
|
+
existing ?? program.command(group).description(`${writes ? 'Manage' : 'Inspect'} ${group}`);
|
|
129
140
|
groups.set(group, parent);
|
|
130
141
|
}
|
|
131
142
|
const paramSchema = schemaOf(op.input?.params);
|
|
@@ -144,7 +155,7 @@ export function registerGenerated(program, deps) {
|
|
|
144
155
|
cmd.option(node.type === 'boolean' ? `--${name}` : `--${name} <value>`, describe || name);
|
|
145
156
|
}
|
|
146
157
|
}
|
|
147
|
-
if (op
|
|
158
|
+
if (isDestructive(op))
|
|
148
159
|
cmd.option('-y, --yes', 'skip the confirmation');
|
|
149
160
|
cmd.action(async (...args) => {
|
|
150
161
|
// commander hands positionals, then the options object, then the Command.
|
|
@@ -153,7 +164,7 @@ export function registerGenerated(program, deps) {
|
|
|
153
164
|
const values = args.slice(0, positional.length);
|
|
154
165
|
const opts = command.optsWithGlobals();
|
|
155
166
|
try {
|
|
156
|
-
if (op
|
|
167
|
+
if (isDestructive(op)) {
|
|
157
168
|
await deps.confirmDestructive(opts.yes, `run ${op.id}`);
|
|
158
169
|
}
|
|
159
170
|
const input = {};
|
|
@@ -174,7 +185,11 @@ export function registerGenerated(program, deps) {
|
|
|
174
185
|
});
|
|
175
186
|
}
|
|
176
187
|
program
|
|
177
|
-
.
|
|
188
|
+
// `[operation]` is OPTIONAL on purpose. With `<operation>` commander rejects
|
|
189
|
+
// `gheima api --list` for a missing argument before the action ever runs, so the
|
|
190
|
+
// `--list` branch below was unreachable — a flag this command's own description tells
|
|
191
|
+
// people to use. Optional here, and the action refuses a call that names neither.
|
|
192
|
+
.command('api [operation] [input]')
|
|
178
193
|
.description('Call any API operation by id. `gheima api --list` shows them all.')
|
|
179
194
|
.option('--list', 'list every operation and exit')
|
|
180
195
|
.option('-y, --yes', 'skip the confirmation on a destructive operation')
|
|
@@ -182,10 +197,22 @@ export function registerGenerated(program, deps) {
|
|
|
182
197
|
const opts = command.optsWithGlobals();
|
|
183
198
|
try {
|
|
184
199
|
if (opts.list) {
|
|
200
|
+
if (isJsonMode()) {
|
|
201
|
+
printJson(invocableOps().map((op) => ({
|
|
202
|
+
id: op.id,
|
|
203
|
+
method: op.method,
|
|
204
|
+
path: op.path,
|
|
205
|
+
summary: op.summary,
|
|
206
|
+
access: op.access,
|
|
207
|
+
destructive: isDestructive(op),
|
|
208
|
+
returnsCredentials: returnsSecret(op),
|
|
209
|
+
})));
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
185
212
|
for (const op of invocableOps()) {
|
|
186
213
|
const marks = [
|
|
187
214
|
op.access,
|
|
188
|
-
op
|
|
215
|
+
isDestructive(op) ? 'destructive' : null,
|
|
189
216
|
returnsSecret(op) ? 'returns credentials' : null,
|
|
190
217
|
]
|
|
191
218
|
.filter(Boolean)
|
|
@@ -194,8 +221,11 @@ export function registerGenerated(program, deps) {
|
|
|
194
221
|
}
|
|
195
222
|
return;
|
|
196
223
|
}
|
|
224
|
+
if (!operation) {
|
|
225
|
+
throw new Error('Specify an operation id, or pass --list to see them all');
|
|
226
|
+
}
|
|
197
227
|
const op = getOp(operation);
|
|
198
|
-
if (op
|
|
228
|
+
if (isDestructive(op))
|
|
199
229
|
await deps.confirmDestructive(opts.yes, `run ${op.id}`);
|
|
200
230
|
const parsed = input ? JSON.parse(input) : {};
|
|
201
231
|
deps.output(await invoke(op, parsed, opts), opts);
|
package/dist/link.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
export const LINK_DIR = '.gheima';
|
|
4
|
+
const LINK_FILE = 'project.json';
|
|
5
|
+
/** The nearest link at or above `from`, with the directory it lives in. */
|
|
6
|
+
export function findLink(from = process.cwd()) {
|
|
7
|
+
let dir = from;
|
|
8
|
+
while (true) {
|
|
9
|
+
const path = join(dir, LINK_DIR, LINK_FILE);
|
|
10
|
+
if (existsSync(path)) {
|
|
11
|
+
try {
|
|
12
|
+
const link = JSON.parse(readFileSync(path, 'utf8'));
|
|
13
|
+
if (typeof link.serviceId === 'string' && link.serviceId)
|
|
14
|
+
return { dir, link };
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
/* unreadable: keep walking rather than fail every command in the tree */
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const parent = dirname(dir);
|
|
21
|
+
if (parent === dir)
|
|
22
|
+
return null;
|
|
23
|
+
dir = parent;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Write the link in `dir`, and keep `.gheima/` out of git: it names one person's service,
|
|
28
|
+
* which a teammate linking their own would overwrite. Returns whether .gitignore changed.
|
|
29
|
+
*/
|
|
30
|
+
export function writeLink(dir, link) {
|
|
31
|
+
mkdirSync(join(dir, LINK_DIR), { recursive: true });
|
|
32
|
+
writeFileSync(join(dir, LINK_DIR, LINK_FILE), JSON.stringify(link, null, 2) + '\n');
|
|
33
|
+
const ignore = join(dir, '.gitignore');
|
|
34
|
+
// Only where git is plausibly in use: never create a .gitignore in an arbitrary directory.
|
|
35
|
+
if (!existsSync(ignore) && !existsSync(join(dir, '.git')))
|
|
36
|
+
return false;
|
|
37
|
+
const current = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
|
|
38
|
+
if (current.split(/\r?\n/).some((l) => l.trim() === `${LINK_DIR}/` || l.trim() === LINK_DIR)) {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
appendFileSync(ignore, `${current && !current.endsWith('\n') ? '\n' : ''}${LINK_DIR}/\n`);
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* `KEY=value`, quoted the way the platform's own .env parser (packages/utils/src/dotenv.ts)
|
|
46
|
+
* reads it back, so `env pull` then `env push` changes nothing. That parser takes single
|
|
47
|
+
* quotes literally and expands only `\n`, `\t` and `\"` inside double quotes, so a value is
|
|
48
|
+
* single-quoted whenever it can be, and double-quoted only when it holds a newline or a `'`.
|
|
49
|
+
* A value that needs double quotes AND holds a literal `\n` or `\t` cannot be written so that
|
|
50
|
+
* parser returns it unchanged (it has no `\\` escape), so it is left out and its key returned
|
|
51
|
+
* in `skipped`, rather than written in a form a later push would silently change. A literal
|
|
52
|
+
* `\"` is fine: its `"` is escaped on the way out and unescaped on the way back.
|
|
53
|
+
*/
|
|
54
|
+
export function toDotenv(vars) {
|
|
55
|
+
const skipped = [];
|
|
56
|
+
const lines = [];
|
|
57
|
+
for (const { key, value } of vars) {
|
|
58
|
+
if (/^[\w./:@+-]*$/.test(value))
|
|
59
|
+
lines.push(`${key}=${value}\n`);
|
|
60
|
+
else if (!value.includes("'") && !value.includes('\n'))
|
|
61
|
+
lines.push(`${key}='${value}'\n`);
|
|
62
|
+
else if (/\\[nt]/.test(value))
|
|
63
|
+
skipped.push(key);
|
|
64
|
+
else
|
|
65
|
+
lines.push(`${key}="${value.replace(/"/g, '\\"').replace(/\n/g, '\\n')}"\n`);
|
|
66
|
+
}
|
|
67
|
+
return { text: lines.join(''), skipped };
|
|
68
|
+
}
|
package/dist/prompt.js
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { createInterface } from 'node:readline';
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import { UsageError } from './exit.js';
|
|
3
|
+
import { isInteractive } from './ui.js';
|
|
4
|
+
/**
|
|
5
|
+
* Prompt for a line of input on the terminal. With nobody there to answer — a pipe, a CI job —
|
|
6
|
+
* it refuses instead of hanging or reading garbage, naming what to pass in its place.
|
|
7
|
+
*/
|
|
8
|
+
export function prompt(question, instead) {
|
|
9
|
+
if (!isInteractive()) {
|
|
10
|
+
return Promise.reject(new UsageError(`${question.replace(/[:?]\s*$/, '')}: no terminal to ask on. Pass ${instead}.`));
|
|
11
|
+
}
|
|
4
12
|
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
5
13
|
return new Promise((resolve) => rl.question(question, (a) => {
|
|
6
14
|
rl.close();
|
|
@@ -9,7 +17,7 @@ export function prompt(question) {
|
|
|
9
17
|
}
|
|
10
18
|
/** Yes/no confirmation (default No). Returns true only on an explicit y/yes. */
|
|
11
19
|
export async function confirm(question) {
|
|
12
|
-
const a = (await prompt(`${question} [y/N]
|
|
20
|
+
const a = (await prompt(`${question} [y/N] `, '--yes')).toLowerCase();
|
|
13
21
|
return a === 'y' || a === 'yes';
|
|
14
22
|
}
|
|
15
23
|
/** Prompt for a secret without echoing it to the terminal. */
|
package/dist/proxy.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Corporate networks reach the internet through a proxy, and Node's built-in fetch ignores
|
|
3
|
+
* HTTPS_PROXY / HTTP_PROXY / NO_PROXY. When one is set, route every request through undici's
|
|
4
|
+
* EnvHttpProxyAgent, which reads all three (lower- and upper-case) exactly as curl does.
|
|
5
|
+
* Imported only then, so a CLI with no proxy configured pays nothing for it.
|
|
6
|
+
*/
|
|
7
|
+
export async function useProxyFromEnv(env = process.env) {
|
|
8
|
+
const proxy = env.HTTPS_PROXY || env.https_proxy || env.HTTP_PROXY || env.http_proxy;
|
|
9
|
+
if (!proxy)
|
|
10
|
+
return false;
|
|
11
|
+
const { EnvHttpProxyAgent, fetch, setGlobalDispatcher } = await import('undici');
|
|
12
|
+
setGlobalDispatcher(new EnvHttpProxyAgent());
|
|
13
|
+
// Node's built-in fetch bundles its own (older) undici, which hangs on a dispatcher from
|
|
14
|
+
// this one; swap in the matching fetch. The SDK reads globalThis.fetch when a client is
|
|
15
|
+
// built, which happens after this runs.
|
|
16
|
+
globalThis.fetch = fetch;
|
|
17
|
+
return true;
|
|
18
|
+
}
|
package/dist/ui.js
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
// Tiny zero-dependency terminal helpers: colors, tables, spinner, JSON output.
|
|
2
2
|
const ESC = String.fromCharCode(27) + '[';
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* One decision for every stream: FORCE_COLOR wins, then NO_COLOR, then CI, then "are both
|
|
5
|
+
* streams a terminal". Deciding per stream would still leak escapes into a pipe whenever a
|
|
6
|
+
* coloured string built for stderr ends up on stdout, so a pipe on either side turns it off.
|
|
7
|
+
*/
|
|
8
|
+
export function colorEnabled(env = process.env) {
|
|
9
|
+
if (env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== '0')
|
|
10
|
+
return true;
|
|
11
|
+
if (env.NO_COLOR !== undefined && env.NO_COLOR !== '')
|
|
12
|
+
return false;
|
|
13
|
+
if (env.CI)
|
|
14
|
+
return false;
|
|
15
|
+
return Boolean(process.stdout.isTTY && process.stderr.isTTY);
|
|
16
|
+
}
|
|
17
|
+
/** A person is there to answer a prompt: stdin and stderr are a terminal and this is not CI. */
|
|
18
|
+
export function isInteractive(env = process.env) {
|
|
19
|
+
return Boolean(process.stdin.isTTY && process.stderr.isTTY && !env.CI);
|
|
20
|
+
}
|
|
21
|
+
const useColor = colorEnabled();
|
|
22
|
+
/**
|
|
23
|
+
* `--json`: stdout carries exactly one JSON document (NDJSON for a stream). Set once per
|
|
24
|
+
* command by the program's preAction hook; everything human-shaped goes to stderr.
|
|
25
|
+
*/
|
|
26
|
+
let jsonMode = false;
|
|
27
|
+
let wroteStdout = false;
|
|
28
|
+
export function setJsonMode(on) {
|
|
29
|
+
jsonMode = on;
|
|
30
|
+
}
|
|
31
|
+
export function isJsonMode() {
|
|
32
|
+
return jsonMode;
|
|
33
|
+
}
|
|
34
|
+
/** Whether this command has put its result on stdout yet. */
|
|
35
|
+
export function hasWrittenResult() {
|
|
36
|
+
return wroteStdout;
|
|
37
|
+
}
|
|
4
38
|
function wrap(code, s) {
|
|
5
39
|
return useColor ? `${ESC}${code}m${s}${ESC}0m` : s;
|
|
6
40
|
}
|
|
@@ -12,8 +46,22 @@ export const color = {
|
|
|
12
46
|
yellow: (s) => wrap(33, s),
|
|
13
47
|
cyan: (s) => wrap(36, s),
|
|
14
48
|
};
|
|
15
|
-
/**
|
|
49
|
+
/** `Last status` → `lastStatus`. */
|
|
50
|
+
const keyOf = (header) => header
|
|
51
|
+
.toLowerCase()
|
|
52
|
+
.replace(/[^a-z0-9]+(.)/g, (_m, c) => c.toUpperCase())
|
|
53
|
+
.replace(/[^a-zA-Z0-9]/g, '');
|
|
54
|
+
/**
|
|
55
|
+
* Print rows as an aligned text table with a dimmed header — or, under `--json`, as an array
|
|
56
|
+
* of objects keyed by the headers, so a command written only for humans still answers a
|
|
57
|
+
* script with data rather than a layout.
|
|
58
|
+
*/
|
|
16
59
|
export function table(headers, rows) {
|
|
60
|
+
if (jsonMode) {
|
|
61
|
+
printJson(rows.map((r) => Object.fromEntries(headers.map((h, i) => [keyOf(h), r[i] ?? null]))));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
wroteStdout = true;
|
|
17
65
|
const cells = rows.map((r) => r.map((c) => (c == null ? '' : String(c))));
|
|
18
66
|
const widths = headers.map((h, i) => Math.max(h.length, ...cells.map((r) => (r[i] ?? '').length), 0));
|
|
19
67
|
const line = (r) => r
|
|
@@ -27,12 +75,23 @@ export function table(headers, rows) {
|
|
|
27
75
|
process.stdout.write(color.dim('(none)') + '\n');
|
|
28
76
|
}
|
|
29
77
|
export function printJson(value) {
|
|
78
|
+
wroteStdout = true;
|
|
30
79
|
process.stdout.write(JSON.stringify(value, null, 2) + '\n');
|
|
31
80
|
}
|
|
81
|
+
/** A result that is not JSON by nature (a shell script): it still counts as the output. */
|
|
82
|
+
export function writeRaw(text) {
|
|
83
|
+
wroteStdout = true;
|
|
84
|
+
process.stdout.write(text);
|
|
85
|
+
}
|
|
86
|
+
/** One line of a stream under `--json` (NDJSON): compact, newline-terminated. */
|
|
87
|
+
export function printJsonLine(value) {
|
|
88
|
+
wroteStdout = true;
|
|
89
|
+
process.stdout.write(JSON.stringify(value) + '\n');
|
|
90
|
+
}
|
|
32
91
|
const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
33
|
-
/** A minimal spinner;
|
|
92
|
+
/** A minimal spinner; a plain line instead when nobody is watching (CI, pipes). */
|
|
34
93
|
export function spinner(text) {
|
|
35
|
-
if (!process.stderr.isTTY) {
|
|
94
|
+
if (!process.stderr.isTTY || process.env.CI) {
|
|
36
95
|
process.stderr.write(text + '\n');
|
|
37
96
|
return { stop: () => { }, update: () => { } };
|
|
38
97
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { configDir } from './config.js';
|
|
5
|
+
/**
|
|
6
|
+
* "A newer @gheima/cli exists" — without ever making a command wait for the registry.
|
|
7
|
+
*
|
|
8
|
+
* A command only reads the cached answer. When that answer is older than a day, a detached
|
|
9
|
+
* child process asks the registry and rewrites the cache for NEXT time, and this process
|
|
10
|
+
* exits without waiting for it. So the notice is up to a day late, never a delay.
|
|
11
|
+
*/
|
|
12
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
13
|
+
const REGISTRY = 'https://registry.npmjs.org/@gheima/cli/latest';
|
|
14
|
+
/** The cache's version reaches the terminal, so it must be a version and nothing else. */
|
|
15
|
+
const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
16
|
+
export function cachePath() {
|
|
17
|
+
return join(configDir(), 'update-check.json');
|
|
18
|
+
}
|
|
19
|
+
/** Scripts and pipes get nothing: no line on stderr, and no request to the registry. */
|
|
20
|
+
export function shouldCheck(argv, env = process.env) {
|
|
21
|
+
if (env.GHEIMA_NO_UPDATE_CHECK === '1' || env.CI)
|
|
22
|
+
return false;
|
|
23
|
+
if (argv.includes('--json'))
|
|
24
|
+
return false;
|
|
25
|
+
return Boolean(process.stderr.isTTY);
|
|
26
|
+
}
|
|
27
|
+
/** `0.10.0` > `0.9.3`. Pre-release tags are ignored: only a release is worth announcing. */
|
|
28
|
+
export function isNewer(latest, current) {
|
|
29
|
+
const parse = (v) => v
|
|
30
|
+
.split('-')[0]
|
|
31
|
+
.split('.')
|
|
32
|
+
.map((n) => Number(n) || 0);
|
|
33
|
+
const [a, b] = [parse(latest), parse(current)];
|
|
34
|
+
for (let i = 0; i < 3; i++) {
|
|
35
|
+
if ((a[i] ?? 0) !== (b[i] ?? 0))
|
|
36
|
+
return (a[i] ?? 0) > (b[i] ?? 0);
|
|
37
|
+
}
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
function readCache() {
|
|
41
|
+
try {
|
|
42
|
+
const c = JSON.parse(readFileSync(cachePath(), 'utf8'));
|
|
43
|
+
return typeof c.checkedAt === 'number' && typeof c.latest === 'string' && SEMVER.test(c.latest)
|
|
44
|
+
? c
|
|
45
|
+
: null;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Arguments to re-run THIS CLI with. Under Node, `execPath` is node and `argv[1]` the script.
|
|
53
|
+
* In a compiled binary, `execPath` is the binary itself and `argv[1]` a virtual path inside
|
|
54
|
+
* it, which must not be passed again or the child would read it as a command.
|
|
55
|
+
*/
|
|
56
|
+
export function selfArgs(...extra) {
|
|
57
|
+
const entry = process.argv[1] ?? '';
|
|
58
|
+
const compiled = entry.includes('$bunfs') || entry.includes('~BUN');
|
|
59
|
+
return compiled ? extra : [entry, ...extra];
|
|
60
|
+
}
|
|
61
|
+
/** The hidden argument that turns this CLI into the background refresher. */
|
|
62
|
+
export const REFRESH_ARG = '__refresh-update-check';
|
|
63
|
+
/**
|
|
64
|
+
* Runs in the detached child: ask the registry, write the cache 0600. Reached through the
|
|
65
|
+
* CLI's own entrypoint, so a proxy from the environment applies here too. Never throws.
|
|
66
|
+
*/
|
|
67
|
+
export async function refreshUpdateCache() {
|
|
68
|
+
try {
|
|
69
|
+
const res = await fetch(REGISTRY, { signal: AbortSignal.timeout(5000) });
|
|
70
|
+
const body = res.ok ? (await res.json()) : null;
|
|
71
|
+
if (typeof body?.version !== 'string' || !SEMVER.test(body.version))
|
|
72
|
+
return;
|
|
73
|
+
mkdirSync(dirname(cachePath()), { recursive: true, mode: 0o700 });
|
|
74
|
+
writeFileSync(cachePath(), JSON.stringify({ checkedAt: Date.now(), latest: body.version }), {
|
|
75
|
+
mode: 0o600,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
/* offline, blocked, malformed: the stamped attempt stands, try again tomorrow */
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The notice to print for `current`, if the cache says a newer release exists. Kicks off a
|
|
84
|
+
* background refresh when the cache is stale. Returns null when there is nothing to say.
|
|
85
|
+
*/
|
|
86
|
+
export function updateNotice(current, now = Date.now()) {
|
|
87
|
+
const cache = readCache();
|
|
88
|
+
if (!cache || now - cache.checkedAt > DAY_MS) {
|
|
89
|
+
try {
|
|
90
|
+
// Stamp the attempt first: offline, the refresh never writes, and without this every
|
|
91
|
+
// command would spawn another one.
|
|
92
|
+
mkdirSync(dirname(cachePath()), { recursive: true, mode: 0o700 });
|
|
93
|
+
writeFileSync(cachePath(), JSON.stringify({ checkedAt: now, latest: cache?.latest ?? current }), { mode: 0o600 });
|
|
94
|
+
spawn(process.execPath, selfArgs(REFRESH_ARG), {
|
|
95
|
+
detached: true,
|
|
96
|
+
stdio: 'ignore',
|
|
97
|
+
}).unref();
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
/* best effort: no notice is better than a failed command */
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (cache && isNewer(cache.latest, current)) {
|
|
104
|
+
return `A newer @gheima/cli is available: ${current} → ${cache.latest}. Update: npm i -g @gheima/cli`;
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
package/dist/version.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gheima/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Command-line interface for the Gheima platform.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -33,9 +33,10 @@
|
|
|
33
33
|
],
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"commander": "^12.1.0",
|
|
36
|
+
"undici": "^7.29.0",
|
|
36
37
|
"zod": "^4.4.3",
|
|
37
|
-
"@gheima/contracts": "0.
|
|
38
|
-
"@gheima/sdk": "0.
|
|
38
|
+
"@gheima/contracts": "0.2.0",
|
|
39
|
+
"@gheima/sdk": "0.3.0"
|
|
39
40
|
},
|
|
40
41
|
"devDependencies": {
|
|
41
42
|
"@arethetypeswrong/cli": "^0.18.5",
|
|
@@ -47,14 +48,15 @@
|
|
|
47
48
|
"@gheima/config": "0.0.0"
|
|
48
49
|
},
|
|
49
50
|
"engines": {
|
|
50
|
-
"node": ">=18"
|
|
51
|
+
"node": ">=20.18.1"
|
|
51
52
|
},
|
|
52
53
|
"scripts": {
|
|
53
|
-
"build": "tsc -p tsconfig.json",
|
|
54
|
+
"build": "node scripts/write-version.mjs && tsc -p tsconfig.json",
|
|
54
55
|
"check:pack": "pnpm build && publint",
|
|
55
56
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
56
57
|
"test": "vitest run",
|
|
57
58
|
"clean": "rm -rf dist .turbo",
|
|
58
|
-
"lint": "eslint ."
|
|
59
|
+
"lint": "eslint .",
|
|
60
|
+
"build:binaries": "pnpm build && bash scripts/build-binaries.sh"
|
|
59
61
|
}
|
|
60
62
|
}
|