@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/cli.js ADDED
@@ -0,0 +1,1298 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+ import { spawn } from 'node:child_process';
4
+ import { readFileSync, createReadStream, createWriteStream, existsSync, statSync } from 'node:fs';
5
+ import { Readable } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { basename } from 'node:path';
8
+ import { Command } from 'commander';
9
+ import { GheimaError, GheimaClient } from '@gheima/sdk';
10
+ import { makeClient } from './client.js';
11
+ import { resolveAuth, setProfile, removeProfile, loadConfig } from './config.js';
12
+ import { prompt, promptHidden, confirm } from './prompt.js';
13
+ import { table, printJson, spinner, success, info, color } from './ui.js';
14
+ import { completionScript } from './completion.js';
15
+ import { registerGenerated } from './generated.js';
16
+ const require = createRequire(import.meta.url);
17
+ const pkg = require('../package.json');
18
+ const program = new Command();
19
+ program
20
+ .name('gheima')
21
+ .description('Gheima platform CLI — deploy and manage services, databases, storage, and more.')
22
+ .version(pkg.version, '-v, --version')
23
+ .option('-k, --key <key>', 'API key (overrides env + stored profile)')
24
+ .option('-u, --url <url>', 'API base URL')
25
+ .option('-p, --profile <name>', 'config profile to use')
26
+ .option('--json', 'output machine-readable JSON')
27
+ .showHelpAfterError();
28
+ /** Global options merged across the program + the invoked subcommand. */
29
+ function globals(cmd) {
30
+ return cmd.optsWithGlobals();
31
+ }
32
+ /**
33
+ * Guard an irreversible action: proceed if `--yes`, else prompt on a TTY. In a
34
+ * non-interactive shell without `--yes`, refuse rather than silently destroying.
35
+ */
36
+ async function confirmDestructive(yes, whatWillHappen) {
37
+ if (yes)
38
+ return;
39
+ if (!process.stdin.isTTY) {
40
+ fail(new Error(`Refusing to ${whatWillHappen} in a non-interactive shell without --yes`));
41
+ }
42
+ if (!(await confirm(`This will ${whatWillHappen}. Continue?`))) {
43
+ process.stderr.write('Aborted.\n');
44
+ process.exit(130);
45
+ }
46
+ }
47
+ /** Read stdin to the end (used to keep secrets off the command line). */
48
+ async function readStdin() {
49
+ const chunks = [];
50
+ for await (const chunk of process.stdin)
51
+ chunks.push(chunk);
52
+ return Buffer.concat(chunks).toString('utf8');
53
+ }
54
+ function fail(err) {
55
+ if (err instanceof GheimaError) {
56
+ process.stderr.write(`${color.red('Error')} (${err.status} ${err.code}): ${err.message}\n`);
57
+ }
58
+ else {
59
+ process.stderr.write(`${color.red('Error')}: ${err instanceof Error ? err.message : String(err)}\n`);
60
+ }
61
+ process.exit(1);
62
+ }
63
+ // ---------------------------------------------------------------------------
64
+ // auth
65
+ // ---------------------------------------------------------------------------
66
+ program
67
+ .command('login')
68
+ .description('Authenticate with an API key and store it in a profile')
69
+ .action(async (_opts, cmd) => {
70
+ const g = globals(cmd);
71
+ const profileName = g.profile || 'default';
72
+ let key = g.key;
73
+ if (!key) {
74
+ info('Create an API key in the dashboard → Settings → API keys.');
75
+ key = await promptHidden('Paste your API key (gh_…): ');
76
+ }
77
+ if (!key)
78
+ fail('No API key provided.');
79
+ const client = new GheimaClient({ apiKey: key, baseUrl: g.url });
80
+ const spin = spinner('Verifying key…');
81
+ try {
82
+ const account = await client.account.get();
83
+ spin.stop();
84
+ setProfile(profileName, { apiKey: key, url: g.url });
85
+ success(`Logged in as ${color.bold(account.name)} (${account.slug}) → profile "${profileName}"`);
86
+ }
87
+ catch (err) {
88
+ spin.stop();
89
+ fail(err);
90
+ }
91
+ });
92
+ program
93
+ .command('logout')
94
+ .description('Remove a stored profile')
95
+ .action((_opts, cmd) => {
96
+ const g = globals(cmd);
97
+ const name = g.profile || loadConfig().current || 'default';
98
+ if (removeProfile(name))
99
+ success(`Removed profile "${name}".`);
100
+ else
101
+ info(`No profile "${name}".`);
102
+ });
103
+ program
104
+ .command('whoami')
105
+ .description('Show the account for the active key')
106
+ .action(async (_opts, cmd) => {
107
+ const g = globals(cmd);
108
+ const client = makeClient(g);
109
+ try {
110
+ const account = await client.account.get();
111
+ if (g.json)
112
+ return printJson(account);
113
+ const auth = resolveAuth(g);
114
+ info(`source: ${auth?.source}${auth?.profile ? ` (profile ${auth.profile})` : ''}`);
115
+ table(['Name', 'Slug', 'Plan', 'Type'], [[account.name, account.slug, account.plan, account.type]]);
116
+ }
117
+ catch (err) {
118
+ fail(err);
119
+ }
120
+ });
121
+ program
122
+ .command('spend-cap')
123
+ .description('Show the monthly spend cap and this month’s spend')
124
+ .action(async (_opts, cmd) => {
125
+ const g = globals(cmd);
126
+ try {
127
+ const res = await makeClient(g).account.getSpendCap();
128
+ if (g.json)
129
+ return printJson(res);
130
+ table(['Cap (MAD)', 'Alert %', 'Spent (MAD)'], [[res.spendCapMad ?? '—', res.spendAlertPct ?? '—', String(res.currentSpendMad)]]);
131
+ }
132
+ catch (err) {
133
+ fail(err);
134
+ }
135
+ });
136
+ program
137
+ .command('spend-cap:set')
138
+ .description('Set or clear the monthly spend cap (MAD) and alert threshold (%)')
139
+ .option('-c, --cap <mad>', 'Monthly cap in whole MAD (omit or "none" to clear)')
140
+ .option('-a, --alert <pct>', 'Alert when spend crosses this % of the cap (omit/"none" to clear)')
141
+ .action(async (opts, cmd) => {
142
+ const g = globals(cmd);
143
+ const parse = (v) => (v == null || v === 'none' ? null : Number(v));
144
+ try {
145
+ const res = await makeClient(g).account.setSpendCap({
146
+ spendCapMad: parse(opts.cap),
147
+ spendAlertPct: parse(opts.alert),
148
+ });
149
+ if (g.json)
150
+ return printJson(res);
151
+ success('Spend cap updated');
152
+ }
153
+ catch (err) {
154
+ fail(err);
155
+ }
156
+ });
157
+ // ---------------------------------------------------------------------------
158
+ // services
159
+ // ---------------------------------------------------------------------------
160
+ const services = program
161
+ .command('services')
162
+ .aliases(['service', 'svc'])
163
+ .description('Manage services');
164
+ services
165
+ .command('list', { isDefault: true })
166
+ .description('List services')
167
+ .action(async (_opts, cmd) => {
168
+ const g = globals(cmd);
169
+ try {
170
+ const all = await makeClient(g).services.list().all();
171
+ if (g.json)
172
+ return printJson(all);
173
+ table(['ID', 'Name', 'Type', 'Status', 'URL'], all.map((s) => [s.id, s.name, s.type, s.status, s.url]));
174
+ }
175
+ catch (err) {
176
+ fail(err);
177
+ }
178
+ });
179
+ services
180
+ .command('get <service>')
181
+ .description('Show service detail')
182
+ .action(async (ref, _opts, cmd) => {
183
+ const g = globals(cmd);
184
+ const client = makeClient(g);
185
+ try {
186
+ const id = await resolveServiceId(client, ref);
187
+ const svc = await client.services.get(id);
188
+ if (g.json)
189
+ return printJson(svc);
190
+ table(['Field', 'Value'], Object.entries(svc).map(([k, v]) => [k, v == null ? '' : String(v)]));
191
+ }
192
+ catch (err) {
193
+ fail(err);
194
+ }
195
+ });
196
+ services
197
+ .command('create')
198
+ .description('Create a service')
199
+ .option('--project <id>', 'project folder id (omitted → the service is ungrouped)')
200
+ .requiredOption('--name <name>', 'service name')
201
+ .option('--type <type>', 'WEB | WORKER | STATIC', 'WEB')
202
+ .option('--repo <url>', 'git repo URL')
203
+ .action(async (opts, cmd) => {
204
+ const g = globals(cmd);
205
+ try {
206
+ const created = await makeClient(g).services.create({
207
+ projectId: opts.project,
208
+ name: opts.name,
209
+ type: opts.type,
210
+ repoUrl: opts.repo,
211
+ });
212
+ if (g.json)
213
+ return printJson(created);
214
+ success(`Created service ${color.bold(created.slug)} (${created.id})`);
215
+ }
216
+ catch (err) {
217
+ fail(err);
218
+ }
219
+ });
220
+ services
221
+ .command('delete <service>')
222
+ .description('Delete a service')
223
+ .option('-y, --yes', 'skip the confirmation prompt')
224
+ .action(async (ref, opts, cmd) => {
225
+ const g = globals(cmd);
226
+ const client = makeClient(g);
227
+ // Resolve before prompting: a typo should fail as "no such service" rather than
228
+ // ask the operator to confirm deleting a name that was never going to match.
229
+ let id;
230
+ try {
231
+ id = await resolveServiceId(client, ref);
232
+ }
233
+ catch (err) {
234
+ fail(err);
235
+ }
236
+ await confirmDestructive(opts.yes, `permanently delete service ${ref}`);
237
+ try {
238
+ await client.services.delete(id);
239
+ success(`Deleted ${ref}`);
240
+ }
241
+ catch (err) {
242
+ fail(err);
243
+ }
244
+ });
245
+ // ---------------------------------------------------------------------------
246
+ // databases / storage / cron / domains (list-focused)
247
+ // ---------------------------------------------------------------------------
248
+ program
249
+ .command('db')
250
+ .alias('databases')
251
+ .description('List databases')
252
+ .action(async (_opts, cmd) => {
253
+ const g = globals(cmd);
254
+ try {
255
+ const all = await makeClient(g).databases.list().all();
256
+ if (g.json)
257
+ return printJson(all);
258
+ table(['ID', 'Name', 'Type', 'Status', 'Branch'], all.map((d) => [d.id, d.name, d.type, d.status, d.isBranch ? 'yes' : '']));
259
+ }
260
+ catch (err) {
261
+ fail(err);
262
+ }
263
+ });
264
+ program
265
+ .command('db:extensions <id>')
266
+ .description('List curated Postgres extensions and whether each is enabled')
267
+ .action(async (id, _opts, cmd) => {
268
+ const g = globals(cmd);
269
+ try {
270
+ const res = await makeClient(g).databases.extensions.list(id);
271
+ if (g.json)
272
+ return printJson(res);
273
+ table(['Name', 'Label', 'Enabled'], res.data.map((e) => [e.name, e.label, e.installed ? 'yes' : '']));
274
+ }
275
+ catch (err) {
276
+ fail(err);
277
+ }
278
+ });
279
+ program
280
+ .command('db:enable-ext <id> <name>')
281
+ .description('Enable a Postgres extension by name (e.g. vector for pgvector)')
282
+ .action(async (id, name, _opts, cmd) => {
283
+ const g = globals(cmd);
284
+ try {
285
+ const res = await makeClient(g).databases.extensions.enable(id, name);
286
+ if (g.json)
287
+ return printJson(res);
288
+ process.stdout.write(`${color.dim('enabled')} ${name}\n`);
289
+ }
290
+ catch (err) {
291
+ fail(err);
292
+ }
293
+ });
294
+ program
295
+ .command('db:backup <id>')
296
+ .description('Show a database backup schedule')
297
+ .action(async (id, _opts, cmd) => {
298
+ const g = globals(cmd);
299
+ try {
300
+ const res = await makeClient(g).databases.backups.getSchedule(id);
301
+ if (g.json)
302
+ return printJson(res);
303
+ if (!res.schedule) {
304
+ process.stdout.write(`${color.dim('no schedule')} (plan retention max: ${res.retentionMax})\n`);
305
+ return;
306
+ }
307
+ const s = res.schedule;
308
+ table(['Schedule', 'TZ', 'Keep', 'Enabled', 'Next run'], [
309
+ [
310
+ s.schedule,
311
+ s.timezone,
312
+ String(s.retentionCount),
313
+ s.enabled ? 'yes' : 'no',
314
+ s.nextRunAt ?? '—',
315
+ ],
316
+ ]);
317
+ }
318
+ catch (err) {
319
+ fail(err);
320
+ }
321
+ });
322
+ program
323
+ .command('db:backup:set <id> <cron>')
324
+ .description('Set a database backup schedule (5-field cron)')
325
+ .option('-k, --keep <n>', 'Snapshots to retain', '7')
326
+ .option('-z, --tz <timezone>', 'IANA timezone', 'UTC')
327
+ .option('--disabled', 'Create the schedule but leave it paused')
328
+ .action(async (id, cron, opts, cmd) => {
329
+ const g = globals(cmd);
330
+ try {
331
+ const res = await makeClient(g).databases.backups.setSchedule(id, {
332
+ schedule: cron,
333
+ timezone: opts.tz,
334
+ retentionCount: Number(opts.keep),
335
+ enabled: !opts.disabled,
336
+ });
337
+ if (g.json)
338
+ return printJson(res);
339
+ process.stdout.write(`${color.dim('scheduled')} keep=${res.retentionCount}\n`);
340
+ }
341
+ catch (err) {
342
+ fail(err);
343
+ }
344
+ });
345
+ program
346
+ .command('db:backup:remove <id>')
347
+ .description('Remove a database backup schedule')
348
+ .action(async (id, _opts, cmd) => {
349
+ const g = globals(cmd);
350
+ try {
351
+ const res = await makeClient(g).databases.backups.deleteSchedule(id);
352
+ if (g.json)
353
+ return printJson(res);
354
+ process.stdout.write(`${color.dim('removed')}\n`);
355
+ }
356
+ catch (err) {
357
+ fail(err);
358
+ }
359
+ });
360
+ const search = program
361
+ .command('search')
362
+ .description('Manage managed search (Meilisearch) instances');
363
+ search
364
+ .command('list', { isDefault: true })
365
+ .description('List search instances')
366
+ .action(async (_opts, cmd) => {
367
+ const g = globals(cmd);
368
+ try {
369
+ const all = await makeClient(g).search.list().all();
370
+ if (g.json)
371
+ return printJson(all);
372
+ table(['ID', 'Name', 'Status', 'Index prefix'], all.map((s) => [s.id, s.name, s.status, s.indexPrefix]));
373
+ }
374
+ catch (err) {
375
+ fail(err);
376
+ }
377
+ });
378
+ search
379
+ .command('create <name>')
380
+ .description('Provision a search instance')
381
+ .action(async (name, _opts, cmd) => {
382
+ const g = globals(cmd);
383
+ try {
384
+ const res = await makeClient(g).search.create(name);
385
+ if (g.json)
386
+ return printJson(res);
387
+ success(`Provisioning ${color.bold(res.name)} (${res.searchInstanceId})`);
388
+ }
389
+ catch (err) {
390
+ fail(err);
391
+ }
392
+ });
393
+ search
394
+ .command('reveal <id>')
395
+ .description('Reveal host + scoped API key + index prefix')
396
+ .action(async (id, _opts, cmd) => {
397
+ const g = globals(cmd);
398
+ try {
399
+ const res = await makeClient(g).search.reveal(id);
400
+ if (g.json)
401
+ return printJson(res);
402
+ table(['Host', 'API key', 'Index prefix'], [[res.host, res.apiKey, res.indexPrefix]]);
403
+ }
404
+ catch (err) {
405
+ fail(err);
406
+ }
407
+ });
408
+ search
409
+ .command('rotate-key <id>')
410
+ .description('Rotate the scoped API key')
411
+ .action(async (id, _opts, cmd) => {
412
+ const g = globals(cmd);
413
+ try {
414
+ await makeClient(g).search.rotateKey(id);
415
+ success('Key rotation queued');
416
+ }
417
+ catch (err) {
418
+ fail(err);
419
+ }
420
+ });
421
+ search
422
+ .command('rm <id>')
423
+ .description('Deprovision a search instance')
424
+ .option('-y, --yes', 'skip the confirmation prompt')
425
+ .action(async (id, opts, cmd) => {
426
+ const g = globals(cmd);
427
+ await confirmDestructive(opts.yes, `deprovision search instance ${id}`);
428
+ try {
429
+ await makeClient(g).search.delete(id);
430
+ success(`Deprovisioning ${id}`);
431
+ }
432
+ catch (err) {
433
+ fail(err);
434
+ }
435
+ });
436
+ const emailCmd = program
437
+ .command('email')
438
+ .description('Manage transactional email (sending domains + send)');
439
+ emailCmd
440
+ .command('domains', { isDefault: true })
441
+ .description('List sending domains')
442
+ .action(async (_opts, cmd) => {
443
+ const g = globals(cmd);
444
+ try {
445
+ const rows = await makeClient(g).email.domains.list();
446
+ if (g.json)
447
+ return printJson(rows);
448
+ table(['ID', 'Domain', 'Status'], rows.map((d) => [d.id, d.domain, d.status]));
449
+ }
450
+ catch (err) {
451
+ fail(err);
452
+ }
453
+ });
454
+ emailCmd
455
+ .command('add <domain>')
456
+ .description('Register a sending domain (prints DNS records to add)')
457
+ .action(async (domain, _opts, cmd) => {
458
+ const g = globals(cmd);
459
+ try {
460
+ const res = await makeClient(g).email.domains.add(domain);
461
+ if (g.json)
462
+ return printJson(res);
463
+ success(`Registered ${color.bold(domain)} (${res.id}). Add these DNS records, then verify:`);
464
+ table(['Type', 'Name', 'Value'], res.records.map((r) => [r.type, r.name, r.value]));
465
+ }
466
+ catch (err) {
467
+ fail(err);
468
+ }
469
+ });
470
+ emailCmd
471
+ .command('verify <id>')
472
+ .description('Re-check the DKIM DNS record for a domain')
473
+ .action(async (id, _opts, cmd) => {
474
+ const g = globals(cmd);
475
+ try {
476
+ const res = await makeClient(g).email.domains.verify(id);
477
+ if (g.json)
478
+ return printJson(res);
479
+ success(res.verified ? 'Verified' : 'Not verified yet — DNS may still be propagating');
480
+ }
481
+ catch (err) {
482
+ fail(err);
483
+ }
484
+ });
485
+ emailCmd
486
+ .command('send <domainId> <from> <to> <subject> <text>')
487
+ .description('Send a plain-text transactional email')
488
+ .action(async (domainId, from, to, subject, text, _opts, cmd) => {
489
+ const g = globals(cmd);
490
+ try {
491
+ const res = await makeClient(g).email.send({ domainId, from, to, subject, text });
492
+ if (g.json)
493
+ return printJson(res);
494
+ success(`Queued (${res.messageId})`);
495
+ }
496
+ catch (err) {
497
+ fail(err);
498
+ }
499
+ });
500
+ const ssoCmd = program.command('sso').description('Manage SSO (OIDC) connections');
501
+ ssoCmd
502
+ .command('list', { isDefault: true })
503
+ .description('List SSO connections')
504
+ .action(async (_opts, cmd) => {
505
+ const g = globals(cmd);
506
+ try {
507
+ const rows = await makeClient(g).sso.list();
508
+ if (g.json)
509
+ return printJson(rows);
510
+ table(['ID', 'Domain', 'Issuer', 'Status'], rows.map((c) => [c.id, c.emailDomain, c.issuer, c.status]));
511
+ }
512
+ catch (err) {
513
+ fail(err);
514
+ }
515
+ });
516
+ ssoCmd
517
+ .command('add <emailDomain> <issuer> <clientId> <clientSecret>')
518
+ .description('Register an OIDC provider for a domain (prints the DNS proof record)')
519
+ .action(async (emailDomain, issuer, clientId, clientSecret, _opts, cmd) => {
520
+ const g = globals(cmd);
521
+ try {
522
+ const res = await makeClient(g).sso.create({ emailDomain, issuer, clientId, clientSecret });
523
+ if (g.json)
524
+ return printJson(res);
525
+ success(`Registered ${color.bold(emailDomain)} (${res.id}). Add this DNS record, then verify:`);
526
+ table(['Type', 'Name', 'Value'], [[res.record.type, res.record.name, res.record.value]]);
527
+ }
528
+ catch (err) {
529
+ fail(err);
530
+ }
531
+ });
532
+ ssoCmd
533
+ .command('verify <id>')
534
+ .description('Re-check the DNS proof record and activate the connection')
535
+ .action(async (id, _opts, cmd) => {
536
+ const g = globals(cmd);
537
+ try {
538
+ const res = await makeClient(g).sso.verify(id);
539
+ if (g.json)
540
+ return printJson(res);
541
+ success(res.verified ? 'Verified and active' : 'Not verified yet — DNS may still be propagating');
542
+ }
543
+ catch (err) {
544
+ fail(err);
545
+ }
546
+ });
547
+ const templates = program.command('templates').description('One-click marketplace templates');
548
+ templates
549
+ .command('list', { isDefault: true })
550
+ .description('List available templates')
551
+ .action(async (_opts, cmd) => {
552
+ const g = globals(cmd);
553
+ try {
554
+ const rows = await makeClient(g).templates.list();
555
+ if (g.json)
556
+ return printJson(rows);
557
+ table(['ID', 'Name', 'Image', 'DB'], rows.map((r) => [r.id, r.name, r.image, r.database ?? '']));
558
+ }
559
+ catch (err) {
560
+ fail(err);
561
+ }
562
+ });
563
+ templates
564
+ .command('deploy <templateId> <name>')
565
+ .description('Deploy a template (omit --project to leave the service ungrouped)')
566
+ .option('--project <id>', 'project folder id (omitted → the service is ungrouped)')
567
+ .action(async (templateId, name, opts, cmd) => {
568
+ const g = globals(cmd);
569
+ try {
570
+ const res = await makeClient(g).templates.deploy({
571
+ templateId,
572
+ name,
573
+ projectId: opts.project,
574
+ });
575
+ if (g.json)
576
+ return printJson(res);
577
+ success(`Deploying ${color.bold(templateId)} → ${res.url}`);
578
+ }
579
+ catch (err) {
580
+ fail(err);
581
+ }
582
+ });
583
+ const queues = program
584
+ .command('queues')
585
+ .description('Manage managed job queues (BullMQ-ready Redis)');
586
+ queues
587
+ .command('list', { isDefault: true })
588
+ .description('List job queues')
589
+ .action(async (_opts, cmd) => {
590
+ const g = globals(cmd);
591
+ try {
592
+ const all = await makeClient(g).queues.list().all();
593
+ if (g.json)
594
+ return printJson(all);
595
+ table(['ID', 'Name', 'Status', 'Key prefix'], all.map((q) => [q.id, q.name, q.status, q.keyPrefix]));
596
+ }
597
+ catch (err) {
598
+ fail(err);
599
+ }
600
+ });
601
+ queues
602
+ .command('create <name>')
603
+ .description('Provision a job queue')
604
+ .action(async (name, _opts, cmd) => {
605
+ const g = globals(cmd);
606
+ try {
607
+ const res = await makeClient(g).queues.create(name);
608
+ if (g.json)
609
+ return printJson(res);
610
+ success(`Provisioning ${color.bold(res.name)} (${res.queueInstanceId})`);
611
+ }
612
+ catch (err) {
613
+ fail(err);
614
+ }
615
+ });
616
+ queues
617
+ .command('reveal <id>')
618
+ .description('Reveal the Redis connection string + key prefix')
619
+ .action(async (id, _opts, cmd) => {
620
+ const g = globals(cmd);
621
+ try {
622
+ const res = await makeClient(g).queues.reveal(id);
623
+ if (g.json)
624
+ return printJson(res);
625
+ table(['Connection string', 'Key prefix'], [[res.connectionString, res.keyPrefix]]);
626
+ }
627
+ catch (err) {
628
+ fail(err);
629
+ }
630
+ });
631
+ queues
632
+ .command('rotate-password <id>')
633
+ .description('Rotate the Redis password')
634
+ .action(async (id, _opts, cmd) => {
635
+ const g = globals(cmd);
636
+ try {
637
+ await makeClient(g).queues.rotatePassword(id);
638
+ success('Password rotation queued');
639
+ }
640
+ catch (err) {
641
+ fail(err);
642
+ }
643
+ });
644
+ queues
645
+ .command('rm <id>')
646
+ .description('Deprovision a job queue')
647
+ .option('-y, --yes', 'skip the confirmation prompt')
648
+ .action(async (id, opts, cmd) => {
649
+ const g = globals(cmd);
650
+ await confirmDestructive(opts.yes, `deprovision queue ${id}`);
651
+ try {
652
+ await makeClient(g).queues.delete(id);
653
+ success(`Deprovisioning ${id}`);
654
+ }
655
+ catch (err) {
656
+ fail(err);
657
+ }
658
+ });
659
+ const storage = program.command('storage').description('Manage object storage');
660
+ storage
661
+ .command('buckets')
662
+ .description('List storage buckets')
663
+ .action(async (_opts, cmd) => {
664
+ const g = globals(cmd);
665
+ try {
666
+ const all = await makeClient(g).storage.buckets.list().all();
667
+ if (g.json)
668
+ return printJson(all);
669
+ table(['ID', 'Name', 'Public'], all.map((b) => [b.id, b.name, b.public ? 'yes' : '']));
670
+ }
671
+ catch (err) {
672
+ fail(err);
673
+ }
674
+ });
675
+ storage
676
+ .command('ls <bucket> [prefix]')
677
+ .description('List objects in a bucket')
678
+ .option('--page', 'fetch only the first page instead of every object')
679
+ .action(async (bucket, prefix, opts, cmd) => {
680
+ const g = globals(cmd);
681
+ try {
682
+ const client = makeClient(g);
683
+ const objects = [];
684
+ const prefixes = [];
685
+ let token;
686
+ // The listing is token-paginated; stopping after page one silently truncates a
687
+ // large bucket, so walk it to the end unless the caller asked for one page.
688
+ do {
689
+ const res = await client.storage.objects.list(bucket, prefix ?? '', token);
690
+ objects.push(...(res.objects ?? []));
691
+ prefixes.push(...(res.prefixes ?? []));
692
+ token = res.nextToken ?? undefined;
693
+ } while (token && !opts.page);
694
+ if (g.json)
695
+ return printJson({ objects, prefixes, nextToken: token ?? null });
696
+ for (const p of prefixes)
697
+ process.stdout.write(`${color.dim(p)}\n`);
698
+ table(['Key', 'Size', 'Modified'], objects.map((o) => [o.key, o.size, o.lastModified]));
699
+ if (token)
700
+ info(`more objects remain — re-run without --page to list them all`);
701
+ }
702
+ catch (err) {
703
+ fail(err);
704
+ }
705
+ });
706
+ storage
707
+ .command('cp <file> <bucket> [key]')
708
+ .description('Upload a local file to a bucket (presigned PUT)')
709
+ .action(async (file, bucket, key, _opts, cmd) => {
710
+ const g = globals(cmd);
711
+ const client = makeClient(g);
712
+ try {
713
+ const size = statSync(file).size;
714
+ const objectKey = key || basename(file);
715
+ const { url } = await client.storage.objects.presignPut(bucket, objectKey);
716
+ // Stream from disk rather than reading the whole object into memory. Content-Length
717
+ // is set explicitly so the request is not chunked — presigned PUTs reject that.
718
+ const res = await fetch(url, {
719
+ method: 'PUT',
720
+ body: Readable.toWeb(createReadStream(file)),
721
+ headers: { 'content-length': String(size) },
722
+ // undici requires duplex for a streaming request body.
723
+ duplex: 'half',
724
+ });
725
+ if (!res.ok)
726
+ fail(`Upload failed: ${res.status} ${res.statusText}`);
727
+ if (g.json)
728
+ return printJson({ key: objectKey, bytes: size });
729
+ success(`Uploaded ${objectKey} (${size} bytes)`);
730
+ }
731
+ catch (err) {
732
+ fail(err);
733
+ }
734
+ });
735
+ storage
736
+ .command('get <bucket> <key> [dest]')
737
+ .description('Download an object from a bucket (presigned GET)')
738
+ .option('-f, --force', 'overwrite the destination file if it already exists')
739
+ .action(async (bucket, key, dest, opts, cmd) => {
740
+ const g = globals(cmd);
741
+ const client = makeClient(g);
742
+ const out = dest || basename(key);
743
+ // Writing over an existing local file is not recoverable — make it deliberate.
744
+ if (existsSync(out) && !opts.force) {
745
+ fail(new Error(`${out} already exists; pass --force to overwrite or give a destination`));
746
+ }
747
+ try {
748
+ const { url } = await client.storage.objects.presignGet(bucket, key);
749
+ const res = await fetch(url);
750
+ if (!res.ok)
751
+ fail(`Download failed: ${res.status} ${res.statusText}`);
752
+ if (!res.body)
753
+ fail(new Error('Download failed: empty response body'));
754
+ // Stream to disk: an object larger than the heap must still download.
755
+ let bytes = 0;
756
+ const source = Readable.fromWeb(res.body);
757
+ source.on('data', (c) => (bytes += c.length));
758
+ await pipeline(source, createWriteStream(out));
759
+ if (g.json)
760
+ return printJson({ key, dest: out, bytes });
761
+ success(`Downloaded ${key} -> ${out} (${bytes} bytes)`);
762
+ }
763
+ catch (err) {
764
+ fail(err);
765
+ }
766
+ });
767
+ storage
768
+ .command('rm <bucket> <key>')
769
+ .description('Delete an object from a bucket')
770
+ .option('-y, --yes', 'skip the confirmation prompt')
771
+ .action(async (bucket, key, opts, cmd) => {
772
+ const g = globals(cmd);
773
+ await confirmDestructive(opts.yes, `delete ${bucket}/${key}`);
774
+ try {
775
+ await makeClient(g).storage.objects.delete(bucket, key);
776
+ success(`Deleted ${key}`);
777
+ }
778
+ catch (err) {
779
+ fail(err);
780
+ }
781
+ });
782
+ program
783
+ .command('cron')
784
+ .description('List cron jobs')
785
+ .action(async (_opts, cmd) => {
786
+ const g = globals(cmd);
787
+ try {
788
+ const all = await makeClient(g).cron.list().all();
789
+ if (g.json)
790
+ return printJson(all);
791
+ table(['ID', 'Name', 'Schedule', 'Enabled'], all.map((c) => [c.id, c.name, c.schedule, c.enabled ? 'yes' : 'no']));
792
+ }
793
+ catch (err) {
794
+ fail(err);
795
+ }
796
+ });
797
+ // ---------------------------------------------------------------------------
798
+ // deploy / logs / env / open / status
799
+ // ---------------------------------------------------------------------------
800
+ /** Resolve a service by id or name to its id. */
801
+ async function resolveServiceId(client, ref) {
802
+ const all = await client.services.list().all();
803
+ const match = all.find((s) => s.id === ref || s.name === ref || s.slug === ref);
804
+ if (!match)
805
+ throw new GheimaError({
806
+ status: 404,
807
+ code: 'not_found',
808
+ message: `No service matching "${ref}"`,
809
+ });
810
+ return match.id;
811
+ }
812
+ program
813
+ .command('webhooks')
814
+ .description('List webhooks')
815
+ .action(async (_opts, cmd) => {
816
+ const g = globals(cmd);
817
+ try {
818
+ const all = await makeClient(g).webhooks.list();
819
+ if (g.json)
820
+ return printJson(all);
821
+ table(['ID', 'URL', 'Events', 'Enabled', 'Last'], all.map((w) => [
822
+ w.id,
823
+ w.url,
824
+ w.events.join(',') || 'all',
825
+ w.enabled ? 'yes' : 'no',
826
+ w.lastStatus ?? '',
827
+ ]));
828
+ }
829
+ catch (err) {
830
+ fail(err);
831
+ }
832
+ });
833
+ program
834
+ .command('deploy [service]')
835
+ .description('Trigger a deployment (by service id or name)')
836
+ .action(async (ref, _opts, cmd) => {
837
+ const g = globals(cmd);
838
+ const client = makeClient(g);
839
+ try {
840
+ if (!ref)
841
+ ref = await prompt('Service id or name: ');
842
+ const id = await resolveServiceId(client, ref);
843
+ const { deploymentId } = await client.services.deploy(id);
844
+ if (g.json)
845
+ return printJson({ deploymentId });
846
+ success(`Deployment queued: ${color.bold(deploymentId)}`);
847
+ }
848
+ catch (err) {
849
+ fail(err);
850
+ }
851
+ });
852
+ program
853
+ .command('logs <service>')
854
+ .description('Show or tail service logs')
855
+ .option('-f, --follow', 'stream new log lines')
856
+ .option('-b, --build', 'show build logs instead of runtime')
857
+ .option('-s, --search <text>', 'filter lines containing text')
858
+ .action(async (ref, opts, cmd) => {
859
+ const g = globals(cmd);
860
+ const client = makeClient(g);
861
+ try {
862
+ const id = await resolveServiceId(client, ref);
863
+ const type = opts.build ? 'build' : 'runtime';
864
+ if (opts.follow) {
865
+ for await (const entry of client.services.streamLogs(id, { type, search: opts.search })) {
866
+ const line = entry.line ?? JSON.stringify(entry);
867
+ process.stdout.write(`${line}\n`);
868
+ }
869
+ return;
870
+ }
871
+ const entries = await client.services.logs(id, { type, search: opts.search });
872
+ if (g.json)
873
+ return printJson(entries);
874
+ for (const e of entries)
875
+ process.stdout.write(`${e.line}\n`);
876
+ }
877
+ catch (err) {
878
+ fail(err);
879
+ }
880
+ });
881
+ const env = program.command('env').description('Manage service environment variables');
882
+ env
883
+ .command('pull <service>')
884
+ .description('List env var keys (values are never returned)')
885
+ .action(async (ref, _opts, cmd) => {
886
+ const g = globals(cmd);
887
+ const client = makeClient(g);
888
+ try {
889
+ const id = await resolveServiceId(client, ref);
890
+ const vars = await client.services.env.list(id);
891
+ if (g.json)
892
+ return printJson(vars);
893
+ table(['Key', 'Value'], vars.map((v) => [v.key, v.masked]));
894
+ }
895
+ catch (err) {
896
+ fail(err);
897
+ }
898
+ });
899
+ env
900
+ .command('set <service> <pair>')
901
+ .description('Set an env var (KEY=value, or KEY with --stdin / --from-file)')
902
+ .option('--stdin', 'read the value from stdin instead of the command line')
903
+ .option('--from-file <path>', 'read the value from a file instead of the command line')
904
+ .action(async (ref, pair, opts, cmd) => {
905
+ const g = globals(cmd);
906
+ const client = makeClient(g);
907
+ if (opts.stdin && opts.fromFile)
908
+ fail('Pass only one of --stdin and --from-file');
909
+ const eq = pair.indexOf('=');
910
+ // A value on argv lands in shell history and is visible in `ps` to every other user
911
+ // on the box; --stdin / --from-file keep the secret off the command line.
912
+ const fromArgv = !opts.stdin && !opts.fromFile;
913
+ if (fromArgv && eq < 1)
914
+ fail('Expected KEY=value (or KEY with --stdin / --from-file)');
915
+ if (!fromArgv && eq !== -1)
916
+ fail('Pass the bare KEY when reading the value from stdin/a file');
917
+ const key = fromArgv ? pair.slice(0, eq) : pair;
918
+ try {
919
+ const value = opts.fromFile
920
+ ? readFileSync(opts.fromFile, 'utf8').replace(/\r?\n$/, '')
921
+ : opts.stdin
922
+ ? (await readStdin()).replace(/\r?\n$/, '')
923
+ : pair.slice(eq + 1);
924
+ const id = await resolveServiceId(client, ref);
925
+ await client.services.env.set(id, key, value);
926
+ success(`Set ${key}`);
927
+ }
928
+ catch (err) {
929
+ fail(err);
930
+ }
931
+ });
932
+ env
933
+ .command('rename <service> <key> <newKey>')
934
+ .description('Rename an env var, keeping its value')
935
+ .action(async (ref, key, newKey, _opts, cmd) => {
936
+ const g = globals(cmd);
937
+ const client = makeClient(g);
938
+ try {
939
+ const id = await resolveServiceId(client, ref);
940
+ // No value in the patch — the CLI never reads the secret to move it.
941
+ await client.services.env.update(id, key, { key: newKey });
942
+ success(`Renamed ${key} to ${newKey}`);
943
+ }
944
+ catch (err) {
945
+ fail(err);
946
+ }
947
+ });
948
+ env
949
+ .command('rm <service> <key>')
950
+ .description('Remove an env var')
951
+ .option('-y, --yes', 'skip the confirmation prompt')
952
+ .action(async (ref, key, opts, cmd) => {
953
+ const g = globals(cmd);
954
+ const client = makeClient(g);
955
+ await confirmDestructive(opts.yes, `remove env var ${key} from ${ref}`);
956
+ try {
957
+ const id = await resolveServiceId(client, ref);
958
+ await client.services.env.remove(id, key);
959
+ success(`Removed ${key}`);
960
+ }
961
+ catch (err) {
962
+ fail(err);
963
+ }
964
+ });
965
+ const envGroups = program
966
+ .command('env-groups')
967
+ .description('Manage reusable env var groups (shared config)');
968
+ envGroups
969
+ .command('list', { isDefault: true })
970
+ .description('List env groups')
971
+ .action(async (_opts, cmd) => {
972
+ const g = globals(cmd);
973
+ try {
974
+ const rows = await makeClient(g).envGroups.list();
975
+ if (g.json)
976
+ return printJson(rows);
977
+ table(['ID', 'Name', 'Vars', 'Services'], rows.map((r) => [r.id, r.name, String(r.variableCount), String(r.serviceCount)]));
978
+ }
979
+ catch (err) {
980
+ fail(err);
981
+ }
982
+ });
983
+ envGroups
984
+ .command('create <name>')
985
+ .description('Create an env group')
986
+ .action(async (name, _opts, cmd) => {
987
+ const g = globals(cmd);
988
+ try {
989
+ const res = await makeClient(g).envGroups.create(name);
990
+ if (g.json)
991
+ return printJson(res);
992
+ success(`Created env group ${color.bold(name)} (${res.id})`);
993
+ }
994
+ catch (err) {
995
+ fail(err);
996
+ }
997
+ });
998
+ envGroups
999
+ .command('import <groupId> <file>')
1000
+ .description('Import a .env file into a group (merges; --replace to overwrite)')
1001
+ .option('--replace', 'Replace all variables instead of merging')
1002
+ .option('-y, --yes', 'skip the confirmation prompt for --replace')
1003
+ .action(async (groupId, file, opts, cmd) => {
1004
+ const g = globals(cmd);
1005
+ // --replace drops every variable already in the group, across every service the
1006
+ // group is attached to. Treat it like the other destructive commands.
1007
+ if (opts.replace) {
1008
+ await confirmDestructive(opts.yes, `replace every variable in env group ${groupId} with the contents of ${file}`);
1009
+ }
1010
+ try {
1011
+ const dotenv = readFileSync(file, 'utf8');
1012
+ const res = await makeClient(g).envGroups.import(groupId, dotenv, !!opts.replace);
1013
+ if (g.json)
1014
+ return printJson(res);
1015
+ success(`Imported ${res.imported} var(s); ${res.total} total`);
1016
+ if (res.invalidLines.length)
1017
+ info(`skipped line(s): ${res.invalidLines.join(', ')}`);
1018
+ }
1019
+ catch (err) {
1020
+ fail(err);
1021
+ }
1022
+ });
1023
+ envGroups
1024
+ .command('attach <groupId> <service>')
1025
+ .description('Attach a group to a service')
1026
+ .action(async (groupId, ref, _opts, cmd) => {
1027
+ const g = globals(cmd);
1028
+ const client = makeClient(g);
1029
+ try {
1030
+ const id = await resolveServiceId(client, ref);
1031
+ await client.envGroups.attach(groupId, id);
1032
+ success('Attached');
1033
+ }
1034
+ catch (err) {
1035
+ fail(err);
1036
+ }
1037
+ });
1038
+ envGroups
1039
+ .command('detach <groupId> <service>')
1040
+ .description('Detach a group from a service')
1041
+ .action(async (groupId, ref, _opts, cmd) => {
1042
+ const g = globals(cmd);
1043
+ const client = makeClient(g);
1044
+ try {
1045
+ const id = await resolveServiceId(client, ref);
1046
+ await client.envGroups.detach(groupId, id);
1047
+ success('Detached');
1048
+ }
1049
+ catch (err) {
1050
+ fail(err);
1051
+ }
1052
+ });
1053
+ const volumes = program
1054
+ .command('volumes')
1055
+ .description('Manage persistent volumes attached to a service');
1056
+ volumes
1057
+ .command('list <service>', { isDefault: true })
1058
+ .description('List volumes attached to a service')
1059
+ .action(async (ref, _opts, cmd) => {
1060
+ const g = globals(cmd);
1061
+ const client = makeClient(g);
1062
+ try {
1063
+ const id = await resolveServiceId(client, ref);
1064
+ const all = await client.services.volumes.list(id);
1065
+ if (g.json)
1066
+ return printJson(all);
1067
+ table(['ID', 'Name', 'Mount path'], all.map((v) => [v.id, v.name, v.mountPath]));
1068
+ }
1069
+ catch (err) {
1070
+ fail(err);
1071
+ }
1072
+ });
1073
+ volumes
1074
+ .command('add <service> <mountPath>')
1075
+ .description('Attach a persistent volume to a service (applies on next deploy)')
1076
+ .option('-n, --name <name>', 'volume name (defaults to the mount path)')
1077
+ .action(async (ref, mountPath, opts, cmd) => {
1078
+ const g = globals(cmd);
1079
+ const client = makeClient(g);
1080
+ try {
1081
+ const id = await resolveServiceId(client, ref);
1082
+ const res = await client.services.volumes.add(id, mountPath, opts.name);
1083
+ if (g.json)
1084
+ return printJson(res);
1085
+ success(`Attached volume at ${color.bold(res.mountPath)} (${res.id}) — applies on next deploy`);
1086
+ }
1087
+ catch (err) {
1088
+ fail(err);
1089
+ }
1090
+ });
1091
+ volumes
1092
+ .command('rm <service> <volumeId>')
1093
+ .description('Detach a volume from a service (data retained)')
1094
+ .option('-y, --yes', 'skip the confirmation prompt')
1095
+ .action(async (ref, volumeId, opts, cmd) => {
1096
+ const g = globals(cmd);
1097
+ const client = makeClient(g);
1098
+ await confirmDestructive(opts.yes, `detach volume ${volumeId} from ${ref}`);
1099
+ try {
1100
+ const id = await resolveServiceId(client, ref);
1101
+ await client.services.volumes.remove(id, volumeId);
1102
+ success(`Detached ${volumeId}`);
1103
+ }
1104
+ catch (err) {
1105
+ fail(err);
1106
+ }
1107
+ });
1108
+ // `list` is the default subcommand, so the older flat form — `gheima domains <service>` —
1109
+ // keeps working unchanged now that this is a group.
1110
+ const domainsCmd = program
1111
+ .command('domains')
1112
+ .description('Manage custom domains attached to a service');
1113
+ domainsCmd
1114
+ .command('list <service>', { isDefault: true })
1115
+ .description('List custom domains on a service')
1116
+ .action(async (ref, _opts, cmd) => {
1117
+ const g = globals(cmd);
1118
+ const client = makeClient(g);
1119
+ try {
1120
+ const id = await resolveServiceId(client, ref);
1121
+ const all = await client.domains.list(id);
1122
+ if (g.json)
1123
+ return printJson(all);
1124
+ table(['ID', 'Domain', 'Verified', 'TLS expires'], all.map((d) => [
1125
+ d.id,
1126
+ d.domain,
1127
+ d.verified ? 'yes' : 'no',
1128
+ d.sslExpiresAt ? new Date(d.sslExpiresAt).toISOString().slice(0, 10) : '—',
1129
+ ]));
1130
+ }
1131
+ catch (err) {
1132
+ fail(err);
1133
+ }
1134
+ });
1135
+ domainsCmd
1136
+ .command('add <service> <domain>')
1137
+ .description('Attach a custom domain (prints the DNS records to add)')
1138
+ .action(async (ref, domain, _opts, cmd) => {
1139
+ const g = globals(cmd);
1140
+ const client = makeClient(g);
1141
+ try {
1142
+ const id = await resolveServiceId(client, ref);
1143
+ const res = await client.domains.add(id, domain);
1144
+ // `add` answers with the id alone, but the DNS records are the only thing the user
1145
+ // can act on — re-read the domain so they are printed here instead of sending
1146
+ // someone back for a second command to find out what to put in their zone.
1147
+ const created = (await client.domains.list(id)).find((d) => d.id === res.id);
1148
+ if (g.json)
1149
+ return printJson(created ?? res);
1150
+ success(`Attached ${color.bold(domain)} (${res.id})`);
1151
+ if (created?.dns) {
1152
+ process.stdout.write('\nAdd these records, then run `gheima domains verify`:\n');
1153
+ table(['Type', 'Host', 'Value'], [
1154
+ ['CNAME', created.dns.cname.host, created.dns.cname.value],
1155
+ ['TXT', created.dns.txt.host, created.dns.txt.value],
1156
+ ]);
1157
+ }
1158
+ }
1159
+ catch (err) {
1160
+ fail(err);
1161
+ }
1162
+ });
1163
+ domainsCmd
1164
+ .command('verify <domainId>')
1165
+ .description('Re-check the TXT challenge and mark the domain verified')
1166
+ .action(async (domainId, _opts, cmd) => {
1167
+ const g = globals(cmd);
1168
+ const client = makeClient(g);
1169
+ try {
1170
+ const res = await client.domains.verify(domainId);
1171
+ if (g.json)
1172
+ return printJson(res);
1173
+ success(`Verified ${domainId}`);
1174
+ }
1175
+ catch (err) {
1176
+ // The API only ever answers `{verified: true}` or a 400 — one for "the TXT record is
1177
+ // not visible yet", one for "it does not match". Both mean the domain did not verify,
1178
+ // so the non-zero exit is right (it is what makes `until gheima domains verify <id>;
1179
+ // do sleep 30; done` terminate). Only the presentation needs help: the server's
1180
+ // sentence is actionable, a raw `bad_request` is not.
1181
+ if (err instanceof GheimaError && err.status === 400) {
1182
+ process.stderr.write(`Not verified — ${err.message}\n`);
1183
+ process.exit(1);
1184
+ }
1185
+ fail(err);
1186
+ }
1187
+ });
1188
+ domainsCmd
1189
+ .command('rm <domainId>')
1190
+ .description('Detach a custom domain from its service')
1191
+ .option('-y, --yes', 'skip the confirmation prompt')
1192
+ .action(async (domainId, opts, cmd) => {
1193
+ const g = globals(cmd);
1194
+ const client = makeClient(g);
1195
+ // Detaching drops the router: the hostname stops serving immediately.
1196
+ await confirmDestructive(opts.yes, `detach domain ${domainId}`);
1197
+ try {
1198
+ await client.domains.remove(domainId);
1199
+ success(`Detached ${domainId}`);
1200
+ }
1201
+ catch (err) {
1202
+ fail(err);
1203
+ }
1204
+ });
1205
+ program
1206
+ .command('open [resource]')
1207
+ .description('Open the dashboard (or a resource) in your browser')
1208
+ .action((resource, _opts, cmd) => {
1209
+ const g = globals(cmd);
1210
+ const auth = resolveAuth(g);
1211
+ const base = (g.url || auth?.url || 'https://gheima.ma').replace(/\/$/, '');
1212
+ const url = resource ? `${base}/${resource.replace(/^\//, '')}` : base;
1213
+ if (g.json)
1214
+ return printJson({ url });
1215
+ // Never interpolate the URL into a shell: `start` needs cmd.exe, so go through
1216
+ // rundll32 instead, which takes the URL as a plain argv entry.
1217
+ const [opener, args] = process.platform === 'darwin'
1218
+ ? ['open', [url]]
1219
+ : process.platform === 'win32'
1220
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
1221
+ : ['xdg-open', [url]];
1222
+ spawn(opener, args, {
1223
+ stdio: 'ignore',
1224
+ detached: true,
1225
+ }).unref();
1226
+ info(`Opening ${url}`);
1227
+ });
1228
+ program
1229
+ .command('status')
1230
+ .description('Show account + resource counts')
1231
+ .action(async (_opts, cmd) => {
1232
+ const g = globals(cmd);
1233
+ const client = makeClient(g);
1234
+ try {
1235
+ const [account, services, databases] = await Promise.all([
1236
+ client.account.get(),
1237
+ client.services.list().all(),
1238
+ client.databases.list().all(),
1239
+ ]);
1240
+ const payload = {
1241
+ account: account.slug,
1242
+ plan: account.plan,
1243
+ services: services.length,
1244
+ databases: databases.length,
1245
+ };
1246
+ if (g.json)
1247
+ return printJson(payload);
1248
+ table(['Account', 'Plan', 'Services', 'Databases'], [[account.slug, account.plan, services.length, databases.length]]);
1249
+ }
1250
+ catch (err) {
1251
+ fail(err);
1252
+ }
1253
+ });
1254
+ program
1255
+ .command('completion [shell]')
1256
+ .description('Print a shell completion script (bash | zsh | fish)')
1257
+ .action((shell) => {
1258
+ process.stdout.write(completionScript(shell || process.env.SHELL?.split('/').pop() || 'bash', program.commands.map((c) => c.name())));
1259
+ });
1260
+ /**
1261
+ * Everything above is hand-written, because those commands carry the experience: they
1262
+ * resolve a service by name, print tables, tail logs, prompt before anything irreversible.
1263
+ * This fills in the rest from the contract registry, skipping any command path already
1264
+ * taken above — so no operation is unreachable from a terminal, and the generated layer
1265
+ * shrinks as the crafted one grows.
1266
+ */
1267
+ registerGenerated(program, {
1268
+ // Always JSON. A generated command's result shape comes from its contract and varies far
1269
+ // too much to lay out as a table, and a half-rendered guess would be worse than the real
1270
+ // thing — the hand-written commands above are where formatting effort belongs.
1271
+ output: (value) => printJson(value),
1272
+ confirmDestructive,
1273
+ fail,
1274
+ });
1275
+ export { program };
1276
+ // Only auto-run when invoked as the binary (not when imported by tests).
1277
+ //
1278
+ // argv[1] is the path the shell used, which for an installed CLI is the package
1279
+ // manager's bin *symlink* (node_modules/.bin/gheima, /usr/local/bin/gheima); the ESM
1280
+ // loader resolves import.meta.url to the real file. Comparing them directly therefore
1281
+ // never matches once installed, and the CLI exits silently without parsing — so resolve
1282
+ // both to a real path before comparing.
1283
+ import { fileURLToPath } from 'node:url';
1284
+ import { realpathSync } from 'node:fs';
1285
+ function isMainModule() {
1286
+ const invoked = process.argv[1];
1287
+ if (!invoked)
1288
+ return false;
1289
+ try {
1290
+ return realpathSync(invoked) === realpathSync(fileURLToPath(import.meta.url));
1291
+ }
1292
+ catch {
1293
+ return false;
1294
+ }
1295
+ }
1296
+ if (isMainModule()) {
1297
+ program.parseAsync(process.argv).catch(fail);
1298
+ }