@kvbox/cli 0.5.46 → 0.5.48

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.46" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.48" : 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(),
@@ -901,11 +913,31 @@ var VolumeUsageSchema = z2.object({
901
913
  cost: z2.object({ amount: z2.number(), currency: z2.string() }).optional(),
902
914
  historyFrom: z2.string().nullable()
903
915
  });
916
+ var UsageDayItemSchema = z2.object({
917
+ id: z2.string(),
918
+ name: z2.string(),
919
+ owner: z2.string(),
920
+ /** Removed by the end of the report's window. */
921
+ removed: z2.boolean(),
922
+ cost: z2.number()
923
+ });
924
+ var UsageDaySchema = z2.object({
925
+ /** `YYYY-MM-DD`, UTC. */
926
+ date: z2.string(),
927
+ from: z2.string(),
928
+ to: z2.string(),
929
+ cost: z2.number(),
930
+ currency: z2.string(),
931
+ boxes: z2.array(UsageDayItemSchema),
932
+ volumes: z2.array(UsageDayItemSchema)
933
+ });
904
934
  var UsageReportSchema = z2.object({
905
935
  window: z2.object({ from: z2.string(), to: z2.string() }),
906
936
  boxes: z2.array(BoxUsageSchema),
907
937
  /** Absent from a side older than #91. */
908
938
  volumes: z2.array(VolumeUsageSchema).optional(),
939
+ /** With `?by=day` only, oldest day first. */
940
+ days: z2.array(UsageDaySchema).optional(),
909
941
  totals: z2.object({
910
942
  seconds: MachineUsageSchema.shape.seconds,
911
943
  vcpuHours: z2.number(),
@@ -1140,7 +1172,9 @@ var TrustCaReportSchema = z2.object({
1140
1172
  pending: z2.array(z2.object({ box: z2.string(), when: SshKeysAppliedSchema, why: z2.string().optional() })),
1141
1173
  failed: z2.array(z2.object({ box: z2.string(), error: z2.string() })),
1142
1174
  /** Local boxes, untouched: they trust the host's key only. */
1143
- local: z2.number().int()
1175
+ local: z2.number().int(),
1176
+ /** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */
1177
+ skipped: z2.array(z2.string()).optional()
1144
1178
  });
1145
1179
  var HostJoinRequestSchema = z2.object({
1146
1180
  token: z2.string().min(1),
@@ -1175,6 +1209,128 @@ var HostInfoSchema = z2.object({
1175
1209
  var HostPatchRequest = z2.object({ country: z2.string().nullable() });
1176
1210
  var CountrySchema = z2.object({ code: z2.string(), name: z2.string() });
1177
1211
 
1212
+ // ../shared/src/managed.ts
1213
+ import { z as z4 } from "zod";
1214
+
1215
+ // ../shared/src/usage.ts
1216
+ import { z as z3 } from "zod";
1217
+ var PricingSchema = z3.object({
1218
+ currency: z3.string().min(1),
1219
+ vcpuHour: z3.number().nonnegative(),
1220
+ ramGibHour: z3.number().nonnegative(),
1221
+ diskGibHour: z3.number().nonnegative(),
1222
+ volumeHour: z3.number().nonnegative().default(0),
1223
+ volumeGibHour: z3.number().nonnegative().default(0),
1224
+ diskIncludedGib: z3.number().int().nonnegative().default(0)
1225
+ });
1226
+ var PriceListSchema = PricingSchema.extend({ welcomeCredit: z3.number().nonnegative() });
1227
+ var HOUR_MS = 36e5;
1228
+ var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
1229
+ function costOf(t, pricing) {
1230
+ return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;
1231
+ }
1232
+ function sumUsage(items, pricing) {
1233
+ const sum = {
1234
+ seconds: { running: 0, standby: 0, hibernated: 0, stopped: 0 },
1235
+ vcpuHours: 0,
1236
+ ramGibHours: 0,
1237
+ diskGibHours: 0
1238
+ };
1239
+ for (const t of items) {
1240
+ for (const s of Object.keys(sum.seconds)) sum.seconds[s] += t.seconds[s];
1241
+ sum.vcpuHours += t.vcpuHours;
1242
+ sum.ramGibHours += t.ramGibHours;
1243
+ sum.diskGibHours += t.diskGibHours;
1244
+ }
1245
+ sum.vcpuHours = round(sum.vcpuHours, 3);
1246
+ sum.ramGibHours = round(sum.ramGibHours, 3);
1247
+ sum.diskGibHours = round(sum.diskGibHours, 3);
1248
+ if (pricing !== void 0) sum.cost = { amount: round(costOf(sum, pricing), 4), currency: pricing.currency };
1249
+ return sum;
1250
+ }
1251
+ var DAY_MS = 24 * HOUR_MS;
1252
+
1253
+ // ../shared/src/managed.ts
1254
+ var PriceSchema = z4.object({ perMonth: z4.number(), storagePerMonth: z4.number(), currency: z4.string() });
1255
+ var ManagedCatalogEntrySchema = z4.object({
1256
+ /** The kind, as in `/managed/<kind>`: `postgres`. */
1257
+ kind: z4.string(),
1258
+ /** The CLI command for it: `pg` (`kvbox pg create …`). */
1259
+ command: z4.string(),
1260
+ title: z4.string(),
1261
+ description: z4.string(),
1262
+ /** The version a new one runs, as shown: `18`. */
1263
+ version: z4.string(),
1264
+ /** The port it serves on, privately and (when public) behind a host port. */
1265
+ port: z4.number().int(),
1266
+ storage: z4.object({ defaultGib: z4.number().int(), minGib: z4.number().int(), maxGib: z4.number().int() }),
1267
+ /** What create takes beside the name, for a form: each optional, `default` in words. */
1268
+ options: z4.array(z4.object({ name: z4.string(), title: z4.string(), description: z4.string(), default: z4.string(), secret: z4.boolean().optional() })),
1269
+ /** A month of it running with the default storage, and each further GB of storage. */
1270
+ price: PriceSchema.extend({ storageGibPerMonth: z4.number() }),
1271
+ /** Whether a host answering now can run it. */
1272
+ available: z4.boolean()
1273
+ });
1274
+ var CreateManagedRequest = z4.object({
1275
+ name: z4.string(),
1276
+ database: z4.string().optional(),
1277
+ user: z4.string().optional(),
1278
+ password: z4.string().optional(),
1279
+ storageGib: z4.number().int().optional(),
1280
+ /** Place it on the host of this box, so the box can be linked to it. */
1281
+ near: z4.string().optional()
1282
+ });
1283
+ var ManagedHealthSchema = z4.object({
1284
+ /** Its first start has finished: the user and the database exist. */
1285
+ ready: z4.boolean(),
1286
+ /** It accepts connections. */
1287
+ accepting: z4.boolean(),
1288
+ version: z4.string(),
1289
+ connections: z4.number().int(),
1290
+ /** The size of the data itself. */
1291
+ dataBytes: z4.number().optional(),
1292
+ /** The storage volume: what is used of it and its size. */
1293
+ storageUsedBytes: z4.number().optional(),
1294
+ storageTotalBytes: z4.number().optional()
1295
+ });
1296
+ var UrlsSchema = z4.object({ private: z4.string(), public: z4.string().optional() });
1297
+ var ManagedSchema = z4.object({
1298
+ kind: z4.string(),
1299
+ name: z4.string(),
1300
+ /** The owning slug, bare. */
1301
+ owner: z4.string(),
1302
+ ownerKind: z4.enum(["user", "org"]),
1303
+ /** `running`, `stopped` (storage only is charged), `hibernated` or `standby` (out of credit), `unknown` (its host does not answer). */
1304
+ status: BoxStatusSchema,
1305
+ /** The catalog version: `18`. */
1306
+ version: z4.string(),
1307
+ database: z4.string(),
1308
+ user: z4.string(),
1309
+ storageGib: z4.number().int(),
1310
+ /** Where a linked box reaches it: `<name>.<slug>.kvbox` (resolves from a box of any slug it is linked to) and the port. */
1311
+ private: z4.object({ host: z4.string(), port: z4.number().int() }),
1312
+ /** Where the internet reaches it, null while it is not public. The port is its own for its whole life. */
1313
+ public: z4.object({ host: z4.string(), port: z4.number().int() }).nullable(),
1314
+ /** The boxes linked to it, as the caller would name them. */
1315
+ links: z4.array(z4.string()),
1316
+ /** The name of the host it runs on, for `--near` and links. */
1317
+ host: z4.string(),
1318
+ country: z4.string().optional(),
1319
+ createdBy: z4.string().nullable(),
1320
+ createdAt: z4.string(),
1321
+ /** Connection strings with the password as `****`. */
1322
+ urls: UrlsSchema,
1323
+ price: PriceSchema,
1324
+ /** Only in `GET /managed/<kind>/<name>` (asked live): null when it is not running or did not answer. */
1325
+ health: ManagedHealthSchema.nullable().optional()
1326
+ });
1327
+ var ManagedSecretSchema = z4.object({ user: z4.string(), password: z4.string(), urls: UrlsSchema });
1328
+ var CreatedManagedSchema = ManagedSchema.extend({ secret: ManagedSecretSchema });
1329
+ var ResetPasswordRequest = z4.object({ password: z4.string().optional() });
1330
+ var SetPublicRequest = z4.object({ on: z4.boolean() });
1331
+ var ManagedLinkRequest = z4.object({ box: z4.string() });
1332
+ var GrowManagedRequest = z4.object({ storageGib: z4.number().int() });
1333
+
1178
1334
  // src/kvm.ts
1179
1335
  import { accessSync, constants, readFileSync, statSync } from "fs";
1180
1336
  import { userInfo } from "os";
@@ -1242,7 +1398,7 @@ function unitActive() {
1242
1398
  // src/client.ts
1243
1399
  var ORG_SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
1244
1400
  function orgOption(opts) {
1245
- if (opts.org === void 0 || opts.org === "") return void 0;
1401
+ if (opts.org === void 0 || opts.org === "" || opts.org === "-") return void 0;
1246
1402
  if (!ORG_SLUG_RE.test(opts.org)) throw new KvboxError(`${opts.org}: not an org slug (lowercase letters, digits, '.', '_' or '-')`);
1247
1403
  return opts.org;
1248
1404
  }
@@ -1329,7 +1485,7 @@ var ServerClient = class {
1329
1485
  * `all`: every box on the platform (platform admins only, #78).
1330
1486
  */
1331
1487
  listMachines(opts = {}) {
1332
- return this.call("GET", `/machines${allQuery(opts)}`, z3.array(MachineSchema), void 0, opts.org);
1488
+ return this.call("GET", `/machines${allQuery(opts)}`, z5.array(MachineSchema), void 0, opts.org);
1333
1489
  }
1334
1490
  createMachine(req) {
1335
1491
  return this.call("POST", "/machines", MachineSchema, req);
@@ -1383,10 +1539,10 @@ var ServerClient = class {
1383
1539
  }
1384
1540
  /** Backups, the control plane's only: a box's disk in object storage. Newest first. */
1385
1541
  listBackups() {
1386
- return this.call("GET", "/backups", z3.array(BackupSchema));
1542
+ return this.call("GET", "/backups", z5.array(BackupSchema));
1387
1543
  }
1388
1544
  boxBackups(name) {
1389
- return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`, z3.array(BackupSchema));
1545
+ return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`, z5.array(BackupSchema));
1390
1546
  }
1391
1547
  boxBackup(name, id) {
1392
1548
  return this.call("GET", `/machines/${encodeURIComponent(name)}/backups/${encodeURIComponent(id)}`, BackupSchema);
@@ -1401,7 +1557,7 @@ var ServerClient = class {
1401
1557
  }
1402
1558
  /** Wake hooks (#101), the control plane's only: a URL and a secret that wake the box. */
1403
1559
  boxHooks(name) {
1404
- return this.call("GET", `/machines/${encodeURIComponent(name)}/hooks`, z3.array(WakeHookSchema));
1560
+ return this.call("GET", `/machines/${encodeURIComponent(name)}/hooks`, z5.array(WakeHookSchema));
1405
1561
  }
1406
1562
  createBoxHook(name) {
1407
1563
  return this.call("POST", `/machines/${encodeURIComponent(name)}/hooks`, CreatedWakeHookSchema);
@@ -1429,7 +1585,7 @@ var ServerClient = class {
1429
1585
  }
1430
1586
  /** Every readable box's subdomains, one entry each. */
1431
1587
  listSubdomains() {
1432
- return this.call("GET", "/subdomains", z3.array(SubdomainSchema));
1588
+ return this.call("GET", "/subdomains", z5.array(SubdomainSchema));
1433
1589
  }
1434
1590
  /** Custom domains (#89), the control plane's only: serve the box at the user's own name. */
1435
1591
  addDomain(name, req) {
@@ -1440,7 +1596,7 @@ var ServerClient = class {
1440
1596
  }
1441
1597
  /** Every readable box's custom domains. */
1442
1598
  listDomains() {
1443
- return this.call("GET", "/domains", z3.array(DomainSchema));
1599
+ return this.call("GET", "/domains", z5.array(DomainSchema));
1444
1600
  }
1445
1601
  /** A running box's own load, memory and disk, asked of its guest (#67). */
1446
1602
  machineStats(name) {
@@ -1469,22 +1625,22 @@ var ServerClient = class {
1469
1625
  return this.call("POST", "/billing/redeem", RedeemResponseSchema, { code });
1470
1626
  }
1471
1627
  deleteMachine(name) {
1472
- return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z3.undefined());
1628
+ return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z5.undefined());
1473
1629
  }
1474
1630
  /** Like `listMachines`, for snapshots. */
1475
1631
  listSnapshots(opts = {}) {
1476
- return this.call("GET", `/snapshots${allQuery(opts)}`, z3.array(SnapshotSchema), void 0, opts.org);
1632
+ return this.call("GET", `/snapshots${allQuery(opts)}`, z5.array(SnapshotSchema), void 0, opts.org);
1477
1633
  }
1478
1634
  createSnapshot(req) {
1479
1635
  return this.call("POST", "/snapshots", SnapshotSchema, req);
1480
1636
  }
1481
1637
  deleteSnapshot(name) {
1482
- return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`, z3.undefined());
1638
+ return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`, z5.undefined());
1483
1639
  }
1484
1640
  // ---- environment variables (#88), a control plane only: the caller's slug, or `--org`'s ----
1485
1641
  /** `org`: that org's list instead of `--org`'s (or the caller's own). */
1486
1642
  listEnv(org) {
1487
- return this.call("GET", "/vars", z3.array(EnvVarSchema), void 0, org);
1643
+ return this.call("GET", "/vars", z5.array(EnvVarSchema), void 0, org);
1488
1644
  }
1489
1645
  setEnv(name, req) {
1490
1646
  return this.call("PUT", `/vars/${encodeURIComponent(name)}`, EnvChangeSchema, req);
@@ -1504,13 +1660,13 @@ var ServerClient = class {
1504
1660
  }
1505
1661
  // ---- volumes (#52) ----
1506
1662
  listVolumes(opts = {}) {
1507
- return this.call("GET", `/volumes${allQuery(opts)}`, z3.array(VolumeSchema), void 0, opts.org);
1663
+ return this.call("GET", `/volumes${allQuery(opts)}`, z5.array(VolumeSchema), void 0, opts.org);
1508
1664
  }
1509
1665
  createVolume(req) {
1510
1666
  return this.call("POST", "/volumes", VolumeSchema, req);
1511
1667
  }
1512
1668
  deleteVolume(name) {
1513
- return this.call("DELETE", `/volumes/${encodeURIComponent(name)}`, z3.undefined());
1669
+ return this.call("DELETE", `/volumes/${encodeURIComponent(name)}`, z5.undefined());
1514
1670
  }
1515
1671
  /** Both answer with the box as it is afterwards (restarted when it was running). */
1516
1672
  attachVolume(name, req) {
@@ -1519,19 +1675,68 @@ var ServerClient = class {
1519
1675
  detachVolume(name, req) {
1520
1676
  return this.call("POST", `/volumes/${encodeURIComponent(name)}/detach`, MachineSchema, req);
1521
1677
  }
1678
+ /** #147: answers the volume at its new size; a running box holding it has restarted by then. */
1679
+ resizeVolume(name, sizeGib) {
1680
+ return this.call("POST", `/volumes/${encodeURIComponent(name)}/resize`, VolumeSchema, { sizeGib });
1681
+ }
1682
+ // ---- managed services (#173): the control plane's alone ----
1683
+ managedPath(kind, name, rest = "") {
1684
+ return `/managed/${encodeURIComponent(kind)}${name === void 0 ? "" : `/${encodeURIComponent(name)}`}${rest}`;
1685
+ }
1686
+ managedCatalog() {
1687
+ return this.call("GET", "/managed/catalog", z5.array(ManagedCatalogEntrySchema));
1688
+ }
1689
+ /** One kind's services, or every kind's when `kind` is left out. */
1690
+ listManaged(kind, opts = {}) {
1691
+ return this.call("GET", `${kind === void 0 ? "/managed" : this.managedPath(kind)}${allQuery(opts)}`, z5.array(ManagedSchema), void 0, opts.org);
1692
+ }
1693
+ createManaged(kind, req) {
1694
+ return this.call("POST", this.managedPath(kind), CreatedManagedSchema, req);
1695
+ }
1696
+ /** With `health`, asked of the service itself. */
1697
+ getManaged(kind, name) {
1698
+ return this.call("GET", this.managedPath(kind, name), ManagedSchema);
1699
+ }
1700
+ deleteManaged(kind, name) {
1701
+ return this.call("DELETE", this.managedPath(kind, name), z5.undefined());
1702
+ }
1703
+ managedPassword(kind, name) {
1704
+ return this.call("GET", this.managedPath(kind, name, "/password"), ManagedSecretSchema);
1705
+ }
1706
+ resetManagedPassword(kind, name, password) {
1707
+ return this.call("POST", this.managedPath(kind, name, "/password"), ManagedSecretSchema, password === void 0 ? {} : { password });
1708
+ }
1709
+ setManagedPublic(kind, name, on) {
1710
+ return this.call("POST", this.managedPath(kind, name, "/public"), ManagedSchema, { on });
1711
+ }
1712
+ linkManaged(kind, name, box) {
1713
+ return this.call("POST", this.managedPath(kind, name, "/links"), ManagedSchema, { box });
1714
+ }
1715
+ unlinkManaged(kind, name, box) {
1716
+ return this.call("DELETE", this.managedPath(kind, name, "/links"), ManagedSchema, { box });
1717
+ }
1718
+ growManaged(kind, name, storageGib) {
1719
+ return this.call("POST", this.managedPath(kind, name, "/grow"), ManagedSchema, { storageGib });
1720
+ }
1721
+ stopManaged(kind, name) {
1722
+ return this.call("POST", this.managedPath(kind, name, "/stop"), ManagedSchema);
1723
+ }
1724
+ startManaged(kind, name) {
1725
+ return this.call("POST", this.managedPath(kind, name, "/start"), ManagedSchema);
1726
+ }
1522
1727
  // ---- control plane only (`kvbox login`, `logout`, `whoami`) ----
1523
1728
  login(req) {
1524
1729
  return this.call("POST", "/login", LoginResponseSchema, req);
1525
1730
  }
1526
1731
  logout() {
1527
- return this.call("POST", "/logout", z3.unknown()).then(() => void 0);
1732
+ return this.call("POST", "/logout", z5.unknown()).then(() => void 0);
1528
1733
  }
1529
1734
  me() {
1530
1735
  return this.call("GET", "/me", MeResponseSchema);
1531
1736
  }
1532
1737
  // ---- orgs (`kvbox org …`) ----
1533
1738
  listOrgs() {
1534
- return this.call("GET", "/orgs", z3.array(OrgMembershipSchema));
1739
+ return this.call("GET", "/orgs", z5.array(OrgMembershipSchema));
1535
1740
  }
1536
1741
  createOrg(req) {
1537
1742
  return this.call("POST", "/orgs", CloudOrgSchema, req);
@@ -1540,16 +1745,16 @@ var ServerClient = class {
1540
1745
  return this.call("GET", `/orgs/${encodeURIComponent(slug)}`, OrgDetailSchema);
1541
1746
  }
1542
1747
  deleteOrg(slug) {
1543
- return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}`, z3.undefined());
1748
+ return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}`, z5.undefined());
1544
1749
  }
1545
1750
  addMember(slug, req) {
1546
- return this.call("POST", `/orgs/${encodeURIComponent(slug)}/members`, z3.undefined(), req);
1751
+ return this.call("POST", `/orgs/${encodeURIComponent(slug)}/members`, z5.undefined(), req);
1547
1752
  }
1548
1753
  setRole(slug, username, role) {
1549
- return this.call("PATCH", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z3.unknown(), { role }).then(() => void 0);
1754
+ return this.call("PATCH", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z5.unknown(), { role }).then(() => void 0);
1550
1755
  }
1551
1756
  removeMember(slug, username) {
1552
- return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z3.undefined());
1757
+ return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z5.undefined());
1553
1758
  }
1554
1759
  /** Sign this machine's key again (#51); the key must be one the user logged in with. */
1555
1760
  sshCert(req) {
@@ -1632,17 +1837,17 @@ function sshArgs(ep, p = paths()) {
1632
1837
  async function waitForSsh(ep, timeoutMs = 3e4) {
1633
1838
  const { connect } = await import("net");
1634
1839
  const deadline = Date.now() + timeoutMs;
1635
- const attempt = () => new Promise((resolve3) => {
1840
+ const attempt = () => new Promise((resolve4) => {
1636
1841
  const sock = connect({ host: ep.host, port: ep.port, timeout: 1e3 });
1637
1842
  sock.once("connect", () => {
1638
1843
  sock.destroy();
1639
- resolve3(true);
1844
+ resolve4(true);
1640
1845
  });
1641
1846
  sock.once("timeout", () => {
1642
1847
  sock.destroy();
1643
- resolve3(false);
1848
+ resolve4(false);
1644
1849
  });
1645
- sock.once("error", () => resolve3(false));
1850
+ sock.once("error", () => resolve4(false));
1646
1851
  });
1647
1852
  while (Date.now() < deadline) {
1648
1853
  if (await attempt()) return;
@@ -1657,8 +1862,8 @@ async function checkDirect(ep) {
1657
1862
  }
1658
1863
  var NOT_A_HOST_HINT = "kvbox-server is not installed, so this machine is not a kvbox host. Set it up with install-server.sh, or log in to the cloud with: kvbox login";
1659
1864
  async function lastErrorLine(logPath, from = 0) {
1660
- const { readFile: readFile8 } = await import("fs/promises");
1661
- const text2 = (await readFile8(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
1865
+ const { readFile: readFile9 } = await import("fs/promises");
1866
+ const text2 = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
1662
1867
  for (const line of text2.trimEnd().split("\n").slice(-20).reverse()) {
1663
1868
  const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
1664
1869
  if (m?.[1] !== void 0) return m[1];
@@ -1787,7 +1992,7 @@ async function select(message, choices, initial = 0) {
1787
1992
  render();
1788
1993
  let done = false;
1789
1994
  try {
1790
- return await new Promise((resolve3, reject) => {
1995
+ return await new Promise((resolve4, reject) => {
1791
1996
  const onData = (chunk) => {
1792
1997
  for (const key of keysIn(chunk)) {
1793
1998
  if (isUp(key)) index = (index - 1 + choices.length) % choices.length;
@@ -1795,7 +2000,7 @@ async function select(message, choices, initial = 0) {
1795
2000
  else if (key === ENTER || key === "\n") {
1796
2001
  inp.off("data", onData);
1797
2002
  done = true;
1798
- resolve3(choices[index].value);
2003
+ resolve4(choices[index].value);
1799
2004
  return;
1800
2005
  } else if (key === CTRL_C || key === CTRL_D) {
1801
2006
  inp.off("data", onData);
@@ -1845,13 +2050,13 @@ async function hiddenText(message) {
1845
2050
  let chars = [];
1846
2051
  let done = false;
1847
2052
  try {
1848
- return await new Promise((resolve3, reject) => {
2053
+ return await new Promise((resolve4, reject) => {
1849
2054
  const onData = (chunk) => {
1850
2055
  for (const key of keysIn(chunk)) {
1851
2056
  if (key === ENTER || key === "\n") {
1852
2057
  inp.off("data", onData);
1853
2058
  done = true;
1854
- resolve3(chars.join(""));
2059
+ resolve4(chars.join(""));
1855
2060
  return;
1856
2061
  }
1857
2062
  if (key === CTRL_C || key === CTRL_D) {
@@ -2163,12 +2368,12 @@ async function runSsh(ssh, opts) {
2163
2368
  timedOut = true;
2164
2369
  child.kill("SIGTERM");
2165
2370
  }, opts.timeout * 1e3);
2166
- const status2 = await new Promise((resolve3, reject) => {
2371
+ const status2 = await new Promise((resolve4, reject) => {
2167
2372
  child.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
2168
2373
  child.once("close", (code, signal) => {
2169
- if (timedOut) resolve3(TIMEOUT_EXIT);
2170
- else if (code !== null) resolve3(code);
2171
- else resolve3(signal === "SIGINT" ? 130 : 1);
2374
+ if (timedOut) resolve4(TIMEOUT_EXIT);
2375
+ else if (code !== null) resolve4(code);
2376
+ else resolve4(signal === "SIGINT" ? 130 : 1);
2172
2377
  });
2173
2378
  }).finally(() => clearTimeout(timer));
2174
2379
  return { status: status2, chunks, timedOut };
@@ -3102,9 +3307,9 @@ function runSwap(ep, mib) {
3102
3307
  const chunks = [];
3103
3308
  child.stdout.on("data", (c2) => chunks.push(c2));
3104
3309
  child.stderr.on("data", (c2) => chunks.push(c2));
3105
- return new Promise((resolve3, reject) => {
3310
+ return new Promise((resolve4, reject) => {
3106
3311
  child.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
3107
- child.once("close", (code) => resolve3({ status: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
3312
+ child.once("close", (code) => resolve4({ status: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
3108
3313
  });
3109
3314
  }
3110
3315
 
@@ -3727,44 +3932,6 @@ var orgCommand = new Command50("org").description("orgs: shared slugs that own b
3727
3932
 
3728
3933
  // src/commands/usage.ts
3729
3934
  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
3935
  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
3936
  for (const [name, value] of [
3770
3937
  ["since", opts.since],
@@ -3961,18 +4128,18 @@ var redeemCommand = new Command53("redeem").description("redeem a promo code for
3961
4128
  });
3962
4129
 
3963
4130
  // src/commands/deploy/index.ts
3964
- import { access as access4, readFile as readFile7 } from "fs/promises";
3965
- import { basename, resolve as resolve2 } from "path";
4131
+ import { access as access5, readFile as readFile8 } from "fs/promises";
4132
+ import { basename as basename2, resolve as resolve3 } from "path";
3966
4133
  import { Command as Command54, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
3967
4134
 
3968
4135
  // src/commands/deploy/config.ts
3969
4136
  import { readFile as readFile6, writeFile as writeFile4 } from "fs/promises";
3970
- import { join as join6 } from "path";
3971
- import { z as z5 } from "zod";
4137
+ import { isAbsolute, join as join6, normalize, relative as relative2 } from "path";
4138
+ import { z as z6 } from "zod";
3972
4139
 
3973
4140
  // src/commands/deploy/templates/docker.ts
3974
4141
  import { readFile as readFile5 } from "fs/promises";
3975
- import { join as join2 } from "path";
4142
+ import { join as join2, relative, sep } from "path";
3976
4143
 
3977
4144
  // src/commands/deploy/templates/server.ts
3978
4145
  var APP_DIR = "/srv/app/current";
@@ -3980,6 +4147,19 @@ var SERVICE = "kvbox-app";
3980
4147
  var START_WAIT_SEC = 30;
3981
4148
  var APP_NOT_LISTENING = 4;
3982
4149
  var LOG_MARKER = "--- kvbox-app log ---";
4150
+ var RELEASE_FAILED = 12;
4151
+ var RELEASE_LOG_LINES = 40;
4152
+ var DEP_WAIT_SEC = 60;
4153
+ var BOX_ENV_PLAIN = "/home/kvbox/.ssh/environment";
4154
+ var shq = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
4155
+ function waitFor(deps) {
4156
+ return deps.map(
4157
+ (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; }'`
4158
+ );
4159
+ }
4160
+ function releaseStep(run3, root) {
4161
+ 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`];
4162
+ }
3983
4163
  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
4164
  function commands(pm) {
3985
4165
  switch (pm) {
@@ -3993,16 +4173,24 @@ function commands(pm) {
3993
4173
  return { setup: [], install: "if [ -f package-lock.json ]; then npm ci; else npm install; fi", build: "npm run build", start: "npm run start" };
3994
4174
  }
3995
4175
  }
4176
+ var DROP_SINGLE = `sudo -n systemctl disable --now --quiet ${SERVICE} 2>/dev/null || true
4177
+ ${DROP_CONTAINER}`;
3996
4178
  function serverRemote(opts) {
3997
4179
  const c2 = commands(opts.pm);
4180
+ const root = opts.target?.root ?? "/srv/app";
4181
+ const appDir = opts.target ? `${root}/current` : APP_DIR;
4182
+ const service = opts.target?.unit ?? SERVICE;
4183
+ const after = opts.target?.after ?? [];
4184
+ const release = opts.target?.release;
3998
4185
  const unit = [
3999
4186
  "[Unit]",
4000
- "Description=kvbox deploy: the app in " + APP_DIR,
4001
- "After=network.target",
4187
+ "Description=kvbox deploy: the app in " + appDir,
4188
+ ["After=network.target", ...after.map((d) => `${d.unit}.service`)].join(" "),
4002
4189
  "",
4003
4190
  "[Service]",
4004
4191
  "User=kvbox",
4005
- `WorkingDirectory=${APP_DIR}`,
4192
+ `WorkingDirectory=${appDir}`,
4193
+ ...waitFor(after),
4006
4194
  // PORT on the command line: the proxied address points at it, and nothing in the environment
4007
4195
  // file below may move the app off it (env's PORT, say, copied from a .env).
4008
4196
  `ExecStart=/usr/bin/env PORT=${opts.port} ${c2.start}`,
@@ -4018,32 +4206,38 @@ function serverRemote(opts) {
4018
4206
  return [
4019
4207
  "set -e",
4020
4208
  "test -d /srv/app -a -w /srv/app || exit 3",
4021
- "rm -rf /srv/app/.incoming /srv/app/.old",
4022
- "mkdir -p /srv/app/.incoming",
4023
- "tar -xf - -C /srv/app/.incoming",
4024
- "cd /srv/app/.incoming",
4209
+ `rm -rf ${root}/.incoming ${root}/.old`,
4210
+ `mkdir -p ${root}/.incoming`,
4211
+ `tar -xf - -C ${root}/.incoming`,
4212
+ `cd ${root}/.incoming`,
4025
4213
  // Not NODE_ENV=production here: the install would skip devDependencies, which the build needs (TypeScript, Tailwind).
4026
4214
  `export ${["CI=1", ...opts.env ?? []].join(" ")}`,
4027
4215
  ...c2.setup,
4028
4216
  c2.install,
4029
4217
  ...opts.build ? [c2.build] : [],
4218
+ // In the new version's directory, with what the service itself will get: the box's variables
4219
+ // (read from the file, a session opened right after a boot may not have them yet), PORT, NODE_ENV.
4220
+ ...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) : [],
4030
4221
  "cd /",
4031
- `sudo -n tee /etc/systemd/system/${SERVICE}.service >/dev/null <<'UNIT'`,
4222
+ // Before the unit is written: in a stack the single deploy's unit is the one being dropped.
4223
+ ...opts.target ? [DROP_SINGLE] : [],
4224
+ `sudo -n tee /etc/systemd/system/${service}.service >/dev/null <<'UNIT'`,
4032
4225
  ...unit,
4033
4226
  "UNIT",
4034
- `if [ -e ${APP_DIR} ]; then mv ${APP_DIR} /srv/app/.old; fi`,
4035
- `mv /srv/app/.incoming ${APP_DIR}`,
4227
+ `if [ -e ${appDir} ]; then mv ${appDir} ${root}/.old; fi`,
4228
+ `mv ${root}/.incoming ${appDir}`,
4036
4229
  "sudo -n systemctl daemon-reload",
4037
- `sudo -n systemctl enable --quiet ${SERVICE}`,
4230
+ `sudo -n systemctl enable --quiet ${service}`,
4038
4231
  // A box that switched from the Docker template: its container holds the same box port.
4039
- DROP_CONTAINER,
4040
- `sudo -n systemctl restart ${SERVICE}`,
4041
- "rm -rf /srv/app/.old",
4232
+ ...opts.target ? [] : [DROP_CONTAINER],
4233
+ // With databases to wait for, the restart itself fails when one never comes: the wait below shows why.
4234
+ `sudo -n systemctl restart ${service}${after.length > 0 ? " || true" : ""}`,
4235
+ `rm -rf ${root}/.old`,
4042
4236
  // bash's /dev/tcp: no curl or nc in the image needed.
4043
4237
  "i=0",
4044
4238
  `until timeout 1 bash -c '</dev/tcp/127.0.0.1/${opts.port}' 2>/dev/null; do`,
4045
4239
  " i=$((i+1))",
4046
- ` if [ "$i" -ge ${START_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${SERVICE} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
4240
+ ` if [ "$i" -ge ${START_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${service} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
4047
4241
  " sleep 1",
4048
4242
  "done"
4049
4243
  ].join("\n");
@@ -4073,9 +4267,14 @@ var dockerTemplate = {
4073
4267
  const dockerfile = await readFile5(join2(ctx.dir, "Dockerfile"), "utf8").catch(() => void 0);
4074
4268
  if (dockerfile === void 0) throw new KvboxError(`${ctx.dir}: no Dockerfile; the Docker template builds the image from it`);
4075
4269
  const containerPort = exposedPort(dockerfile);
4270
+ if (ctx.context !== void 0 && ctx.context !== ctx.dir) {
4271
+ const dockerfilePath = relative(ctx.context, join2(ctx.dir, "Dockerfile")).split(sep).join("/");
4272
+ return { outDir: ctx.context, exclude: ["node_modules", ".git", ".venv"], pm: "npm", what: "the build context", dockerfile: dockerfilePath, ...containerPort !== void 0 ? { containerPort } : {} };
4273
+ }
4076
4274
  return { outDir: ctx.dir, exclude: ["node_modules", ".git"], pm: "npm", what: "the source", ...containerPort !== void 0 ? { containerPort } : {} };
4077
4275
  },
4078
- remote(built, port) {
4276
+ remote(built, port, target) {
4277
+ if (target) return dockerServiceRemote(port, target, built.dockerfile);
4079
4278
  return dockerRemote(port, built.containerPort ?? port);
4080
4279
  }
4081
4280
  };
@@ -4109,6 +4308,70 @@ function dockerRemote(port, containerPort) {
4109
4308
  "done"
4110
4309
  ].join("\n");
4111
4310
  }
4311
+ function dockerServiceRemote(port, target, dockerfile) {
4312
+ const image = target.unit;
4313
+ const after = target.after ?? [];
4314
+ const built = target.release !== void 0 ? `${image}:next` : image;
4315
+ const unit = [
4316
+ "[Unit]",
4317
+ `Description=kvbox deploy: the container ${image}`,
4318
+ ["After=docker.service network-online.target", ...after.map((d) => `${d.unit}.service`)].join(" "),
4319
+ "Requires=docker.service",
4320
+ "",
4321
+ "[Service]",
4322
+ // A box that never had a variable has no file yet, and docker refuses a missing --env-file.
4323
+ `ExecStartPre=/bin/sh -c '[ -e ${BOX_ENV_PLAIN} ] || install -m 600 -o kvbox -g kvbox /dev/null ${BOX_ENV_PLAIN}'`,
4324
+ ...waitFor(after),
4325
+ `ExecStartPre=-/usr/bin/docker rm -f ${image}`,
4326
+ `ExecStart=/usr/bin/docker run --rm --name ${image} --network host --env-file ${BOX_ENV_PLAIN} -e PORT=${port} ${image}`,
4327
+ `ExecStop=/usr/bin/docker stop ${image}`,
4328
+ "Restart=always",
4329
+ "RestartSec=2",
4330
+ "",
4331
+ "[Install]",
4332
+ "WantedBy=multi-user.target"
4333
+ ];
4334
+ const root = target.root;
4335
+ return [
4336
+ "set -eo pipefail",
4337
+ "test -d /srv/app -a -w /srv/app || exit 3",
4338
+ "command -v docker >/dev/null || exit 3",
4339
+ `rm -rf ${root}/.incoming ${root}/.old`,
4340
+ `mkdir -p ${root}/.incoming`,
4341
+ `tar -xf - -C ${root}/.incoming`,
4342
+ `cd ${root}/.incoming`,
4343
+ // Quoted: the path is the user's `dir`, which may hold a space.
4344
+ `docker build --progress=plain${dockerfile !== void 0 ? ` -f ${shq(dockerfile)}` : ""} -t ${built} . 2>&1 | tail -n ${BUILD_LOG_LINES}`,
4345
+ "cd /",
4346
+ ...target.release !== void 0 ? [
4347
+ `[ -e ${BOX_ENV_PLAIN} ] || install -m 600 /dev/null ${BOX_ENV_PLAIN}`,
4348
+ ...releaseStep(`docker run --rm --network host --env-file ${BOX_ENV_PLAIN} -e PORT=${port} ${built} sh -c ${shq(target.release)}`, root),
4349
+ `docker tag ${built} ${image}:latest`,
4350
+ `docker rmi ${built} >/dev/null`
4351
+ ] : [],
4352
+ // The single deploy's app or container would hold its port and RAM beside the services.
4353
+ DROP_SINGLE,
4354
+ `sudo -n tee /etc/systemd/system/${target.unit}.service >/dev/null <<'UNIT'`,
4355
+ ...unit,
4356
+ "UNIT",
4357
+ `if [ -e ${root}/current ]; then mv ${root}/current ${root}/.old; fi`,
4358
+ `mv ${root}/.incoming ${root}/current`,
4359
+ `rm -rf ${root}/.old`,
4360
+ "sudo -n systemctl daemon-reload",
4361
+ "sudo -n systemctl enable --quiet docker",
4362
+ `sudo -n systemctl enable --quiet ${target.unit}`,
4363
+ // With databases to wait for, the restart itself fails when one never comes: the wait below shows why.
4364
+ `sudo -n systemctl restart ${target.unit}${after.length > 0 ? " || true" : ""}`,
4365
+ "docker image prune -f >/dev/null",
4366
+ // The box's network: the port is the box's own, and nothing but the app answers on it.
4367
+ "i=0",
4368
+ `until timeout 1 bash -c '</dev/tcp/127.0.0.1/${port}' 2>/dev/null; do`,
4369
+ " i=$((i+1))",
4370
+ ` if [ "$i" -ge ${START_WAIT_SEC} ] || ! systemctl is-active --quiet ${target.unit}; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${target.unit} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
4371
+ " sleep 1",
4372
+ "done"
4373
+ ].join("\n");
4374
+ }
4112
4375
 
4113
4376
  // src/commands/deploy/templates/pm.ts
4114
4377
  import { access } from "fs/promises";
@@ -4144,8 +4407,8 @@ var nextjsTemplate = {
4144
4407
  const pm = await packageManager(ctx.dir);
4145
4408
  return { outDir: ctx.dir, exclude: ["node_modules", ".next", ".git"], pm, what: "the source", boxBuild: true };
4146
4409
  },
4147
- remote(built, port) {
4148
- return serverRemote({ pm: built.pm, port, build: true, env: ["NEXT_TELEMETRY_DISABLED=1"] });
4410
+ remote(built, port, target) {
4411
+ return serverRemote({ pm: built.pm, port, build: true, env: ["NEXT_TELEMETRY_DISABLED=1"], ...target ? { target } : {} });
4149
4412
  }
4150
4413
  };
4151
4414
 
@@ -4171,8 +4434,8 @@ var nodeTemplate = {
4171
4434
  const boxBuild = typeof ctx.pkg.scripts["build"] === "string";
4172
4435
  return { outDir: ctx.dir, exclude: ["node_modules", ".git"], pm, what: "the source", boxBuild };
4173
4436
  },
4174
- remote(built, port) {
4175
- return serverRemote({ pm: built.pm, port, build: built.boxBuild === true });
4437
+ remote(built, port, target) {
4438
+ return serverRemote({ pm: built.pm, port, build: built.boxBuild === true, ...target ? { target } : {} });
4176
4439
  }
4177
4440
  };
4178
4441
 
@@ -4184,10 +4447,10 @@ var OUT_DIRS = ["dist", "build"];
4184
4447
  async function runBuild(dir, pm) {
4185
4448
  const args = runScript(pm, "build");
4186
4449
  info(`${color.dim("$")} ${pm} ${args.join(" ")}`);
4187
- const status2 = await new Promise((resolve3, reject) => {
4450
+ const status2 = await new Promise((resolve4, reject) => {
4188
4451
  const child = spawn4(pm, args, { cwd: dir, stdio: ["ignore", process.stderr, process.stderr], shell: process.platform === "win32" });
4189
4452
  child.once("error", (err) => reject(new KvboxError(`could not run ${pm}: ${err.message}`)));
4190
- child.once("close", (code) => resolve3(code ?? 1));
4453
+ child.once("close", (code) => resolve4(code ?? 1));
4191
4454
  });
4192
4455
  if (status2 !== 0) throw new KvboxError(`the build failed (${pm} exited ${status2}); nothing was deployed`);
4193
4456
  }
@@ -4217,9 +4480,23 @@ var reactTemplate = {
4217
4480
  `the build left no ${candidates.join(" or ")}/index.html. The React template ships a directory of static files; set "dist" in kvbox.json to the build output directory, or pick the right template with --template`
4218
4481
  );
4219
4482
  },
4220
- remote: nginxRemote
4483
+ remote: (_built, _port, target) => nginxRemote(target)
4221
4484
  };
4222
- function nginxRemote() {
4485
+ function nginxRemote(target) {
4486
+ if (target) {
4487
+ return [
4488
+ "set -e",
4489
+ "test -d /srv/app -a -w /srv/app || exit 3",
4490
+ DROP_SINGLE,
4491
+ `rm -rf ${target.root}/.incoming ${target.root}/.old`,
4492
+ `mkdir -p ${target.root}/.incoming`,
4493
+ `tar -xf - -C ${target.root}/.incoming`,
4494
+ `chmod -R a+rX ${target.root}/.incoming`,
4495
+ `if [ -e ${target.root}/dist ]; then mv ${target.root}/dist ${target.root}/.old; fi`,
4496
+ `mv ${target.root}/.incoming ${target.root}/dist`,
4497
+ `rm -rf ${target.root}/.old`
4498
+ ].join("\n");
4499
+ }
4223
4500
  return [
4224
4501
  "set -e",
4225
4502
  "test -e /etc/nginx/sites-enabled/kvbox-app || exit 3",
@@ -4262,7 +4539,7 @@ var staticTemplate = {
4262
4539
  const pm = ctx.pkg !== void 0 ? await packageManager(ctx.dir) : "npm";
4263
4540
  return { outDir, ...dist !== void 0 ? { dist } : {}, exclude: EXCLUDE, pm, what: dist !== void 0 ? `${dist}/` : "the directory" };
4264
4541
  },
4265
- remote: nginxRemote
4542
+ remote: (_built, _port, target) => nginxRemote(target)
4266
4543
  };
4267
4544
 
4268
4545
  // src/commands/deploy/templates/index.ts
@@ -4282,23 +4559,160 @@ function detectTemplates(pkg, dir = NO_FACTS) {
4282
4559
  var DEPLOY_AUTO_HIBERNATE_SEC = 3600;
4283
4560
  var CONFIG_FILE = "kvbox.json";
4284
4561
  var BOX_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
4285
- var DeployConfigSchema = z5.object({
4286
- template: z5.enum(TEMPLATE_IDS),
4287
- name: z5.string().regex(BOX_NAME_RE, "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit"),
4562
+ var DeployConfigSchema = z6.object({
4563
+ template: z6.enum(TEMPLATE_IDS),
4564
+ name: z6.string().regex(BOX_NAME_RE, "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit"),
4288
4565
  /** The org whose box it is; absent for the user's own. */
4289
- org: z5.string().regex(ORG_SLUG_RE, "not an org slug").optional(),
4566
+ org: z6.string().regex(ORG_SLUG_RE, "not an org slug").optional(),
4290
4567
  /** The HTTPS name (`<subdomain>.kvbox.app`); absent when deploying to this machine's own host. */
4291
- subdomain: z5.string().check((ctx) => {
4568
+ subdomain: z6.string().check((ctx) => {
4292
4569
  const problem = subdomainProblem(ctx.value);
4293
4570
  if (problem) ctx.issues.push({ code: "custom", message: problem, input: ctx.value });
4294
4571
  }).optional(),
4295
- size: z5.enum(SIZE_NAMES).optional(),
4572
+ size: z6.enum(SIZE_NAMES).optional(),
4296
4573
  /** The build output directory, relative to the app; the template's default when absent. */
4297
- dist: z5.string().optional(),
4574
+ dist: z6.string().optional(),
4298
4575
  /** The port a Next.js app or Node server serves; the template's (3000) when absent. */
4299
- port: z5.number().int().min(1).max(65535).optional()
4300
- });
4301
- async function readConfig(dir) {
4576
+ port: z6.number().int().min(1).max(65535).optional()
4577
+ });
4578
+ var SERVICE_KEY_RE = /^[a-z][a-z0-9-]{0,19}$/;
4579
+ var RESERVED_SERVICE_KEYS = ["app", "agent", "init", "volumes"];
4580
+ var STATIC_TEMPLATES = ["react", "static"];
4581
+ var FRONT_PORT = 80;
4582
+ var ROUTE_RE = /^\/(?:[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*)?$/;
4583
+ var POSTGRES = "postgres";
4584
+ var POSTGRES_PORT = 5432;
4585
+ var POSTGRES_IMAGE = "postgres:17";
4586
+ var POSTGRES_ENV = "DATABASE_URL";
4587
+ var IMAGE_RE = /^[a-z0-9][a-z0-9._/:@-]*$/;
4588
+ var ServiceSchema = z6.strictObject({
4589
+ template: z6.enum([...TEMPLATE_IDS, POSTGRES]),
4590
+ /** The service's directory, relative to the one holding kvbox.json; every template but postgres has one. */
4591
+ dir: z6.string().min(1).optional(),
4592
+ /** A postgres service's image, `postgres:17` when absent (`pgvector/pgvector:pg17` for vectors). */
4593
+ image: z6.string().regex(IMAGE_RE, "an image name like postgres:17").optional(),
4594
+ /** The volume (a key of `volumes`) a postgres service keeps its data on. */
4595
+ volume: z6.string().optional(),
4596
+ /** The box variable a postgres service's URL is written to, `DATABASE_URL` when absent. */
4597
+ env: z6.string().optional(),
4598
+ /** 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`. */
4599
+ context: z6.string().min(1).optional(),
4600
+ dist: z6.string().optional(),
4601
+ /**
4602
+ * A command run once per deploy in the service's new version (a docker service: in a container of
4603
+ * the new image; node, nextjs: in the new source, installed and built), with the box's variables,
4604
+ * before it replaces the running one. Migrations, mostly. A failing one stops that service's deploy.
4605
+ */
4606
+ release: z6.string().optional(),
4607
+ /** The box port of a service with its own server; the template's (3000) when absent. */
4608
+ port: z6.number().int().min(1).max(65535).optional(),
4609
+ /** The URL paths that go to this service, each with everything under it; the prefix is kept. */
4610
+ paths: z6.array(z6.string().regex(ROUTE_RE, "a path like / or /api, no trailing slash")).min(1).optional()
4611
+ });
4612
+ var StackConfigSchema = z6.strictObject({
4613
+ name: DeployConfigSchema.shape.name.optional(),
4614
+ org: DeployConfigSchema.shape.org,
4615
+ subdomain: DeployConfigSchema.shape.subdomain,
4616
+ size: DeployConfigSchema.shape.size,
4617
+ /** The stack's volumes, name to size ("10GB"): made for its box and attached to it on the first deploy that needs one. */
4618
+ volumes: z6.record(z6.string(), z6.string()).optional(),
4619
+ services: z6.record(z6.string(), ServiceSchema)
4620
+ });
4621
+ function volumeGib(text2) {
4622
+ const mib = parseMib(text2);
4623
+ if (mib === void 0 || mib === 0 || mib % 1024 !== 0 || mib / 1024 > MAX_VOLUME_GIB) return void 0;
4624
+ return mib / 1024;
4625
+ }
4626
+ function stackServices(stack, defaultPort, exposed = /* @__PURE__ */ new Map()) {
4627
+ const services = [];
4628
+ const ports = /* @__PURE__ */ new Map();
4629
+ const routes = /* @__PURE__ */ new Map();
4630
+ const entries = Object.entries(stack.services);
4631
+ if (entries.length === 0) throw new KvboxError(`${CONFIG_FILE}: services: at least one service`);
4632
+ for (const [name, size] of Object.entries(stack.volumes ?? {})) {
4633
+ if (!VOLUME_NAME_RE.test(name)) throw new KvboxError(`${CONFIG_FILE}: volumes.${name}: a volume name is ${VOLUME_NAME_RULE}`);
4634
+ if (volumeGib(size) === void 0) throw new KvboxError(`${CONFIG_FILE}: volumes.${name}: ${size} is not a size; write whole GB, like "10GB" (at most ${MAX_VOLUME_GIB})`);
4635
+ }
4636
+ const volumeUsers = /* @__PURE__ */ new Map();
4637
+ const envUsers = /* @__PURE__ */ new Map();
4638
+ for (const [key, config] of entries) {
4639
+ const at = `${CONFIG_FILE}: services.${key}`;
4640
+ if (!SERVICE_KEY_RE.test(key)) throw new KvboxError(`${at}: a service name is 1-20 chars, lowercase letters, digits and '-', starting with a letter`);
4641
+ if (RESERVED_SERVICE_KEYS.includes(key)) throw new KvboxError(`${at}: the name ${key} is taken by kvbox itself; call the service something else (web, api, site)`);
4642
+ const outside = (p) => isAbsolute(p) || p.split(/[\\/]/).includes("..");
4643
+ if (config.template === POSTGRES) {
4644
+ services.push(postgresService(key, config, stack, { volumeUsers, envUsers }, ports));
4645
+ continue;
4646
+ }
4647
+ for (const field of ["image", "volume", "env"]) {
4648
+ if (config[field] !== void 0) throw new KvboxError(`${at}.${field}: only a postgres service has one`);
4649
+ }
4650
+ if (config.dir === void 0) throw new KvboxError(`${at}.dir: the service's directory, relative to ${CONFIG_FILE}`);
4651
+ if (outside(config.dir)) throw new KvboxError(`${at}.dir: a directory inside the project, relative to ${CONFIG_FILE}`);
4652
+ if (config.context !== void 0) {
4653
+ if (config.template !== "docker") throw new KvboxError(`${at}.context: only a docker service has a build context`);
4654
+ if (outside(config.context)) throw new KvboxError(`${at}.context: a directory inside the project, relative to ${CONFIG_FILE}`);
4655
+ const rel = relative2(normalize(config.context), normalize(config.dir));
4656
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new KvboxError(`${at}.context: must hold the service's dir (${config.dir}), where its Dockerfile is`);
4657
+ }
4658
+ const isStatic = STATIC_TEMPLATES.includes(config.template);
4659
+ const paths2 = config.paths ?? [];
4660
+ 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`);
4661
+ if (config.release !== void 0) {
4662
+ 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`);
4663
+ if (config.release.trim() === "" || /[\r\n]/.test(config.release)) throw new KvboxError(`${at}.release: one command on one line, like "release": "npm run migrate"`);
4664
+ }
4665
+ if (isStatic && paths2.length === 0) throw new KvboxError(`${at}.paths: say where the site is served, for example "paths": ["/"]`);
4666
+ let port;
4667
+ if (!isStatic) {
4668
+ const fromExpose = config.port === void 0 ? exposed.get(key) : void 0;
4669
+ port = config.port ?? fromExpose ?? defaultPort(config.template);
4670
+ const instead = `set its own "port" in ${CONFIG_FILE}; the container must listen on it, given as PORT`;
4671
+ if (port === FRONT_PORT) {
4672
+ if (fromExpose !== void 0) throw new KvboxError(`${at}: its Dockerfile EXPOSEs ${FRONT_PORT}, nginx's, the front door of the box; ${instead}`);
4673
+ throw new KvboxError(`${at}.port: ${FRONT_PORT} is nginx's, the front door of the box; pick another`);
4674
+ }
4675
+ const other = ports.get(port);
4676
+ if (other !== void 0) {
4677
+ if (fromExpose !== void 0) throw new KvboxError(`${at}: its Dockerfile EXPOSEs ${port}, which is also ${other}'s; ${instead}`);
4678
+ throw new KvboxError(`${at}.port: ${port} is also ${other}'s; give each service its own "port"`);
4679
+ }
4680
+ ports.set(port, key);
4681
+ }
4682
+ for (const path of paths2) {
4683
+ const other = routes.get(path);
4684
+ if (other !== void 0) throw new KvboxError(`${at}.paths: ${path} is also ${other}'s; a path goes to one service`);
4685
+ routes.set(path, key);
4686
+ }
4687
+ services.push({ key, config, static: isStatic, ...port !== void 0 ? { port } : {}, paths: paths2 });
4688
+ }
4689
+ return services;
4690
+ }
4691
+ function postgresService(key, config, stack, { volumeUsers, envUsers }, ports) {
4692
+ const at = `${CONFIG_FILE}: services.${key}`;
4693
+ for (const field of ["dir", "context", "dist", "release", "paths"]) {
4694
+ 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" : ""}`);
4695
+ }
4696
+ const env = config.env ?? POSTGRES_ENV;
4697
+ const envProblem = envNameProblem(env);
4698
+ if (envProblem !== null) throw new KvboxError(`${at}.env: ${envProblem}`);
4699
+ const envOwner = envUsers.get(env);
4700
+ if (envOwner !== void 0) throw new KvboxError(`${at}.env: ${env} already holds ${envOwner}'s URL; give each database its own "env" (like ${key.toUpperCase().replace(/-/g, "_")}_URL)`);
4701
+ envUsers.set(env, key);
4702
+ if (config.volume !== void 0) {
4703
+ if (stack.volumes?.[config.volume] === void 0) throw new KvboxError(`${at}.volume: no volume ${config.volume} in "volumes"; add it there with its size, like "volumes": { "${config.volume}": "10GB" }`);
4704
+ const other2 = volumeUsers.get(config.volume);
4705
+ if (other2 !== void 0) throw new KvboxError(`${at}.volume: ${config.volume} already holds ${other2}'s data; give each database its own volume`);
4706
+ volumeUsers.set(config.volume, key);
4707
+ }
4708
+ const port = config.port ?? POSTGRES_PORT;
4709
+ if (port === FRONT_PORT) throw new KvboxError(`${at}.port: ${FRONT_PORT} is nginx's, the front door of the box; pick another`);
4710
+ const other = ports.get(port);
4711
+ if (other !== void 0) throw new KvboxError(`${at}.port: ${port} is also ${other}'s; give each service its own "port"`);
4712
+ ports.set(port, key);
4713
+ return { key, config, static: false, port, paths: [], postgres: { image: config.image ?? POSTGRES_IMAGE, env, ...config.volume !== void 0 ? { volume: config.volume } : {} } };
4714
+ }
4715
+ async function readDeployFile(dir) {
4302
4716
  const path = join6(dir, CONFIG_FILE);
4303
4717
  let raw;
4304
4718
  try {
@@ -4313,12 +4727,13 @@ async function readConfig(dir) {
4313
4727
  } catch {
4314
4728
  throw new KvboxError(`${path}: not valid JSON`);
4315
4729
  }
4316
- const parsed = DeployConfigSchema.safeParse(json2);
4730
+ const stack = typeof json2 === "object" && json2 !== null && "services" in json2;
4731
+ const parsed = stack ? StackConfigSchema.safeParse(json2) : DeployConfigSchema.safeParse(json2);
4317
4732
  if (!parsed.success) {
4318
4733
  const issue = parsed.error.issues[0];
4319
4734
  throw new KvboxError(`${path}: ${issue.path.join(".") || "file"}: ${issue.message}`);
4320
4735
  }
4321
- return parsed.data;
4736
+ return stack ? { kind: "stack", config: parsed.data } : { kind: "single", config: parsed.data };
4322
4737
  }
4323
4738
  async function writeConfig(dir, config) {
4324
4739
  await writeFile4(join6(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
@@ -4369,122 +4784,706 @@ async function ship(ep, dir, remote, exclude = []) {
4369
4784
  tar.once("close", (code) => {
4370
4785
  if (code !== 0) ssh.stdin.end();
4371
4786
  });
4372
- const tarDone = new Promise((resolve3) => tar.once("close", () => resolve3()));
4373
- const status2 = await new Promise((resolve3, reject) => {
4787
+ const tarDone = new Promise((resolve4) => tar.once("close", () => resolve4()));
4788
+ const status2 = await new Promise((resolve4, reject) => {
4374
4789
  ssh.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
4375
4790
  ssh.once("close", (code, signal) => {
4376
4791
  tar.stdout.unpipe(ssh.stdin);
4377
4792
  tar.stdout.resume();
4378
4793
  tar.kill();
4379
- resolve3(code ?? (signal === "SIGINT" ? 130 : 1));
4794
+ resolve4(code ?? (signal === "SIGINT" ? 130 : 1));
4380
4795
  });
4381
4796
  });
4382
4797
  await tarDone;
4383
4798
  return { status: status2, output: Buffer.concat(chunks).toString("utf8") };
4384
4799
  }
4385
- var shipping = { ship, measure, waitForSsh };
4800
+ async function run(ep, remote) {
4801
+ const ssh = spawn5("ssh", [...sshArgs(ep), remote], { stdio: ["ignore", "pipe", "pipe"] });
4802
+ const chunks = [];
4803
+ ssh.stdout.on("data", (c2) => chunks.push(c2));
4804
+ ssh.stderr.on("data", (c2) => chunks.push(c2));
4805
+ const status2 = await new Promise((resolve4, reject) => {
4806
+ ssh.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
4807
+ ssh.once("close", (code, signal) => resolve4(code ?? (signal === "SIGINT" ? 130 : 1)));
4808
+ });
4809
+ return { status: status2, output: Buffer.concat(chunks).toString("utf8") };
4810
+ }
4811
+ var shipping = { ship, run, measure, waitForSsh };
4386
4812
 
4387
- // src/commands/deploy/index.ts
4388
- var deployCommand = new Command54("deploy").description("put the app in this directory (React, Next.js, a Node server, a Dockerfile or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the box port of a Next.js app, Node server or container (default 3000; saved to kvbox.json)", parsePort).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
4389
- const dir = resolve2(dirArg ?? ".");
4390
- const pkg = await readPackageJson(dir);
4391
- const facts = { indexHtml: await exists(resolve2(dir, "index.html")), dockerfile: await exists(resolve2(dir, "Dockerfile")) };
4392
- const saved = await readConfig(dir);
4393
- const globals = cmd.optsWithGlobals();
4394
- const orgFlag = orgOption(globals);
4395
- const org = orgFlag ?? saved?.org;
4396
- const client = await clientFor({ ...globals.local ? { local: true } : {}, ...org !== void 0 ? { org } : {} });
4397
- try {
4398
- const cloud = client.target.kind === "cloud";
4399
- if (!cloud && org !== void 0) throw new KvboxError("--org needs a control plane: kvbox login, or drop --org");
4400
- const { config, template, fresh } = await settle(dir, pkg, facts, saved, opts, orgFlag, cloud);
4401
- if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, config);
4402
- await writeConfig(dir, config);
4403
- if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
4404
- `);
4405
- info(`${color.bold("Building")} ${color.cyan(config.name)} ${color.dim(`(${template.label})`)}`);
4406
- const built = await template.build({ dir, pkg, dist: config.dist });
4407
- if (built.dist !== void 0 && built.dist !== config.dist) await writeConfig(dir, { ...config, dist: built.dist });
4408
- const size = await shipping.measure(built.outDir, built.exclude);
4409
- info("");
4410
- const { box: found, ref, created } = await findOrCreate(client, config);
4411
- const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
4412
- const wasRunning = !created && found.status === "running";
4413
- const box = created || wasRunning ? found : await wakeUp(client, found, ref);
4414
- const ep = sshEndpoint(box, client.target);
4415
- if (!wasRunning) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(ep));
4416
- const port = config.port ?? template.port;
4417
- const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port), built.exclude);
4418
- const there = built.boxBuild ? "installing and building there" : "installing there";
4419
- const doing = built.dist === void 0 ? `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref} and ${there}, a minute or two\u2026` : `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}\u2026`;
4420
- let result = await spin(doing, shipIt);
4421
- if (result.status === SSH_FAILED3 && await renewAfterRefusal(client, cert, box.owner)) {
4422
- info("renewed your SSH certificate, trying again\u2026");
4423
- result = await spin(doing, shipIt);
4424
- }
4425
- if (result.status === SSH_FAILED3) throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `
4813
+ // src/commands/deploy/box.ts
4814
+ var NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
4815
+ function refuseFailedShip(result, ctx) {
4816
+ const { ref, template, port, built, service } = ctx;
4817
+ const app = service ? `service ${service.key}` : "the app";
4818
+ if (result.status === SSH_FAILED3) throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `
4426
4819
  ${result.output.trim()}` : ""}`, SSH_FAILED3);
4427
- if (result.status === IMAGE_TOO_OLD) {
4428
- throw new KvboxError(
4429
- `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`
4430
- );
4431
- }
4432
- if (result.status === APP_NOT_LISTENING) {
4433
- const log = result.output.split(LOG_MARKER)[1]?.trim();
4434
- const where = built.containerPort !== void 0 && built.containerPort !== port ? `the container's port ${built.containerPort} (box port ${port})` : `port ${port}`;
4435
- throw new KvboxError(
4436
- `the app did not answer on ${where} within ${START_WAIT_SEC} s: it crashed, or listens on another port. ${template.listens ?? `It must listen on process.env.PORT (${port})`}${template.customPort ? ", or say its port with --port" : ""}. Its log: kvbox exec ${ref} -- ${template.logs ?? "journalctl -u kvbox-app"}${log ? `
4820
+ if (result.status === IMAGE_TOO_OLD) {
4821
+ throw new KvboxError(
4822
+ `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`
4823
+ );
4824
+ }
4825
+ if (result.status === RELEASE_FAILED) {
4826
+ const log = result.output.split(LOG_MARKER)[1]?.trim();
4827
+ throw new KvboxError(
4828
+ `${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 ? `
4437
4829
  last lines:
4438
4830
  ${log}` : ""}`
4439
- );
4440
- }
4441
- if (result.status !== 0) throw new KvboxError(`deploying to ${ref} failed (exit ${result.status}):
4831
+ );
4832
+ }
4833
+ if (result.status === APP_NOT_LISTENING) {
4834
+ const log = result.output.split(LOG_MARKER)[1]?.trim();
4835
+ const where = built.containerPort !== void 0 && built.containerPort !== port ? `the container's port ${built.containerPort} (box port ${port})` : `port ${port}`;
4836
+ const fix = service ? `, or say its port with "port" in ${CONFIG_FILE}` : template.customPort ? ", or say its port with --port" : "";
4837
+ const listens = service && template.id === "docker" ? `The container must listen on PORT (${port}), on the box's own network` : template.listens ?? `It must listen on process.env.PORT (${port})`;
4838
+ throw new KvboxError(
4839
+ `${app} did not answer on ${service ? `port ${port}` : where} within ${START_WAIT_SEC} s: it crashed, or listens on another port. ${listens}${fix}. Its log: kvbox exec ${ref} -- ${service ? `journalctl -u ${service.unit}` : template.logs ?? "journalctl -u kvbox-app"}${log ? `
4840
+ last lines:
4841
+ ${log}` : ""}`
4842
+ );
4843
+ }
4844
+ if (result.status !== 0) throw new KvboxError(`deploying ${service ? `service ${service.key} ` : ""}to ${ref} failed (exit ${result.status}):
4442
4845
  ${result.output.trim()}`);
4443
- let url = `http://${box.ip}${port === 80 ? "" : `:${port}`}`;
4444
- if (cloud) {
4445
- const got = await address(client, box, ref, config, port);
4446
- url = got.url;
4447
- if (got.subdomain !== config.subdomain) await writeConfig(dir, { ...config, subdomain: got.subdomain, ...built.dist !== void 0 && built.dist !== config.dist ? { dist: built.dist } : {} });
4448
- }
4449
- if (opts.json) {
4450
- json({ box: ref, created, template: template.id, url, ...built.dist !== void 0 ? { dist: built.dist } : {}, files: size.files, bytes: size.bytes });
4451
- return;
4452
- }
4453
- process.stdout.write(`${url}
4454
- `);
4455
- info(`${color.green("\u2713")} ${color.bold(config.name)} is live at ${color.bold(url)}`);
4456
- info(` box ${ref}${created ? " (new)" : ""} \xB7 ${template.label} \xB7 ${size.files} files, ${gb(size.bytes)}`);
4457
- info(` redeploy: kvbox deploy${dirArg !== void 0 ? ` ${dirArg}` : ""}`);
4458
- } finally {
4459
- await client.close();
4846
+ }
4847
+ async function findOrCreate(client, config) {
4848
+ const user = me(client);
4849
+ const slug = config.org ?? user;
4850
+ const named = (await client.listMachines()).filter((b) => b.name === config.name);
4851
+ let box = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
4852
+ let created = false;
4853
+ if (!box) {
4854
+ box = await spin(`booting a new box ${config.name}\u2026`, client.createMachine({ name: config.name, ...config.size !== void 0 ? { size: config.size } : {}, autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));
4855
+ created = true;
4856
+ info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);
4460
4857
  }
4461
- });
4462
- function portProblem(v) {
4463
- const n = Number(v);
4464
- return !/^\d+$/.test(v) || n < 1 || n > 65535;
4858
+ return { box, ref: displayName(box, user), created };
4465
4859
  }
4466
- function parsePort(v) {
4467
- if (portProblem(v)) throw new InvalidArgumentError2("expected a port, 1-65535");
4468
- return Number(v);
4860
+ async function existingAddresses(client, config) {
4861
+ const slug = config.org ?? me(client);
4862
+ return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
4469
4863
  }
4470
- var exists = (path) => access4(path).then(() => true, () => false);
4471
- async function readPackageJson(dir) {
4472
- try {
4473
- return JSON.parse(await readFile7(resolve2(dir, "package.json"), "utf8"));
4474
- } catch (err) {
4475
- if (err.code === "ENOENT") return void 0;
4476
- throw new KvboxError(`${resolve2(dir, "package.json")}: ${err.message}`);
4477
- }
4864
+ async function refuseOtherAddress(client, config) {
4865
+ const have = await existingAddresses(client, config);
4866
+ if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
4867
+ const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
4868
+ throw new KvboxError(
4869
+ `box ${ref} already has ${MAX_BOX_SUBDOMAINS} addresses (${have.map((s) => s.subdomain).join(", ")}), none of them ${config.subdomain}. Deploy to one: kvbox deploy --sub <name>. Or free one: kvbox vm proxy release ${ref} --sub <name>`
4870
+ );
4478
4871
  }
4479
- async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
4480
- const [detected, ...also] = detectTemplates(pkg, facts);
4481
- if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
4482
- if (opts.sub !== void 0) assertSubdomain(opts.sub);
4483
- const renamed = saved !== void 0 && (opts.name !== void 0 && opts.name !== saved.name || orgFlag !== void 0 && orgFlag !== saved.org);
4484
- const savedSub = renamed ? void 0 : saved?.subdomain;
4485
- const defaults = {
4872
+ async function address(client, box, ref, config, port) {
4873
+ const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
4874
+ const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
4875
+ if (have) {
4876
+ if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
4877
+ return { url: have.url, subdomain: have.subdomain };
4878
+ }
4879
+ const wanted = config.subdomain ?? subdomainFor(config.name);
4880
+ try {
4881
+ const sub = await spin(`claiming https://${wanted}.kvbox.app\u2026`, client.claimSubdomain(ref, { name: wanted, port }));
4882
+ return { url: sub.url, subdomain: sub.subdomain };
4883
+ } catch (err) {
4884
+ if (!(err instanceof KvboxError)) throw err;
4885
+ throw new KvboxError(`${err.message}
4886
+ the app is on box ${ref} but has no address yet: pick another with kvbox deploy --sub <name> (saved to ${CONFIG_FILE})`);
4887
+ }
4888
+ }
4889
+
4890
+ // src/commands/deploy/stack.ts
4891
+ import { access as access4, readFile as readFile7 } from "fs/promises";
4892
+ import { basename, join as join8, resolve as resolve2 } from "path";
4893
+
4894
+ // src/commands/deploy/postgres.ts
4895
+ import { randomBytes } from "crypto";
4896
+ var POSTGRES_USER = "kvbox";
4897
+ var POSTGRES_DB = "app";
4898
+ var ENV_MISSING = 6;
4899
+ var VOLUME_NOT_MOUNTED = 7;
4900
+ var DB_NOT_READY = 8;
4901
+ var URL_OTHER_PORT = 9;
4902
+ var URL_FOREIGN = 10;
4903
+ var OTHER_DATA = 11;
4904
+ var DB_WAIT_SEC = 90;
4905
+ var AGENT = "/usr/local/sbin/kvbox-agent";
4906
+ var ENV_WAIT_SEC = 60;
4907
+ function newPassword() {
4908
+ return randomBytes(24).toString("hex");
4909
+ }
4910
+ function postgresUrl(password, port) {
4911
+ return `postgres://${POSTGRES_USER}:${password}@127.0.0.1:${port}/${POSTGRES_DB}`;
4912
+ }
4913
+ function postgresRemote(o) {
4914
+ const { root, unit } = o.target;
4915
+ const mount = `/mnt/${o.volume}`;
4916
+ const key = o.target.root.split("/").pop();
4917
+ const data = `${mount}/${key}`;
4918
+ const envFile = `${root}/current/postgres.env`;
4919
+ const unitText = [
4920
+ "[Unit]",
4921
+ `Description=kvbox deploy: the database ${unit}`,
4922
+ "After=docker.service kvbox-volumes.service network-online.target",
4923
+ "Requires=docker.service",
4924
+ "",
4925
+ "[Service]",
4926
+ `ExecStartPre=/usr/bin/mountpoint -q ${mount}`,
4927
+ `ExecStartPre=-/usr/bin/docker rm -f ${unit}`,
4928
+ `ExecStart=/usr/bin/docker run --rm --name ${unit} --network host --env-file ${envFile} -e POSTGRES_USER=${POSTGRES_USER} -e POSTGRES_DB=${POSTGRES_DB} -e PGDATA=/kvbox-data/pgdata -v ${data}:/kvbox-data ${o.image} -c listen_addresses=127.0.0.1 -c port=${o.port}`,
4929
+ `ExecStop=/usr/bin/docker stop ${unit}`,
4930
+ "Restart=always",
4931
+ "RestartSec=2",
4932
+ "",
4933
+ "[Install]",
4934
+ "WantedBy=multi-user.target"
4935
+ ];
4936
+ return [
4937
+ "set -eo pipefail",
4938
+ "test -d /srv/app -a -w /srv/app || exit 3",
4939
+ "command -v docker >/dev/null || exit 3",
4940
+ // The host hands a booting box its variables a few seconds after it starts. Only an agent that marks
4941
+ // it (base v0.12.0+) is waited for: on an older image the file never comes, and every deploy would stall.
4942
+ `if grep -qs env-ready ${AGENT}; then i=0; until [ -e /run/kvbox/env-ready ] || [ "$i" -ge ${ENV_WAIT_SEC} ]; do i=$((i+1)); sleep 1; done; fi`,
4943
+ `url=$(sed -n 's/^${o.env}=//p' ${BOX_ENV_PLAIN} 2>/dev/null | head -n 1 || true)`,
4944
+ `[ -n "$url" ] || exit ${ENV_MISSING}`,
4945
+ // Only a URL this CLI made, for this port, is the database's: never a value set for something else.
4946
+ `pw=\${url#postgres://${POSTGRES_USER}:}`,
4947
+ "pw=${pw%%@*}",
4948
+ `case "$pw" in ''|*[!0-9a-f]*) exit ${URL_FOREIGN} ;; esac`,
4949
+ `case "$url" in "${postgresUrl("$pw", o.port)}") ;; "postgres://${POSTGRES_USER}:$pw@127.0.0.1:"*"/${POSTGRES_DB}") exit ${URL_OTHER_PORT} ;; *) exit ${URL_FOREIGN} ;; esac`,
4950
+ `mountpoint -q ${mount} || exit ${VOLUME_NOT_MOUNTED}`,
4951
+ `mkdir -p ${root}/current`,
4952
+ // One database per volume: another service's data there is a renamed service, never started empty beside it.
4953
+ // Its pgdata (mode 700, postgres's) is seen from the folder above, which is this user's.
4954
+ `for f in ${mount}/*/pgdata; do [ -d "$f" ] || continue; o=\${f#${mount}/}; o=\${o%%/*}; [ "$o" = ${key} ] || { echo "$o"; exit ${OTHER_DATA}; }; done`,
4955
+ `mkdir -p ${data}`,
4956
+ `(umask 077; printf 'POSTGRES_PASSWORD=%s\\n' "$pw" > ${envFile})`,
4957
+ `docker image inspect ${o.image} >/dev/null 2>&1 || docker pull -q ${o.image} >/dev/null`,
4958
+ DROP_SINGLE,
4959
+ `cat > ${root}/.unit <<'UNIT'`,
4960
+ ...unitText,
4961
+ "UNIT",
4962
+ "changed=0",
4963
+ `if ! cmp -s ${root}/.unit /etc/systemd/system/${unit}.service; then sudo -n cp ${root}/.unit /etc/systemd/system/${unit}.service; sudo -n systemctl daemon-reload; changed=1; fi`,
4964
+ `rm -f ${root}/.unit`,
4965
+ "sudo -n systemctl enable --quiet docker",
4966
+ `sudo -n systemctl enable --quiet ${unit}`,
4967
+ `if [ "$changed" = 1 ] || ! systemctl is-active --quiet ${unit}; then sudo -n systemctl restart ${unit}; fi`,
4968
+ // Ready on TCP, not only on its socket: during the first start's initdb it listens on no port.
4969
+ "i=0",
4970
+ `until docker exec ${unit} pg_isready -q -h 127.0.0.1 -p ${o.port} 2>/dev/null; do`,
4971
+ " i=$((i+1))",
4972
+ ` if [ "$i" -ge ${DB_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${unit} -n 20 --no-pager -o cat || true; exit ${DB_NOT_READY}; fi`,
4973
+ " sleep 1",
4974
+ "done",
4975
+ // The box's password is the one that counts, whatever the data was made with (a new box on an old volume).
4976
+ // Over the local socket (trust in the image), whose name carries the port: without -p it is 5432's.
4977
+ `docker exec ${unit} psql -q -p ${o.port} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c "ALTER ROLE ${POSTGRES_USER} PASSWORD '$pw'" >/dev/null`
4978
+ ].join("\n");
4979
+ }
4980
+
4981
+ // src/commands/deploy/nginx.ts
4982
+ var STACK_SITE = "kvbox-stack";
4983
+ var SITE_REFUSED = 5;
4984
+ var NO_PREVIOUS_SITE = "--- kvbox: no previous stack site ---";
4985
+ var PROXY = (port) => [
4986
+ `proxy_pass http://127.0.0.1:${port};`,
4987
+ "proxy_http_version 1.1;",
4988
+ "proxy_set_header Host $http_host;",
4989
+ "proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
4990
+ "proxy_set_header X-Forwarded-Proto $kvbox_proto;",
4991
+ // WebSocket, and streamed answers (server-sent events) as they are written.
4992
+ "proxy_set_header Upgrade $http_upgrade;",
4993
+ "proxy_set_header Connection $kvbox_connection;",
4994
+ "proxy_buffering off;",
4995
+ "proxy_read_timeout 3600s;"
4996
+ ];
4997
+ var block2 = (head, body) => [` ${head} {`, ...body.map((l) => ` ${l}`), " }", ""];
4998
+ function locations(service, path) {
4999
+ const dist = `/srv/app/${service.key}/dist`;
5000
+ if (service.static) {
5001
+ if (path === "/") return block2("location /", [`root ${dist};`, "try_files $uri $uri/ /index.html;"]);
5002
+ return [...block2(`location = ${path}`, [`return 301 ${path}/;`]), ...block2(`location ${path}/`, [`alias ${dist}/;`, `try_files $uri $uri/ ${path}/index.html;`])];
5003
+ }
5004
+ const proxy = PROXY(service.port);
5005
+ if (path === "/") return block2("location /", proxy);
5006
+ return [...block2(`location = ${path}`, proxy), ...block2(`location ${path}/`, proxy)];
5007
+ }
5008
+ function stackSite(services) {
5009
+ const routed = services.flatMap((s) => s.paths.map((path) => ({ service: s, path })));
5010
+ const root = routed.find((r) => r.path === "/");
5011
+ return [
5012
+ "# Written by kvbox deploy from kvbox.json; the next deploy writes it again.",
5013
+ "map $http_upgrade $kvbox_connection {",
5014
+ " default upgrade;",
5015
+ " '' close;",
5016
+ "}",
5017
+ "map $http_x_forwarded_proto $kvbox_proto {",
5018
+ " default $http_x_forwarded_proto;",
5019
+ " '' $scheme;",
5020
+ "}",
5021
+ "server {",
5022
+ " listen 80 default_server;",
5023
+ " listen [::]:80 default_server;",
5024
+ " server_name _;",
5025
+ " index index.html;",
5026
+ // The app behind a path decides how much it takes.
5027
+ " client_max_body_size 0;",
5028
+ "",
5029
+ " gzip on;",
5030
+ " gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;",
5031
+ "",
5032
+ ...routed.flatMap((r) => locations(r.service, r.path)),
5033
+ // No service at the top: say so instead of nginx's own welcome page.
5034
+ ...root ? [] : block2("location /", ["return 404;"]),
5035
+ "}",
5036
+ ""
5037
+ ].join("\n");
5038
+ }
5039
+ function frontRemote(site) {
5040
+ const available = `/etc/nginx/sites-available/${STACK_SITE}`;
5041
+ const enabled2 = `/etc/nginx/sites-enabled/${STACK_SITE}`;
5042
+ return [
5043
+ "set -e",
5044
+ "command -v nginx >/dev/null || exit 3",
5045
+ `if [ -e ${available} ]; then sudo -n cp -f ${available} ${available}.old; fi`,
5046
+ `sudo -n tee ${available} >/dev/null <<'KVBOX_SITE'`,
5047
+ site,
5048
+ "KVBOX_SITE",
5049
+ `sudo -n ln -sf ${available} ${enabled2}`,
5050
+ "sudo -n rm -f /etc/nginx/sites-enabled/kvbox-app",
5051
+ "if ! sudo -n nginx -t 2>&1; then",
5052
+ ` if [ -e ${available}.old ]; then sudo -n mv -f ${available}.old ${available}; else echo '${NO_PREVIOUS_SITE}'; sudo -n rm -f ${available} ${enabled2}; sudo -n ln -sf /etc/nginx/sites-available/kvbox-app /etc/nginx/sites-enabled/kvbox-app; fi`,
5053
+ ` exit ${SITE_REFUSED}`,
5054
+ "fi",
5055
+ `sudo -n rm -f ${available}.old`,
5056
+ "sudo -n systemctl enable --now --quiet nginx",
5057
+ "sudo -n systemctl reload nginx"
5058
+ ].join("\n");
5059
+ }
5060
+
5061
+ // src/commands/deploy/stack.ts
5062
+ var STACK_SIZE = "s";
5063
+ var exists = (path) => access4(path).then(() => true, () => false);
5064
+ async function deployStack(d) {
5065
+ const { dir, opts, client, cloud } = d;
5066
+ if (opts.template !== void 0 || opts.port !== void 0) throw new KvboxError(`--template and --port are one app's; with several services each says its own in ${CONFIG_FILE}`);
5067
+ const exposed = await exposedPorts(dir, d.stack);
5068
+ const portOf = (template) => templateById(template).port;
5069
+ pick(stackServices(d.stack, portOf, exposed), opts.only);
5070
+ const config = await settle(d);
5071
+ const services = stackServices(config, portOf, exposed);
5072
+ const picked = pick(services, opts.only);
5073
+ if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, { ...config, name: config.name });
5074
+ let saved = config;
5075
+ if (JSON.stringify(saved) !== JSON.stringify(d.stack)) await writeConfig(dir, saved);
5076
+ const box = { name: config.name, org: config.org, subdomain: config.subdomain, size: config.size };
5077
+ const all = [];
5078
+ for (const service of picked) {
5079
+ if (service.postgres) continue;
5080
+ const template = templateById(service.config.template);
5081
+ const serviceDir = resolve2(dir, service.config.dir);
5082
+ if (!await exists(serviceDir)) throw new KvboxError(`${CONFIG_FILE}: services.${service.key}.dir: no directory ${serviceDir}`);
5083
+ info(`${color.bold("Building")} ${color.cyan(service.key)} ${color.dim(`(${template.label})`)}`);
5084
+ const context = service.config.context !== void 0 ? resolve2(dir, service.config.context) : void 0;
5085
+ const built = await template.build({ dir: serviceDir, pkg: await readPackageJson(serviceDir), dist: service.config.dist, ...context !== void 0 ? { context } : {} });
5086
+ if (built.dist !== void 0 && built.dist !== service.config.dist) {
5087
+ saved = { ...saved, services: { ...saved.services, [service.key]: { ...saved.services[service.key], dist: built.dist } } };
5088
+ await writeConfig(dir, saved);
5089
+ }
5090
+ all.push({ service, template, built, size: await shipping.measure(built.outDir, built.exclude) });
5091
+ }
5092
+ info("");
5093
+ const { box: found, ref, created } = await findOrCreate(client, box);
5094
+ const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
5095
+ const wasRunning = !created && found.status === "running";
5096
+ const machine = created || wasRunning ? found : await wakeUp(client, found, ref);
5097
+ const ep = sshEndpoint(machine, client.target);
5098
+ if (!wasRunning) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(ep));
5099
+ let renewed = false;
5100
+ const renewOnce = async () => {
5101
+ if (renewed || !await renewAfterRefusal(client, cert, machine.owner)) return false;
5102
+ renewed = true;
5103
+ info("renewed your SSH certificate, trying again\u2026");
5104
+ return true;
5105
+ };
5106
+ const databases = picked.filter((s) => s.postgres);
5107
+ if (databases.length > 0) await deployDatabases({ client, ref, owner: machine.owner, name: machine.name, ep, volumes: config.volumes ?? {}, databases, renewOnce });
5108
+ const after = services.filter((s) => s.postgres).map((s) => ({ unit: `kvbox-${s.key}`, port: s.port }));
5109
+ for (const { service, template, built, size } of all) {
5110
+ const release = service.config.release;
5111
+ const target = { root: `/srv/app/${service.key}`, unit: `kvbox-${service.key}`, ...release !== void 0 ? { release } : {}, ...after.length > 0 && !service.static ? { after } : {} };
5112
+ const port = service.port ?? FRONT_PORT;
5113
+ const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port, target), built.exclude);
5114
+ 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";
5115
+ const doing = `${service.key}: shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}${there}${release !== void 0 ? ", then its release command" : ""}\u2026`;
5116
+ let result = await spin(doing, shipIt);
5117
+ if (result.status === SSH_FAILED3 && await renewOnce()) result = await spin(doing, shipIt);
5118
+ refuseFailedShip(result, { ref, template, port, built, ...service.static ? {} : { service: { key: service.key, unit: target.unit, ...release !== void 0 ? { release } : {} } } });
5119
+ }
5120
+ 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))));
5121
+ 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`);
5122
+ if (front.status === SITE_REFUSED) {
5123
+ const first = front.output.includes(NO_PREVIOUS_SITE);
5124
+ 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";
5125
+ throw new KvboxError(`nginx in box ${ref} refused the routes made from ${CONFIG_FILE}; ${after2}. The services themselves were deployed.
5126
+ ${front.output.replace(NO_PREVIOUS_SITE, "").trim()}`);
5127
+ }
5128
+ if (front.status !== 0) throw new KvboxError(`setting up nginx in box ${ref} failed (exit ${front.status}):
5129
+ ${front.output.trim()}`);
5130
+ const missing = picked.length < services.length ? await neverShipped(ep, services.filter((s) => !picked.includes(s))) : [];
5131
+ let url = `http://${machine.ip}`;
5132
+ if (cloud) {
5133
+ const got = await address(client, machine, ref, box, FRONT_PORT);
5134
+ url = got.url;
5135
+ if (got.subdomain !== saved.subdomain) await writeConfig(dir, { ...saved, subdomain: got.subdomain });
5136
+ }
5137
+ if (opts.json) {
5138
+ json({
5139
+ box: ref,
5140
+ created,
5141
+ url,
5142
+ services: [
5143
+ ...databases.map((s) => ({ key: s.key, template: POSTGRES, image: s.postgres.image, volume: s.postgres.volume, env: s.postgres.env, port: s.port, paths: [] })),
5144
+ ...all.map(({ service, template, built, size }) => ({
5145
+ key: service.key,
5146
+ template: template.id,
5147
+ files: size.files,
5148
+ bytes: size.bytes,
5149
+ ...built.dist !== void 0 ? { dist: built.dist } : {},
5150
+ ...service.port !== void 0 ? { port: service.port } : {},
5151
+ ...service.config.release !== void 0 ? { release: service.config.release } : {},
5152
+ paths: service.paths
5153
+ }))
5154
+ ],
5155
+ ...missing.length > 0 ? { missing: missing.map((s) => s.key) } : {}
5156
+ });
5157
+ return;
5158
+ }
5159
+ process.stdout.write(`${url}
5160
+ `);
5161
+ info(`${color.green("\u2713")} ${color.bold(config.name)} is live at ${color.bold(url)}`);
5162
+ info(` box ${ref}${created ? " (new)" : ""}`);
5163
+ for (const s of databases) {
5164
+ const vol = s.postgres.volume;
5165
+ info(` ${color.cyan(s.key)} \xB7 Postgres ${s.postgres.image} \xB7 port ${s.port} \xB7 data on volume ${vol} (${config.volumes?.[vol] ?? "?"}) \xB7 URL in ${s.postgres.env}`);
5166
+ }
5167
+ for (const { service, template, size } of all) {
5168
+ const where = service.paths.length > 0 ? service.paths.join(", ") : "no path, reached by the other services only";
5169
+ info(` ${color.cyan(service.key)} \xB7 ${template.label} \xB7 ${where}${service.port !== void 0 ? ` \xB7 port ${service.port}` : ""} \xB7 ${size.files} files, ${gb(size.bytes)}`);
5170
+ }
5171
+ for (const s of missing) {
5172
+ const where = s.postgres ? `no database, and no service gets ${s.postgres.env},` : s.paths.length > 0 ? `${s.paths.join(", ")} answer${s.paths.length === 1 ? "s" : ""} nothing` : "nothing runs";
5173
+ warn(` ! ${s.key} was never deployed to this box: ${where} until kvbox deploy --only ${s.key} (or a full kvbox deploy)`);
5174
+ }
5175
+ const at = d.dirArg !== void 0 ? ` ${d.dirArg}` : "";
5176
+ info(` redeploy: kvbox deploy${at} one service: kvbox deploy${at} --only <service>`);
5177
+ }
5178
+ async function exposedPorts(dir, stack) {
5179
+ const ports = /* @__PURE__ */ new Map();
5180
+ for (const [key, s] of Object.entries(stack.services)) {
5181
+ if (s.template !== "docker" || s.port !== void 0 || s.dir === void 0) continue;
5182
+ const text2 = await readFile7(resolve2(dir, s.dir, "Dockerfile"), "utf8").catch(() => void 0);
5183
+ const port = text2 !== void 0 ? exposedPort(text2) : void 0;
5184
+ if (port !== void 0) ports.set(key, port);
5185
+ }
5186
+ return ports;
5187
+ }
5188
+ async function deployDatabases(d) {
5189
+ const { client, ref } = d;
5190
+ let stale = false;
5191
+ const own = new Set((await client.boxEnv(ref)).vars.map((v) => v.name));
5192
+ for (const s of d.databases) {
5193
+ const pg = s.postgres;
5194
+ if (own.has(pg.env)) continue;
5195
+ await spin(`${s.key}: making a password, its URL in the box variable ${pg.env} (secret)\u2026`, client.setBoxEnv(ref, pg.env, { value: postgresUrl(newPassword(), s.port), secret: true }));
5196
+ stale = true;
5197
+ }
5198
+ let restarted = false;
5199
+ const slug = slugOf(d.owner);
5200
+ const existing = (await client.listVolumes()).filter((v) => slugOf(v.owner) === slug);
5201
+ for (const s of d.databases) {
5202
+ const name = s.postgres.volume;
5203
+ const have = existing.find((v) => v.name === name);
5204
+ if (have?.attachedTo === d.name) continue;
5205
+ if (have && have.attachedTo !== null) throw new KvboxError(`volume ${name} (in ${CONFIG_FILE} for ${s.key}) is attached to box ${have.attachedTo}. Detach it there (kvbox volume detach ${name} ${have.attachedTo}), or name another volume for ${s.key}`);
5206
+ if (have?.host !== void 0) {
5207
+ const boxHost = (await client.listMachines()).find((m) => m.name === d.name && slugOf(m.owner) === slug)?.host;
5208
+ if (boxHost !== void 0 && boxHost !== have.host) {
5209
+ throw new KvboxError(
5210
+ `volume ${name} (${s.key}'s data) is on host ${have.host} and box ${ref} on host ${boxHost}: a volume attaches only to a box on its own host, and its data cannot move yet. Deploy to a box on ${have.host} (one that is still there, --name), or name another volume for ${s.key} in ${CONFIG_FILE} for a new, empty database`
5211
+ );
5212
+ }
5213
+ }
5214
+ if (!have) {
5215
+ const sizeGib = volumeGib(d.volumes[name]);
5216
+ await spin(`${s.key}: making volume ${name} (${sizeGib} GB) for box ${ref}\u2026`, client.createVolume({ name, sizeGib, box: ref }));
5217
+ }
5218
+ await spin(`${s.key}: attaching volume ${name} to box ${ref} (the box restarts once)\u2026`, client.attachVolume(name, { box: ref }));
5219
+ restarted = true;
5220
+ }
5221
+ const restart = async (why) => {
5222
+ info(`restarting box ${ref} so ${why}`);
5223
+ await spin(`restarting box ${ref}\u2026`, async () => {
5224
+ await client.stopMachine(ref);
5225
+ await client.startMachine(ref);
5226
+ });
5227
+ restarted = true;
5228
+ };
5229
+ if (stale && !restarted) await restart("it gets the new database URL");
5230
+ if (restarted) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
5231
+ for (const s of d.databases) {
5232
+ const pg = s.postgres;
5233
+ const script = postgresRemote({ target: { root: `/srv/app/${s.key}`, unit: `kvbox-${s.key}` }, image: pg.image, volume: pg.volume, env: pg.env, port: s.port });
5234
+ const doing = `${s.key}: starting ${pg.image} with its data on volume ${pg.volume} (the first start takes a while)\u2026`;
5235
+ const runScript2 = async () => {
5236
+ const result2 = await spin(doing, shipping.run(d.ep, script));
5237
+ return result2.status === SSH_FAILED3 && await d.renewOnce() ? spin(doing, shipping.run(d.ep, script)) : result2;
5238
+ };
5239
+ let result = await runScript2();
5240
+ if (result.status === ENV_MISSING && !restarted) {
5241
+ await restart(`it gets ${pg.env}`);
5242
+ await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
5243
+ result = await runScript2();
5244
+ }
5245
+ if (result.status === URL_OTHER_PORT) {
5246
+ await spin(`${s.key}: the database moved to port ${s.port}; a new URL in ${pg.env} (secret)\u2026`, client.setBoxEnv(ref, pg.env, { value: postgresUrl(newPassword(), s.port), secret: true }));
5247
+ await restart(`it gets ${pg.env} for port ${s.port}`);
5248
+ await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
5249
+ result = await runScript2();
5250
+ }
5251
+ refuseFailedDatabase(result, s, ref);
5252
+ }
5253
+ }
5254
+ function refuseFailedDatabase(result, s, ref) {
5255
+ const pg = s.postgres;
5256
+ const unit = `kvbox-${s.key}`;
5257
+ switch (result.status) {
5258
+ case 0:
5259
+ return;
5260
+ case SSH_FAILED3:
5261
+ throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `
5262
+ ${result.output.trim()}` : ""}`, SSH_FAILED3);
5263
+ case IMAGE_TOO_OLD:
5264
+ throw new KvboxError(`box ${ref} runs an image too old for a database service (base v0.9.1 or newer). Update the box (kvbox vm update ${ref}), or deploy under another name (--name) to get a fresh box`);
5265
+ case ENV_MISSING:
5266
+ throw new KvboxError(`box ${ref} has not got the variable ${pg.env} although it is set (kvbox env ls --box ${ref}). Restart the box (kvbox stop ${ref} && kvbox start ${ref}) and deploy again`);
5267
+ case VOLUME_NOT_MOUNTED:
5268
+ throw new KvboxError(`volume ${pg.volume} is attached to box ${ref} but not mounted at /mnt/${pg.volume}: the box's image is too old for volumes (base v0.9.1 or newer, kvbox vm update ${ref}), or the box needs a restart. The database was not started, so nothing was written to the box's own disk`);
5269
+ case URL_FOREIGN:
5270
+ throw new KvboxError(`box ${ref}'s variable ${pg.env} holds something other than ${s.key}'s URL (another database?), so ${s.key} was not started. Name another variable for ${s.key} ("env" in ${CONFIG_FILE}), or remove it (kvbox env rm ${pg.env} --box ${ref}) and deploy again`);
5271
+ case URL_OTHER_PORT:
5272
+ throw new KvboxError(`box ${ref} still has ${s.key}'s URL for another port after a restart. Restart the box (kvbox stop ${ref} && kvbox start ${ref}) and deploy again`);
5273
+ case OTHER_DATA: {
5274
+ const other = result.output.trim().split("\n").at(-1);
5275
+ throw new KvboxError(
5276
+ `volume ${pg.volume} holds the database of service ${other}, not ${s.key}'s (a renamed service?), so ${s.key} was not started. To keep that data as ${s.key}'s: kvbox exec ${ref} -- 'sudo systemctl disable --now kvbox-${other}; sudo mv /mnt/${pg.volume}/${other} /mnt/${pg.volume}/${s.key}', then deploy again. Otherwise give ${s.key} another volume`
5277
+ );
5278
+ }
5279
+ case DB_NOT_READY: {
5280
+ const log = result.output.split(LOG_MARKER)[1]?.trim();
5281
+ throw new KvboxError(`${s.key}: ${pg.image} did not answer on port ${s.port} within ${DB_WAIT_SEC} s. Its log: kvbox exec ${ref} -- journalctl -u ${unit}${log ? `
5282
+ last lines:
5283
+ ${log}` : ""}`);
5284
+ }
5285
+ default:
5286
+ throw new KvboxError(`starting ${s.key} in ${ref} failed (exit ${result.status}):
5287
+ ${result.output.trim()}`);
5288
+ }
5289
+ }
5290
+ async function neverShipped(ep, services) {
5291
+ if (services.length === 0) return [];
5292
+ const checks = services.map((s) => `[ -e /srv/app/${s.key}/${s.static ? "dist" : "current"} ] || echo ${s.key}`);
5293
+ const result = await shipping.run(ep, checks.join("\n"));
5294
+ if (result.status !== 0) return [];
5295
+ const keys = new Set(result.output.split("\n").map((l) => l.trim()));
5296
+ return services.filter((s) => keys.has(s.key));
5297
+ }
5298
+ function pick(services, only) {
5299
+ if (only === void 0) return services;
5300
+ for (const key of only) {
5301
+ if (!services.some((s) => s.key === key)) throw new KvboxError(`--only ${key}: no such service in ${CONFIG_FILE} (it has ${services.map((s) => s.key).join(", ")})`);
5302
+ }
5303
+ return services.filter((s) => only.includes(s.key));
5304
+ }
5305
+ async function settle(d) {
5306
+ const { stack, opts, orgFlag, cloud } = d;
5307
+ if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
5308
+ if (opts.sub !== void 0) assertSubdomain(opts.sub);
5309
+ const renamed = stack.name !== void 0 && (opts.name !== void 0 && opts.name !== stack.name || orgFlag !== void 0 && orgFlag !== stack.org);
5310
+ const savedSub = renamed ? void 0 : stack.subdomain;
5311
+ const defaults = { name: opts.name ?? stack.name ?? nameFromDir(basename(d.dir)), size: opts.size ?? stack.size ?? STACK_SIZE };
5312
+ const open = {
5313
+ name: opts.name === void 0 && stack.name === void 0,
5314
+ subdomain: cloud && opts.sub === void 0 && savedSub === void 0,
5315
+ size: opts.size === void 0 && stack.size === void 0,
5316
+ // Only for the databases this run deploys: one left out by --only is asked when it is deployed.
5317
+ volumes: Object.entries(stack.services).filter(([key, s]) => s.template === POSTGRES && s.volume === void 0 && (opts.only === void 0 || opts.only.includes(key))).map(([key]) => key)
5318
+ };
5319
+ const anyOpen = open.name || open.subdomain || open.size || open.volumes.length > 0;
5320
+ const accountVolumes = open.volumes.length > 0 ? new Set((await d.client.listVolumes()).map((v) => v.name)) : /* @__PURE__ */ new Set();
5321
+ if (anyOpen && !opts.yes && !interactive()) {
5322
+ throw new KvboxError(
5323
+ `kvbox deploy asks a few questions the first time, and this is not a terminal. Pass -y to take the defaults (box ${defaults.name}${cloud ? `, https://${opts.sub ?? savedSub ?? subdomainFor(defaults.name)}.kvbox.app` : ""}, size ${defaults.size}${defaultVolumes(defaults.name, stack.volumes ?? {}, accountVolumes, open.volumes).map(([key, v]) => `, a ${VOLUME_GIB} GB volume ${v} for ${key}`).join("")}), or answer with --name${cloud ? ", --sub" : ""} and --size, or in ${CONFIG_FILE}`
5324
+ );
5325
+ }
5326
+ const ask = anyOpen && !opts.yes;
5327
+ if (ask) info(`${color.bold("kvbox deploy")} ${color.dim(d.dir)} ${color.dim(`\xB7 ${Object.keys(stack.services).length} services`)}
5328
+ `);
5329
+ let name = defaults.name;
5330
+ if (open.name && ask) name = await text("Box name", { default: defaults.name, validate: (a) => BOX_NAME_RE.test(a) ? void 0 : NAME_RULE });
5331
+ let subdomain = opts.sub ?? savedSub ?? (cloud ? subdomainFor(name) : void 0);
5332
+ if (open.subdomain && ask) {
5333
+ subdomain = await text("Address", {
5334
+ default: subdomainFor(name),
5335
+ validate: (a) => {
5336
+ const problem = subdomainProblem(a);
5337
+ return problem ? `that name ${problem}` : void 0;
5338
+ }
5339
+ });
5340
+ info(` ${color.dim(`https://${subdomain}.kvbox.app`)}`);
5341
+ }
5342
+ let size = defaults.size;
5343
+ if (open.size && ask) {
5344
+ size = await select("Box size", SIZE_NAMES.map((s) => ({ value: s, label: s, hint: `${SIZES[s].vcpu} vCPU, ${SIZES[s].memMib / 1024} GB RAM, ${SIZES[s].diskGib} GB disk` })), SIZE_NAMES.indexOf(STACK_SIZE));
5345
+ }
5346
+ const volumes = { ...stack.volumes };
5347
+ const services = { ...stack.services };
5348
+ for (const key of open.volumes) {
5349
+ let volume = volumeNameFor(name, volumes, accountVolumes);
5350
+ let gib = `${VOLUME_GIB}GB`;
5351
+ if (ask) {
5352
+ volume = await text(`Volume for ${key}'s data`, { default: volume, validate: (a) => !VOLUME_NAME_RE.test(a) ? VOLUME_NAME_RULE : volumes[a] !== void 0 ? "already a volume of this stack" : accountVolumes.has(a) ? `already a volume of yours, another box's data; to reuse it on purpose, name it in ${CONFIG_FILE}` : void 0 });
5353
+ gib = await text("Volume size", { default: gib, validate: (a) => volumeGib(a) === void 0 ? "whole GB, like 10GB" : void 0 });
5354
+ }
5355
+ volumes[volume] = gib;
5356
+ services[key] = { ...services[key], volume };
5357
+ }
5358
+ if (ask) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
5359
+ `);
5360
+ const org = orgFlag ?? stack.org;
5361
+ return {
5362
+ name,
5363
+ ...org !== void 0 ? { org } : {},
5364
+ ...subdomain !== void 0 ? { subdomain } : {},
5365
+ size,
5366
+ ...Object.keys(volumes).length > 0 ? { volumes } : {},
5367
+ services
5368
+ };
5369
+ }
5370
+ var VOLUME_GIB = 10;
5371
+ function defaultVolumes(box, stackVolumes, account, keys) {
5372
+ const taken = { ...stackVolumes };
5373
+ return keys.map((key) => {
5374
+ const v = volumeNameFor(box, taken, account);
5375
+ taken[v] = `${VOLUME_GIB}GB`;
5376
+ return [key, v];
5377
+ });
5378
+ }
5379
+ function volumeNameFor(box, taken, account = /* @__PURE__ */ new Set()) {
5380
+ const free = (n) => taken[n] === void 0 && !account.has(n);
5381
+ const base = `${box.slice(0, 9).replace(/-+$/, "")}-db`;
5382
+ if (free(base)) return base;
5383
+ for (let i = 2; ; i++) {
5384
+ const n = `${box.slice(0, 8).replace(/-+$/, "")}-db${i}`;
5385
+ if (free(n)) return n;
5386
+ }
5387
+ }
5388
+ async function readPackageJson(dir) {
5389
+ try {
5390
+ return JSON.parse(await readFile7(join8(dir, "package.json"), "utf8"));
5391
+ } catch (err) {
5392
+ if (err.code === "ENOENT") return void 0;
5393
+ throw new KvboxError(`${join8(dir, "package.json")}: ${err.message}`);
5394
+ }
5395
+ }
5396
+
5397
+ // src/commands/deploy/index.ts
5398
+ var deployCommand = new Command54("deploy").description("put the app in this directory (React, Next.js, a Node server, a Dockerfile or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the box port of a Next.js app, Node server or container (default 3000; saved to kvbox.json)", parsePort).option("--only <service>", "with several services in kvbox.json: deploy this one only (repeatable)", (v, all) => [...all ?? [], v]).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
5399
+ const dir = resolve3(dirArg ?? ".");
5400
+ const pkg = await readPackageJson2(dir);
5401
+ const facts = { indexHtml: await exists2(resolve3(dir, "index.html")), dockerfile: await exists2(resolve3(dir, "Dockerfile")) };
5402
+ const file = await readDeployFile(dir);
5403
+ const saved = file?.kind === "single" ? file.config : void 0;
5404
+ const globals = cmd.optsWithGlobals();
5405
+ const orgFlag = orgOption(globals);
5406
+ const org = orgFlag ?? file?.config.org;
5407
+ const client = await clientFor({ ...globals.local ? { local: true } : {}, ...org !== void 0 ? { org } : {} });
5408
+ try {
5409
+ const cloud = client.target.kind === "cloud";
5410
+ if (!cloud && org !== void 0) throw new KvboxError("--org needs a control plane: kvbox login, or drop --org");
5411
+ if (file?.kind === "stack") {
5412
+ await deployStack({ dir, dirArg, stack: file.config, opts, orgFlag, client, cloud });
5413
+ return;
5414
+ }
5415
+ if (opts.only !== void 0) throw new KvboxError(`--only picks a service of a ${CONFIG_FILE} with "services"; this one describes a single app`);
5416
+ const { config, template, fresh } = await settle2(dir, pkg, facts, saved, opts, orgFlag, cloud);
5417
+ if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, config);
5418
+ await writeConfig(dir, config);
5419
+ if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
5420
+ `);
5421
+ info(`${color.bold("Building")} ${color.cyan(config.name)} ${color.dim(`(${template.label})`)}`);
5422
+ const built = await template.build({ dir, pkg, dist: config.dist });
5423
+ if (built.dist !== void 0 && built.dist !== config.dist) await writeConfig(dir, { ...config, dist: built.dist });
5424
+ const size = await shipping.measure(built.outDir, built.exclude);
5425
+ info("");
5426
+ const { box: found, ref, created } = await findOrCreate(client, config);
5427
+ const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
5428
+ const wasRunning = !created && found.status === "running";
5429
+ const box = created || wasRunning ? found : await wakeUp(client, found, ref);
5430
+ const ep = sshEndpoint(box, client.target);
5431
+ if (!wasRunning) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(ep));
5432
+ const port = config.port ?? template.port;
5433
+ const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port), built.exclude);
5434
+ const there = built.boxBuild ? "installing and building there" : "installing there";
5435
+ const doing = built.dist === void 0 ? `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref} and ${there}, a minute or two\u2026` : `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}\u2026`;
5436
+ let result = await spin(doing, shipIt);
5437
+ if (result.status === SSH_FAILED3 && await renewAfterRefusal(client, cert, box.owner)) {
5438
+ info("renewed your SSH certificate, trying again\u2026");
5439
+ result = await spin(doing, shipIt);
5440
+ }
5441
+ refuseFailedShip(result, { ref, template, port, built });
5442
+ let url = `http://${box.ip}${port === 80 ? "" : `:${port}`}`;
5443
+ if (cloud) {
5444
+ const got = await address(client, box, ref, config, port);
5445
+ url = got.url;
5446
+ if (got.subdomain !== config.subdomain) await writeConfig(dir, { ...config, subdomain: got.subdomain, ...built.dist !== void 0 && built.dist !== config.dist ? { dist: built.dist } : {} });
5447
+ }
5448
+ if (opts.json) {
5449
+ json({ box: ref, created, template: template.id, url, ...built.dist !== void 0 ? { dist: built.dist } : {}, files: size.files, bytes: size.bytes });
5450
+ return;
5451
+ }
5452
+ process.stdout.write(`${url}
5453
+ `);
5454
+ info(`${color.green("\u2713")} ${color.bold(config.name)} is live at ${color.bold(url)}`);
5455
+ info(` box ${ref}${created ? " (new)" : ""} \xB7 ${template.label} \xB7 ${size.files} files, ${gb(size.bytes)}`);
5456
+ info(` redeploy: kvbox deploy${dirArg !== void 0 ? ` ${dirArg}` : ""}`);
5457
+ } finally {
5458
+ await client.close();
5459
+ }
5460
+ });
5461
+ function portProblem(v) {
5462
+ const n = Number(v);
5463
+ return !/^\d+$/.test(v) || n < 1 || n > 65535;
5464
+ }
5465
+ function parsePort(v) {
5466
+ if (portProblem(v)) throw new InvalidArgumentError2("expected a port, 1-65535");
5467
+ return Number(v);
5468
+ }
5469
+ var exists2 = (path) => access5(path).then(() => true, () => false);
5470
+ async function readPackageJson2(dir) {
5471
+ try {
5472
+ return JSON.parse(await readFile8(resolve3(dir, "package.json"), "utf8"));
5473
+ } catch (err) {
5474
+ if (err.code === "ENOENT") return void 0;
5475
+ throw new KvboxError(`${resolve3(dir, "package.json")}: ${err.message}`);
5476
+ }
5477
+ }
5478
+ async function settle2(dir, pkg, facts, saved, opts, orgFlag, cloud) {
5479
+ const [detected, ...also] = detectTemplates(pkg, facts);
5480
+ if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
5481
+ if (opts.sub !== void 0) assertSubdomain(opts.sub);
5482
+ const renamed = saved !== void 0 && (opts.name !== void 0 && opts.name !== saved.name || orgFlag !== void 0 && orgFlag !== saved.org);
5483
+ const savedSub = renamed ? void 0 : saved?.subdomain;
5484
+ const defaults = {
4486
5485
  template: opts.template ?? saved?.template ?? detected?.id,
4487
- name: opts.name ?? saved?.name ?? nameFromDir(basename(dir)),
5486
+ name: opts.name ?? saved?.name ?? nameFromDir(basename2(dir)),
4488
5487
  subdomain: opts.sub ?? savedSub,
4489
5488
  size: opts.size ?? saved?.size
4490
5489
  };
@@ -4551,52 +5550,9 @@ async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
4551
5550
  };
4552
5551
  return { config, template, fresh };
4553
5552
  }
4554
- var NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
4555
- async function findOrCreate(client, config) {
4556
- const user = me(client);
4557
- const slug = config.org ?? user;
4558
- const named = (await client.listMachines()).filter((b) => b.name === config.name);
4559
- let box = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
4560
- let created = false;
4561
- if (!box) {
4562
- box = await spin(`booting a new box ${config.name}\u2026`, client.createMachine({ name: config.name, ...config.size !== void 0 ? { size: config.size } : {}, autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));
4563
- created = true;
4564
- info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);
4565
- }
4566
- return { box, ref: displayName(box, user), created };
4567
- }
4568
- async function existingAddresses(client, config) {
4569
- const slug = config.org ?? me(client);
4570
- return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
4571
- }
4572
- async function refuseOtherAddress(client, config) {
4573
- const have = await existingAddresses(client, config);
4574
- if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
4575
- const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
4576
- throw new KvboxError(
4577
- `box ${ref} already has ${MAX_BOX_SUBDOMAINS} addresses (${have.map((s) => s.subdomain).join(", ")}), none of them ${config.subdomain}. Deploy to one: kvbox deploy --sub <name>. Or free one: kvbox vm proxy release ${ref} --sub <name>`
4578
- );
4579
- }
4580
- async function address(client, box, ref, config, port) {
4581
- const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
4582
- const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
4583
- if (have) {
4584
- if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
4585
- return { url: have.url, subdomain: have.subdomain };
4586
- }
4587
- const wanted = config.subdomain ?? subdomainFor(config.name);
4588
- try {
4589
- const sub = await spin(`claiming https://${wanted}.kvbox.app\u2026`, client.claimSubdomain(ref, { name: wanted, port }));
4590
- return { url: sub.url, subdomain: sub.subdomain };
4591
- } catch (err) {
4592
- if (!(err instanceof KvboxError)) throw err;
4593
- throw new KvboxError(`${err.message}
4594
- the app is on box ${ref} but has no address yet: pick another with kvbox deploy --sub <name> (saved to ${CONFIG_FILE})`);
4595
- }
4596
- }
4597
5553
 
4598
5554
  // src/commands/volume/index.ts
4599
- import { Command as Command60 } from "commander";
5555
+ import { Command as Command61 } from "commander";
4600
5556
 
4601
5557
  // src/commands/volume/attach.ts
4602
5558
  import { Command as Command55 } from "commander";
@@ -4624,11 +5580,11 @@ var attachCommand = new Command55("attach").description("attach a volume to a bo
4624
5580
 
4625
5581
  // src/commands/volume/create.ts
4626
5582
  import { Command as Command56 } from "commander";
4627
- function parseGib2(text2) {
5583
+ function parseGib2(text2, label = "--size") {
4628
5584
  const mib = parseMib(text2);
4629
- if (mib === void 0 || mib % 1024 !== 0) throw new KvboxError(`--size ${text2}: write whole GB, like 50 or 50GB`);
5585
+ if (mib === void 0 || mib % 1024 !== 0) throw new KvboxError(`${label} ${text2}: write whole GB, like 50 or 50GB`);
4630
5586
  const gib = mib / 1024;
4631
- if (gib > MAX_VOLUME_GIB) throw new KvboxError(`--size ${text2}: a volume is at most ${MAX_VOLUME_GIB} GB`);
5587
+ if (gib > MAX_VOLUME_GIB) throw new KvboxError(`${label} ${text2}: a volume is at most ${MAX_VOLUME_GIB} GB`);
4632
5588
  return gib;
4633
5589
  }
4634
5590
  function sizeProblem(answer) {
@@ -4697,9 +5653,23 @@ var detachCommand = new Command57("detach").description("detach a volume from a
4697
5653
  }
4698
5654
  });
4699
5655
 
4700
- // src/commands/volume/ls.ts
5656
+ // src/commands/volume/grow.ts
4701
5657
  import { Command as Command58 } from "commander";
4702
- 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) => {
5658
+ 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) => {
5659
+ const sizeGib = parseGib2(size, "size");
5660
+ const client = await clientFor(cmd.optsWithGlobals());
5661
+ try {
5662
+ const vol = await spin(`growing volume ${name} to ${sizeGib} GB\u2026`, client.resizeVolume(name, sizeGib));
5663
+ if (opts.json) json(vol);
5664
+ else info(`${color.green("\u2713")} volume ${name} is ${vol.sizeGib} GB${vol.attachedTo ? color.dim(` (box ${vol.attachedTo} was restarted if it was running)`) : ""}`);
5665
+ } finally {
5666
+ await client.close();
5667
+ }
5668
+ });
5669
+
5670
+ // src/commands/volume/ls.ts
5671
+ import { Command as Command59 } from "commander";
5672
+ 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) => {
4703
5673
  const client = await clientFor(cmd.optsWithGlobals());
4704
5674
  try {
4705
5675
  const cloud = client.target.kind === "cloud";
@@ -4730,8 +5700,8 @@ var lsCommand8 = new Command58("ls").alias("list").description("list volumes: si
4730
5700
  });
4731
5701
 
4732
5702
  // src/commands/volume/rm.ts
4733
- import { Command as Command59 } from "commander";
4734
- 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) => {
5703
+ import { Command as Command60 } from "commander";
5704
+ 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) => {
4735
5705
  if (!await confirm(`Delete volume ${name} and everything on it?`, opts.yes ?? false)) {
4736
5706
  info("cancelled");
4737
5707
  process.exitCode = 1;
@@ -4747,14 +5717,309 @@ var rmCommand7 = new Command59("rm").alias("remove").description("delete a volum
4747
5717
  });
4748
5718
 
4749
5719
  // src/commands/volume/index.ts
4750
- 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);
5720
+ 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);
4751
5721
  for (const cmd of volumeCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal volumes)");
4752
5722
 
4753
- // src/commands/env/index.ts
5723
+ // src/commands/managed/kind.ts
5724
+ import { Command as Command74 } from "commander";
5725
+
5726
+ // src/commands/managed/create.ts
5727
+ import { Command as Command63 } from "commander";
5728
+ import { setTimeout as sleep3 } from "timers/promises";
5729
+
5730
+ // src/commands/managed/shared.ts
5731
+ import "commander";
5732
+ var POSTGRES2 = { kind: "postgres", command: "pg", aliases: ["postgres"], title: "PostgreSQL" };
5733
+ var KINDS = [POSTGRES2];
5734
+ async function managedClient(cmd) {
5735
+ const client = await clientFor(cmd.optsWithGlobals());
5736
+ if (client.target.kind !== "cloud") {
5737
+ await client.close();
5738
+ throw new KvboxError("managed databases run on the kvbox cloud: kvbox login first (this host's own socket has none)");
5739
+ }
5740
+ return client;
5741
+ }
5742
+ var shownName = (m, user) => m.owner === user ? m.name : `${m.owner}/${m.name}`;
5743
+ var storageText = (m) => m.health?.storageUsedBytes !== void 0 ? `${gb(m.health.storageUsedBytes)} of ${m.storageGib} GB used` : `${m.storageGib} GB`;
5744
+ 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;
5745
+ function stateText(m) {
5746
+ if (m.status === "stopped") return `${status(m.status)} ${color.dim("(only its storage is charged)")}`;
5747
+ if (m.status !== "running" || m.health === void 0) return status(m.status);
5748
+ if (m.health === null) return `${status(m.status)}${color.dim(", not answering yet")}`;
5749
+ if (!m.health.ready) return `${status(m.status)}${color.dim(", still setting itself up")}`;
5750
+ return `${status(m.status)}, ${m.health.accepting ? "accepting connections" : color.yellow("not accepting connections")}`;
5751
+ }
5752
+ function infoRows(spec, m, user) {
5753
+ const name = shownName(m, user);
5754
+ const rows2 = [
5755
+ ["name", color.bold(name)],
5756
+ ["status", stateText(m)],
5757
+ ["version", `${spec.title} ${m.health?.version ?? m.version}`]
5758
+ ];
5759
+ if (user !== void 0 && m.owner !== user) rows2.push(["owner", m.owner]);
5760
+ if (m.health) rows2.push(["connections", String(m.health.connections)]);
5761
+ rows2.push(["storage", `${storageText(m)}${nearlyFull(m) ? color.yellow(` almost full: kvbox ${spec.command} grow ${name} <GB>`) : ""}`]);
5762
+ rows2.push(["database", m.database], ["user", m.user], ["password", color.dim(`kvbox ${spec.command} password ${name}`)]);
5763
+ 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>)`)}`]);
5764
+ rows2.push(["public", m.urls.public ?? color.dim(`off (kvbox ${spec.command} public ${name} on)`)]);
5765
+ 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)")}`]);
5766
+ rows2.push(["created", `${age(m.createdAt)}${m.createdBy ? ` by ${m.createdBy}` : ""}`]);
5767
+ return rows2;
5768
+ }
5769
+ function printRows(rows2) {
5770
+ const width2 = Math.max(...rows2.map(([label]) => label.length));
5771
+ for (const [label, value] of rows2) process.stdout.write(`${color.dim(label.padEnd(width2))} ${value}
5772
+ `);
5773
+ }
5774
+ function secretRows(secret) {
5775
+ return [
5776
+ ["user", secret.user],
5777
+ ["password", secret.password],
5778
+ ["private", secret.urls.private],
5779
+ ...secret.urls.public ? [["public", secret.urls.public]] : []
5780
+ ];
5781
+ }
5782
+ function parseStorage(text2, flag) {
5783
+ const m = /^\s*(\d+)\s*(g|gb|gib)?\s*$/i.exec(text2);
5784
+ if (!m || Number(m[1]) < 1) throw new KvboxError(`${flag} ${text2}: write whole GB, like 50 or 50GB`);
5785
+ return Number(m[1]);
5786
+ }
5787
+
5788
+ // src/commands/managed/create.ts
5789
+ var READY_WAIT_MS = 9e4;
5790
+ var READY_STEP_MS = 2e3;
5791
+ var createCommand4 = (spec) => 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").option("--database <name>", "the database created in it (default: the name)").option("--user <name>", "the user that owns it (default: the name)").option("--password <password>", "that user's password (default: generated)").option("--storage <gb>", "storage for the data in GB (default: 10; 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) => {
5792
+ const req = {
5793
+ name,
5794
+ ...opts.database !== void 0 ? { database: opts.database } : {},
5795
+ ...opts.user !== void 0 ? { user: opts.user } : {},
5796
+ ...opts.password !== void 0 ? { password: opts.password } : {},
5797
+ ...opts.storage !== void 0 ? { storageGib: parseStorage(opts.storage, "--storage") } : {},
5798
+ ...opts.near !== void 0 ? { near: opts.near } : {}
5799
+ };
5800
+ const client = await managedClient(cmd);
5801
+ try {
5802
+ const made = await spin(`creating ${spec.title} database ${name}\u2026`, client.createManaged(spec.kind, req));
5803
+ const shown = shownName(made, me(client));
5804
+ const ready = await spin(`starting ${spec.title}\u2026`, async () => {
5805
+ for (const until = Date.now() + READY_WAIT_MS; Date.now() < until; await sleep3(READY_STEP_MS)) {
5806
+ const now = await client.getManaged(spec.kind, shown).catch(() => void 0);
5807
+ if (now?.health?.ready && now.health.accepting) return true;
5808
+ }
5809
+ return false;
5810
+ });
5811
+ if (opts.json) {
5812
+ json({ ...made, ready });
5813
+ return;
5814
+ }
5815
+ 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)`)}`);
5816
+ const rows2 = [["database", made.database], ...secretRows(made.secret)];
5817
+ printRows(rows2.map(([label, value]) => [` ${label}`, value]));
5818
+ info("");
5819
+ info("Nobody can reach it yet. To let something in:");
5820
+ info(` a box on the same host kvbox ${spec.command} link ${shown} <box> ${color.dim(`(a new one: kvbox new <box> --near ${shown})`)}`);
5821
+ info(` the internet kvbox ${spec.command} public ${shown} on`);
5822
+ 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}`));
5823
+ 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}`));
5824
+ } finally {
5825
+ await client.close();
5826
+ }
5827
+ });
5828
+
5829
+ // src/commands/managed/grow.ts
4754
5830
  import { Command as Command64 } from "commander";
5831
+ 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) => {
5832
+ const storageGib = parseStorage(size, "size");
5833
+ const client = await managedClient(cmd);
5834
+ try {
5835
+ const m = await spin(`growing ${name} to ${storageGib} GB (it restarts once)\u2026`, client.growManaged(spec.kind, name, storageGib));
5836
+ if (opts.json) json(m);
5837
+ 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)`)}`);
5838
+ } finally {
5839
+ await client.close();
5840
+ }
5841
+ });
5842
+
5843
+ // src/commands/managed/info.ts
5844
+ import { Command as Command65 } from "commander";
5845
+ 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) => {
5846
+ const client = await managedClient(cmd);
5847
+ try {
5848
+ const m = await client.getManaged(spec.kind, name);
5849
+ if (opts.json) json(m);
5850
+ else printRows(infoRows(spec, m, me(client)));
5851
+ } finally {
5852
+ await client.close();
5853
+ }
5854
+ });
5855
+
5856
+ // src/commands/managed/link.ts
5857
+ import { Command as Command66 } from "commander";
5858
+ 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) => {
5859
+ const client = await managedClient(cmd);
5860
+ try {
5861
+ const m = await spin(`linking ${box} to ${name}\u2026`, client.linkManaged(spec.kind, name, box));
5862
+ if (opts.json) {
5863
+ json(m);
5864
+ return;
5865
+ }
5866
+ info(`${color.green("\u2713")} box ${box} can reach database ${name}`);
5867
+ info(` inside ${box}: ${m.urls.private} ${color.dim(`(the password: kvbox ${spec.command} password ${name})`)}`);
5868
+ } finally {
5869
+ await client.close();
5870
+ }
5871
+ });
5872
+
5873
+ // src/commands/managed/ls.ts
5874
+ import { Command as Command67 } from "commander";
5875
+ function listRows(items, user, kindColumn) {
5876
+ return items.map((m) => ({
5877
+ owner: m.owner === user ? "private" : m.owner,
5878
+ name: boxName(m.name),
5879
+ ...kindColumn ? { kind: KINDS.find((k) => k.kind === m.kind)?.title ?? m.kind } : {},
5880
+ status: status(m.status),
5881
+ version: m.version,
5882
+ storage: `${m.storageGib}GB`,
5883
+ public: m.public ? `${m.public.host}:${m.public.port}` : "-",
5884
+ linked: m.links.length > 0 ? m.links.join(", ") : "-",
5885
+ created: age(m.createdAt)
5886
+ }));
5887
+ }
5888
+ 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) => {
5889
+ const client = await managedClient(cmd);
5890
+ try {
5891
+ const items = await client.listManaged(spec?.kind, { all: opts.all });
5892
+ if (opts.json) {
5893
+ json(items);
5894
+ return;
5895
+ }
5896
+ if (items.length === 0) {
5897
+ info(`no ${spec ? `${spec.title} ` : "managed "}databases yet; make one with: kvbox ${spec?.command ?? KINDS[0].command} create <name>`);
5898
+ return;
5899
+ }
5900
+ const user = client.target.kind === "cloud" ? client.target.user : void 0;
5901
+ table(listRows(items, user, spec === void 0));
5902
+ } finally {
5903
+ await client.close();
5904
+ }
5905
+ });
5906
+
5907
+ // src/commands/managed/password.ts
5908
+ import { Command as Command68 } from "commander";
5909
+ 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) => {
5910
+ const client = await managedClient(cmd);
5911
+ try {
5912
+ const secret = opts.reset ? await spin(`setting a new password on ${name}\u2026`, client.resetManagedPassword(spec.kind, name)) : await client.managedPassword(spec.kind, name);
5913
+ if (opts.json) {
5914
+ json(secret);
5915
+ return;
5916
+ }
5917
+ if (opts.reset) info(`${color.green("\u2713")} database ${name} has a new password; the old one no longer works`);
5918
+ printRows(secretRows(secret));
5919
+ } finally {
5920
+ await client.close();
5921
+ }
5922
+ });
5923
+
5924
+ // src/commands/managed/public.ts
5925
+ import { Command as Command69 } from "commander";
5926
+ 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) => {
5927
+ if (state !== "on" && state !== "off") throw new KvboxError(`write on or off: kvbox ${spec.command} public ${name} on`);
5928
+ const client = await managedClient(cmd);
5929
+ try {
5930
+ const m = await spin(`${state === "on" ? "opening" : "closing"} ${name}\u2026`, client.setManagedPublic(spec.kind, name, state === "on"));
5931
+ if (opts.json) {
5932
+ json(m);
5933
+ return;
5934
+ }
5935
+ if (m.public) {
5936
+ info(`${color.green("\u2713")} database ${name} is reachable from the internet at ${color.bold(`${m.public.host}:${m.public.port}`)}`);
5937
+ info(` ${m.urls.public} ${color.dim(`(the password: kvbox ${spec.command} password ${name})`)}`);
5938
+ } else {
5939
+ info(`${color.green("\u2713")} database ${name} is closed to the internet; turning it on again gives the same address`);
5940
+ }
5941
+ } finally {
5942
+ await client.close();
5943
+ }
5944
+ });
5945
+
5946
+ // src/commands/managed/rm.ts
5947
+ import { Command as Command70 } from "commander";
5948
+ 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) => {
5949
+ const client = await managedClient(cmd);
5950
+ try {
5951
+ if (!await confirm(`Delete database ${name} and all its data? There is no backup.`, opts.yes ?? false)) {
5952
+ info("cancelled");
5953
+ process.exitCode = 1;
5954
+ return;
5955
+ }
5956
+ await spin(`deleting database ${name}\u2026`, client.deleteManaged(spec.kind, name));
5957
+ info(`${color.green("\u2713")} database ${name} deleted`);
5958
+ } finally {
5959
+ await client.close();
5960
+ }
5961
+ });
5962
+
5963
+ // src/commands/managed/start.ts
5964
+ import { Command as Command71 } from "commander";
5965
+ 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) => {
5966
+ const client = await managedClient(cmd);
5967
+ try {
5968
+ const m = await spin(`starting ${name}\u2026`, client.startManaged(spec.kind, name));
5969
+ if (opts.json) json(m);
5970
+ else info(`${color.green("\u2713")} database ${name} is ${m.status}`);
5971
+ } finally {
5972
+ await client.close();
5973
+ }
5974
+ });
5975
+
5976
+ // src/commands/managed/stop.ts
5977
+ import { Command as Command72 } from "commander";
5978
+ 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) => {
5979
+ const client = await managedClient(cmd);
5980
+ try {
5981
+ const m = await spin(`stopping ${name}\u2026`, client.stopManaged(spec.kind, name));
5982
+ if (opts.json) json(m);
5983
+ 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}`)}`);
5984
+ } finally {
5985
+ await client.close();
5986
+ }
5987
+ });
5988
+
5989
+ // src/commands/managed/unlink.ts
5990
+ import { Command as Command73 } from "commander";
5991
+ 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) => {
5992
+ const client = await managedClient(cmd);
5993
+ try {
5994
+ const m = await spin(`unlinking ${box} from ${name}\u2026`, client.unlinkManaged(spec.kind, name, box));
5995
+ if (opts.json) json(m);
5996
+ else info(`${color.green("\u2713")} box ${box} no longer reaches database ${name}`);
5997
+ } finally {
5998
+ await client.close();
5999
+ }
6000
+ });
6001
+
6002
+ // src/commands/managed/kind.ts
6003
+ function kindCommand(spec, description) {
6004
+ const command = new Command74(spec.command).aliases(spec.aliases).description(description);
6005
+ for (const make of [createCommand4, lsCommand9, infoCommand, passwordCommand, publicCommand, linkCommand2, unlinkCommand2, growCommand2, stopCommand2, startCommand2, rmCommand8]) {
6006
+ command.addCommand(make(spec).option("--org <slug>", "act in this org (- for your personal databases)"));
6007
+ }
6008
+ return command;
6009
+ }
6010
+
6011
+ // src/commands/pg/index.ts
6012
+ var pgCommand = kindCommand(POSTGRES2, "managed PostgreSQL: a database kvbox runs for you, private until you link a box or make it public");
6013
+
6014
+ // src/commands/managed/index.ts
6015
+ import { Command as Command75 } from "commander";
6016
+ var managedCommand = new Command75("managed").description("databases kvbox runs for you, every kind together (Postgres: kvbox pg)").addCommand(lsCommand9().option("--org <slug>", "act in this org (- for your personal databases)"));
6017
+
6018
+ // src/commands/env/index.ts
6019
+ import { Command as Command79 } from "commander";
4755
6020
 
4756
6021
  // src/commands/env/ls.ts
4757
- import { Command as Command61 } from "commander";
6022
+ import { Command as Command76 } from "commander";
4758
6023
 
4759
6024
  // src/commands/env/shared.ts
4760
6025
  function requireCloud4(client) {
@@ -4781,7 +6046,7 @@ function firstBootHint(box, name) {
4781
6046
  }
4782
6047
 
4783
6048
  // src/commands/env/ls.ts
4784
- 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) => {
6049
+ 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) => {
4785
6050
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4786
6051
  try {
4787
6052
  if (opts.box !== void 0) {
@@ -4820,8 +6085,8 @@ var lsCommand9 = new Command61("ls").alias("list").description("list the variabl
4820
6085
  });
4821
6086
 
4822
6087
  // src/commands/env/rm.ts
4823
- import { Command as Command62 } from "commander";
4824
- 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) => {
6088
+ import { Command as Command77 } from "commander";
6089
+ 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) => {
4825
6090
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4826
6091
  try {
4827
6092
  const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
@@ -4858,8 +6123,8 @@ var rmCommand8 = new Command62("rm").alias("remove").description("remove variabl
4858
6123
  });
4859
6124
 
4860
6125
  // src/commands/env/set.ts
4861
- import { Command as Command63 } from "commander";
4862
- 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) => {
6126
+ import { Command as Command78 } from "commander";
6127
+ 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) => {
4863
6128
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4864
6129
  try {
4865
6130
  const owner = opts.box === void 0 ? requireCloud4(client) : void 0;
@@ -4896,14 +6161,14 @@ var setCommand2 = new Command63("set").description("add or change a variable; bo
4896
6161
  });
4897
6162
 
4898
6163
  // src/commands/env/index.ts
4899
- 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);
6164
+ 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);
4900
6165
  for (const cmd of envCommand.commands) cmd.option("--org <slug>", "the org's variables instead of yours");
4901
6166
 
4902
6167
  // src/commands/domain/index.ts
4903
- import { Command as Command68 } from "commander";
6168
+ import { Command as Command83 } from "commander";
4904
6169
 
4905
6170
  // src/commands/domain/add.ts
4906
- import { Command as Command65 } from "commander";
6171
+ import { Command as Command80 } from "commander";
4907
6172
 
4908
6173
  // src/commands/domain/shared.ts
4909
6174
  function requireCloud5(client) {
@@ -4923,7 +6188,7 @@ function hostIn(name, zone) {
4923
6188
  }
4924
6189
 
4925
6190
  // src/commands/domain/add.ts
4926
- 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) => {
6191
+ 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) => {
4927
6192
  const domain = assertDomain(domainArg.trim().toLowerCase());
4928
6193
  const port = opts.port === void 0 ? void 0 : parsePorts([opts.port])[0];
4929
6194
  const client = await clientFor(cmd.optsWithGlobals());
@@ -4959,8 +6224,8 @@ kvbox checks every minute; ${domain} is served at ${d.url} once its records are
4959
6224
  });
4960
6225
 
4961
6226
  // src/commands/domain/ls.ts
4962
- import { Command as Command66 } from "commander";
4963
- 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) => {
6227
+ import { Command as Command81 } from "commander";
6228
+ 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) => {
4964
6229
  const client = await clientFor(cmd.optsWithGlobals());
4965
6230
  try {
4966
6231
  requireCloud5(client);
@@ -4989,8 +6254,8 @@ var lsCommand10 = new Command66("ls").alias("list").description("list your custo
4989
6254
  });
4990
6255
 
4991
6256
  // src/commands/domain/rm.ts
4992
- import { Command as Command67 } from "commander";
4993
- 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) => {
6257
+ import { Command as Command82 } from "commander";
6258
+ 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) => {
4994
6259
  const domain = domainArg.trim().toLowerCase();
4995
6260
  const client = await clientFor(cmd.optsWithGlobals());
4996
6261
  try {
@@ -5011,15 +6276,15 @@ var rmCommand9 = new Command67("rm").alias("remove").description("stop serving a
5011
6276
  });
5012
6277
 
5013
6278
  // src/commands/domain/index.ts
5014
- var domainCommand = new Command68("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand10).addCommand(rmCommand9);
6279
+ var domainCommand = new Command83("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand11).addCommand(rmCommand10);
5015
6280
  for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
5016
6281
 
5017
6282
  // src/commands/update.ts
5018
6283
  import { spawn as spawn6 } from "child_process";
5019
6284
  import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
5020
6285
  import { tmpdir } from "os";
5021
- import { join as join8 } from "path";
5022
- import { Command as Command69 } from "commander";
6286
+ import { join as join9 } from "path";
6287
+ import { Command as Command84 } from "commander";
5023
6288
 
5024
6289
  // src/update.ts
5025
6290
  import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
@@ -5131,26 +6396,26 @@ async function download(url) {
5131
6396
  if (!body.startsWith("#!")) throw new KvboxError(`${url} did not return a shell script`);
5132
6397
  return body;
5133
6398
  }
5134
- function run(cmd, args) {
5135
- return new Promise((resolve3, reject) => {
6399
+ function run2(cmd, args) {
6400
+ return new Promise((resolve4, reject) => {
5136
6401
  const child = spawn6(cmd, args, { stdio: "inherit" });
5137
6402
  child.on("error", (err) => reject(new KvboxError(`could not run ${cmd}: ${err.message}`)));
5138
- child.on("exit", (code, signal) => resolve3(code ?? (signal ? 1 : 0)));
6403
+ child.on("exit", (code, signal) => resolve4(code ?? (signal ? 1 : 0)));
5139
6404
  });
5140
6405
  }
5141
- var selfUpdateCommand = new Command69("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
6406
+ var selfUpdateCommand = new Command84("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
5142
6407
  suppressUpdateNotice();
5143
6408
  const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
5144
6409
  let code;
5145
6410
  if (process.platform === "win32") {
5146
- code = await run(inst.cmd, inst.args);
6411
+ code = await run2(inst.cmd, inst.args);
5147
6412
  } else {
5148
6413
  const script = await download(inst.url);
5149
- const dir = mkdtempSync(join8(tmpdir(), "kvbox-update-"));
5150
- const file = join8(dir, "install.sh");
6414
+ const dir = mkdtempSync(join9(tmpdir(), "kvbox-update-"));
6415
+ const file = join9(dir, "install.sh");
5151
6416
  try {
5152
6417
  writeFileSync2(file, script, { mode: 448 });
5153
- code = await run(inst.cmd, inst.args.map((a) => a === "{script}" ? file : a));
6418
+ code = await run2(inst.cmd, inst.args.map((a) => a === "{script}" ? file : a));
5154
6419
  } finally {
5155
6420
  rmSync(dir, { recursive: true, force: true });
5156
6421
  }
@@ -5202,6 +6467,8 @@ var HELP_GROUPS = [
5202
6467
  ["vm", "everything about boxes: fork, rescale, ports, hooks, backups"],
5203
6468
  ["snapshots", "freeze a running box into a snapshot, start new boxes from it"],
5204
6469
  ["volume", "disks of their own that move between boxes"],
6470
+ ["pg", "managed PostgreSQL: a database kvbox runs for you"],
6471
+ ["managed", "every managed database, whatever its kind"],
5205
6472
  ["env", "environment variables and secrets every box of yours gets"],
5206
6473
  ["domain", "serve a box at a domain of your own"]
5207
6474
  ]
@@ -5259,10 +6526,12 @@ function installRootHelp(program) {
5259
6526
 
5260
6527
  // src/program.ts
5261
6528
  function buildProgram() {
5262
- 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();
6529
+ 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();
5263
6530
  program.addCommand(vmCommand);
5264
6531
  program.addCommand(snapshotsCommand);
5265
6532
  program.addCommand(volumeCommand);
6533
+ program.addCommand(pgCommand);
6534
+ program.addCommand(managedCommand);
5266
6535
  program.addCommand(envCommand);
5267
6536
  program.addCommand(domainCommand);
5268
6537
  program.addCommand(loginCommand);