@kvbox/cli 0.5.47 → 0.5.49

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/kvbox.js CHANGED
@@ -149,7 +149,7 @@ async function spin(message, work, opts = {}) {
149
149
  }
150
150
 
151
151
  // src/program.ts
152
- import { Command as Command70 } from "commander";
152
+ import { Command as Command85 } from "commander";
153
153
 
154
154
  // ../shared/src/version.ts
155
155
  import { createRequire } from "module";
@@ -164,7 +164,7 @@ function versionOf(srcFileUrl, injected) {
164
164
  }
165
165
 
166
166
  // src/version.ts
167
- var VERSION = versionOf(import.meta.url, true ? "0.5.47" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.49" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command37 } from "commander";
@@ -426,7 +426,7 @@ import { openSync } from "fs";
426
426
  import { mkdir as mkdir2, readFile as readFile3, stat } from "fs/promises";
427
427
  import { setTimeout as sleep } from "timers/promises";
428
428
  import { Agent, request } from "undici";
429
- import { z as z3 } from "zod";
429
+ import { z as z5 } from "zod";
430
430
 
431
431
  // ../shared/src/api.ts
432
432
  import { z as z2 } from "zod";
@@ -459,10 +459,17 @@ var PortForwardSchema = z2.object({
459
459
  hostPort: z2.number().int(),
460
460
  proto: PortProtoSchema,
461
461
  /** The host's public address; only the control plane fills it in, as for `ssh`. */
462
- address: z2.string().optional()
462
+ address: z2.string().optional(),
463
+ /**
464
+ * Closed but kept (#173): nothing reaches the box through it, and the host port stays the box's, so
465
+ * publishing the same box port again opens the same number. Absent: open while the box runs.
466
+ */
467
+ closed: z2.literal(true).optional()
463
468
  });
464
469
  var PortsRequest = z2.object({
465
- ports: z2.array(z2.object({ guestPort: z2.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
470
+ ports: z2.array(z2.object({ guestPort: z2.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),
471
+ /** `DELETE` only (#173): close the ports but keep their host ports for the box (`closed`). */
472
+ keep: z2.boolean().optional()
466
473
  });
467
474
  var BoxPortSchema = z2.number().int().min(1).max(65535);
468
475
  var BoxLinkSchema = z2.object({ from: z2.string(), port: BoxPortSchema });
@@ -646,6 +653,11 @@ var CreateVolumeRequest = z2.object({
646
653
  var AttachVolumeRequest = z2.object({
647
654
  box: z2.string()
648
655
  });
656
+ var ResizeVolumeRequest = z2.object({
657
+ sizeGib: z2.number().int().min(1).max(MAX_VOLUME_GIB)
658
+ });
659
+ var RunScriptRequest = z2.object({ input: z2.unknown().optional() });
660
+ var ScriptOutputSchema = z2.object({ output: z2.unknown() });
649
661
  var EnvVarSchema = z2.object({
650
662
  name: z2.string(),
651
663
  value: z2.string().optional(),
@@ -790,6 +802,15 @@ var CapacitySchema = z2.object({
790
802
  version: z2.string().optional()
791
803
  });
792
804
  var ImageSchema = z2.object({ name: z2.string(), version: z2.string().nullable() });
805
+ var ImageIndexSchema = z2.object({
806
+ updatedAt: z2.string(),
807
+ images: z2.record(z2.string(), z2.object({ version: z2.string().min(1), minServer: z2.string().min(1).optional() }))
808
+ });
809
+ var LatestImagesSchema = z2.object({
810
+ updatedAt: z2.string().nullable(),
811
+ images: ImageIndexSchema.shape.images,
812
+ checkedAt: z2.string().nullable()
813
+ });
793
814
  var RecoveryReportSchema = z2.object({
794
815
  at: z2.string(),
795
816
  booted: z2.array(z2.string()),
@@ -901,11 +922,31 @@ var VolumeUsageSchema = z2.object({
901
922
  cost: z2.object({ amount: z2.number(), currency: z2.string() }).optional(),
902
923
  historyFrom: z2.string().nullable()
903
924
  });
925
+ var UsageDayItemSchema = z2.object({
926
+ id: z2.string(),
927
+ name: z2.string(),
928
+ owner: z2.string(),
929
+ /** Removed by the end of the report's window. */
930
+ removed: z2.boolean(),
931
+ cost: z2.number()
932
+ });
933
+ var UsageDaySchema = z2.object({
934
+ /** `YYYY-MM-DD`, UTC. */
935
+ date: z2.string(),
936
+ from: z2.string(),
937
+ to: z2.string(),
938
+ cost: z2.number(),
939
+ currency: z2.string(),
940
+ boxes: z2.array(UsageDayItemSchema),
941
+ volumes: z2.array(UsageDayItemSchema)
942
+ });
904
943
  var UsageReportSchema = z2.object({
905
944
  window: z2.object({ from: z2.string(), to: z2.string() }),
906
945
  boxes: z2.array(BoxUsageSchema),
907
946
  /** Absent from a side older than #91. */
908
947
  volumes: z2.array(VolumeUsageSchema).optional(),
948
+ /** With `?by=day` only, oldest day first. */
949
+ days: z2.array(UsageDaySchema).optional(),
909
950
  totals: z2.object({
910
951
  seconds: MachineUsageSchema.shape.seconds,
911
952
  vcpuHours: z2.number(),
@@ -1140,7 +1181,9 @@ var TrustCaReportSchema = z2.object({
1140
1181
  pending: z2.array(z2.object({ box: z2.string(), when: SshKeysAppliedSchema, why: z2.string().optional() })),
1141
1182
  failed: z2.array(z2.object({ box: z2.string(), error: z2.string() })),
1142
1183
  /** Local boxes, untouched: they trust the host's key only. */
1143
- local: z2.number().int()
1184
+ local: z2.number().int(),
1185
+ /** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */
1186
+ skipped: z2.array(z2.string()).optional()
1144
1187
  });
1145
1188
  var HostJoinRequestSchema = z2.object({
1146
1189
  token: z2.string().min(1),
@@ -1175,6 +1218,134 @@ var HostInfoSchema = z2.object({
1175
1218
  var HostPatchRequest = z2.object({ country: z2.string().nullable() });
1176
1219
  var CountrySchema = z2.object({ code: z2.string(), name: z2.string() });
1177
1220
 
1221
+ // ../shared/src/managed.ts
1222
+ import { z as z4 } from "zod";
1223
+
1224
+ // ../shared/src/usage.ts
1225
+ import { z as z3 } from "zod";
1226
+ var PricingSchema = z3.object({
1227
+ currency: z3.string().min(1),
1228
+ vcpuHour: z3.number().nonnegative(),
1229
+ ramGibHour: z3.number().nonnegative(),
1230
+ diskGibHour: z3.number().nonnegative(),
1231
+ volumeHour: z3.number().nonnegative().default(0),
1232
+ volumeGibHour: z3.number().nonnegative().default(0),
1233
+ diskIncludedGib: z3.number().int().nonnegative().default(0)
1234
+ });
1235
+ var PriceListSchema = PricingSchema.extend({ welcomeCredit: z3.number().nonnegative() });
1236
+ var HOUR_MS = 36e5;
1237
+ var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
1238
+ function costOf(t, pricing) {
1239
+ return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;
1240
+ }
1241
+ function sumUsage(items, pricing) {
1242
+ const sum = {
1243
+ seconds: { running: 0, standby: 0, hibernated: 0, stopped: 0 },
1244
+ vcpuHours: 0,
1245
+ ramGibHours: 0,
1246
+ diskGibHours: 0
1247
+ };
1248
+ for (const t of items) {
1249
+ for (const s of Object.keys(sum.seconds)) sum.seconds[s] += t.seconds[s];
1250
+ sum.vcpuHours += t.vcpuHours;
1251
+ sum.ramGibHours += t.ramGibHours;
1252
+ sum.diskGibHours += t.diskGibHours;
1253
+ }
1254
+ sum.vcpuHours = round(sum.vcpuHours, 3);
1255
+ sum.ramGibHours = round(sum.ramGibHours, 3);
1256
+ sum.diskGibHours = round(sum.diskGibHours, 3);
1257
+ if (pricing !== void 0) sum.cost = { amount: round(costOf(sum, pricing), 4), currency: pricing.currency };
1258
+ return sum;
1259
+ }
1260
+ var DAY_MS = 24 * HOUR_MS;
1261
+
1262
+ // ../shared/src/managed.ts
1263
+ var PriceSchema = z4.object({ perMonth: z4.number(), storagePerMonth: z4.number(), currency: z4.string() });
1264
+ var ManagedCatalogEntrySchema = z4.object({
1265
+ /** The kind, as in `/managed/<kind>`: `postgres`. */
1266
+ kind: z4.string(),
1267
+ /** The CLI command for it: `pg` (`kvbox pg create …`). */
1268
+ command: z4.string(),
1269
+ title: z4.string(),
1270
+ description: z4.string(),
1271
+ /** The version a new one runs, as shown: `18`. */
1272
+ version: z4.string(),
1273
+ /** The port a linked box reaches it on. */
1274
+ port: z4.number().int(),
1275
+ /** The port `public on` opens behind a host port: `port` again unless the kind serves TLS on another. */
1276
+ publicPort: z4.number().int(),
1277
+ /** Its guide, as a URL. */
1278
+ docs: z4.string().optional(),
1279
+ storage: z4.object({ defaultGib: z4.number().int(), minGib: z4.number().int(), maxGib: z4.number().int() }),
1280
+ /**
1281
+ * What create takes of this kind alone, beside what every kind takes (name, password, storage, near): a
1282
+ * flag and a form field each, all optional, `default` in words.
1283
+ */
1284
+ options: z4.array(z4.object({ name: z4.string(), title: z4.string(), description: z4.string(), default: z4.string() })),
1285
+ /** A month of it running with the default storage, and each further GB of storage. */
1286
+ price: PriceSchema.extend({ storageGibPerMonth: z4.number() }),
1287
+ /** Whether a host answering now can run it. */
1288
+ available: z4.boolean()
1289
+ });
1290
+ var CreateManagedRequest = z4.object({
1291
+ name: z4.string(),
1292
+ /** The kind's own options by name (its catalog entry lists them); the kind checks them. */
1293
+ options: z4.record(z4.string(), z4.string()).optional(),
1294
+ password: z4.string().optional(),
1295
+ storageGib: z4.number().int().optional(),
1296
+ /** Place it on the host of this box, so the box can be linked to it. */
1297
+ near: z4.string().optional()
1298
+ });
1299
+ var ManagedHealthSchema = z4.object({
1300
+ /** Its first start has finished: it has set itself up on its storage. */
1301
+ ready: z4.boolean(),
1302
+ /** It accepts connections. */
1303
+ accepting: z4.boolean(),
1304
+ version: z4.string(),
1305
+ /** The storage volume: what is used of it and its size. */
1306
+ storageUsedBytes: z4.number().optional(),
1307
+ storageTotalBytes: z4.number().optional(),
1308
+ /** What else the kind reports, ready to show: `{title: "Connections", value: "3"}`. */
1309
+ facts: z4.array(z4.object({ title: z4.string(), value: z4.string() }))
1310
+ });
1311
+ var UrlsSchema = z4.object({ private: z4.string(), public: z4.string().optional() });
1312
+ var ManagedSchema = z4.object({
1313
+ kind: z4.string(),
1314
+ name: z4.string(),
1315
+ /** The owning slug, bare. */
1316
+ owner: z4.string(),
1317
+ ownerKind: z4.enum(["user", "org"]),
1318
+ /** `running`, `stopped` (storage only is charged), `hibernated` or `standby` (out of credit), `unknown` (its host does not answer). */
1319
+ status: BoxStatusSchema,
1320
+ /** The catalog version: `18`. */
1321
+ version: z4.string(),
1322
+ /** What the kind keeps of its create options, defaults filled in: `{database, user}` for Postgres, `{}` for a kind with none. */
1323
+ settings: z4.record(z4.string(), z4.string()),
1324
+ storageGib: z4.number().int(),
1325
+ /** Where a linked box reaches it: `<name>.<slug>.kvbox` (resolves from a box of any slug it is linked to) and the port. */
1326
+ private: z4.object({ host: z4.string(), port: z4.number().int() }),
1327
+ /** Where the internet reaches it, null while it is not public. The port is its own for its whole life. */
1328
+ public: z4.object({ host: z4.string(), port: z4.number().int() }).nullable(),
1329
+ /** The boxes linked to it, as the caller would name them. */
1330
+ links: z4.array(z4.string()),
1331
+ /** The name of the host it runs on, for `--near` and links. */
1332
+ host: z4.string(),
1333
+ country: z4.string().optional(),
1334
+ createdBy: z4.string().nullable(),
1335
+ createdAt: z4.string(),
1336
+ /** Connection strings with the password as `****`. */
1337
+ urls: UrlsSchema,
1338
+ price: PriceSchema,
1339
+ /** Only in `GET /managed/<kind>/<name>` (asked live): null when it is not running or did not answer. */
1340
+ health: ManagedHealthSchema.nullable().optional()
1341
+ });
1342
+ var ManagedSecretSchema = z4.object({ password: z4.string(), urls: UrlsSchema });
1343
+ var CreatedManagedSchema = ManagedSchema.extend({ secret: ManagedSecretSchema });
1344
+ var ResetPasswordRequest = z4.object({ password: z4.string().optional() });
1345
+ var SetPublicRequest = z4.object({ on: z4.boolean() });
1346
+ var ManagedLinkRequest = z4.object({ box: z4.string() });
1347
+ var GrowManagedRequest = z4.object({ storageGib: z4.number().int() });
1348
+
1178
1349
  // src/kvm.ts
1179
1350
  import { accessSync, constants, readFileSync, statSync } from "fs";
1180
1351
  import { userInfo } from "os";
@@ -1242,7 +1413,7 @@ function unitActive() {
1242
1413
  // src/client.ts
1243
1414
  var ORG_SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
1244
1415
  function orgOption(opts) {
1245
- if (opts.org === void 0 || opts.org === "") return void 0;
1416
+ if (opts.org === void 0 || opts.org === "" || opts.org === "-") return void 0;
1246
1417
  if (!ORG_SLUG_RE.test(opts.org)) throw new KvboxError(`${opts.org}: not an org slug (lowercase letters, digits, '.', '_' or '-')`);
1247
1418
  return opts.org;
1248
1419
  }
@@ -1329,7 +1500,7 @@ var ServerClient = class {
1329
1500
  * `all`: every box on the platform (platform admins only, #78).
1330
1501
  */
1331
1502
  listMachines(opts = {}) {
1332
- return this.call("GET", `/machines${allQuery(opts)}`, z3.array(MachineSchema), void 0, opts.org);
1503
+ return this.call("GET", `/machines${allQuery(opts)}`, z5.array(MachineSchema), void 0, opts.org);
1333
1504
  }
1334
1505
  createMachine(req) {
1335
1506
  return this.call("POST", "/machines", MachineSchema, req);
@@ -1383,10 +1554,10 @@ var ServerClient = class {
1383
1554
  }
1384
1555
  /** Backups, the control plane's only: a box's disk in object storage. Newest first. */
1385
1556
  listBackups() {
1386
- return this.call("GET", "/backups", z3.array(BackupSchema));
1557
+ return this.call("GET", "/backups", z5.array(BackupSchema));
1387
1558
  }
1388
1559
  boxBackups(name) {
1389
- return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`, z3.array(BackupSchema));
1560
+ return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`, z5.array(BackupSchema));
1390
1561
  }
1391
1562
  boxBackup(name, id) {
1392
1563
  return this.call("GET", `/machines/${encodeURIComponent(name)}/backups/${encodeURIComponent(id)}`, BackupSchema);
@@ -1401,7 +1572,7 @@ var ServerClient = class {
1401
1572
  }
1402
1573
  /** Wake hooks (#101), the control plane's only: a URL and a secret that wake the box. */
1403
1574
  boxHooks(name) {
1404
- return this.call("GET", `/machines/${encodeURIComponent(name)}/hooks`, z3.array(WakeHookSchema));
1575
+ return this.call("GET", `/machines/${encodeURIComponent(name)}/hooks`, z5.array(WakeHookSchema));
1405
1576
  }
1406
1577
  createBoxHook(name) {
1407
1578
  return this.call("POST", `/machines/${encodeURIComponent(name)}/hooks`, CreatedWakeHookSchema);
@@ -1429,7 +1600,7 @@ var ServerClient = class {
1429
1600
  }
1430
1601
  /** Every readable box's subdomains, one entry each. */
1431
1602
  listSubdomains() {
1432
- return this.call("GET", "/subdomains", z3.array(SubdomainSchema));
1603
+ return this.call("GET", "/subdomains", z5.array(SubdomainSchema));
1433
1604
  }
1434
1605
  /** Custom domains (#89), the control plane's only: serve the box at the user's own name. */
1435
1606
  addDomain(name, req) {
@@ -1440,7 +1611,7 @@ var ServerClient = class {
1440
1611
  }
1441
1612
  /** Every readable box's custom domains. */
1442
1613
  listDomains() {
1443
- return this.call("GET", "/domains", z3.array(DomainSchema));
1614
+ return this.call("GET", "/domains", z5.array(DomainSchema));
1444
1615
  }
1445
1616
  /** A running box's own load, memory and disk, asked of its guest (#67). */
1446
1617
  machineStats(name) {
@@ -1469,22 +1640,22 @@ var ServerClient = class {
1469
1640
  return this.call("POST", "/billing/redeem", RedeemResponseSchema, { code });
1470
1641
  }
1471
1642
  deleteMachine(name) {
1472
- return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z3.undefined());
1643
+ return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z5.undefined());
1473
1644
  }
1474
1645
  /** Like `listMachines`, for snapshots. */
1475
1646
  listSnapshots(opts = {}) {
1476
- return this.call("GET", `/snapshots${allQuery(opts)}`, z3.array(SnapshotSchema), void 0, opts.org);
1647
+ return this.call("GET", `/snapshots${allQuery(opts)}`, z5.array(SnapshotSchema), void 0, opts.org);
1477
1648
  }
1478
1649
  createSnapshot(req) {
1479
1650
  return this.call("POST", "/snapshots", SnapshotSchema, req);
1480
1651
  }
1481
1652
  deleteSnapshot(name) {
1482
- return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`, z3.undefined());
1653
+ return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`, z5.undefined());
1483
1654
  }
1484
1655
  // ---- environment variables (#88), a control plane only: the caller's slug, or `--org`'s ----
1485
1656
  /** `org`: that org's list instead of `--org`'s (or the caller's own). */
1486
1657
  listEnv(org) {
1487
- return this.call("GET", "/vars", z3.array(EnvVarSchema), void 0, org);
1658
+ return this.call("GET", "/vars", z5.array(EnvVarSchema), void 0, org);
1488
1659
  }
1489
1660
  setEnv(name, req) {
1490
1661
  return this.call("PUT", `/vars/${encodeURIComponent(name)}`, EnvChangeSchema, req);
@@ -1504,13 +1675,13 @@ var ServerClient = class {
1504
1675
  }
1505
1676
  // ---- volumes (#52) ----
1506
1677
  listVolumes(opts = {}) {
1507
- return this.call("GET", `/volumes${allQuery(opts)}`, z3.array(VolumeSchema), void 0, opts.org);
1678
+ return this.call("GET", `/volumes${allQuery(opts)}`, z5.array(VolumeSchema), void 0, opts.org);
1508
1679
  }
1509
1680
  createVolume(req) {
1510
1681
  return this.call("POST", "/volumes", VolumeSchema, req);
1511
1682
  }
1512
1683
  deleteVolume(name) {
1513
- return this.call("DELETE", `/volumes/${encodeURIComponent(name)}`, z3.undefined());
1684
+ return this.call("DELETE", `/volumes/${encodeURIComponent(name)}`, z5.undefined());
1514
1685
  }
1515
1686
  /** Both answer with the box as it is afterwards (restarted when it was running). */
1516
1687
  attachVolume(name, req) {
@@ -1519,19 +1690,68 @@ var ServerClient = class {
1519
1690
  detachVolume(name, req) {
1520
1691
  return this.call("POST", `/volumes/${encodeURIComponent(name)}/detach`, MachineSchema, req);
1521
1692
  }
1693
+ /** #147: answers the volume at its new size; a running box holding it has restarted by then. */
1694
+ resizeVolume(name, sizeGib) {
1695
+ return this.call("POST", `/volumes/${encodeURIComponent(name)}/resize`, VolumeSchema, { sizeGib });
1696
+ }
1697
+ // ---- managed services (#173): the control plane's alone ----
1698
+ managedPath(kind, name, rest = "") {
1699
+ return `/managed/${encodeURIComponent(kind)}${name === void 0 ? "" : `/${encodeURIComponent(name)}`}${rest}`;
1700
+ }
1701
+ managedCatalog() {
1702
+ return this.call("GET", "/managed/catalog", z5.array(ManagedCatalogEntrySchema));
1703
+ }
1704
+ /** One kind's services, or every kind's when `kind` is left out. */
1705
+ listManaged(kind, opts = {}) {
1706
+ return this.call("GET", `${kind === void 0 ? "/managed" : this.managedPath(kind)}${allQuery(opts)}`, z5.array(ManagedSchema), void 0, opts.org);
1707
+ }
1708
+ createManaged(kind, req) {
1709
+ return this.call("POST", this.managedPath(kind), CreatedManagedSchema, req);
1710
+ }
1711
+ /** With `health`, asked of the service itself. */
1712
+ getManaged(kind, name) {
1713
+ return this.call("GET", this.managedPath(kind, name), ManagedSchema);
1714
+ }
1715
+ deleteManaged(kind, name) {
1716
+ return this.call("DELETE", this.managedPath(kind, name), z5.undefined());
1717
+ }
1718
+ managedPassword(kind, name) {
1719
+ return this.call("GET", this.managedPath(kind, name, "/password"), ManagedSecretSchema);
1720
+ }
1721
+ resetManagedPassword(kind, name, password) {
1722
+ return this.call("POST", this.managedPath(kind, name, "/password"), ManagedSecretSchema, password === void 0 ? {} : { password });
1723
+ }
1724
+ setManagedPublic(kind, name, on) {
1725
+ return this.call("POST", this.managedPath(kind, name, "/public"), ManagedSchema, { on });
1726
+ }
1727
+ linkManaged(kind, name, box) {
1728
+ return this.call("POST", this.managedPath(kind, name, "/links"), ManagedSchema, { box });
1729
+ }
1730
+ unlinkManaged(kind, name, box) {
1731
+ return this.call("DELETE", this.managedPath(kind, name, "/links"), ManagedSchema, { box });
1732
+ }
1733
+ growManaged(kind, name, storageGib) {
1734
+ return this.call("POST", this.managedPath(kind, name, "/grow"), ManagedSchema, { storageGib });
1735
+ }
1736
+ stopManaged(kind, name) {
1737
+ return this.call("POST", this.managedPath(kind, name, "/stop"), ManagedSchema);
1738
+ }
1739
+ startManaged(kind, name) {
1740
+ return this.call("POST", this.managedPath(kind, name, "/start"), ManagedSchema);
1741
+ }
1522
1742
  // ---- control plane only (`kvbox login`, `logout`, `whoami`) ----
1523
1743
  login(req) {
1524
1744
  return this.call("POST", "/login", LoginResponseSchema, req);
1525
1745
  }
1526
1746
  logout() {
1527
- return this.call("POST", "/logout", z3.unknown()).then(() => void 0);
1747
+ return this.call("POST", "/logout", z5.unknown()).then(() => void 0);
1528
1748
  }
1529
1749
  me() {
1530
1750
  return this.call("GET", "/me", MeResponseSchema);
1531
1751
  }
1532
1752
  // ---- orgs (`kvbox org …`) ----
1533
1753
  listOrgs() {
1534
- return this.call("GET", "/orgs", z3.array(OrgMembershipSchema));
1754
+ return this.call("GET", "/orgs", z5.array(OrgMembershipSchema));
1535
1755
  }
1536
1756
  createOrg(req) {
1537
1757
  return this.call("POST", "/orgs", CloudOrgSchema, req);
@@ -1540,16 +1760,16 @@ var ServerClient = class {
1540
1760
  return this.call("GET", `/orgs/${encodeURIComponent(slug)}`, OrgDetailSchema);
1541
1761
  }
1542
1762
  deleteOrg(slug) {
1543
- return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}`, z3.undefined());
1763
+ return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}`, z5.undefined());
1544
1764
  }
1545
1765
  addMember(slug, req) {
1546
- return this.call("POST", `/orgs/${encodeURIComponent(slug)}/members`, z3.undefined(), req);
1766
+ return this.call("POST", `/orgs/${encodeURIComponent(slug)}/members`, z5.undefined(), req);
1547
1767
  }
1548
1768
  setRole(slug, username, role) {
1549
- return this.call("PATCH", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z3.unknown(), { role }).then(() => void 0);
1769
+ return this.call("PATCH", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z5.unknown(), { role }).then(() => void 0);
1550
1770
  }
1551
1771
  removeMember(slug, username) {
1552
- return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z3.undefined());
1772
+ return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z5.undefined());
1553
1773
  }
1554
1774
  /** Sign this machine's key again (#51); the key must be one the user logged in with. */
1555
1775
  sshCert(req) {
@@ -3727,44 +3947,6 @@ var orgCommand = new Command50("org").description("orgs: shared slugs that own b
3727
3947
 
3728
3948
  // src/commands/usage.ts
3729
3949
  import { Command as Command51 } from "commander";
3730
-
3731
- // ../shared/src/usage.ts
3732
- import { z as z4 } from "zod";
3733
- var PricingSchema = z4.object({
3734
- currency: z4.string().min(1),
3735
- vcpuHour: z4.number().nonnegative(),
3736
- ramGibHour: z4.number().nonnegative(),
3737
- diskGibHour: z4.number().nonnegative(),
3738
- volumeHour: z4.number().nonnegative().default(0),
3739
- volumeGibHour: z4.number().nonnegative().default(0),
3740
- diskIncludedGib: z4.number().int().nonnegative().default(0)
3741
- });
3742
- var PriceListSchema = PricingSchema.extend({ welcomeCredit: z4.number().nonnegative() });
3743
- var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
3744
- function costOf(t, pricing) {
3745
- return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;
3746
- }
3747
- function sumUsage(items, pricing) {
3748
- const sum = {
3749
- seconds: { running: 0, standby: 0, hibernated: 0, stopped: 0 },
3750
- vcpuHours: 0,
3751
- ramGibHours: 0,
3752
- diskGibHours: 0
3753
- };
3754
- for (const t of items) {
3755
- for (const s of Object.keys(sum.seconds)) sum.seconds[s] += t.seconds[s];
3756
- sum.vcpuHours += t.vcpuHours;
3757
- sum.ramGibHours += t.ramGibHours;
3758
- sum.diskGibHours += t.diskGibHours;
3759
- }
3760
- sum.vcpuHours = round(sum.vcpuHours, 3);
3761
- sum.ramGibHours = round(sum.ramGibHours, 3);
3762
- sum.diskGibHours = round(sum.diskGibHours, 3);
3763
- if (pricing !== void 0) sum.cost = { amount: round(costOf(sum, pricing), 4), currency: pricing.currency };
3764
- return sum;
3765
- }
3766
-
3767
- // src/commands/usage.ts
3768
3950
  var usageCommand2 = new Command51("usage").description("what your boxes and volumes used this month (or --since/--until): running time, vCPU-h, RAM and disk GiB-h, cost").option("--since <date>", "count from this date, e.g. 2026-10-01 (default: the 1st of this month)").option("--until <date>", "count up to this date (default: now)").option("--org <slug>", "one org's boxes only").option("-a, --all", "every box on the platform (platform admins only)").option("--by-user", "one line per user who made the boxes (e.g. who spent what in --org)").option("--json", "print as JSON").action(async (opts, cmd) => {
3769
3951
  for (const [name, value] of [
3770
3952
  ["since", opts.since],
@@ -3968,7 +4150,7 @@ import { Command as Command54, InvalidArgumentError as InvalidArgumentError2, Op
3968
4150
  // src/commands/deploy/config.ts
3969
4151
  import { readFile as readFile6, writeFile as writeFile4 } from "fs/promises";
3970
4152
  import { isAbsolute, join as join6, normalize, relative as relative2 } from "path";
3971
- import { z as z5 } from "zod";
4153
+ import { z as z6 } from "zod";
3972
4154
 
3973
4155
  // src/commands/deploy/templates/docker.ts
3974
4156
  import { readFile as readFile5 } from "fs/promises";
@@ -3980,6 +4162,19 @@ var SERVICE = "kvbox-app";
3980
4162
  var START_WAIT_SEC = 30;
3981
4163
  var APP_NOT_LISTENING = 4;
3982
4164
  var LOG_MARKER = "--- kvbox-app log ---";
4165
+ var RELEASE_FAILED = 12;
4166
+ var RELEASE_LOG_LINES = 40;
4167
+ var DEP_WAIT_SEC = 60;
4168
+ var BOX_ENV_PLAIN = "/home/kvbox/.ssh/environment";
4169
+ var shq = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
4170
+ function waitFor(deps) {
4171
+ return deps.map(
4172
+ (d) => `ExecStartPre=/bin/bash -c 'timeout ${DEP_WAIT_SEC} bash -c "until (exec 3<>/dev/tcp/127.0.0.1/${d.port}) 2>/dev/null; do sleep 1; done" || { echo "kvbox: the database ${d.unit} did not answer on port ${d.port} within ${DEP_WAIT_SEC} s, so this service was not started"; exit 1; }'`
4173
+ );
4174
+ }
4175
+ function releaseStep(run3, root) {
4176
+ return [`if ! ${run3} > ${root}/.release.log 2>&1 </dev/null; then echo '${LOG_MARKER}'; tail -n ${RELEASE_LOG_LINES} ${root}/.release.log; exit ${RELEASE_FAILED}; fi`];
4177
+ }
3983
4178
  var DROP_CONTAINER = `if systemctl is-active --quiet docker && docker inspect ${SERVICE} >/dev/null 2>&1; then docker rm -f ${SERVICE} >/dev/null 2>&1 || true; docker rmi ${SERVICE} >/dev/null 2>&1 || true; sudo -n systemctl disable --quiet docker 2>/dev/null || true; fi`;
3984
4179
  function commands(pm) {
3985
4180
  switch (pm) {
@@ -4000,14 +4195,17 @@ function serverRemote(opts) {
4000
4195
  const root = opts.target?.root ?? "/srv/app";
4001
4196
  const appDir = opts.target ? `${root}/current` : APP_DIR;
4002
4197
  const service = opts.target?.unit ?? SERVICE;
4198
+ const after = opts.target?.after ?? [];
4199
+ const release = opts.target?.release;
4003
4200
  const unit = [
4004
4201
  "[Unit]",
4005
4202
  "Description=kvbox deploy: the app in " + appDir,
4006
- "After=network.target",
4203
+ ["After=network.target", ...after.map((d) => `${d.unit}.service`)].join(" "),
4007
4204
  "",
4008
4205
  "[Service]",
4009
4206
  "User=kvbox",
4010
4207
  `WorkingDirectory=${appDir}`,
4208
+ ...waitFor(after),
4011
4209
  // PORT on the command line: the proxied address points at it, and nothing in the environment
4012
4210
  // file below may move the app off it (env's PORT, say, copied from a .env).
4013
4211
  `ExecStart=/usr/bin/env PORT=${opts.port} ${c2.start}`,
@@ -4032,6 +4230,9 @@ function serverRemote(opts) {
4032
4230
  ...c2.setup,
4033
4231
  c2.install,
4034
4232
  ...opts.build ? [c2.build] : [],
4233
+ // In the new version's directory, with what the service itself will get: the box's variables
4234
+ // (read from the file, a session opened right after a boot may not have them yet), PORT, NODE_ENV.
4235
+ ...release !== void 0 ? releaseStep(`( if [ -r ${BOX_ENV_PLAIN} ]; then while IFS= read -r kv; do [ -z "$kv" ] || export "$kv"; done < ${BOX_ENV_PLAIN}; fi; export PORT=${opts.port} NODE_ENV=production; sh -c ${shq(release)} )`, root) : [],
4035
4236
  "cd /",
4036
4237
  // Before the unit is written: in a stack the single deploy's unit is the one being dropped.
4037
4238
  ...opts.target ? [DROP_SINGLE] : [],
@@ -4044,7 +4245,8 @@ function serverRemote(opts) {
4044
4245
  `sudo -n systemctl enable --quiet ${service}`,
4045
4246
  // A box that switched from the Docker template: its container holds the same box port.
4046
4247
  ...opts.target ? [] : [DROP_CONTAINER],
4047
- `sudo -n systemctl restart ${service}`,
4248
+ // With databases to wait for, the restart itself fails when one never comes: the wait below shows why.
4249
+ `sudo -n systemctl restart ${service}${after.length > 0 ? " || true" : ""}`,
4048
4250
  `rm -rf ${root}/.old`,
4049
4251
  // bash's /dev/tcp: no curl or nc in the image needed.
4050
4252
  "i=0",
@@ -4121,18 +4323,20 @@ function dockerRemote(port, containerPort) {
4121
4323
  "done"
4122
4324
  ].join("\n");
4123
4325
  }
4124
- var BOX_ENV_PLAIN = "/home/kvbox/.ssh/environment";
4125
4326
  function dockerServiceRemote(port, target, dockerfile) {
4126
4327
  const image = target.unit;
4328
+ const after = target.after ?? [];
4329
+ const built = target.release !== void 0 ? `${image}:next` : image;
4127
4330
  const unit = [
4128
4331
  "[Unit]",
4129
4332
  `Description=kvbox deploy: the container ${image}`,
4130
- "After=docker.service network-online.target",
4333
+ ["After=docker.service network-online.target", ...after.map((d) => `${d.unit}.service`)].join(" "),
4131
4334
  "Requires=docker.service",
4132
4335
  "",
4133
4336
  "[Service]",
4134
4337
  // A box that never had a variable has no file yet, and docker refuses a missing --env-file.
4135
4338
  `ExecStartPre=/bin/sh -c '[ -e ${BOX_ENV_PLAIN} ] || install -m 600 -o kvbox -g kvbox /dev/null ${BOX_ENV_PLAIN}'`,
4339
+ ...waitFor(after),
4136
4340
  `ExecStartPre=-/usr/bin/docker rm -f ${image}`,
4137
4341
  `ExecStart=/usr/bin/docker run --rm --name ${image} --network host --env-file ${BOX_ENV_PLAIN} -e PORT=${port} ${image}`,
4138
4342
  `ExecStop=/usr/bin/docker stop ${image}`,
@@ -4152,8 +4356,14 @@ function dockerServiceRemote(port, target, dockerfile) {
4152
4356
  `tar -xf - -C ${root}/.incoming`,
4153
4357
  `cd ${root}/.incoming`,
4154
4358
  // Quoted: the path is the user's `dir`, which may hold a space.
4155
- `docker build --progress=plain${dockerfile !== void 0 ? ` -f '${dockerfile.replaceAll("'", `'\\''`)}'` : ""} -t ${image} . 2>&1 | tail -n ${BUILD_LOG_LINES}`,
4359
+ `docker build --progress=plain${dockerfile !== void 0 ? ` -f ${shq(dockerfile)}` : ""} -t ${built} . 2>&1 | tail -n ${BUILD_LOG_LINES}`,
4156
4360
  "cd /",
4361
+ ...target.release !== void 0 ? [
4362
+ `[ -e ${BOX_ENV_PLAIN} ] || install -m 600 /dev/null ${BOX_ENV_PLAIN}`,
4363
+ ...releaseStep(`docker run --rm --network host --env-file ${BOX_ENV_PLAIN} -e PORT=${port} ${built} sh -c ${shq(target.release)}`, root),
4364
+ `docker tag ${built} ${image}:latest`,
4365
+ `docker rmi ${built} >/dev/null`
4366
+ ] : [],
4157
4367
  // The single deploy's app or container would hold its port and RAM beside the services.
4158
4368
  DROP_SINGLE,
4159
4369
  `sudo -n tee /etc/systemd/system/${target.unit}.service >/dev/null <<'UNIT'`,
@@ -4165,7 +4375,8 @@ function dockerServiceRemote(port, target, dockerfile) {
4165
4375
  "sudo -n systemctl daemon-reload",
4166
4376
  "sudo -n systemctl enable --quiet docker",
4167
4377
  `sudo -n systemctl enable --quiet ${target.unit}`,
4168
- `sudo -n systemctl restart ${target.unit}`,
4378
+ // With databases to wait for, the restart itself fails when one never comes: the wait below shows why.
4379
+ `sudo -n systemctl restart ${target.unit}${after.length > 0 ? " || true" : ""}`,
4169
4380
  "docker image prune -f >/dev/null",
4170
4381
  // The box's network: the port is the box's own, and nothing but the app answers on it.
4171
4382
  "i=0",
@@ -4363,21 +4574,21 @@ function detectTemplates(pkg, dir = NO_FACTS) {
4363
4574
  var DEPLOY_AUTO_HIBERNATE_SEC = 3600;
4364
4575
  var CONFIG_FILE = "kvbox.json";
4365
4576
  var BOX_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
4366
- var DeployConfigSchema = z5.object({
4367
- template: z5.enum(TEMPLATE_IDS),
4368
- name: z5.string().regex(BOX_NAME_RE, "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit"),
4577
+ var DeployConfigSchema = z6.object({
4578
+ template: z6.enum(TEMPLATE_IDS),
4579
+ name: z6.string().regex(BOX_NAME_RE, "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit"),
4369
4580
  /** The org whose box it is; absent for the user's own. */
4370
- org: z5.string().regex(ORG_SLUG_RE, "not an org slug").optional(),
4581
+ org: z6.string().regex(ORG_SLUG_RE, "not an org slug").optional(),
4371
4582
  /** The HTTPS name (`<subdomain>.kvbox.app`); absent when deploying to this machine's own host. */
4372
- subdomain: z5.string().check((ctx) => {
4583
+ subdomain: z6.string().check((ctx) => {
4373
4584
  const problem = subdomainProblem(ctx.value);
4374
4585
  if (problem) ctx.issues.push({ code: "custom", message: problem, input: ctx.value });
4375
4586
  }).optional(),
4376
- size: z5.enum(SIZE_NAMES).optional(),
4587
+ size: z6.enum(SIZE_NAMES).optional(),
4377
4588
  /** The build output directory, relative to the app; the template's default when absent. */
4378
- dist: z5.string().optional(),
4589
+ dist: z6.string().optional(),
4379
4590
  /** The port a Next.js app or Node server serves; the template's (3000) when absent. */
4380
- port: z5.number().int().min(1).max(65535).optional()
4591
+ port: z6.number().int().min(1).max(65535).optional()
4381
4592
  });
4382
4593
  var SERVICE_KEY_RE = /^[a-z][a-z0-9-]{0,19}$/;
4383
4594
  var RESERVED_SERVICE_KEYS = ["app", "agent", "init", "volumes"];
@@ -4389,32 +4600,38 @@ var POSTGRES_PORT = 5432;
4389
4600
  var POSTGRES_IMAGE = "postgres:17";
4390
4601
  var POSTGRES_ENV = "DATABASE_URL";
4391
4602
  var IMAGE_RE = /^[a-z0-9][a-z0-9._/:@-]*$/;
4392
- var ServiceSchema = z5.strictObject({
4393
- template: z5.enum([...TEMPLATE_IDS, POSTGRES]),
4603
+ var ServiceSchema = z6.strictObject({
4604
+ template: z6.enum([...TEMPLATE_IDS, POSTGRES]),
4394
4605
  /** The service's directory, relative to the one holding kvbox.json; every template but postgres has one. */
4395
- dir: z5.string().min(1).optional(),
4606
+ dir: z6.string().min(1).optional(),
4396
4607
  /** A postgres service's image, `postgres:17` when absent (`pgvector/pgvector:pg17` for vectors). */
4397
- image: z5.string().regex(IMAGE_RE, "an image name like postgres:17").optional(),
4608
+ image: z6.string().regex(IMAGE_RE, "an image name like postgres:17").optional(),
4398
4609
  /** The volume (a key of `volumes`) a postgres service keeps its data on. */
4399
- volume: z5.string().optional(),
4610
+ volume: z6.string().optional(),
4400
4611
  /** The box variable a postgres service's URL is written to, `DATABASE_URL` when absent. */
4401
- env: z5.string().optional(),
4612
+ env: z6.string().optional(),
4402
4613
  /** A docker service's build context, relative to kvbox.json, when it is not `dir` (a monorepo built from its root); the Dockerfile stays in `dir`. */
4403
- context: z5.string().min(1).optional(),
4404
- dist: z5.string().optional(),
4614
+ context: z6.string().min(1).optional(),
4615
+ dist: z6.string().optional(),
4616
+ /**
4617
+ * A command run once per deploy in the service's new version (a docker service: in a container of
4618
+ * the new image; node, nextjs: in the new source, installed and built), with the box's variables,
4619
+ * before it replaces the running one. Migrations, mostly. A failing one stops that service's deploy.
4620
+ */
4621
+ release: z6.string().optional(),
4405
4622
  /** The box port of a service with its own server; the template's (3000) when absent. */
4406
- port: z5.number().int().min(1).max(65535).optional(),
4623
+ port: z6.number().int().min(1).max(65535).optional(),
4407
4624
  /** The URL paths that go to this service, each with everything under it; the prefix is kept. */
4408
- paths: z5.array(z5.string().regex(ROUTE_RE, "a path like / or /api, no trailing slash")).min(1).optional()
4625
+ paths: z6.array(z6.string().regex(ROUTE_RE, "a path like / or /api, no trailing slash")).min(1).optional()
4409
4626
  });
4410
- var StackConfigSchema = z5.strictObject({
4627
+ var StackConfigSchema = z6.strictObject({
4411
4628
  name: DeployConfigSchema.shape.name.optional(),
4412
4629
  org: DeployConfigSchema.shape.org,
4413
4630
  subdomain: DeployConfigSchema.shape.subdomain,
4414
4631
  size: DeployConfigSchema.shape.size,
4415
4632
  /** The stack's volumes, name to size ("10GB"): made for its box and attached to it on the first deploy that needs one. */
4416
- volumes: z5.record(z5.string(), z5.string()).optional(),
4417
- services: z5.record(z5.string(), ServiceSchema)
4633
+ volumes: z6.record(z6.string(), z6.string()).optional(),
4634
+ services: z6.record(z6.string(), ServiceSchema)
4418
4635
  });
4419
4636
  function volumeGib(text2) {
4420
4637
  const mib = parseMib(text2);
@@ -4456,6 +4673,10 @@ function stackServices(stack, defaultPort, exposed = /* @__PURE__ */ new Map())
4456
4673
  const isStatic = STATIC_TEMPLATES.includes(config.template);
4457
4674
  const paths2 = config.paths ?? [];
4458
4675
  if (isStatic && config.port !== void 0) throw new KvboxError(`${at}.port: a ${config.template} service has no port of its own; nginx serves its files`);
4676
+ if (config.release !== void 0) {
4677
+ if (isStatic) throw new KvboxError(`${at}.release: a ${config.template} service is files only, nothing runs in the box; put the command on the service that has the server`);
4678
+ if (config.release.trim() === "" || /[\r\n]/.test(config.release)) throw new KvboxError(`${at}.release: one command on one line, like "release": "npm run migrate"`);
4679
+ }
4459
4680
  if (isStatic && paths2.length === 0) throw new KvboxError(`${at}.paths: say where the site is served, for example "paths": ["/"]`);
4460
4681
  let port;
4461
4682
  if (!isStatic) {
@@ -4484,7 +4705,7 @@ function stackServices(stack, defaultPort, exposed = /* @__PURE__ */ new Map())
4484
4705
  }
4485
4706
  function postgresService(key, config, stack, { volumeUsers, envUsers }, ports) {
4486
4707
  const at = `${CONFIG_FILE}: services.${key}`;
4487
- for (const field of ["dir", "context", "dist", "paths"]) {
4708
+ for (const field of ["dir", "context", "dist", "release", "paths"]) {
4488
4709
  if (config[field] !== void 0) throw new KvboxError(`${at}.${field}: a postgres service has none${field === "paths" ? "; it is reached by the other services on 127.0.0.1, never from the internet" : ""}`);
4489
4710
  }
4490
4711
  const env = config.env ?? POSTGRES_ENV;
@@ -4616,6 +4837,14 @@ ${result.output.trim()}` : ""}`, SSH_FAILED3);
4616
4837
  `box ${ref} runs an image too old for the ${template.label} template (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}) once its host has the new image, or deploy under another name (--name) to get a fresh box`
4617
4838
  );
4618
4839
  }
4840
+ if (result.status === RELEASE_FAILED) {
4841
+ const log = result.output.split(LOG_MARKER)[1]?.trim();
4842
+ throw new KvboxError(
4843
+ `${app}: its release command (${service?.release ?? "release"}) failed, so the new version was not started. Nothing in box ${ref} was replaced: a version of ${service?.key ?? "it"} already running keeps running${log ? `
4844
+ last lines:
4845
+ ${log}` : ""}`
4846
+ );
4847
+ }
4619
4848
  if (result.status === APP_NOT_LISTENING) {
4620
4849
  const log = result.output.split(LOG_MARKER)[1]?.trim();
4621
4850
  const where = built.containerPort !== void 0 && built.containerPort !== port ? `the container's port ${built.containerPort} (box port ${port})` : `port ${port}`;
@@ -4891,22 +5120,24 @@ async function deployStack(d) {
4891
5120
  };
4892
5121
  const databases = picked.filter((s) => s.postgres);
4893
5122
  if (databases.length > 0) await deployDatabases({ client, ref, owner: machine.owner, name: machine.name, ep, volumes: config.volumes ?? {}, databases, renewOnce });
5123
+ const after = services.filter((s) => s.postgres).map((s) => ({ unit: `kvbox-${s.key}`, port: s.port }));
4894
5124
  for (const { service, template, built, size } of all) {
4895
- const target = { root: `/srv/app/${service.key}`, unit: `kvbox-${service.key}` };
5125
+ const release = service.config.release;
5126
+ const target = { root: `/srv/app/${service.key}`, unit: `kvbox-${service.key}`, ...release !== void 0 ? { release } : {}, ...after.length > 0 && !service.static ? { after } : {} };
4896
5127
  const port = service.port ?? FRONT_PORT;
4897
5128
  const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port, target), built.exclude);
4898
5129
  const there = service.static ? "" : template.id === "docker" ? " and building the image there, a minute or two" : built.boxBuild ? " and installing and building there, a minute or two" : " and installing there, a minute or two";
4899
- const doing = `${service.key}: shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}${there}\u2026`;
5130
+ const doing = `${service.key}: shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}${there}${release !== void 0 ? ", then its release command" : ""}\u2026`;
4900
5131
  let result = await spin(doing, shipIt);
4901
5132
  if (result.status === SSH_FAILED3 && await renewOnce()) result = await spin(doing, shipIt);
4902
- refuseFailedShip(result, { ref, template, port, built, ...service.static ? {} : { service: { key: service.key, unit: target.unit } } });
5133
+ refuseFailedShip(result, { ref, template, port, built, ...service.static ? {} : { service: { key: service.key, unit: target.unit, ...release !== void 0 ? { release } : {} } } });
4903
5134
  }
4904
5135
  const front = await spin(`pointing the box's front door at ${services.length === 1 ? "the service" : `the ${services.length} services`}\u2026`, shipping.run(ep, frontRemote(stackSite(services))));
4905
5136
  if (front.status === IMAGE_TOO_OLD) throw new KvboxError(`box ${ref} has no nginx: its image is too old (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}), or deploy under another name (--name) to get a fresh box`);
4906
5137
  if (front.status === SITE_REFUSED) {
4907
5138
  const first = front.output.includes(NO_PREVIOUS_SITE);
4908
- const after = first ? "this was the box's first stack, so there are no previous routes to keep, and any single app it ran was stopped for the services: its address answers nothing until a deploy whose routes nginx takes" : "the previous ones keep serving";
4909
- throw new KvboxError(`nginx in box ${ref} refused the routes made from ${CONFIG_FILE}; ${after}. The services themselves were deployed.
5139
+ const after2 = first ? "this was the box's first stack, so there are no previous routes to keep, and any single app it ran was stopped for the services: its address answers nothing until a deploy whose routes nginx takes" : "the previous ones keep serving";
5140
+ throw new KvboxError(`nginx in box ${ref} refused the routes made from ${CONFIG_FILE}; ${after2}. The services themselves were deployed.
4910
5141
  ${front.output.replace(NO_PREVIOUS_SITE, "").trim()}`);
4911
5142
  }
4912
5143
  if (front.status !== 0) throw new KvboxError(`setting up nginx in box ${ref} failed (exit ${front.status}):
@@ -4932,6 +5163,7 @@ ${front.output.trim()}`);
4932
5163
  bytes: size.bytes,
4933
5164
  ...built.dist !== void 0 ? { dist: built.dist } : {},
4934
5165
  ...service.port !== void 0 ? { port: service.port } : {},
5166
+ ...service.config.release !== void 0 ? { release: service.config.release } : {},
4935
5167
  paths: service.paths
4936
5168
  }))
4937
5169
  ],
@@ -5335,7 +5567,7 @@ async function settle2(dir, pkg, facts, saved, opts, orgFlag, cloud) {
5335
5567
  }
5336
5568
 
5337
5569
  // src/commands/volume/index.ts
5338
- import { Command as Command60 } from "commander";
5570
+ import { Command as Command61 } from "commander";
5339
5571
 
5340
5572
  // src/commands/volume/attach.ts
5341
5573
  import { Command as Command55 } from "commander";
@@ -5363,11 +5595,11 @@ var attachCommand = new Command55("attach").description("attach a volume to a bo
5363
5595
 
5364
5596
  // src/commands/volume/create.ts
5365
5597
  import { Command as Command56 } from "commander";
5366
- function parseGib2(text2) {
5598
+ function parseGib2(text2, label = "--size") {
5367
5599
  const mib = parseMib(text2);
5368
- if (mib === void 0 || mib % 1024 !== 0) throw new KvboxError(`--size ${text2}: write whole GB, like 50 or 50GB`);
5600
+ if (mib === void 0 || mib % 1024 !== 0) throw new KvboxError(`${label} ${text2}: write whole GB, like 50 or 50GB`);
5369
5601
  const gib = mib / 1024;
5370
- if (gib > MAX_VOLUME_GIB) throw new KvboxError(`--size ${text2}: a volume is at most ${MAX_VOLUME_GIB} GB`);
5602
+ if (gib > MAX_VOLUME_GIB) throw new KvboxError(`${label} ${text2}: a volume is at most ${MAX_VOLUME_GIB} GB`);
5371
5603
  return gib;
5372
5604
  }
5373
5605
  function sizeProblem(answer) {
@@ -5436,9 +5668,23 @@ var detachCommand = new Command57("detach").description("detach a volume from a
5436
5668
  }
5437
5669
  });
5438
5670
 
5439
- // src/commands/volume/ls.ts
5671
+ // src/commands/volume/grow.ts
5440
5672
  import { Command as Command58 } from "commander";
5441
- var lsCommand8 = new Command58("ls").alias("list").description("list volumes: size, what they occupy, which box has them").option("-a, --all", "every volume on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
5673
+ var growCommand = new Command58("grow").alias("resize").description("make a volume larger (a running box holding it is restarted once)").argument("<volume>", "volume name").argument("<GB>", "the new size in GB, larger than what it has").option("--json", "print the volume as JSON").action(async (name, size, opts, cmd) => {
5674
+ const sizeGib = parseGib2(size, "size");
5675
+ const client = await clientFor(cmd.optsWithGlobals());
5676
+ try {
5677
+ const vol = await spin(`growing volume ${name} to ${sizeGib} GB\u2026`, client.resizeVolume(name, sizeGib));
5678
+ if (opts.json) json(vol);
5679
+ else info(`${color.green("\u2713")} volume ${name} is ${vol.sizeGib} GB${vol.attachedTo ? color.dim(` (box ${vol.attachedTo} was restarted if it was running)`) : ""}`);
5680
+ } finally {
5681
+ await client.close();
5682
+ }
5683
+ });
5684
+
5685
+ // src/commands/volume/ls.ts
5686
+ import { Command as Command59 } from "commander";
5687
+ var lsCommand8 = new Command59("ls").alias("list").description("list volumes: size, what they occupy, which box has them").option("-a, --all", "every volume on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
5442
5688
  const client = await clientFor(cmd.optsWithGlobals());
5443
5689
  try {
5444
5690
  const cloud = client.target.kind === "cloud";
@@ -5469,8 +5715,8 @@ var lsCommand8 = new Command58("ls").alias("list").description("list volumes: si
5469
5715
  });
5470
5716
 
5471
5717
  // src/commands/volume/rm.ts
5472
- import { Command as Command59 } from "commander";
5473
- var rmCommand7 = new Command59("rm").alias("remove").description("delete a volume and everything on it (detach it first)").argument("<name>", "volume name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
5718
+ import { Command as Command60 } from "commander";
5719
+ var rmCommand7 = new Command60("rm").alias("remove").description("delete a volume and everything on it (detach it first)").argument("<name>", "volume name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
5474
5720
  if (!await confirm(`Delete volume ${name} and everything on it?`, opts.yes ?? false)) {
5475
5721
  info("cancelled");
5476
5722
  process.exitCode = 1;
@@ -5486,14 +5732,337 @@ var rmCommand7 = new Command59("rm").alias("remove").description("delete a volum
5486
5732
  });
5487
5733
 
5488
5734
  // src/commands/volume/index.ts
5489
- var volumeCommand = new Command60("volume").aliases(["volumes", "vol"]).description("disks of their own: create one, attach it to a box at /mnt/<name>, move it to another box later").addCommand(createCommand3).addCommand(lsCommand8).addCommand(attachCommand).addCommand(detachCommand).addCommand(rmCommand7);
5735
+ var volumeCommand = new Command61("volume").aliases(["volumes", "vol"]).description("disks of their own: create one, attach it to a box at /mnt/<name>, move it to another box later").addCommand(createCommand3).addCommand(lsCommand8).addCommand(attachCommand).addCommand(detachCommand).addCommand(growCommand).addCommand(rmCommand7);
5490
5736
  for (const cmd of volumeCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal volumes)");
5491
5737
 
5492
- // src/commands/env/index.ts
5738
+ // src/commands/managed/kind.ts
5739
+ import { Command as Command74 } from "commander";
5740
+
5741
+ // src/commands/managed/create.ts
5742
+ import { Command as Command63 } from "commander";
5743
+ import { setTimeout as sleep3 } from "timers/promises";
5744
+
5745
+ // src/commands/managed/shared.ts
5746
+ import "commander";
5747
+ var POSTGRES2 = {
5748
+ kind: "postgres",
5749
+ command: "pg",
5750
+ aliases: ["postgres"],
5751
+ title: "PostgreSQL",
5752
+ storageGib: 10,
5753
+ options: [
5754
+ { name: "database", arg: "name", help: "the database created in it (default: the name)" },
5755
+ { name: "user", arg: "name", help: "the user that owns it (default: the name)" }
5756
+ ]
5757
+ };
5758
+ var REDIS = {
5759
+ kind: "redis",
5760
+ command: "redis",
5761
+ aliases: [],
5762
+ title: "Redis (Valkey)",
5763
+ storageGib: 5,
5764
+ options: []
5765
+ };
5766
+ var KINDS = [POSTGRES2, REDIS];
5767
+ async function managedClient(cmd) {
5768
+ const client = await clientFor(cmd.optsWithGlobals());
5769
+ if (client.target.kind !== "cloud") {
5770
+ await client.close();
5771
+ throw new KvboxError("managed databases run on the kvbox cloud: kvbox login first (this host's own socket has none)");
5772
+ }
5773
+ return client;
5774
+ }
5775
+ var shownName = (m, user) => m.owner === user ? m.name : `${m.owner}/${m.name}`;
5776
+ var storageText = (m) => m.health?.storageUsedBytes !== void 0 ? `${gb(m.health.storageUsedBytes)} of ${m.storageGib} GB used` : `${m.storageGib} GB`;
5777
+ var nearlyFull = (m) => m.health?.storageUsedBytes !== void 0 && m.health.storageTotalBytes !== void 0 && m.health.storageTotalBytes > 0 && m.health.storageUsedBytes / m.health.storageTotalBytes >= 0.9;
5778
+ function stateText(m) {
5779
+ if (m.status === "stopped") return `${status(m.status)} ${color.dim("(only its storage is charged)")}`;
5780
+ if (m.status !== "running" || m.health === void 0) return status(m.status);
5781
+ if (m.health === null) return `${status(m.status)}${color.dim(", not answering yet")}`;
5782
+ if (!m.health.ready) return `${status(m.status)}${color.dim(", still setting itself up")}`;
5783
+ return `${status(m.status)}, ${m.health.accepting ? "accepting connections" : color.yellow("not accepting connections")}`;
5784
+ }
5785
+ function infoRows(spec, m, user) {
5786
+ const name = shownName(m, user);
5787
+ const rows2 = [
5788
+ ["name", color.bold(name)],
5789
+ ["status", stateText(m)],
5790
+ ["version", `${spec.title} ${m.health?.version ?? m.version}`]
5791
+ ];
5792
+ if (user !== void 0 && m.owner !== user) rows2.push(["owner", m.owner]);
5793
+ for (const fact of m.health?.facts ?? []) rows2.push([fact.title.toLowerCase(), fact.value]);
5794
+ rows2.push(["storage", `${storageText(m)}${nearlyFull(m) ? color.yellow(` almost full: kvbox ${spec.command} grow ${name} <GB>`) : ""}`]);
5795
+ rows2.push(...settingRows(spec, m.settings), ["password", color.dim(`kvbox ${spec.command} password ${name}`)]);
5796
+ rows2.push(["private", `${m.urls.private} ${color.dim(m.links.length > 0 ? `(from ${m.links.join(", ")})` : `(no box is linked: kvbox ${spec.command} link ${name} <box>)`)}`]);
5797
+ rows2.push(["public", m.urls.public ?? color.dim(`off (kvbox ${spec.command} public ${name} on)`)]);
5798
+ rows2.push(["cost", `${money(m.price.perMonth, m.price.currency)} a month while it runs, ${money(m.price.storagePerMonth, m.price.currency)} stopped ${color.dim("(estimated)")}`]);
5799
+ rows2.push(["created", `${age(m.createdAt)}${m.createdBy ? ` by ${m.createdBy}` : ""}`]);
5800
+ return rows2;
5801
+ }
5802
+ function printRows(rows2) {
5803
+ const width2 = Math.max(...rows2.map(([label]) => label.length));
5804
+ for (const [label, value] of rows2) process.stdout.write(`${color.dim(label.padEnd(width2))} ${value}
5805
+ `);
5806
+ }
5807
+ function settingRows(spec, settings) {
5808
+ const order = spec.options.map((o) => o.name);
5809
+ const names2 = [...order.filter((name) => settings[name] !== void 0), ...Object.keys(settings).filter((name) => !order.includes(name))];
5810
+ return names2.map((name) => [name, settings[name]]);
5811
+ }
5812
+ function secretRows(secret) {
5813
+ return [
5814
+ ["password", secret.password],
5815
+ ["private", secret.urls.private],
5816
+ ...secret.urls.public ? [["public", secret.urls.public]] : []
5817
+ ];
5818
+ }
5819
+ function parseStorage(text2, flag) {
5820
+ const m = /^\s*(\d+)\s*(g|gb|gib)?\s*$/i.exec(text2);
5821
+ if (!m || Number(m[1]) < 1) throw new KvboxError(`${flag} ${text2}: write whole GB, like 50 or 50GB`);
5822
+ return Number(m[1]);
5823
+ }
5824
+
5825
+ // src/commands/managed/create.ts
5826
+ var READY_WAIT_MS = 9e4;
5827
+ var READY_STEP_MS = 2e3;
5828
+ var createCommand4 = (spec) => {
5829
+ const command = new Command63("create").alias("new").description(`create a ${spec.title} database: a name is all it needs`).argument("<name>", "its name (1-12 chars, lowercase letters, digits and '-'); a linked box reaches it at <name>.<account>.kvbox");
5830
+ for (const o of spec.options) command.option(`--${o.name} <${o.arg}>`, o.help);
5831
+ return command.option("--password <password>", "its password (default: generated)").option("--storage <gb>", `storage for the data in GB (default: ${spec.storageGib}; it can grow later)`).option("--near <box>", "run it on the host of this box, so the box can be linked to it").option("--json", "print it as JSON, password included").action(async (name, opts, cmd) => {
5832
+ const options = Object.fromEntries(spec.options.flatMap((o) => typeof opts[o.name] === "string" ? [[o.name, opts[o.name]]] : []));
5833
+ const req = {
5834
+ name,
5835
+ ...Object.keys(options).length > 0 ? { options } : {},
5836
+ ...opts.password !== void 0 ? { password: opts.password } : {},
5837
+ ...opts.storage !== void 0 ? { storageGib: parseStorage(opts.storage, "--storage") } : {},
5838
+ ...opts.near !== void 0 ? { near: opts.near } : {}
5839
+ };
5840
+ const client = await managedClient(cmd);
5841
+ try {
5842
+ const made = await spin(`creating ${spec.title} database ${name}\u2026`, client.createManaged(spec.kind, req));
5843
+ const shown = shownName(made, me(client));
5844
+ const ready = await spin(`starting ${spec.title}\u2026`, async () => {
5845
+ for (const until = Date.now() + READY_WAIT_MS; Date.now() < until; await sleep3(READY_STEP_MS)) {
5846
+ const now = await client.getManaged(spec.kind, shown).catch(() => void 0);
5847
+ if (now?.health?.ready && now.health.accepting) return true;
5848
+ }
5849
+ return false;
5850
+ });
5851
+ if (opts.json) {
5852
+ json({ ...made, ready });
5853
+ return;
5854
+ }
5855
+ info(`${color.green("\u2713")} database ${color.bold(shown)} ${ready ? "is ready" : "is created and still starting"} ${color.dim(`(${spec.title} ${made.version}, ${made.storageGib} GB of storage)`)}`);
5856
+ printRows([...settingRows(spec, made.settings), ...secretRows(made.secret)].map(([label, value]) => [` ${label}`, value]));
5857
+ info("");
5858
+ info("Nobody can reach it yet. To let something in:");
5859
+ info(` a box on the same host kvbox ${spec.command} link ${shown} <box> ${color.dim(`(a new one: kvbox new <box> --near ${shown})`)}`);
5860
+ info(` the internet kvbox ${spec.command} public ${shown} on`);
5861
+ info(color.dim(`It costs about ${money(made.price.perMonth, made.price.currency)} a month while it runs, ${money(made.price.storagePerMonth, made.price.currency)} stopped. The password again: kvbox ${spec.command} password ${shown}`));
5862
+ if (!ready) info(color.dim(`It was not answering after ${READY_WAIT_MS / 1e3} s; see how it is with: kvbox ${spec.command} info ${shown}`));
5863
+ } finally {
5864
+ await client.close();
5865
+ }
5866
+ });
5867
+ };
5868
+
5869
+ // src/commands/managed/grow.ts
5493
5870
  import { Command as Command64 } from "commander";
5871
+ var growCommand2 = (spec) => new Command64("grow").description("give a database more storage (it restarts once)").argument("<db>", "its name").argument("<GB>", "the new size in GB, larger than what it has").option("--json", "print as JSON").action(async (name, size, opts, cmd) => {
5872
+ const storageGib = parseStorage(size, "size");
5873
+ const client = await managedClient(cmd);
5874
+ try {
5875
+ const m = await spin(`growing ${name} to ${storageGib} GB (it restarts once)\u2026`, client.growManaged(spec.kind, name, storageGib));
5876
+ if (opts.json) json(m);
5877
+ else info(`${color.green("\u2713")} database ${name} has ${m.storageGib} GB of storage ${color.dim(`(about ${money(m.price.perMonth, m.price.currency)} a month while it runs)`)}`);
5878
+ } finally {
5879
+ await client.close();
5880
+ }
5881
+ });
5882
+
5883
+ // src/commands/managed/info.ts
5884
+ import { Command as Command65 } from "commander";
5885
+ var infoCommand = (spec) => new Command65("info").alias("get").description("show one database: status, storage used, how to connect").argument("<db>", "its name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
5886
+ const client = await managedClient(cmd);
5887
+ try {
5888
+ const m = await client.getManaged(spec.kind, name);
5889
+ if (opts.json) json(m);
5890
+ else printRows(infoRows(spec, m, me(client)));
5891
+ } finally {
5892
+ await client.close();
5893
+ }
5894
+ });
5895
+
5896
+ // src/commands/managed/link.ts
5897
+ import { Command as Command66 } from "commander";
5898
+ var linkCommand2 = (spec) => new Command66("link").description("let a box reach a database privately (same host)").argument("<db>", "the database").argument("<box>", "the box that connects to it").option("--json", "print as JSON").action(async (name, box, opts, cmd) => {
5899
+ const client = await managedClient(cmd);
5900
+ try {
5901
+ const m = await spin(`linking ${box} to ${name}\u2026`, client.linkManaged(spec.kind, name, box));
5902
+ if (opts.json) {
5903
+ json(m);
5904
+ return;
5905
+ }
5906
+ info(`${color.green("\u2713")} box ${box} can reach database ${name}`);
5907
+ info(` inside ${box}: ${m.urls.private} ${color.dim(`(the password: kvbox ${spec.command} password ${name})`)}`);
5908
+ } finally {
5909
+ await client.close();
5910
+ }
5911
+ });
5912
+
5913
+ // src/commands/managed/ls.ts
5914
+ import { Command as Command67 } from "commander";
5915
+ function listRows(items, user, kindColumn) {
5916
+ return items.map((m) => ({
5917
+ owner: m.owner === user ? "private" : m.owner,
5918
+ name: boxName(m.name),
5919
+ ...kindColumn ? { kind: KINDS.find((k) => k.kind === m.kind)?.title ?? m.kind } : {},
5920
+ status: status(m.status),
5921
+ version: m.version,
5922
+ storage: `${m.storageGib}GB`,
5923
+ public: m.public ? `${m.public.host}:${m.public.port}` : "-",
5924
+ linked: m.links.length > 0 ? m.links.join(", ") : "-",
5925
+ created: age(m.createdAt)
5926
+ }));
5927
+ }
5928
+ var lsCommand9 = (spec) => new Command67("ls").alias("list").description(spec ? `list your ${spec.title} databases` : "list every managed database, whatever its kind").option("-a, --all", "every one on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
5929
+ const client = await managedClient(cmd);
5930
+ try {
5931
+ const items = await client.listManaged(spec?.kind, { all: opts.all });
5932
+ if (opts.json) {
5933
+ json(items);
5934
+ return;
5935
+ }
5936
+ if (items.length === 0) {
5937
+ info(`no ${spec ? `${spec.title} ` : "managed "}databases yet; make one with: kvbox ${spec?.command ?? KINDS[0].command} create <name>`);
5938
+ return;
5939
+ }
5940
+ const user = client.target.kind === "cloud" ? client.target.user : void 0;
5941
+ table(listRows(items, user, spec === void 0));
5942
+ } finally {
5943
+ await client.close();
5944
+ }
5945
+ });
5946
+
5947
+ // src/commands/managed/password.ts
5948
+ import { Command as Command68 } from "commander";
5949
+ var passwordCommand = (spec) => new Command68("password").description("show a database's password, or set a new one with --reset").argument("<db>", "its name").option("--reset", "make a new password; the old one stops working").option("--json", "print as JSON").action(async (name, opts, cmd) => {
5950
+ const client = await managedClient(cmd);
5951
+ try {
5952
+ const secret = opts.reset ? await spin(`setting a new password on ${name}\u2026`, client.resetManagedPassword(spec.kind, name)) : await client.managedPassword(spec.kind, name);
5953
+ if (opts.json) {
5954
+ json(secret);
5955
+ return;
5956
+ }
5957
+ if (opts.reset) info(`${color.green("\u2713")} database ${name} has a new password; the old one no longer works`);
5958
+ printRows(secretRows(secret));
5959
+ } finally {
5960
+ await client.close();
5961
+ }
5962
+ });
5963
+
5964
+ // src/commands/managed/public.ts
5965
+ import { Command as Command69 } from "commander";
5966
+ var publicCommand = (spec) => new Command69("public").description("open a database to the internet, or close it again").argument("<db>", "its name").argument("<state>", "on: reachable from anywhere with the password; off: only linked boxes").option("--json", "print as JSON").action(async (name, state, opts, cmd) => {
5967
+ if (state !== "on" && state !== "off") throw new KvboxError(`write on or off: kvbox ${spec.command} public ${name} on`);
5968
+ const client = await managedClient(cmd);
5969
+ try {
5970
+ const m = await spin(`${state === "on" ? "opening" : "closing"} ${name}\u2026`, client.setManagedPublic(spec.kind, name, state === "on"));
5971
+ if (opts.json) {
5972
+ json(m);
5973
+ return;
5974
+ }
5975
+ if (m.public) {
5976
+ info(`${color.green("\u2713")} database ${name} is reachable from the internet at ${color.bold(`${m.public.host}:${m.public.port}`)}`);
5977
+ info(` ${m.urls.public} ${color.dim(`(the password: kvbox ${spec.command} password ${name})`)}`);
5978
+ } else {
5979
+ info(`${color.green("\u2713")} database ${name} is closed to the internet; turning it on again gives the same address`);
5980
+ }
5981
+ } finally {
5982
+ await client.close();
5983
+ }
5984
+ });
5985
+
5986
+ // src/commands/managed/rm.ts
5987
+ import { Command as Command70 } from "commander";
5988
+ var rmCommand8 = (spec) => new Command70("rm").alias("remove").description("delete a database and all its data").argument("<db>", "its name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
5989
+ const client = await managedClient(cmd);
5990
+ try {
5991
+ if (!await confirm(`Delete database ${name} and all its data? There is no backup.`, opts.yes ?? false)) {
5992
+ info("cancelled");
5993
+ process.exitCode = 1;
5994
+ return;
5995
+ }
5996
+ await spin(`deleting database ${name}\u2026`, client.deleteManaged(spec.kind, name));
5997
+ info(`${color.green("\u2713")} database ${name} deleted`);
5998
+ } finally {
5999
+ await client.close();
6000
+ }
6001
+ });
6002
+
6003
+ // src/commands/managed/start.ts
6004
+ import { Command as Command71 } from "commander";
6005
+ var startCommand2 = (spec) => new Command71("start").description("run a stopped database again").argument("<db>", "its name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
6006
+ const client = await managedClient(cmd);
6007
+ try {
6008
+ const m = await spin(`starting ${name}\u2026`, client.startManaged(spec.kind, name));
6009
+ if (opts.json) json(m);
6010
+ else info(`${color.green("\u2713")} database ${name} is ${m.status}`);
6011
+ } finally {
6012
+ await client.close();
6013
+ }
6014
+ });
6015
+
6016
+ // src/commands/managed/stop.ts
6017
+ import { Command as Command72 } from "commander";
6018
+ var stopCommand2 = (spec) => new Command72("stop").description("shut a database down, keeping its data (only its storage is charged)").argument("<db>", "its name").option("--json", "print as JSON").action(async (name, opts, cmd) => {
6019
+ const client = await managedClient(cmd);
6020
+ try {
6021
+ const m = await spin(`stopping ${name}\u2026`, client.stopManaged(spec.kind, name));
6022
+ if (opts.json) json(m);
6023
+ else info(`${color.green("\u2713")} database ${name} is stopped; its data is kept ${color.dim(`(${money(m.price.storagePerMonth, m.price.currency)} a month for the storage). Start it with: kvbox ${spec.command} start ${name}`)}`);
6024
+ } finally {
6025
+ await client.close();
6026
+ }
6027
+ });
6028
+
6029
+ // src/commands/managed/unlink.ts
6030
+ import { Command as Command73 } from "commander";
6031
+ var unlinkCommand2 = (spec) => new Command73("unlink").description("stop a box from reaching a database").argument("<db>", "the database").argument("<box>", "the box that was linked to it").option("--json", "print as JSON").action(async (name, box, opts, cmd) => {
6032
+ const client = await managedClient(cmd);
6033
+ try {
6034
+ const m = await spin(`unlinking ${box} from ${name}\u2026`, client.unlinkManaged(spec.kind, name, box));
6035
+ if (opts.json) json(m);
6036
+ else info(`${color.green("\u2713")} box ${box} no longer reaches database ${name}`);
6037
+ } finally {
6038
+ await client.close();
6039
+ }
6040
+ });
6041
+
6042
+ // src/commands/managed/kind.ts
6043
+ function kindCommand(spec, description) {
6044
+ const command = new Command74(spec.command).aliases(spec.aliases).description(description);
6045
+ for (const make of [createCommand4, lsCommand9, infoCommand, passwordCommand, publicCommand, linkCommand2, unlinkCommand2, growCommand2, stopCommand2, startCommand2, rmCommand8]) {
6046
+ command.addCommand(make(spec).option("--org <slug>", "act in this org (- for your personal databases)"));
6047
+ }
6048
+ return command;
6049
+ }
6050
+
6051
+ // src/commands/pg/index.ts
6052
+ var pgCommand = kindCommand(POSTGRES2, "managed PostgreSQL: a database kvbox runs for you, private until you link a box or make it public");
6053
+
6054
+ // src/commands/redis/index.ts
6055
+ var redisCommand = kindCommand(REDIS, "managed Redis (Valkey): a Redis kvbox runs for you, private until you link a box or make it public");
6056
+
6057
+ // src/commands/managed/index.ts
6058
+ import { Command as Command75 } from "commander";
6059
+ var managedCommand = new Command75("managed").description(`databases kvbox runs for you, every kind together (${KINDS.map((k) => `${k.title}: kvbox ${k.command}`).join(", ")})`).addCommand(lsCommand9().option("--org <slug>", "act in this org (- for your personal databases)"));
6060
+
6061
+ // src/commands/env/index.ts
6062
+ import { Command as Command79 } from "commander";
5494
6063
 
5495
6064
  // src/commands/env/ls.ts
5496
- import { Command as Command61 } from "commander";
6065
+ import { Command as Command76 } from "commander";
5497
6066
 
5498
6067
  // src/commands/env/shared.ts
5499
6068
  function requireCloud4(client) {
@@ -5520,7 +6089,7 @@ function firstBootHint(box, name) {
5520
6089
  }
5521
6090
 
5522
6091
  // src/commands/env/ls.ts
5523
- var lsCommand9 = new Command61("ls").alias("list").description("list the variables (a secret shows as (sealed))").option("--box <box>", "what this box gets: its own variables and the ones it inherits").option("--json", "print as JSON").action(async (opts, cmd) => {
6092
+ var lsCommand10 = new Command76("ls").alias("list").description("list the variables (a secret shows as (sealed))").option("--box <box>", "what this box gets: its own variables and the ones it inherits").option("--json", "print as JSON").action(async (opts, cmd) => {
5524
6093
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
5525
6094
  try {
5526
6095
  if (opts.box !== void 0) {
@@ -5559,8 +6128,8 @@ var lsCommand9 = new Command61("ls").alias("list").description("list the variabl
5559
6128
  });
5560
6129
 
5561
6130
  // src/commands/env/rm.ts
5562
- import { Command as Command62 } from "commander";
5563
- var rmCommand8 = new Command62("rm").alias("remove").description("remove variables; boxes lose them when they next start").argument("<names...>", "variable names").option("-y, --yes", "do not ask for confirmation").option("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names2, opts, cmd) => {
6131
+ import { Command as Command77 } from "commander";
6132
+ var rmCommand9 = new Command77("rm").alias("remove").description("remove variables; boxes lose them when they next start").argument("<names...>", "variable names").option("-y, --yes", "do not ask for confirmation").option("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names2, opts, cmd) => {
5564
6133
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
5565
6134
  try {
5566
6135
  const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
@@ -5597,8 +6166,8 @@ var rmCommand8 = new Command62("rm").alias("remove").description("remove variabl
5597
6166
  });
5598
6167
 
5599
6168
  // src/commands/env/set.ts
5600
- import { Command as Command63 } from "commander";
5601
- var setCommand2 = new Command63("set").description("add or change a variable; boxes get it when they next start").argument("[name]", "variable name, e.g. DATABASE_URL (asked for when left out)").argument("[value]", "its value (asked for when left out; hidden with --secret)").option("--secret", "write-only: the value is never shown again, by any command").option("--box <box>", "this box's own variable, over yours (or the org's) of the same name").option("--json", "print as JSON").action(async (nameArg, valueArg, opts, cmd) => {
6169
+ import { Command as Command78 } from "commander";
6170
+ var setCommand2 = new Command78("set").description("add or change a variable; boxes get it when they next start").argument("[name]", "variable name, e.g. DATABASE_URL (asked for when left out)").argument("[value]", "its value (asked for when left out; hidden with --secret)").option("--secret", "write-only: the value is never shown again, by any command").option("--box <box>", "this box's own variable, over yours (or the org's) of the same name").option("--json", "print as JSON").action(async (nameArg, valueArg, opts, cmd) => {
5602
6171
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
5603
6172
  try {
5604
6173
  const owner = opts.box === void 0 ? requireCloud4(client) : void 0;
@@ -5635,14 +6204,14 @@ var setCommand2 = new Command63("set").description("add or change a variable; bo
5635
6204
  });
5636
6205
 
5637
6206
  // src/commands/env/index.ts
5638
- var envCommand = new Command64("env").description("environment variables every box of yours gets when it starts (secrets too)").addCommand(lsCommand9, { isDefault: true }).addCommand(setCommand2).addCommand(rmCommand8);
6207
+ var envCommand = new Command79("env").description("environment variables every box of yours gets when it starts (secrets too)").addCommand(lsCommand10, { isDefault: true }).addCommand(setCommand2).addCommand(rmCommand9);
5639
6208
  for (const cmd of envCommand.commands) cmd.option("--org <slug>", "the org's variables instead of yours");
5640
6209
 
5641
6210
  // src/commands/domain/index.ts
5642
- import { Command as Command68 } from "commander";
6211
+ import { Command as Command83 } from "commander";
5643
6212
 
5644
6213
  // src/commands/domain/add.ts
5645
- import { Command as Command65 } from "commander";
6214
+ import { Command as Command80 } from "commander";
5646
6215
 
5647
6216
  // src/commands/domain/shared.ts
5648
6217
  function requireCloud5(client) {
@@ -5662,7 +6231,7 @@ function hostIn(name, zone) {
5662
6231
  }
5663
6232
 
5664
6233
  // src/commands/domain/add.ts
5665
- var addCommand3 = new Command65("add").description("serve a box at a domain of your own, https://<domain>, with its certificate made for you").argument("<domain>", "a domain you control, like example.com or app.example.com").argument("<box>", "box name").option("--port <port>", "the box port the domain serves (default: the port of its kvbox.app address)").option("--json", "print the domain as JSON").action(async (domainArg, name, opts, cmd) => {
6234
+ var addCommand3 = new Command80("add").description("serve a box at a domain of your own, https://<domain>, with its certificate made for you").argument("<domain>", "a domain you control, like example.com or app.example.com").argument("<box>", "box name").option("--port <port>", "the box port the domain serves (default: the port of its kvbox.app address)").option("--json", "print the domain as JSON").action(async (domainArg, name, opts, cmd) => {
5666
6235
  const domain = assertDomain(domainArg.trim().toLowerCase());
5667
6236
  const port = opts.port === void 0 ? void 0 : parsePorts([opts.port])[0];
5668
6237
  const client = await clientFor(cmd.optsWithGlobals());
@@ -5698,8 +6267,8 @@ kvbox checks every minute; ${domain} is served at ${d.url} once its records are
5698
6267
  });
5699
6268
 
5700
6269
  // src/commands/domain/ls.ts
5701
- import { Command as Command66 } from "commander";
5702
- var lsCommand10 = new Command66("ls").alias("list").description("list your custom domains and whether they are live").option("--json", "print as JSON").action(async (opts, cmd) => {
6270
+ import { Command as Command81 } from "commander";
6271
+ var lsCommand11 = new Command81("ls").alias("list").description("list your custom domains and whether they are live").option("--json", "print as JSON").action(async (opts, cmd) => {
5703
6272
  const client = await clientFor(cmd.optsWithGlobals());
5704
6273
  try {
5705
6274
  requireCloud5(client);
@@ -5728,8 +6297,8 @@ var lsCommand10 = new Command66("ls").alias("list").description("list your custo
5728
6297
  });
5729
6298
 
5730
6299
  // src/commands/domain/rm.ts
5731
- import { Command as Command67 } from "commander";
5732
- var rmCommand9 = new Command67("rm").alias("remove").description("stop serving a box at a custom domain").argument("<domain>", "the domain").option("-y, --yes", "do not ask for confirmation").action(async (domainArg, opts, cmd) => {
6300
+ import { Command as Command82 } from "commander";
6301
+ var rmCommand10 = new Command82("rm").alias("remove").description("stop serving a box at a custom domain").argument("<domain>", "the domain").option("-y, --yes", "do not ask for confirmation").action(async (domainArg, opts, cmd) => {
5733
6302
  const domain = domainArg.trim().toLowerCase();
5734
6303
  const client = await clientFor(cmd.optsWithGlobals());
5735
6304
  try {
@@ -5750,7 +6319,7 @@ var rmCommand9 = new Command67("rm").alias("remove").description("stop serving a
5750
6319
  });
5751
6320
 
5752
6321
  // src/commands/domain/index.ts
5753
- var domainCommand = new Command68("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand10).addCommand(rmCommand9);
6322
+ var domainCommand = new Command83("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand11).addCommand(rmCommand10);
5754
6323
  for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
5755
6324
 
5756
6325
  // src/commands/update.ts
@@ -5758,7 +6327,7 @@ import { spawn as spawn6 } from "child_process";
5758
6327
  import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
5759
6328
  import { tmpdir } from "os";
5760
6329
  import { join as join9 } from "path";
5761
- import { Command as Command69 } from "commander";
6330
+ import { Command as Command84 } from "commander";
5762
6331
 
5763
6332
  // src/update.ts
5764
6333
  import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
@@ -5877,7 +6446,7 @@ function run2(cmd, args) {
5877
6446
  child.on("exit", (code, signal) => resolve4(code ?? (signal ? 1 : 0)));
5878
6447
  });
5879
6448
  }
5880
- var selfUpdateCommand = new Command69("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
6449
+ var selfUpdateCommand = new Command84("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
5881
6450
  suppressUpdateNotice();
5882
6451
  const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
5883
6452
  let code;
@@ -5941,6 +6510,9 @@ var HELP_GROUPS = [
5941
6510
  ["vm", "everything about boxes: fork, rescale, ports, hooks, backups"],
5942
6511
  ["snapshots", "freeze a running box into a snapshot, start new boxes from it"],
5943
6512
  ["volume", "disks of their own that move between boxes"],
6513
+ ["pg", "managed PostgreSQL: a database kvbox runs for you"],
6514
+ ["redis", "managed Redis (Valkey): a Redis kvbox runs for you"],
6515
+ ["managed", "every managed database, whatever its kind"],
5944
6516
  ["env", "environment variables and secrets every box of yours gets"],
5945
6517
  ["domain", "serve a box at a domain of your own"]
5946
6518
  ]
@@ -5998,10 +6570,13 @@ function installRootHelp(program) {
5998
6570
 
5999
6571
  // src/program.ts
6000
6572
  function buildProgram() {
6001
- const program = new Command70("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
6573
+ const program = new Command85("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
6002
6574
  program.addCommand(vmCommand);
6003
6575
  program.addCommand(snapshotsCommand);
6004
6576
  program.addCommand(volumeCommand);
6577
+ program.addCommand(pgCommand);
6578
+ program.addCommand(redisCommand);
6579
+ program.addCommand(managedCommand);
6005
6580
  program.addCommand(envCommand);
6006
6581
  program.addCommand(domainCommand);
6007
6582
  program.addCommand(loginCommand);