@kvbox/cli 0.6.5 → 0.6.7

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
@@ -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.6.5" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.6.7" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command37 } from "commander";
@@ -283,7 +283,7 @@ function paths(home = kvboxHome()) {
283
283
  * disk, given to Firecracker by its relative name (`volumeDriveRel`), so a snapshot's vmstate names
284
284
  * it relative to whichever box dir it is restored into. There it is a same-size empty placeholder.
285
285
  */
286
- volumeDrive: (volume) => join(dir, volumeDriveRel(volume))
286
+ volumeDrive: (volume2) => join(dir, volumeDriveRel(volume2))
287
287
  };
288
288
  },
289
289
  /** Volumes are filed like boxes, by owner: volumes/<owner>/<name> (#52). */
@@ -328,11 +328,11 @@ function paths(home = kvboxHome()) {
328
328
  }
329
329
  };
330
330
  }
331
- function volumeDriveRel(volume) {
332
- return `volume-${volume}.ext4`;
331
+ function volumeDriveRel(volume2) {
332
+ return `volume-${volume2}.ext4`;
333
333
  }
334
- function volumeMountPath(volume) {
335
- return `/mnt/${volume}`;
334
+ function volumeMountPath(volume2) {
335
+ return `/mnt/${volume2}`;
336
336
  }
337
337
 
338
338
  // src/session.ts
@@ -672,7 +672,13 @@ var StartRunRequest = z.object({
672
672
  id: z.string().regex(BOX_RUN_ID_RE),
673
673
  command: z.string().min(1).max(8192),
674
674
  /** The command and everything it started are killed after this long. */
675
- timeoutSec: z.number().int().min(1).max(86400)
675
+ timeoutSec: z.number().int().min(1).max(86400),
676
+ /**
677
+ * The caller will read the output back (`exec`, #188): the box's kvbox-agent must know `runOutput`
678
+ * (base v0.16.0+), which the host checks before the command starts, so an older box is `box-outdated`
679
+ * without having run anything.
680
+ */
681
+ output: z.boolean().optional()
676
682
  });
677
683
  var StartRunAnswerSchema = z.object({
678
684
  id: z.string(),
@@ -686,9 +692,47 @@ var BoxRunSchema = z.object({
686
692
  id: z.string(),
687
693
  state: z.enum(BOX_RUN_STATES),
688
694
  /** With `exited`; 128 + the signal for a command a signal ended. */
689
- exitCode: z.number().int().optional()
695
+ exitCode: z.number().int().optional(),
696
+ /**
697
+ * With `exited` and `timeout`: how long the command itself ran, by the box's own clock (base v0.15.1
698
+ * and later). The asker learns of the end seconds late, so its own count is too long.
699
+ */
700
+ durationMs: z.number().int().nonnegative().optional()
690
701
  });
691
702
  var RunRefusalSchema = z.object({ error: z.string(), code: z.string().optional() });
703
+ var RUN_OUTPUT_MAX_BYTES = 1 << 20;
704
+ var RUN_STREAMS = ["stdout", "stderr"];
705
+ var RunOutputSchema = z.object({
706
+ id: z.string(),
707
+ stream: z.enum(RUN_STREAMS),
708
+ offset: z.number().int().nonnegative(),
709
+ size: z.number().int().nonnegative(),
710
+ data: z.string()
711
+ });
712
+ var DEFAULT_EXEC_TIMEOUT_SEC = 600;
713
+ var ExecRequest = z.object({
714
+ command: z.string().min(1).max(8192),
715
+ /** The command and everything it started are killed after this long (default DEFAULT_EXEC_TIMEOUT_SEC). */
716
+ timeoutSec: z.number().int().min(1).max(86400).optional()
717
+ });
718
+ var ExecStartSchema = z.object({
719
+ id: z.string(),
720
+ /** The box was asleep and this request woke it. */
721
+ woke: z.boolean()
722
+ });
723
+ var ExecSchema = z.object({
724
+ id: z.string(),
725
+ state: z.enum(BOX_RUN_STATES),
726
+ /** With `exited`; 128 + the signal for a command a signal ended. */
727
+ exitCode: z.number().int().optional(),
728
+ /** With `exited` and `timeout`: how long the command itself ran. */
729
+ durationMs: z.number().int().nonnegative().optional(),
730
+ stdout: z.string().optional(),
731
+ stderr: z.string().optional(),
732
+ stdoutBytes: z.number().int().nonnegative().optional(),
733
+ stderrBytes: z.number().int().nonnegative().optional(),
734
+ truncated: z.boolean().optional()
735
+ });
692
736
  var EnvVarSchema = z.object({
693
737
  name: z.string(),
694
738
  value: z.string().optional(),
@@ -1047,7 +1091,7 @@ var VolumeEventsResponseSchema = z.object({
1047
1091
  events: z.array(VolumeEventRowSchema),
1048
1092
  next: z.number().int()
1049
1093
  });
1050
- var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
1094
+ var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit", "box-outdated"];
1051
1095
  var ApiErrorCodeSchema = z.enum(API_ERROR_CODES);
1052
1096
  var ApiErrorSchema = z.object({
1053
1097
  error: z.string(),
@@ -1368,10 +1412,10 @@ function isLoopback(hostname) {
1368
1412
  return hostname === "localhost" || hostname.startsWith("127.") || hostname === "[::1]";
1369
1413
  }
1370
1414
  function normalizeUrl(input) {
1371
- const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`;
1415
+ const withScheme2 = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`;
1372
1416
  let url;
1373
1417
  try {
1374
- url = new URL(withScheme);
1418
+ url = new URL(withScheme2);
1375
1419
  } catch {
1376
1420
  throw new KvboxError(`not a URL: ${input}`);
1377
1421
  }
@@ -1469,16 +1513,16 @@ async function forgetCertOf(p) {
1469
1513
  }
1470
1514
  async function ensureCert(client, p = paths(), now = Date.now(), opts = {}) {
1471
1515
  if (client.target.kind !== "cloud") return "local";
1472
- const fromEnv = client.target.env === true;
1473
- const session = fromEnv ? null : await readSession(p);
1474
- if (!fromEnv && !session) return "local";
1516
+ const fromEnv2 = client.target.env === true;
1517
+ const session = fromEnv2 ? null : await readSession(p);
1518
+ if (!fromEnv2 && !session) return "local";
1475
1519
  if (session) {
1476
1520
  const expires = session.sshCertExpires ? new Date(session.sshCertExpires).getTime() : 0;
1477
1521
  const onDisk = await readFile2(p.sshCert, "utf8").then(() => true, () => false);
1478
1522
  const names2 = opts.owner === void 0 || (session.sshCertPrincipals ?? []).includes(opts.owner);
1479
1523
  if (onDisk && expires - now > RENEW_BEFORE_MS && names2 && !opts.force) return "kept";
1480
1524
  }
1481
- const publicKey = fromEnv ? await ensureSshKey(p) : await readFile2(`${p.sshKey}.pub`, "utf8").catch(() => null);
1525
+ const publicKey = fromEnv2 ? await ensureSshKey(p) : await readFile2(`${p.sshKey}.pub`, "utf8").catch(() => null);
1482
1526
  if (publicKey === null) throw new KvboxError(`could not renew your SSH certificate: no key at ${p.sshKey}.pub; run: kvbox login`);
1483
1527
  let signed;
1484
1528
  try {
@@ -1502,35 +1546,524 @@ async function ensureCert(client, p = paths(), now = Date.now(), opts = {}) {
1502
1546
  import { spawn } from "child_process";
1503
1547
  import { openSync } from "fs";
1504
1548
  import { mkdir as mkdir3, readFile as readFile3, stat } from "fs/promises";
1505
- import { setTimeout as sleep } from "timers/promises";
1549
+ import { setTimeout as sleep2 } from "timers/promises";
1506
1550
  import { Agent, request } from "undici";
1507
- import { z as z7 } from "zod";
1508
1551
 
1509
- // ../shared/src/managed.ts
1552
+ // ../sdk/src/machines.ts
1553
+ import { z as z3 } from "zod";
1554
+
1555
+ // ../sdk/src/errors.ts
1556
+ var KvboxSdkError = class extends Error {
1557
+ constructor(message, options) {
1558
+ super(message, options);
1559
+ this.name = "KvboxSdkError";
1560
+ }
1561
+ };
1562
+ var KvboxApiError = class extends KvboxSdkError {
1563
+ status;
1564
+ code;
1565
+ apiError;
1566
+ constructor(status2, message, opts = {}) {
1567
+ super(message);
1568
+ this.name = "KvboxApiError";
1569
+ this.status = status2;
1570
+ this.code = opts.code;
1571
+ this.apiError = opts.apiError ?? true;
1572
+ }
1573
+ };
1574
+ var UnauthorizedError = class extends KvboxApiError {
1575
+ constructor(status2, message, opts = {}) {
1576
+ super(status2, message, opts);
1577
+ this.name = "UnauthorizedError";
1578
+ }
1579
+ };
1580
+ var PaymentRequiredError = class extends KvboxApiError {
1581
+ constructor(status2, message, opts = {}) {
1582
+ super(status2, message, opts);
1583
+ this.name = "PaymentRequiredError";
1584
+ }
1585
+ };
1586
+ var NotFoundError = class extends KvboxApiError {
1587
+ constructor(status2, message, opts = {}) {
1588
+ super(status2, message, opts);
1589
+ this.name = "NotFoundError";
1590
+ }
1591
+ };
1592
+ var ConflictError = class extends KvboxApiError {
1593
+ constructor(status2, message, opts = {}) {
1594
+ super(status2, message, opts);
1595
+ this.name = "ConflictError";
1596
+ }
1597
+ };
1598
+ var BoxOutdatedError = class extends ConflictError {
1599
+ constructor(status2, message, opts = {}) {
1600
+ super(status2, message, opts);
1601
+ this.name = "BoxOutdatedError";
1602
+ }
1603
+ };
1604
+ function apiError(status2, message, opts = {}) {
1605
+ switch (status2) {
1606
+ case 401:
1607
+ return new UnauthorizedError(status2, message, opts);
1608
+ case 402:
1609
+ return new PaymentRequiredError(status2, message, opts);
1610
+ case 404:
1611
+ return new NotFoundError(status2, message, opts);
1612
+ case 409:
1613
+ return opts.code === "box-outdated" ? new BoxOutdatedError(status2, message, opts) : new ConflictError(status2, message, opts);
1614
+ default:
1615
+ return new KvboxApiError(status2, message, opts);
1616
+ }
1617
+ }
1618
+ var KvboxConnectionError = class extends KvboxSdkError {
1619
+ code;
1620
+ constructor(message, code, options) {
1621
+ super(message, options);
1622
+ this.name = "KvboxConnectionError";
1623
+ this.code = code;
1624
+ }
1625
+ };
1626
+ var KvboxTimeoutError = class extends KvboxSdkError {
1627
+ timeoutMs;
1628
+ constructor(message, timeoutMs) {
1629
+ super(message);
1630
+ this.name = "KvboxTimeoutError";
1631
+ this.timeoutMs = timeoutMs;
1632
+ }
1633
+ };
1634
+ var KvboxResponseError = class extends KvboxSdkError {
1635
+ status;
1636
+ reason;
1637
+ constructor(status2, message, reason = "not-json", options) {
1638
+ super(message, options);
1639
+ this.name = "KvboxResponseError";
1640
+ this.status = status2;
1641
+ this.reason = reason;
1642
+ }
1643
+ };
1644
+
1645
+ // ../sdk/src/machines.ts
1646
+ var FORK_TIMEOUT_MS = 66e4;
1647
+ var listQuery = (opts) => opts.all ? "?all=1" : "";
1648
+ var box = (name, rest = "") => `/machines/${encodeURIComponent(name)}${rest}`;
1649
+ var sleep = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
1650
+ var passing = (err) => err instanceof KvboxConnectionError || err instanceof KvboxTimeoutError || err instanceof KvboxApiError && [502, 503, 504].includes(err.status);
1651
+ var Machines = class {
1652
+ constructor(transport) {
1653
+ this.transport = transport;
1654
+ this.ports = {
1655
+ add: (name, req, opts = {}) => this.transport.request("POST", box(name, "/ports"), MachineSchema, { body: req, org: opts.org }),
1656
+ remove: (name, req, opts = {}) => this.transport.request("DELETE", box(name, "/ports"), MachineSchema, { body: req, org: opts.org })
1657
+ };
1658
+ }
1659
+ transport;
1660
+ /** Publish and close a box's ports. */
1661
+ ports;
1662
+ /** Every box the caller can read (their own and their orgs'), sorted by owner then name. */
1663
+ list(opts = {}) {
1664
+ return this.transport.request("GET", `/machines${listQuery(opts)}`, z3.array(MachineSchema), { org: opts.org });
1665
+ }
1666
+ /**
1667
+ * One box, found in the listing (the API has no route for a single box). `slug/name` looks in that
1668
+ * slug only. A bare name is the caller's own box first, else the only org box of that name; one in
1669
+ * two orgs is an error that asks for `slug/name` or `org`. None: `NotFoundError`.
1670
+ */
1671
+ get(name, opts = {}) {
1672
+ return this.find(name, opts.org);
1673
+ }
1674
+ /** `get`, its listing call limited to `timeoutMs` (default: the client's). */
1675
+ async find(name, orgOpt, timeoutMs) {
1676
+ const slash = name.indexOf("/");
1677
+ const [org, bare] = slash === -1 ? [orgOpt, name] : [name.slice(0, slash), name.slice(slash + 1)];
1678
+ const listing = await this.transport.request("GET", "/machines", z3.array(MachineSchema), { org, timeoutMs });
1679
+ const named = listing.filter((m) => m.name === bare && (slash === -1 || slugOf2(m.owner) === org));
1680
+ if (named.length <= 1) {
1681
+ if (named[0] !== void 0) return named[0];
1682
+ throw new NotFoundError(404, `box ${name}: not found`);
1683
+ }
1684
+ const own = named.filter((m) => m.ownerKind === "user");
1685
+ if (own.length === 1) return own[0];
1686
+ throw new KvboxSdkError(`box ${name} exists in ${named.map((m) => slugOf2(m.owner)).join(", ")}; say which with slug/name or the org option`);
1687
+ }
1688
+ /**
1689
+ * Make a box and boot it. The answer comes once the VM has started (status `running`); the guest
1690
+ * system inside is still booting for a few seconds after (see `waitUntilReady`). A box from an
1691
+ * image that serves something answers `connect` (its URL with the password) this once.
1692
+ * `org` (this call's, else the client's): the new box goes to that org, else to the caller's own slug.
1693
+ */
1694
+ create(req = {}, opts = {}) {
1695
+ return this.transport.request("POST", "/machines", MachineSchema, { body: req, org: opts.org });
1696
+ }
1697
+ /** Remove the box and its disk. */
1698
+ async remove(name, opts = {}) {
1699
+ await this.transport.request("DELETE", box(name), z3.undefined(), { org: opts.org });
1700
+ }
1701
+ /** Boot a stopped box. */
1702
+ start(name, opts = {}) {
1703
+ return this.transport.request("POST", box(name, "/start"), MachineSchema, { body: opts.force ? { force: true } : void 0, org: opts.org });
1704
+ }
1705
+ /** Shut the box down; its disk stays. */
1706
+ stop(name, opts = {}) {
1707
+ return this.transport.request("POST", box(name, "/stop"), MachineSchema, { org: opts.org });
1708
+ }
1709
+ /** Freeze the running box in memory (standby). */
1710
+ pause(name, opts = {}) {
1711
+ return this.transport.request("POST", box(name, "/pause"), MachineSchema, { org: opts.org });
1712
+ }
1713
+ /** Unfreeze a box in standby. */
1714
+ resume(name, opts = {}) {
1715
+ return this.transport.request("POST", box(name, "/resume"), MachineSchema, { org: opts.org });
1716
+ }
1717
+ /** Write the box's memory to disk and free it; `wake` brings the box back where it was. */
1718
+ hibernate(name, opts = {}) {
1719
+ return this.transport.request("POST", box(name, "/hibernate"), MachineSchema, { org: opts.org });
1720
+ }
1721
+ /** Bring a hibernated box back, processes and all. */
1722
+ wake(name, opts = {}) {
1723
+ return this.transport.request("POST", box(name, "/wake"), MachineSchema, { body: opts.force ? { force: true } : void 0, org: opts.org });
1724
+ }
1725
+ /**
1726
+ * A copy of box `name` on the same host. The copy goes to `org` (the client's, or this call's),
1727
+ * else to the caller's own slug; the source is found without it, so name it `slug/name` when it is an org's.
1728
+ */
1729
+ fork(name, req = {}, opts = {}) {
1730
+ const timeoutMs = opts.timeoutMs ?? Math.max(FORK_TIMEOUT_MS, this.transport.timeoutMs);
1731
+ return this.transport.request("POST", box(name, "/fork"), MachineSchema, { body: req, org: opts.org, timeoutMs });
1732
+ }
1733
+ /**
1734
+ * Resolve with the box once it is `running`, looking every `intervalMs`.
1735
+ *
1736
+ * What "ready" means: `create`, `start` and `fork` already answer once the VM is started (status
1737
+ * `running`, an address and, through the cloud, `ssh`), and `wake`/`resume` once its memory is
1738
+ * back. What the API does not tell is the guest's own boot: sshd and kvbox-agent listen a few
1739
+ * seconds after a cold start, and nothing in a box's listing says when. So this waits for what the
1740
+ * listing does say: status `running` (a box whose host has not answered lately is `unknown` until
1741
+ * it does; any other status may still change, for instance while someone else starts it). A
1742
+ * command run in the box right after should still allow for the guest's few seconds.
1743
+ * Not found is thrown at once; nothing answering, or a 502/503/504, is waited through.
1744
+ */
1745
+ async waitUntilReady(name, opts = {}) {
1746
+ const timeoutMs = opts.timeoutMs ?? 12e4;
1747
+ const intervalMs = opts.intervalMs ?? 1e3;
1748
+ const deadline = Date.now() + timeoutMs;
1749
+ let last;
1750
+ for (; ; ) {
1751
+ try {
1752
+ const m = await this.find(name, opts.org, Math.max(1, Math.min(deadline - Date.now(), this.transport.timeoutMs)));
1753
+ if (m.status === "running") return m;
1754
+ last = m.status;
1755
+ } catch (err) {
1756
+ if (!passing(err)) throw err;
1757
+ last = err.message;
1758
+ }
1759
+ const left = deadline - Date.now();
1760
+ if (left <= 0) throw new KvboxTimeoutError(`box ${name} was not running within ${Math.round(timeoutMs / 1e3)}s (last: ${last})`, timeoutMs);
1761
+ await sleep(Math.min(intervalMs, left));
1762
+ }
1763
+ }
1764
+ /**
1765
+ * Run `command` in the box and resolve once it is over, with its exit code and output.
1766
+ *
1767
+ * The command runs as the box's user (`kvbox`) in its home, through a login shell (`bash -lc`) with
1768
+ * the owner's environment variables: one string, as you would type it after `kvbox exec web --`.
1769
+ * No terminal and no stdin. A hibernated or paused box is woken first; a stopped one is refused
1770
+ * (`ConflictError`), and so is a box whose image is from before base v0.16.0 (`BoxOutdatedError`).
1771
+ * A slug that may not spend gets a `PaymentRequiredError`.
1772
+ *
1773
+ * `timeoutMs` (default 600 000, at most 24 h) is the command's time limit, in whole seconds on the
1774
+ * box: then it and everything it started are killed, and the result has `timedOut` and no exit
1775
+ * code. The SDK waits a minute past it before giving up with a `KvboxTimeoutError`. `stdout` and
1776
+ * `stderr` are the first MiB of each, as UTF-8 text; `truncated` says one was longer.
1777
+ * The command is polled every `pollMs` (default 1000); a moment without the API is waited through.
1778
+ */
1779
+ async exec(name, command, opts = {}) {
1780
+ const timeoutSec = execTimeoutSec(opts.timeoutMs);
1781
+ const pollMs = opts.pollMs ?? 1e3;
1782
+ const { id } = await this.startExec(name, command, opts);
1783
+ const startedAt = Date.now();
1784
+ const deadline = startedAt + timeoutSec * 1e3 + EXEC_GRACE_MS;
1785
+ let last;
1786
+ for (; ; ) {
1787
+ try {
1788
+ const run3 = await this.getExec(name, id, { org: opts.org });
1789
+ if (run3.state === "unknown") throw new KvboxSdkError(`box ${name} no longer knows command ${id}: it restarted while the command ran`);
1790
+ if (run3.state !== "running") {
1791
+ return {
1792
+ exitCode: run3.exitCode ?? null,
1793
+ timedOut: run3.state === "timeout",
1794
+ stdout: run3.stdout ?? "",
1795
+ stderr: run3.stderr ?? "",
1796
+ truncated: run3.truncated ?? false,
1797
+ durationMs: run3.durationMs ?? Date.now() - startedAt
1798
+ };
1799
+ }
1800
+ last = "running";
1801
+ } catch (err) {
1802
+ if (!passing(err)) throw err;
1803
+ last = err.message;
1804
+ }
1805
+ const left = deadline - Date.now();
1806
+ if (left <= 0) throw new KvboxTimeoutError(`command ${id} in box ${name} had not ended within ${Math.round((deadline - startedAt) / 1e3)}s (last: ${last})`, deadline - startedAt);
1807
+ await sleep(Math.min(pollMs, left));
1808
+ }
1809
+ }
1810
+ /**
1811
+ * Start `command` in the box and answer at once with its `id` (what `exec` does first): for a
1812
+ * command you do not wait on, or one you look at later with `getExec`. `woke`: the box was asleep.
1813
+ * A box that is still waking (503) is asked again, for up to five minutes: its own time, not the command's.
1814
+ */
1815
+ async startExec(name, command, opts = {}) {
1816
+ const timeoutSec = execTimeoutSec(opts.timeoutMs);
1817
+ const deadline = Date.now() + EXEC_WAKE_MS;
1818
+ for (; ; ) {
1819
+ try {
1820
+ return await this.transport.request("POST", box(name, "/exec"), ExecStartSchema, { body: { command, timeoutSec }, org: opts.org });
1821
+ } catch (err) {
1822
+ if (!(err instanceof KvboxApiError && err.status === 503) || Date.now() + (opts.pollMs ?? 1e3) >= deadline) throw err;
1823
+ await sleep(opts.pollMs ?? 1e3);
1824
+ }
1825
+ }
1826
+ }
1827
+ /**
1828
+ * How a command started with `exec` or `startExec` stands; once it is over, with its output (see `Exec`).
1829
+ * A box that went to sleep since is woken to answer, so a slug that may not spend gets a `PaymentRequiredError`.
1830
+ */
1831
+ getExec(name, id, opts = {}) {
1832
+ return this.transport.request("GET", box(name, `/exec/${encodeURIComponent(id)}`), ExecSchema, { org: opts.org });
1833
+ }
1834
+ };
1835
+ var EXEC_GRACE_MS = 6e4;
1836
+ var EXEC_WAKE_MS = 5 * 6e4;
1837
+ var MAX_EXEC_TIMEOUT_SEC = 86400;
1838
+ function execTimeoutSec(timeoutMs) {
1839
+ if (timeoutMs === void 0) return DEFAULT_EXEC_TIMEOUT_SEC;
1840
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new KvboxSdkError(`timeoutMs must be a number of milliseconds, not ${String(timeoutMs)}`);
1841
+ return Math.min(Math.max(Math.ceil(timeoutMs / 1e3), 1), MAX_EXEC_TIMEOUT_SEC);
1842
+ }
1843
+ var slugOf2 = (owner) => {
1844
+ const at = owner.indexOf("@");
1845
+ return at === -1 ? owner : owner.slice(0, at);
1846
+ };
1847
+
1848
+ // ../sdk/src/snapshots.ts
1510
1849
  import { z as z4 } from "zod";
1850
+ var Snapshots = class {
1851
+ constructor(transport) {
1852
+ this.transport = transport;
1853
+ }
1854
+ transport;
1855
+ /** Every snapshot the caller can read. */
1856
+ list(opts = {}) {
1857
+ return this.transport.request("GET", `/snapshots${listQuery(opts)}`, z4.array(SnapshotSchema), { org: opts.org });
1858
+ }
1859
+ /** Snapshot box `req.box` as `req.name` (`replace`: retake one that exists). The box is paused while it is taken. */
1860
+ create(req, opts = {}) {
1861
+ return this.transport.request("POST", "/snapshots", SnapshotSchema, { body: req, org: opts.org });
1862
+ }
1863
+ async remove(name, opts = {}) {
1864
+ await this.transport.request("DELETE", `/snapshots/${encodeURIComponent(name)}`, z4.undefined(), { org: opts.org });
1865
+ }
1866
+ };
1867
+
1868
+ // ../sdk/src/transport.ts
1869
+ import { z as z5 } from "zod";
1870
+ var Transport = class {
1871
+ baseUrl;
1872
+ org;
1873
+ apiKey;
1874
+ fetch;
1875
+ /** A request's default limit. */
1876
+ timeoutMs;
1877
+ constructor(opts) {
1878
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
1879
+ this.apiKey = opts.apiKey;
1880
+ this.org = opts.org;
1881
+ this.fetch = opts.fetch;
1882
+ this.timeoutMs = opts.timeoutMs;
1883
+ }
1884
+ /** `host:port` of the base URL, for messages. */
1885
+ get host() {
1886
+ try {
1887
+ return new URL(this.baseUrl).host;
1888
+ } catch {
1889
+ return this.baseUrl;
1890
+ }
1891
+ }
1892
+ /**
1893
+ * `method path`, the answer parsed with `schema` (an empty body is `undefined`, so a 204 takes
1894
+ * `z.undefined()`; one that does not fit is a `KvboxResponseError`). A status outside 200-299 is a
1895
+ * `KvboxApiError` (redirects are not followed).
1896
+ */
1897
+ async request(method, path, schema, opts = {}) {
1898
+ const { status: status2, text: text2 } = await this.send(method, path, opts);
1899
+ if (status2 < 200 || status2 >= 300) {
1900
+ const parsed2 = LooseApiErrorSchema.safeParse(safeJson(text2) ?? {});
1901
+ if (!parsed2.success) throw apiError(status2, `${this.host} answered ${status2}`, { apiError: false });
1902
+ const code = ApiErrorCodeSchema.safeParse(parsed2.data.code);
1903
+ throw apiError(status2, parsed2.data.error, { code: code.success ? code.data : void 0 });
1904
+ }
1905
+ const json2 = text2 === "" ? void 0 : safeJson(text2);
1906
+ if (text2 !== "" && json2 === void 0) throw new KvboxResponseError(status2, `${this.host} answered ${status2} with something that is not JSON`);
1907
+ const parsed = schema.safeParse(json2);
1908
+ if (!parsed.success) throw new KvboxResponseError(status2, `${this.host} answered ${method} ${path} with something this SDK does not expect: ${parsed.error.message}`, "schema", { cause: parsed.error });
1909
+ return parsed.data;
1910
+ }
1911
+ /** The raw answer: status and body text. Where a request that is not plain JSON (a stream) would start. */
1912
+ async send(method, path, opts) {
1913
+ const headers = {};
1914
+ if (opts.body !== void 0) headers["content-type"] = "application/json";
1915
+ if (this.apiKey !== void 0 && this.apiKey !== "") headers["authorization"] = `Bearer ${this.apiKey}`;
1916
+ const org = opts.org ?? this.org;
1917
+ if (org !== void 0) headers["x-kvbox-org"] = org;
1918
+ const timeoutMs = opts.timeoutMs ?? this.timeoutMs;
1919
+ const timedOut = () => new KvboxTimeoutError(`${this.host} did not answer ${method} ${path} within ${Math.round(timeoutMs / 1e3)}s`, timeoutMs);
1920
+ let res;
1921
+ try {
1922
+ res = await this.fetch(this.baseUrl + path, {
1923
+ method,
1924
+ headers,
1925
+ ...opts.body === void 0 ? {} : { body: JSON.stringify(opts.body) },
1926
+ signal: AbortSignal.timeout(timeoutMs),
1927
+ redirect: "manual"
1928
+ });
1929
+ } catch (err) {
1930
+ if (isTimeout(err)) throw timedOut();
1931
+ const code = errorCode(err);
1932
+ throw new KvboxConnectionError(`could not reach ${this.host}${code === void 0 ? "" : ` (${code})`}`, code, { cause: err });
1933
+ }
1934
+ try {
1935
+ return { status: res.status, text: await res.text() };
1936
+ } catch (err) {
1937
+ if (isTimeout(err)) throw timedOut();
1938
+ const code = errorCode(err);
1939
+ throw new KvboxResponseError(res.status, `${this.host} answered ${res.status} but the answer was cut off${code === void 0 ? "" : ` (${code})`}`, "cut-off", { cause: err });
1940
+ }
1941
+ }
1942
+ };
1943
+ var LooseApiErrorSchema = z5.object({ error: z5.string(), code: z5.string().optional() });
1944
+ function safeJson(text2) {
1945
+ try {
1946
+ return JSON.parse(text2);
1947
+ } catch {
1948
+ return void 0;
1949
+ }
1950
+ }
1951
+ var isTimeout = (err) => err instanceof Error && (err.name === "TimeoutError" || err.cause instanceof Error && err.cause.name === "TimeoutError");
1952
+ function errorCode(err) {
1953
+ for (let e = err, depth = 0; e !== void 0 && e !== null && depth < 4; e = e.cause, depth++) {
1954
+ const code = e.code;
1955
+ if (typeof code === "string") return code;
1956
+ }
1957
+ return void 0;
1958
+ }
1959
+
1960
+ // ../sdk/src/volumes.ts
1961
+ import { z as z6 } from "zod";
1962
+ var volume = (name, rest = "") => `/volumes/${encodeURIComponent(name)}${rest}`;
1963
+ var Volumes = class {
1964
+ constructor(transport) {
1965
+ this.transport = transport;
1966
+ }
1967
+ transport;
1968
+ list(opts = {}) {
1969
+ return this.transport.request("GET", `/volumes${listQuery(opts)}`, z6.array(VolumeSchema), { org: opts.org });
1970
+ }
1971
+ /**
1972
+ * Make a volume of `sizeGib` GiB. Through the cloud `box` is required: the volume is made on that
1973
+ * box's host (it attaches only to a box there). It is not attached yet: call `attach`.
1974
+ */
1975
+ create(req, opts = {}) {
1976
+ return this.transport.request("POST", "/volumes", VolumeSchema, { body: req, org: opts.org });
1977
+ }
1978
+ /** Attach the volume to `box`; a running box restarts to take it, a hibernated one is refused. The answer is the box. */
1979
+ attach(name, box2, opts = {}) {
1980
+ return this.transport.request("POST", volume(name, "/attach"), MachineSchema, { body: { box: box2 }, org: opts.org });
1981
+ }
1982
+ /** Detach it from `box` (restarting a running box); the data stays on the volume. */
1983
+ detach(name, box2, opts = {}) {
1984
+ return this.transport.request("POST", volume(name, "/detach"), MachineSchema, { body: { box: box2 }, org: opts.org });
1985
+ }
1986
+ /** Grow the volume to `sizeGib` (never shrinks); a running box that holds it restarts. */
1987
+ grow(name, sizeGib, opts = {}) {
1988
+ return this.transport.request("POST", volume(name, "/resize"), VolumeSchema, { body: { sizeGib }, org: opts.org });
1989
+ }
1990
+ /** Remove the volume and its data; it must be detached first. */
1991
+ async remove(name, opts = {}) {
1992
+ await this.transport.request("DELETE", volume(name), z6.undefined(), { org: opts.org });
1993
+ }
1994
+ };
1995
+
1996
+ // ../sdk/src/client.ts
1997
+ var DEFAULT_BASE_URL = "https://api.kvbox.sh";
1998
+ var DEFAULT_TIMEOUT_MS = 3e5;
1999
+ function fromEnv(name) {
2000
+ try {
2001
+ const env = globalThis.process?.env;
2002
+ const value = env?.[name]?.trim();
2003
+ return value === void 0 || value === "" ? void 0 : value;
2004
+ } catch {
2005
+ return void 0;
2006
+ }
2007
+ }
2008
+ var withScheme = (url) => /^[a-z][a-z0-9+.-]*:\/\//i.test(url) ? url : `https://${url}`;
2009
+ var Kvbox = class {
2010
+ machines;
2011
+ snapshots;
2012
+ volumes;
2013
+ transport;
2014
+ constructor(opts = {}) {
2015
+ this.transport = new Transport({
2016
+ baseUrl: withScheme(opts.baseUrl ?? fromEnv("KVBOX_URL") ?? DEFAULT_BASE_URL),
2017
+ apiKey: opts.apiKey ?? fromEnv("KVBOX_TOKEN"),
2018
+ org: opts.org,
2019
+ fetch: opts.fetch ?? ((url, init) => globalThis.fetch(url, init)),
2020
+ timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
2021
+ });
2022
+ this.machines = new Machines(this.transport);
2023
+ this.snapshots = new Snapshots(this.transport);
2024
+ this.volumes = new Volumes(this.transport);
2025
+ }
2026
+ /** The API this client talks to, without a trailing slash. */
2027
+ get baseUrl() {
2028
+ return this.transport.baseUrl;
2029
+ }
2030
+ /**
2031
+ * Any route of the API, for what the namespaces do not cover yet: `method path`, the JSON answer
2032
+ * checked with `schema` (an empty answer is `undefined`). Errors are the SDK's, as everywhere.
2033
+ */
2034
+ request(method, path, schema, opts = {}) {
2035
+ return this.transport.request(method, path, schema, opts);
2036
+ }
2037
+ };
2038
+
2039
+ // src/client.ts
2040
+ import { z as z11 } from "zod";
2041
+
2042
+ // ../shared/src/managed.ts
2043
+ import { z as z8 } from "zod";
1511
2044
 
1512
2045
  // ../shared/src/usage.ts
1513
- import { z as z3 } from "zod";
1514
- var PricingSchema = z3.object({
1515
- currency: z3.string().min(1),
1516
- vcpuHour: z3.number().nonnegative(),
1517
- ramGibHour: z3.number().nonnegative(),
1518
- diskGibHour: z3.number().nonnegative(),
1519
- volumeHour: z3.number().nonnegative().default(0),
1520
- volumeGibHour: z3.number().nonnegative().default(0),
1521
- diskIncludedGib: z3.number().int().nonnegative().default(0),
2046
+ import { z as z7 } from "zod";
2047
+ var PricingSchema = z7.object({
2048
+ currency: z7.string().min(1),
2049
+ vcpuHour: z7.number().nonnegative(),
2050
+ ramGibHour: z7.number().nonnegative(),
2051
+ diskGibHour: z7.number().nonnegative(),
2052
+ volumeHour: z7.number().nonnegative().default(0),
2053
+ volumeGibHour: z7.number().nonnegative().default(0),
2054
+ diskIncludedGib: z7.number().int().nonnegative().default(0),
1522
2055
  /**
1523
2056
  * Object storage (#182): an hour of a slug's storage existing, whatever it holds, which covers its
1524
2057
  * hidden box and the first `storageIncludedGib` of its size; each GiB above that is `storageGibHour`.
1525
2058
  * A price list from before object storage charges nothing for it.
1526
2059
  */
1527
- storageHour: z3.number().nonnegative().default(0),
1528
- storageGibHour: z3.number().nonnegative().default(0),
1529
- storageIncludedGib: z3.number().int().nonnegative().default(0),
2060
+ storageHour: z7.number().nonnegative().default(0),
2061
+ storageGibHour: z7.number().nonnegative().default(0),
2062
+ storageIncludedGib: z7.number().int().nonnegative().default(0),
1530
2063
  /** The cron service (#190): an hour of one cron service existing, whatever it holds or fires. A price list from before it charges nothing. */
1531
- cronHour: z3.number().nonnegative().default(0)
2064
+ cronHour: z7.number().nonnegative().default(0)
1532
2065
  });
1533
- var PriceListSchema = PricingSchema.extend({ welcomeCredit: z3.number().nonnegative() });
2066
+ var PriceListSchema = PricingSchema.extend({ welcomeCredit: z7.number().nonnegative() });
1534
2067
  var HOUR_MS = 36e5;
1535
2068
  var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
1536
2069
  function costOf(t, pricing) {
@@ -1558,250 +2091,250 @@ function sumUsage(items, pricing) {
1558
2091
  var DAY_MS = 24 * HOUR_MS;
1559
2092
 
1560
2093
  // ../shared/src/managed.ts
1561
- var PriceSchema = z4.object({ perMonth: z4.number(), storagePerMonth: z4.number(), currency: z4.string() });
1562
- var ManagedCatalogEntrySchema = z4.object({
2094
+ var PriceSchema = z8.object({ perMonth: z8.number(), storagePerMonth: z8.number(), currency: z8.string() });
2095
+ var ManagedCatalogEntrySchema = z8.object({
1563
2096
  /** The kind, as in `/managed/<kind>`: `postgres`. */
1564
- kind: z4.string(),
2097
+ kind: z8.string(),
1565
2098
  /** The CLI command for it: `pg` (`kvbox pg create …`). */
1566
- command: z4.string(),
1567
- title: z4.string(),
1568
- description: z4.string(),
2099
+ command: z8.string(),
2100
+ title: z8.string(),
2101
+ description: z8.string(),
1569
2102
  /** The version a new one runs, as shown: `18`. */
1570
- version: z4.string(),
2103
+ version: z8.string(),
1571
2104
  /** The port a linked box reaches it on. */
1572
- port: z4.number().int(),
2105
+ port: z8.number().int(),
1573
2106
  /** The port `public on` opens behind a host port: `port` again unless the kind serves TLS on another. */
1574
- publicPort: z4.number().int(),
2107
+ publicPort: z8.number().int(),
1575
2108
  /** Its guide, as a URL. */
1576
- docs: z4.string().optional(),
1577
- storage: z4.object({ defaultGib: z4.number().int(), minGib: z4.number().int(), maxGib: z4.number().int() }),
2109
+ docs: z8.string().optional(),
2110
+ storage: z8.object({ defaultGib: z8.number().int(), minGib: z8.number().int(), maxGib: z8.number().int() }),
1578
2111
  /**
1579
2112
  * What create takes of this kind alone, beside what every kind takes (name, password, storage, near): a
1580
2113
  * flag and a form field each, all optional, `default` in words.
1581
2114
  */
1582
- options: z4.array(z4.object({ name: z4.string(), title: z4.string(), description: z4.string(), default: z4.string() })),
2115
+ options: z8.array(z8.object({ name: z8.string(), title: z8.string(), description: z8.string(), default: z8.string() })),
1583
2116
  /** A month of it running with the default storage, and each further GB of storage. */
1584
- price: PriceSchema.extend({ storageGibPerMonth: z4.number() }),
2117
+ price: PriceSchema.extend({ storageGibPerMonth: z8.number() }),
1585
2118
  /** Whether a host answering now can run it. */
1586
- available: z4.boolean()
2119
+ available: z8.boolean()
1587
2120
  });
1588
- var CreateManagedRequest = z4.object({
1589
- name: z4.string(),
2121
+ var CreateManagedRequest = z8.object({
2122
+ name: z8.string(),
1590
2123
  /** The kind's own options by name (its catalog entry lists them); the kind checks them. */
1591
- options: z4.record(z4.string(), z4.string()).optional(),
1592
- password: z4.string().optional(),
1593
- storageGib: z4.number().int().optional(),
2124
+ options: z8.record(z8.string(), z8.string()).optional(),
2125
+ password: z8.string().optional(),
2126
+ storageGib: z8.number().int().optional(),
1594
2127
  /** Place it on the host of this box, so the box can be linked to it. */
1595
- near: z4.string().optional()
2128
+ near: z8.string().optional()
1596
2129
  });
1597
- var ManagedHealthSchema = z4.object({
2130
+ var ManagedHealthSchema = z8.object({
1598
2131
  /** Its first start has finished: it has set itself up on its storage. */
1599
- ready: z4.boolean(),
2132
+ ready: z8.boolean(),
1600
2133
  /** It accepts connections. */
1601
- accepting: z4.boolean(),
1602
- version: z4.string(),
2134
+ accepting: z8.boolean(),
2135
+ version: z8.string(),
1603
2136
  /** The storage volume: what is used of it and its size. */
1604
- storageUsedBytes: z4.number().optional(),
1605
- storageTotalBytes: z4.number().optional(),
2137
+ storageUsedBytes: z8.number().optional(),
2138
+ storageTotalBytes: z8.number().optional(),
1606
2139
  /** What else the kind reports, ready to show: `{title: "Connections", value: "3"}`. */
1607
- facts: z4.array(z4.object({ title: z4.string(), value: z4.string() }))
2140
+ facts: z8.array(z8.object({ title: z8.string(), value: z8.string() }))
1608
2141
  });
1609
- var UrlsSchema = z4.object({ private: z4.string(), public: z4.string().optional() });
1610
- var ManagedSchema = z4.object({
1611
- kind: z4.string(),
1612
- name: z4.string(),
2142
+ var UrlsSchema = z8.object({ private: z8.string(), public: z8.string().optional() });
2143
+ var ManagedSchema = z8.object({
2144
+ kind: z8.string(),
2145
+ name: z8.string(),
1613
2146
  /** The owning slug, bare. */
1614
- owner: z4.string(),
1615
- ownerKind: z4.enum(["user", "org"]),
2147
+ owner: z8.string(),
2148
+ ownerKind: z8.enum(["user", "org"]),
1616
2149
  /** `running`, `stopped` (storage only is charged), `hibernated` or `standby` (out of credit), `unknown` (its host does not answer). */
1617
2150
  status: BoxStatusSchema,
1618
2151
  /** The catalog version: `18`. */
1619
- version: z4.string(),
2152
+ version: z8.string(),
1620
2153
  /** What the kind keeps of its create options, defaults filled in: `{database, user}` for Postgres, `{}` for a kind with none. */
1621
- settings: z4.record(z4.string(), z4.string()),
1622
- storageGib: z4.number().int(),
2154
+ settings: z8.record(z8.string(), z8.string()),
2155
+ storageGib: z8.number().int(),
1623
2156
  /** Where a linked box reaches it: `<name>.<slug>.kvbox` (resolves from a box of any slug it is linked to) and the port. */
1624
- private: z4.object({ host: z4.string(), port: z4.number().int() }),
2157
+ private: z8.object({ host: z8.string(), port: z8.number().int() }),
1625
2158
  /** Where the internet reaches it, null while it is not public. The port is its own for its whole life. */
1626
- public: z4.object({ host: z4.string(), port: z4.number().int() }).nullable(),
2159
+ public: z8.object({ host: z8.string(), port: z8.number().int() }).nullable(),
1627
2160
  /** The boxes linked to it, as the caller would name them. */
1628
- links: z4.array(z4.string()),
2161
+ links: z8.array(z8.string()),
1629
2162
  /** The name of the host it runs on, for `--near` and links. */
1630
- host: z4.string(),
1631
- country: z4.string().optional(),
1632
- createdBy: z4.string().nullable(),
1633
- createdAt: z4.string(),
2163
+ host: z8.string(),
2164
+ country: z8.string().optional(),
2165
+ createdBy: z8.string().nullable(),
2166
+ createdAt: z8.string(),
1634
2167
  /** Connection strings with the password as `****`. */
1635
2168
  urls: UrlsSchema,
1636
2169
  price: PriceSchema,
1637
2170
  /** Only in `GET /managed/<kind>/<name>` (asked live): null when it is not running or did not answer. */
1638
2171
  health: ManagedHealthSchema.nullable().optional()
1639
2172
  });
1640
- var ManagedSecretSchema = z4.object({ password: z4.string(), urls: UrlsSchema });
2173
+ var ManagedSecretSchema = z8.object({ password: z8.string(), urls: UrlsSchema });
1641
2174
  var CreatedManagedSchema = ManagedSchema.extend({ secret: ManagedSecretSchema });
1642
- var ResetPasswordRequest = z4.object({ password: z4.string().optional() });
1643
- var SetPublicRequest = z4.object({ on: z4.boolean() });
1644
- var ManagedLinkRequest = z4.object({ box: z4.string() });
1645
- var GrowManagedRequest = z4.object({ storageGib: z4.number().int() });
2175
+ var ResetPasswordRequest = z8.object({ password: z8.string().optional() });
2176
+ var SetPublicRequest = z8.object({ on: z8.boolean() });
2177
+ var ManagedLinkRequest = z8.object({ box: z8.string() });
2178
+ var GrowManagedRequest = z8.object({ storageGib: z8.number().int() });
1646
2179
 
1647
2180
  // ../shared/src/cron.ts
1648
- import { z as z5 } from "zod";
2181
+ import { z as z9 } from "zod";
1649
2182
  var DEFAULT_CRON_COMMAND_TIMEOUT_SEC = 600;
1650
2183
  var MAX_CRON_COMMAND_TIMEOUT_SEC = 3600;
1651
2184
  var CRON_RUN_LOG_DIR = "/var/log/kvbox/runs";
1652
2185
  var CRON_METHODS = ["GET", "POST"];
1653
2186
  var CRON_OUTCOMES = ["running", "ok", "failed", "timeout", "no-credit", "box-stopped", "host-down", "host-outdated", "lost", "still-running", "box-outdated"];
1654
- var CronServiceSchema = z5.object({
1655
- owner: z5.string(),
1656
- ownerKind: z5.enum(["user", "org"]),
1657
- name: z5.string(),
2187
+ var CronServiceSchema = z9.object({
2188
+ owner: z9.string(),
2189
+ ownerKind: z9.enum(["user", "org"]),
2190
+ name: z9.string(),
1658
2191
  /** Runs kept per trigger. */
1659
- keepRuns: z5.number().int(),
1660
- triggers: z5.number().int(),
1661
- createdBy: z5.string().nullable(),
1662
- createdAt: z5.string(),
2192
+ keepRuns: z9.number().int(),
2193
+ triggers: z9.number().int(),
2194
+ createdBy: z9.string().nullable(),
2195
+ createdAt: z9.string(),
1663
2196
  /** What it costs while it exists; on the answer to `POST /cron` only. */
1664
- price: z5.object({ perMonth: z5.number(), currency: z5.string() }).optional()
2197
+ price: z9.object({ perMonth: z9.number(), currency: z9.string() }).optional()
1665
2198
  });
1666
2199
  var triggerCommon = {
1667
- id: z5.string(),
1668
- service: z5.string(),
1669
- owner: z5.string(),
2200
+ id: z9.string(),
2201
+ service: z9.string(),
2202
+ owner: z9.string(),
1670
2203
  /** The box it acts on; a trigger is removed with its box. */
1671
- box: z5.string(),
2204
+ box: z9.string(),
1672
2205
  /** Five fields, `minute hour day-of-month month day-of-week`. */
1673
- expr: z5.string(),
2206
+ expr: z9.string(),
1674
2207
  /** An IANA zone (`Europe/Bucharest`) the expression is read in; `UTC` unless said. */
1675
- timezone: z5.string(),
2208
+ timezone: z9.string(),
1676
2209
  /** False: paused, it fires again when resumed. */
1677
- enabled: z5.boolean(),
2210
+ enabled: z9.boolean(),
1678
2211
  /** When it fires next (ISO); null while paused. */
1679
- nextRunAt: z5.string().nullable(),
1680
- lastRunAt: z5.string().nullable(),
1681
- lastOutcome: z5.enum(CRON_OUTCOMES).nullable(),
1682
- createdBy: z5.string().nullable(),
1683
- createdAt: z5.string()
2212
+ nextRunAt: z9.string().nullable(),
2213
+ lastRunAt: z9.string().nullable(),
2214
+ lastOutcome: z9.enum(CRON_OUTCOMES).nullable(),
2215
+ createdBy: z9.string().nullable(),
2216
+ createdAt: z9.string()
1684
2217
  };
1685
- var CronHttpTriggerSchema = z5.object({
2218
+ var CronHttpTriggerSchema = z9.object({
1686
2219
  ...triggerCommon,
1687
- kind: z5.literal("http"),
1688
- method: z5.enum(CRON_METHODS),
1689
- port: z5.number().int(),
2220
+ kind: z9.literal("http"),
2221
+ method: z9.enum(CRON_METHODS),
2222
+ port: z9.number().int(),
1690
2223
  /** Path and query, starting with `/`. */
1691
- path: z5.string()
2224
+ path: z9.string()
1692
2225
  });
1693
- var CronCommandTriggerSchema = z5.object({
2226
+ var CronCommandTriggerSchema = z9.object({
1694
2227
  ...triggerCommon,
1695
- kind: z5.literal("command"),
2228
+ kind: z9.literal("command"),
1696
2229
  /** Run by a login shell as the box's user, in its home. */
1697
- command: z5.string(),
2230
+ command: z9.string(),
1698
2231
  /** The command is stopped after this long. */
1699
- timeoutSec: z5.number().int()
2232
+ timeoutSec: z9.number().int()
1700
2233
  });
1701
- var CronTriggerSchema = z5.discriminatedUnion("kind", [CronHttpTriggerSchema, CronCommandTriggerSchema]);
1702
- var CronRunSchema = z5.object({
2234
+ var CronTriggerSchema = z9.discriminatedUnion("kind", [CronHttpTriggerSchema, CronCommandTriggerSchema]);
2235
+ var CronRunSchema = z9.object({
1703
2236
  /** The slot this run was for (ISO); a run asked for by hand has the moment it was asked. */
1704
- scheduledFor: z5.string(),
1705
- startedAt: z5.string(),
2237
+ scheduledFor: z9.string(),
2238
+ startedAt: z9.string(),
1706
2239
  /** Null while `running`, and for a run that was never sent. */
1707
- durationMs: z5.number().int().nullable(),
2240
+ durationMs: z9.number().int().nullable(),
1708
2241
  /** The box's HTTP status; null when it never answered, and for a command. */
1709
- status: z5.number().int().nullable(),
2242
+ status: z9.number().int().nullable(),
1710
2243
  /** A command's exit code (128 + the signal when one ended it); null until it ends, and for a request. */
1711
- exitCode: z5.number().int().nullable(),
1712
- /** The file in the box that holds what a command printed; null for a request and for a command that never started. */
1713
- output: z5.string().nullable(),
1714
- outcome: z5.enum(CRON_OUTCOMES),
2244
+ exitCode: z9.number().int().nullable(),
2245
+ /** The files in the box that hold what a command printed (a shell pattern, `cron-<n>.*`); null for a request and for a command that never started. */
2246
+ output: z9.string().nullable(),
2247
+ outcome: z9.enum(CRON_OUTCOMES),
1715
2248
  /** Why it did not end `ok`, in a line. */
1716
- error: z5.string().nullable(),
2249
+ error: z9.string().nullable(),
1717
2250
  /** The box was hibernated and this run woke it. */
1718
- woke: z5.boolean()
2251
+ woke: z9.boolean()
1719
2252
  });
1720
- var CronCatalogSchema = z5.object({
1721
- price: z5.object({ perMonth: z5.number(), currency: z5.string() }),
1722
- maxServices: z5.number().int(),
1723
- maxTriggers: z5.number().int(),
1724
- keepRuns: z5.number().int(),
2253
+ var CronCatalogSchema = z9.object({
2254
+ price: z9.object({ perMonth: z9.number(), currency: z9.string() }),
2255
+ maxServices: z9.number().int(),
2256
+ maxTriggers: z9.number().int(),
2257
+ keepRuns: z9.number().int(),
1725
2258
  /** The shortest time between two runs of one trigger, in seconds. */
1726
- minIntervalSeconds: z5.number().int(),
2259
+ minIntervalSeconds: z9.number().int(),
1727
2260
  /** How long a box has to answer, in seconds. */
1728
- timeoutSeconds: z5.number().int(),
2261
+ timeoutSeconds: z9.number().int(),
1729
2262
  /** How long a command may run: unless the trigger says, and at most. */
1730
- commandTimeoutSeconds: z5.number().int(),
1731
- maxCommandTimeoutSeconds: z5.number().int(),
1732
- docs: z5.string().optional()
1733
- });
1734
- var CreateCronServiceRequest = z5.object({ name: z5.string() });
1735
- var CreateCronTriggerRequest = z5.object({
1736
- box: z5.string().min(1),
1737
- expr: z5.string().min(1),
1738
- timezone: z5.string().optional(),
2263
+ commandTimeoutSeconds: z9.number().int(),
2264
+ maxCommandTimeoutSeconds: z9.number().int(),
2265
+ docs: z9.string().optional()
2266
+ });
2267
+ var CreateCronServiceRequest = z9.object({ name: z9.string() });
2268
+ var CreateCronTriggerRequest = z9.object({
2269
+ box: z9.string().min(1),
2270
+ expr: z9.string().min(1),
2271
+ timezone: z9.string().optional(),
1739
2272
  /** A request: `port`, with `method` and `path`. */
1740
- method: z5.enum(CRON_METHODS).optional(),
1741
- port: z5.number().int().min(1).max(65535).optional(),
1742
- path: z5.string().optional(),
2273
+ method: z9.enum(CRON_METHODS).optional(),
2274
+ port: z9.number().int().min(1).max(65535).optional(),
2275
+ path: z9.string().optional(),
1743
2276
  /** Or a command, with `timeoutSec`; exactly one of `port` and `command`. */
1744
- command: z5.string().optional(),
1745
- timeoutSec: z5.number().int().optional()
2277
+ command: z9.string().optional(),
2278
+ timeoutSec: z9.number().int().optional()
1746
2279
  });
1747
- var UpdateCronTriggerRequest = z5.object({ enabled: z5.boolean() });
2280
+ var UpdateCronTriggerRequest = z9.object({ enabled: z9.boolean() });
1748
2281
  var cronTarget = (t) => t.kind === "command" ? `${t.box}$ ${t.command}` : `${t.method} ${t.box}:${t.port}${t.path}`;
1749
2282
 
1750
2283
  // ../shared/src/storage.ts
1751
- import { z as z6 } from "zod";
1752
- var RegionSchema = z6.object({ name: z6.string(), country: z6.string().nullable() });
1753
- var ObjectStorageSchema = z6.object({
1754
- owner: z6.string(),
1755
- ownerKind: z6.enum(["user", "org"]),
2284
+ import { z as z10 } from "zod";
2285
+ var RegionSchema = z10.object({ name: z10.string(), country: z10.string().nullable() });
2286
+ var ObjectStorageSchema = z10.object({
2287
+ owner: z10.string(),
2288
+ ownerKind: z10.enum(["user", "org"]),
1756
2289
  /** `https://s3-<slug>.<domain>`: what an S3 client is given, with path-style addressing. Null while the address is not claimed. */
1757
- endpoint: z6.string().nullable(),
2290
+ endpoint: z10.string().nullable(),
1758
2291
  /** The S3 region every client of it signs with (`ro-west-1`): its host's when it was made. */
1759
- region: z6.string(),
2292
+ region: z10.string(),
1760
2293
  /** The most it may hold. */
1761
- sizeGib: z6.number().int(),
2294
+ sizeGib: z10.number().int(),
1762
2295
  /** `running` when it answers; `unknown` while its host is not heard from. */
1763
2296
  status: BoxStatusSchema,
1764
2297
  /** With `?live=1`, when the storage answered: what is on its disk, and the disk's real size. */
1765
- usedBytes: z6.number().optional(),
1766
- totalBytes: z6.number().optional(),
1767
- host: z6.string(),
1768
- country: z6.string().optional(),
1769
- buckets: z6.number().int(),
1770
- price: z6.object({ perMonth: z6.number(), currency: z6.string() }),
1771
- createdAt: z6.string()
1772
- });
1773
- var BucketSchema = z6.object({
1774
- name: z6.string(),
1775
- owner: z6.string(),
1776
- ownerKind: z6.enum(["user", "org"]),
1777
- endpoint: z6.string().nullable(),
1778
- region: z6.string(),
1779
- keys: z6.number().int(),
1780
- objects: z6.number().optional(),
1781
- bytes: z6.number().optional(),
1782
- createdBy: z6.string().nullable(),
1783
- createdAt: z6.string()
1784
- });
1785
- var CreateBucketRequest = z6.object({
1786
- name: z6.string(),
1787
- sizeGib: z6.number().int().optional(),
1788
- near: z6.string().optional(),
1789
- region: z6.string().optional()
1790
- });
1791
- var CreatedBucketSchema = BucketSchema.extend({ storage: ObjectStorageSchema, storageCreated: z6.boolean() });
2298
+ usedBytes: z10.number().optional(),
2299
+ totalBytes: z10.number().optional(),
2300
+ host: z10.string(),
2301
+ country: z10.string().optional(),
2302
+ buckets: z10.number().int(),
2303
+ price: z10.object({ perMonth: z10.number(), currency: z10.string() }),
2304
+ createdAt: z10.string()
2305
+ });
2306
+ var BucketSchema = z10.object({
2307
+ name: z10.string(),
2308
+ owner: z10.string(),
2309
+ ownerKind: z10.enum(["user", "org"]),
2310
+ endpoint: z10.string().nullable(),
2311
+ region: z10.string(),
2312
+ keys: z10.number().int(),
2313
+ objects: z10.number().optional(),
2314
+ bytes: z10.number().optional(),
2315
+ createdBy: z10.string().nullable(),
2316
+ createdAt: z10.string()
2317
+ });
2318
+ var CreateBucketRequest = z10.object({
2319
+ name: z10.string(),
2320
+ sizeGib: z10.number().int().optional(),
2321
+ near: z10.string().optional(),
2322
+ region: z10.string().optional()
2323
+ });
2324
+ var CreatedBucketSchema = BucketSchema.extend({ storage: ObjectStorageSchema, storageCreated: z10.boolean() });
1792
2325
  var BucketInfoSchema = BucketSchema.extend({ storage: ObjectStorageSchema });
1793
- var BucketKeySchema = z6.object({
1794
- id: z6.string(),
1795
- name: z6.string(),
1796
- bucket: z6.string(),
1797
- owner: z6.string(),
1798
- readOnly: z6.boolean(),
1799
- createdBy: z6.string().nullable(),
1800
- createdAt: z6.string()
1801
- });
1802
- var CreateBucketKeyRequest = z6.object({ name: z6.string().optional(), readOnly: z6.boolean().optional() });
1803
- var CreatedBucketKeySchema = BucketKeySchema.extend({ secret: z6.string(), endpoint: z6.string().nullable(), region: z6.string() });
1804
- var GrowStorageRequest = z6.object({ sizeGib: z6.number().int() });
2326
+ var BucketKeySchema = z10.object({
2327
+ id: z10.string(),
2328
+ name: z10.string(),
2329
+ bucket: z10.string(),
2330
+ owner: z10.string(),
2331
+ readOnly: z10.boolean(),
2332
+ createdBy: z10.string().nullable(),
2333
+ createdAt: z10.string()
2334
+ });
2335
+ var CreateBucketKeyRequest = z10.object({ name: z10.string().optional(), readOnly: z10.boolean().optional() });
2336
+ var CreatedBucketKeySchema = BucketKeySchema.extend({ secret: z10.string(), endpoint: z10.string().nullable(), region: z10.string() });
2337
+ var GrowStorageRequest = z10.object({ sizeGib: z10.number().int() });
1805
2338
 
1806
2339
  // src/kvm.ts
1807
2340
  import { accessSync, constants, readFileSync, statSync } from "fs";
@@ -1877,11 +2410,11 @@ function orgOption(opts) {
1877
2410
  async function resolveTarget(opts, p = paths()) {
1878
2411
  if (!opts.local) {
1879
2412
  const org = orgOption(opts);
1880
- const fromEnv = envLogin();
1881
- if (fromEnv) {
1882
- const asking = new ServerClient({ kind: "cloud", ...fromEnv, env: true }, { autoStart: false });
2413
+ const fromEnv2 = envLogin();
2414
+ if (fromEnv2) {
2415
+ const asking = new ServerClient({ kind: "cloud", ...fromEnv2, env: true }, { autoStart: false });
1883
2416
  const user = await asking.me().finally(() => asking.close());
1884
- return { kind: "cloud", ...fromEnv, env: true, user: user.username, ...org === void 0 ? {} : { org } };
2417
+ return { kind: "cloud", ...fromEnv2, env: true, user: user.username, ...org === void 0 ? {} : { org } };
1885
2418
  }
1886
2419
  const session = await readSession(p);
1887
2420
  if (session) return { kind: "cloud", url: session.url, token: session.token, user: session.user, ...org === void 0 ? {} : { org } };
@@ -1893,35 +2426,42 @@ var ServerClient = class {
1893
2426
  constructor(target, opts = {}) {
1894
2427
  this.target = target;
1895
2428
  this.autoStart = opts.autoStart ?? true;
1896
- if (target.kind === "local") {
1897
- this.dispatcher = new Agent({ connect: { socketPath: target.socketPath } });
1898
- this.base = "http://kvbox";
1899
- } else {
1900
- this.dispatcher = new Agent();
1901
- this.base = target.url;
1902
- }
2429
+ const limits = { headersTimeout: 0, bodyTimeout: 0 };
2430
+ this.dispatcher = target.kind === "local" ? new Agent({ ...limits, connect: { socketPath: target.socketPath } }) : new Agent(limits);
2431
+ const dispatcher = this.dispatcher;
2432
+ const fetch2 = async (url, init) => {
2433
+ const res = await request(url, { dispatcher, method: init.method, headers: init.headers, body: init.body ?? null, signal: init.signal ?? null });
2434
+ return { status: res.statusCode, text: () => res.body.text() };
2435
+ };
2436
+ this.sdk = new Kvbox({
2437
+ baseUrl: target.kind === "local" ? "http://kvbox" : target.url,
2438
+ // never the environment's: the target already says which key, if any (`--local` has none)
2439
+ apiKey: target.kind === "cloud" ? target.token : "",
2440
+ fetch: fetch2
2441
+ });
1903
2442
  }
1904
2443
  target;
1905
2444
  dispatcher;
1906
- base;
2445
+ /** The SDK, which sends every request (one copy of the HTTP code); this class keeps the CLI's wording. */
2446
+ sdk;
1907
2447
  autoStart;
1908
2448
  startedOnce = false;
1909
2449
  async call(method, path, schema, body, org = this.target.kind === "cloud" ? this.target.org : void 0, timeoutMs) {
1910
- const headers = {};
1911
- if (body !== void 0) headers["content-type"] = "application/json";
1912
- if (this.target.kind === "cloud" && this.target.token !== "") headers["authorization"] = `Bearer ${this.target.token}`;
1913
- if (this.target.kind === "cloud" && org !== void 0) headers["x-kvbox-org"] = org;
1914
- let res;
1915
2450
  try {
1916
- res = await request(this.base + path, {
1917
- dispatcher: this.dispatcher,
1918
- method,
1919
- headers,
1920
- body: body === void 0 ? null : JSON.stringify(body),
1921
- ...timeoutMs !== void 0 ? { headersTimeout: timeoutMs, bodyTimeout: timeoutMs } : {}
1922
- });
2451
+ return await this.sdk.request(method, path, schema, { body, org: this.target.kind === "cloud" ? org : void 0, timeoutMs });
1923
2452
  } catch (err) {
1924
- const code = err.code ?? err.cause;
2453
+ return this.failed(err, () => this.call(method, path, schema, body, org, timeoutMs));
2454
+ }
2455
+ }
2456
+ /** The SDK's error in the CLI's words; nothing listening locally starts the daemon once and `retry`s (architecture: "auto-start"). */
2457
+ async failed(err, retry) {
2458
+ const where = this.target.kind === "cloud" ? hostOf(this.target.url) : "kvbox-server";
2459
+ if (err instanceof KvboxTimeoutError) {
2460
+ if (this.target.kind === "local") throw new KvboxError(`kvbox-server did not answer within ${Math.round(err.timeoutMs / 1e3)}s`);
2461
+ throw new CallError(cloudDown(this.target.url, "timeout"), 0);
2462
+ }
2463
+ if (err instanceof KvboxConnectionError) {
2464
+ const code = err.code ?? (err.cause instanceof Error ? err.cause.message : err.message);
1925
2465
  if (this.target.kind === "local") {
1926
2466
  if (this.autoStart && !this.startedOnce) {
1927
2467
  this.startedOnce = true;
@@ -1929,31 +2469,29 @@ var ServerClient = class {
1929
2469
  await spin("starting kvbox-server\u2026", startLocalServer(paths(), 5e3)).catch((err2) => {
1930
2470
  throw noLogin && err2 instanceof KvboxError && err2.message === NOT_A_HOST_HINT ? new KvboxError(NOT_LOGGED_IN) : err2;
1931
2471
  });
1932
- return this.call(method, path, schema, body, org, timeoutMs);
2472
+ return retry();
1933
2473
  }
1934
- throw new KvboxError(`kvbox-server is not running (${String(code)}); start it with: kvbox-server start -d`);
2474
+ throw new KvboxError(`kvbox-server is not running (${code}); start it with: kvbox-server start -d`);
1935
2475
  }
1936
- throw new CallError(cloudDown(this.target.url, String(code)), 0);
2476
+ throw new CallError(cloudDown(this.target.url, code), 0);
1937
2477
  }
1938
- const text2 = await res.body.text();
1939
- const where = this.target.kind === "cloud" ? hostOf(this.target.url) : "kvbox-server";
1940
- if (res.statusCode >= 300) {
1941
- const parsed = ApiErrorSchema.safeParse(safeJson(text2) ?? {});
1942
- if (!parsed.success) throw new CallError(`${where} answered ${res.statusCode}`, res.statusCode);
2478
+ if (err instanceof KvboxApiError) {
2479
+ if (!err.apiError) throw new CallError(`${where} answered ${err.status}`, err.status);
1943
2480
  if (this.target.kind === "cloud" && this.target.token !== "") {
1944
- if (res.statusCode === 401) {
2481
+ if (err.status === 401) {
1945
2482
  throw new KvboxError(this.target.env ? `${where} refused the API key in KVBOX_TOKEN: it was removed or has expired` : "session expired: kvbox login");
1946
2483
  }
1947
- if (res.statusCode === 404 && this.target.org !== void 0 && parsed.data.error === `org ${this.target.org}: not found`) {
1948
- throw new KvboxError(`${parsed.data.error} (you are not in it, or it is gone)`);
2484
+ if (err.status === 404 && this.target.org !== void 0 && err.message === `org ${this.target.org}: not found`) {
2485
+ throw new KvboxError(`${err.message} (you are not in it, or it is gone)`);
1949
2486
  }
1950
2487
  }
1951
- throw new CallError(parsed.data.error, res.statusCode, res.statusCode === 501 ? 2 : 1);
2488
+ throw new CallError(err.message, err.status, err.status === 501 ? 2 : 1);
1952
2489
  }
1953
- if (text2 === "") return schema.parse(void 0);
1954
- const json2 = safeJson(text2);
1955
- if (json2 === void 0) throw new KvboxError(`${where} answered ${res.statusCode} with something that is not JSON`);
1956
- return schema.parse(json2);
2490
+ if (err instanceof KvboxResponseError) {
2491
+ if (err.reason === "schema") throw err.cause;
2492
+ throw new KvboxError(err.reason === "cut-off" ? `${where} answered ${err.status} but the answer was cut off` : `${where} answered ${err.status} with something that is not JSON`);
2493
+ }
2494
+ throw err;
1957
2495
  }
1958
2496
  health() {
1959
2497
  return this.call("GET", "/health", HealthSchema);
@@ -1966,7 +2504,7 @@ var ServerClient = class {
1966
2504
  * `all`: every box on the platform (platform admins only, #78).
1967
2505
  */
1968
2506
  listMachines(opts = {}) {
1969
- return this.call("GET", `/machines${allQuery(opts)}`, z7.array(MachineSchema), void 0, opts.org);
2507
+ return this.call("GET", `/machines${allQuery(opts)}`, z11.array(MachineSchema), void 0, opts.org);
1970
2508
  }
1971
2509
  createMachine(req) {
1972
2510
  return this.call("POST", "/machines", MachineSchema, req);
@@ -2020,10 +2558,10 @@ var ServerClient = class {
2020
2558
  }
2021
2559
  /** Backups, the control plane's only: a box's disk in object storage. Newest first. */
2022
2560
  listBackups() {
2023
- return this.call("GET", "/backups", z7.array(BackupSchema));
2561
+ return this.call("GET", "/backups", z11.array(BackupSchema));
2024
2562
  }
2025
2563
  boxBackups(name) {
2026
- return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`, z7.array(BackupSchema));
2564
+ return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`, z11.array(BackupSchema));
2027
2565
  }
2028
2566
  boxBackup(name, id) {
2029
2567
  return this.call("GET", `/machines/${encodeURIComponent(name)}/backups/${encodeURIComponent(id)}`, BackupSchema);
@@ -2034,10 +2572,10 @@ var ServerClient = class {
2034
2572
  }
2035
2573
  /** A volume's backups (#168): the same as a box's, of the volume's disk. Newest first. */
2036
2574
  listVolumeBackups() {
2037
- return this.call("GET", "/backups?kind=volume", z7.array(VolumeBackupSchema));
2575
+ return this.call("GET", "/backups?kind=volume", z11.array(VolumeBackupSchema));
2038
2576
  }
2039
2577
  volumeBackups(name) {
2040
- return this.call("GET", `/volumes/${encodeURIComponent(name)}/backups`, z7.array(VolumeBackupSchema));
2578
+ return this.call("GET", `/volumes/${encodeURIComponent(name)}/backups`, z11.array(VolumeBackupSchema));
2041
2579
  }
2042
2580
  volumeBackup(name, id) {
2043
2581
  return this.call("GET", `/volumes/${encodeURIComponent(name)}/backups/${encodeURIComponent(id)}`, VolumeBackupSchema);
@@ -2056,7 +2594,7 @@ var ServerClient = class {
2056
2594
  }
2057
2595
  /** Wake hooks (#101), the control plane's only: a URL and a secret that wake the box. */
2058
2596
  boxHooks(name) {
2059
- return this.call("GET", `/machines/${encodeURIComponent(name)}/hooks`, z7.array(WakeHookSchema));
2597
+ return this.call("GET", `/machines/${encodeURIComponent(name)}/hooks`, z11.array(WakeHookSchema));
2060
2598
  }
2061
2599
  createBoxHook(name) {
2062
2600
  return this.call("POST", `/machines/${encodeURIComponent(name)}/hooks`, CreatedWakeHookSchema);
@@ -2084,7 +2622,7 @@ var ServerClient = class {
2084
2622
  }
2085
2623
  /** Every readable box's subdomains, one entry each. */
2086
2624
  listSubdomains() {
2087
- return this.call("GET", "/subdomains", z7.array(SubdomainSchema));
2625
+ return this.call("GET", "/subdomains", z11.array(SubdomainSchema));
2088
2626
  }
2089
2627
  /** Custom domains (#89), the control plane's only: serve the box at the user's own name. */
2090
2628
  addDomain(name, req) {
@@ -2095,7 +2633,7 @@ var ServerClient = class {
2095
2633
  }
2096
2634
  /** Every readable box's custom domains. */
2097
2635
  listDomains() {
2098
- return this.call("GET", "/domains", z7.array(DomainSchema));
2636
+ return this.call("GET", "/domains", z11.array(DomainSchema));
2099
2637
  }
2100
2638
  /** A running box's own load, memory and disk, asked of its guest (#67). */
2101
2639
  machineStats(name) {
@@ -2124,22 +2662,22 @@ var ServerClient = class {
2124
2662
  return this.call("POST", "/billing/redeem", RedeemResponseSchema, { code });
2125
2663
  }
2126
2664
  deleteMachine(name) {
2127
- return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z7.undefined());
2665
+ return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z11.undefined());
2128
2666
  }
2129
2667
  /** Like `listMachines`, for snapshots. */
2130
2668
  listSnapshots(opts = {}) {
2131
- return this.call("GET", `/snapshots${allQuery(opts)}`, z7.array(SnapshotSchema), void 0, opts.org);
2669
+ return this.call("GET", `/snapshots${allQuery(opts)}`, z11.array(SnapshotSchema), void 0, opts.org);
2132
2670
  }
2133
2671
  createSnapshot(req) {
2134
2672
  return this.call("POST", "/snapshots", SnapshotSchema, req);
2135
2673
  }
2136
2674
  deleteSnapshot(name) {
2137
- return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`, z7.undefined());
2675
+ return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`, z11.undefined());
2138
2676
  }
2139
2677
  // ---- environment variables (#88), a control plane only: the caller's slug, or `--org`'s ----
2140
2678
  /** `org`: that org's list instead of `--org`'s (or the caller's own). */
2141
2679
  listEnv(org) {
2142
- return this.call("GET", "/vars", z7.array(EnvVarSchema), void 0, org);
2680
+ return this.call("GET", "/vars", z11.array(EnvVarSchema), void 0, org);
2143
2681
  }
2144
2682
  setEnv(name, req) {
2145
2683
  return this.call("PUT", `/vars/${encodeURIComponent(name)}`, EnvChangeSchema, req);
@@ -2159,13 +2697,13 @@ var ServerClient = class {
2159
2697
  }
2160
2698
  // ---- volumes (#52) ----
2161
2699
  listVolumes(opts = {}) {
2162
- return this.call("GET", `/volumes${allQuery(opts)}`, z7.array(VolumeSchema), void 0, opts.org);
2700
+ return this.call("GET", `/volumes${allQuery(opts)}`, z11.array(VolumeSchema), void 0, opts.org);
2163
2701
  }
2164
2702
  createVolume(req) {
2165
2703
  return this.call("POST", "/volumes", VolumeSchema, req);
2166
2704
  }
2167
2705
  deleteVolume(name) {
2168
- return this.call("DELETE", `/volumes/${encodeURIComponent(name)}`, z7.undefined());
2706
+ return this.call("DELETE", `/volumes/${encodeURIComponent(name)}`, z11.undefined());
2169
2707
  }
2170
2708
  /** Both answer with the box as it is afterwards (restarted when it was running). */
2171
2709
  attachVolume(name, req) {
@@ -2180,7 +2718,7 @@ var ServerClient = class {
2180
2718
  }
2181
2719
  // ---- cron service (#190): the control plane's alone ----
2182
2720
  listCronServices(opts = {}) {
2183
- return this.call("GET", `/cron${allQuery(opts)}`, z7.array(CronServiceSchema), void 0, opts.org);
2721
+ return this.call("GET", `/cron${allQuery(opts)}`, z11.array(CronServiceSchema), void 0, opts.org);
2184
2722
  }
2185
2723
  createCronService(name) {
2186
2724
  return this.call("POST", "/cron", CronServiceSchema, { name });
@@ -2189,10 +2727,10 @@ var ServerClient = class {
2189
2727
  return this.call("GET", `/cron/${encodeURIComponent(name)}`, CronServiceSchema);
2190
2728
  }
2191
2729
  deleteCronService(name) {
2192
- return this.call("DELETE", `/cron/${encodeURIComponent(name)}`, z7.undefined());
2730
+ return this.call("DELETE", `/cron/${encodeURIComponent(name)}`, z11.undefined());
2193
2731
  }
2194
2732
  listCronTriggers(service) {
2195
- return this.call("GET", `/cron/${encodeURIComponent(service)}/triggers`, z7.array(CronTriggerSchema));
2733
+ return this.call("GET", `/cron/${encodeURIComponent(service)}/triggers`, z11.array(CronTriggerSchema));
2196
2734
  }
2197
2735
  addCronTrigger(service, req) {
2198
2736
  return this.call("POST", `/cron/${encodeURIComponent(service)}/triggers`, CronTriggerSchema, req);
@@ -2202,18 +2740,18 @@ var ServerClient = class {
2202
2740
  return this.call("PATCH", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}`, CronTriggerSchema, { enabled: enabled2 });
2203
2741
  }
2204
2742
  deleteCronTrigger(service, id) {
2205
- return this.call("DELETE", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}`, z7.undefined());
2743
+ return this.call("DELETE", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}`, z11.undefined());
2206
2744
  }
2207
2745
  /** Marks it due: kvbox-cron fires it within a few seconds. */
2208
2746
  runCronTrigger(service, id) {
2209
2747
  return this.call("POST", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}/run`, CronTriggerSchema);
2210
2748
  }
2211
2749
  listCronRuns(service, id, limit) {
2212
- return this.call("GET", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}/runs${limit === void 0 ? "" : `?limit=${limit}`}`, z7.array(CronRunSchema));
2750
+ return this.call("GET", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}/runs${limit === void 0 ? "" : `?limit=${limit}`}`, z11.array(CronRunSchema));
2213
2751
  }
2214
2752
  // ---- object storage (#182): the control plane's alone ----
2215
2753
  listBuckets(opts = {}) {
2216
- return this.call("GET", `/buckets${allQuery(opts)}`, z7.array(BucketSchema), void 0, opts.org);
2754
+ return this.call("GET", `/buckets${allQuery(opts)}`, z11.array(BucketSchema), void 0, opts.org);
2217
2755
  }
2218
2756
  /** The first bucket of a slug also makes its storage: a box boots twice, so this may take a couple of minutes. */
2219
2757
  createBucket(req) {
@@ -2223,19 +2761,19 @@ var ServerClient = class {
2223
2761
  return this.call("GET", `/buckets/${encodeURIComponent(name)}`, BucketInfoSchema);
2224
2762
  }
2225
2763
  deleteBucket(name, force = false) {
2226
- return this.call("DELETE", `/buckets/${encodeURIComponent(name)}${force ? "?force=1" : ""}`, z7.undefined());
2764
+ return this.call("DELETE", `/buckets/${encodeURIComponent(name)}${force ? "?force=1" : ""}`, z11.undefined());
2227
2765
  }
2228
2766
  listBucketKeys(name) {
2229
- return this.call("GET", `/buckets/${encodeURIComponent(name)}/keys`, z7.array(BucketKeySchema));
2767
+ return this.call("GET", `/buckets/${encodeURIComponent(name)}/keys`, z11.array(BucketKeySchema));
2230
2768
  }
2231
2769
  createBucketKey(name, req) {
2232
2770
  return this.call("POST", `/buckets/${encodeURIComponent(name)}/keys`, CreatedBucketKeySchema, req);
2233
2771
  }
2234
2772
  deleteBucketKey(name, id) {
2235
- return this.call("DELETE", `/buckets/${encodeURIComponent(name)}/keys/${encodeURIComponent(id)}`, z7.undefined());
2773
+ return this.call("DELETE", `/buckets/${encodeURIComponent(name)}/keys/${encodeURIComponent(id)}`, z11.undefined());
2236
2774
  }
2237
2775
  listStorage(opts = {}) {
2238
- return this.call("GET", `/storage${allQuery(opts)}`, z7.array(ObjectStorageSchema), void 0, opts.org);
2776
+ return this.call("GET", `/storage${allQuery(opts)}`, z11.array(ObjectStorageSchema), void 0, opts.org);
2239
2777
  }
2240
2778
  growStorage(sizeGib) {
2241
2779
  return this.call("POST", "/storage/grow", ObjectStorageSchema, { sizeGib });
@@ -2245,11 +2783,11 @@ var ServerClient = class {
2245
2783
  return `/managed/${encodeURIComponent(kind)}${name === void 0 ? "" : `/${encodeURIComponent(name)}`}${rest}`;
2246
2784
  }
2247
2785
  managedCatalog() {
2248
- return this.call("GET", "/managed/catalog", z7.array(ManagedCatalogEntrySchema));
2786
+ return this.call("GET", "/managed/catalog", z11.array(ManagedCatalogEntrySchema));
2249
2787
  }
2250
2788
  /** One kind's services, or every kind's when `kind` is left out. */
2251
2789
  listManaged(kind, opts = {}) {
2252
- return this.call("GET", `${kind === void 0 ? "/managed" : this.managedPath(kind)}${allQuery(opts)}`, z7.array(ManagedSchema), void 0, opts.org);
2790
+ return this.call("GET", `${kind === void 0 ? "/managed" : this.managedPath(kind)}${allQuery(opts)}`, z11.array(ManagedSchema), void 0, opts.org);
2253
2791
  }
2254
2792
  createManaged(kind, req) {
2255
2793
  return this.call("POST", this.managedPath(kind), CreatedManagedSchema, req);
@@ -2259,7 +2797,7 @@ var ServerClient = class {
2259
2797
  return this.call("GET", this.managedPath(kind, name), ManagedSchema);
2260
2798
  }
2261
2799
  deleteManaged(kind, name) {
2262
- return this.call("DELETE", this.managedPath(kind, name), z7.undefined());
2800
+ return this.call("DELETE", this.managedPath(kind, name), z11.undefined());
2263
2801
  }
2264
2802
  managedPassword(kind, name) {
2265
2803
  return this.call("GET", this.managedPath(kind, name, "/password"), ManagedSecretSchema);
@@ -2270,11 +2808,11 @@ var ServerClient = class {
2270
2808
  setManagedPublic(kind, name, on) {
2271
2809
  return this.call("POST", this.managedPath(kind, name, "/public"), ManagedSchema, { on });
2272
2810
  }
2273
- linkManaged(kind, name, box) {
2274
- return this.call("POST", this.managedPath(kind, name, "/links"), ManagedSchema, { box });
2811
+ linkManaged(kind, name, box2) {
2812
+ return this.call("POST", this.managedPath(kind, name, "/links"), ManagedSchema, { box: box2 });
2275
2813
  }
2276
- unlinkManaged(kind, name, box) {
2277
- return this.call("DELETE", this.managedPath(kind, name, "/links"), ManagedSchema, { box });
2814
+ unlinkManaged(kind, name, box2) {
2815
+ return this.call("DELETE", this.managedPath(kind, name, "/links"), ManagedSchema, { box: box2 });
2278
2816
  }
2279
2817
  growManaged(kind, name, storageGib) {
2280
2818
  return this.call("POST", this.managedPath(kind, name, "/grow"), ManagedSchema, { storageGib });
@@ -2297,24 +2835,24 @@ var ServerClient = class {
2297
2835
  return this.call("POST", "/login/device/token", DeviceLoginPollSchema, { deviceCode });
2298
2836
  }
2299
2837
  logout() {
2300
- return this.call("POST", "/logout", z7.unknown()).then(() => void 0);
2838
+ return this.call("POST", "/logout", z11.unknown()).then(() => void 0);
2301
2839
  }
2302
2840
  me() {
2303
2841
  return this.call("GET", "/me", MeResponseSchema);
2304
2842
  }
2305
2843
  // ---- API keys (`kvbox key …`, #189) ----
2306
2844
  listApiKeys() {
2307
- return this.call("GET", "/keys", z7.array(ApiKeySchema));
2845
+ return this.call("GET", "/keys", z11.array(ApiKeySchema));
2308
2846
  }
2309
2847
  createApiKey(req) {
2310
2848
  return this.call("POST", "/keys", CreatedApiKeySchema, req);
2311
2849
  }
2312
2850
  deleteApiKey(name) {
2313
- return this.call("DELETE", `/keys/${encodeURIComponent(name)}`, z7.unknown()).then(() => void 0);
2851
+ return this.call("DELETE", `/keys/${encodeURIComponent(name)}`, z11.unknown()).then(() => void 0);
2314
2852
  }
2315
2853
  // ---- orgs (`kvbox org …`) ----
2316
2854
  listOrgs() {
2317
- return this.call("GET", "/orgs", z7.array(OrgMembershipSchema));
2855
+ return this.call("GET", "/orgs", z11.array(OrgMembershipSchema));
2318
2856
  }
2319
2857
  createOrg(req) {
2320
2858
  return this.call("POST", "/orgs", CloudOrgSchema, req);
@@ -2323,16 +2861,16 @@ var ServerClient = class {
2323
2861
  return this.call("GET", `/orgs/${encodeURIComponent(slug)}`, OrgDetailSchema);
2324
2862
  }
2325
2863
  deleteOrg(slug) {
2326
- return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}`, z7.undefined());
2864
+ return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}`, z11.undefined());
2327
2865
  }
2328
2866
  addMember(slug, req) {
2329
- return this.call("POST", `/orgs/${encodeURIComponent(slug)}/members`, z7.undefined(), req);
2867
+ return this.call("POST", `/orgs/${encodeURIComponent(slug)}/members`, z11.undefined(), req);
2330
2868
  }
2331
2869
  setRole(slug, username, role) {
2332
- return this.call("PATCH", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z7.unknown(), { role }).then(() => void 0);
2870
+ return this.call("PATCH", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z11.unknown(), { role }).then(() => void 0);
2333
2871
  }
2334
2872
  removeMember(slug, username) {
2335
- return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z7.undefined());
2873
+ return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z11.undefined());
2336
2874
  }
2337
2875
  /** Sign this machine's key again (#51); the key must be one the user logged in with. */
2338
2876
  sshCert(req) {
@@ -2366,15 +2904,8 @@ function cloudDown(url, code) {
2366
2904
  const hint = host.endsWith("kvbox.sh") ? "check status.kvbox.sh" : "use --local for this machine, or kvbox logout";
2367
2905
  return `${host} is not available or is down (${code}). You are logged in there, so kvbox talks to it instead of this machine; ${hint}`;
2368
2906
  }
2369
- function safeJson(text2) {
2370
- try {
2371
- return JSON.parse(text2);
2372
- } catch {
2373
- return void 0;
2374
- }
2375
- }
2376
- async function wakeUp(client, box, name) {
2377
- switch (box.status) {
2907
+ async function wakeUp(client, box2, name) {
2908
+ switch (box2.status) {
2378
2909
  case "standby":
2379
2910
  info(`box ${name} is in standby; resuming it`);
2380
2911
  return spin(`resuming ${name}\u2026`, client.resumeMachine(name));
@@ -2385,7 +2916,7 @@ async function wakeUp(client, box, name) {
2385
2916
  info(`box ${name} is stopped; starting it`);
2386
2917
  return spin(`booting ${name}\u2026`, client.startMachine(name));
2387
2918
  default:
2388
- return box;
2919
+ return box2;
2389
2920
  }
2390
2921
  }
2391
2922
  function boxesFor(client, text2) {
@@ -2397,10 +2928,10 @@ var me = (client) => client.target.kind === "cloud" ? client.target.user : void
2397
2928
  async function clientFor(opts, client = {}) {
2398
2929
  return new ServerClient(await resolveTarget(opts), client);
2399
2930
  }
2400
- function sshEndpoint(box, target, direct = false) {
2401
- if (target.kind === "local" || direct) return { host: box.ip, port: 22, user: BOX_SSH_USER };
2402
- if (box.ssh === void 0) throw new KvboxError(`box ${box.name} has no public SSH port`);
2403
- return { ...box.ssh, alias: `${box.id}.${box.ssh.host}` };
2931
+ function sshEndpoint(box2, target, direct = false) {
2932
+ if (target.kind === "local" || direct) return { host: box2.ip, port: 22, user: BOX_SSH_USER };
2933
+ if (box2.ssh === void 0) throw new KvboxError(`box ${box2.name} has no public SSH port`);
2934
+ return { ...box2.ssh, alias: `${box2.id}.${box2.ssh.host}` };
2404
2935
  }
2405
2936
  function sshArgs(ep, p = paths()) {
2406
2937
  const hostKey = ep.alias === void 0 ? ["-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null"] : ["-o", "StrictHostKeyChecking=accept-new", "-o", `UserKnownHostsFile=${p.sshKnownHosts}`, "-o", `HostKeyAlias=${ep.alias}`];
@@ -2508,12 +3039,12 @@ async function serving(p, timeoutMs, check) {
2508
3039
  await probe.close();
2509
3040
  }
2510
3041
  }
2511
- await sleep(100);
3042
+ await sleep2(100);
2512
3043
  }
2513
3044
  throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
2514
3045
  }
2515
- function subdomainPath(box, path, sub) {
2516
- return `/machines/${encodeURIComponent(box)}/subdomain${path}${sub !== void 0 ? `?sub=${encodeURIComponent(sub)}` : ""}`;
3046
+ function subdomainPath(box2, path, sub) {
3047
+ return `/machines/${encodeURIComponent(box2)}/subdomain${path}${sub !== void 0 ? `?sub=${encodeURIComponent(sub)}` : ""}`;
2517
3048
  }
2518
3049
 
2519
3050
  // src/prompt.ts
@@ -2788,7 +3319,7 @@ var newCommand = new Command("new").description("boot a new box from an image (t
2788
3319
  }
2789
3320
  try {
2790
3321
  const what = opts.from !== void 0 ? `restoring ${name ?? "a new box"} from snapshot ${opts.from}\u2026` : `booting ${name ?? "a new box"}${opts.base !== void 0 && opts.base !== "base" ? ` from image ${opts.base}` : ""}\u2026`;
2791
- const box = await spin(what, client.createMachine({
3322
+ const box2 = await spin(what, client.createMachine({
2792
3323
  ...name !== void 0 ? { name } : {},
2793
3324
  ...opts.size !== void 0 ? { size: opts.size } : {},
2794
3325
  ...opts.from !== void 0 ? { from: opts.from } : {},
@@ -2800,54 +3331,54 @@ var newCommand = new Command("new").description("boot a new box from an image (t
2800
3331
  ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
2801
3332
  ...opts.force ? { force: true } : {}
2802
3333
  }));
2803
- if (autoHibernateSec && !box.autoHibernateSec) warn(`box ${name ?? box.name}: its host runs a kvbox-server too old for auto-hibernate; it will not hibernate on its own`);
2804
- if (opts.base !== void 0 && opts.base !== "base" && box.image === void 0) {
2805
- warn(`box ${box.name}: its host runs a kvbox-server too old for images; it booted the base image, not ${opts.base}`);
3334
+ if (autoHibernateSec && !box2.autoHibernateSec) warn(`box ${name ?? box2.name}: its host runs a kvbox-server too old for auto-hibernate; it will not hibernate on its own`);
3335
+ if (opts.base !== void 0 && opts.base !== "base" && box2.image === void 0) {
3336
+ warn(`box ${box2.name}: its host runs a kvbox-server too old for images; it booted the base image, not ${opts.base}`);
2806
3337
  }
2807
3338
  if (env.length > 0) {
2808
- const kept = await keptVars(client, displayName(box, me(client)), env.map((v) => v.name));
2809
- if (kept === "too old") warn(`box ${box.name}: its host runs a kvbox-server too old for a box's own variables; it has none of the -e ones`);
2810
- else if (kept !== true) warn(`box ${box.name}: could not check its -e variables (${kept}); kvbox env ls --box ${displayName(box, me(client))} shows them`);
3339
+ const kept = await keptVars(client, displayName(box2, me(client)), env.map((v) => v.name));
3340
+ if (kept === "too old") warn(`box ${box2.name}: its host runs a kvbox-server too old for a box's own variables; it has none of the -e ones`);
3341
+ else if (kept !== true) warn(`box ${box2.name}: could not check its -e variables (${kept}); kvbox env ls --box ${displayName(box2, me(client))} shows them`);
2811
3342
  }
2812
3343
  if (opts.json) {
2813
- json(box);
3344
+ json(box2);
2814
3345
  return;
2815
3346
  }
2816
3347
  const user = client.target.kind === "cloud" ? client.target.user : void 0;
2817
- process.stdout.write(`${box.name}
3348
+ process.stdout.write(`${box2.name}
2818
3349
  `);
2819
- info(`${color.green("\u2713")} ${describe(box, user)}`);
2820
- if (opts.from !== void 0) info(` connect with: kvbox connect ${displayName(box, user)} (already up: everything that ran in the snapshot is running)`);
2821
- else info(` connect with: kvbox connect ${displayName(box, user)} (SSH is up a couple of seconds after boot)`);
2822
- if (box.autoHibernateSec) info(` it ${autoHibernateText(box.autoHibernateSec, box.idleCheck)}`);
2823
- if (box.connect !== void 0) {
2824
- info(` reach it at: ${box.connect}`);
2825
- info(` from another box once linked: kvbox vm link <box> ${displayName(box, user)} --port <port>`);
2826
- info(` its variables: kvbox env ls --box ${displayName(box, user)}`);
2827
- }
2828
- if (box.image === "gh-runner") {
2829
- info(` wake it on queued jobs: kvbox vm hook create ${displayName(box, user)}`);
3350
+ info(`${color.green("\u2713")} ${describe(box2, user)}`);
3351
+ if (opts.from !== void 0) info(` connect with: kvbox connect ${displayName(box2, user)} (already up: everything that ran in the snapshot is running)`);
3352
+ else info(` connect with: kvbox connect ${displayName(box2, user)} (SSH is up a couple of seconds after boot)`);
3353
+ if (box2.autoHibernateSec) info(` it ${autoHibernateText(box2.autoHibernateSec, box2.idleCheck)}`);
3354
+ if (box2.connect !== void 0) {
3355
+ info(` reach it at: ${box2.connect}`);
3356
+ info(` from another box once linked: kvbox vm link <box> ${displayName(box2, user)} --port <port>`);
3357
+ info(` its variables: kvbox env ls --box ${displayName(box2, user)}`);
3358
+ }
3359
+ if (box2.image === "gh-runner") {
3360
+ info(` wake it on queued jobs: kvbox vm hook create ${displayName(box2, user)}`);
2830
3361
  info(` then add it on GitHub: Settings \u2192 Webhooks \u2192 Add webhook (the hook's URL and secret, content type application/json, event Workflow jobs)`);
2831
3362
  }
2832
3363
  } finally {
2833
3364
  await client.close();
2834
3365
  }
2835
3366
  });
2836
- async function keptVars(client, box, names2) {
3367
+ async function keptVars(client, box2, names2) {
2837
3368
  try {
2838
- const have = new Set((await client.boxEnv(box)).vars.map((v) => v.name));
3369
+ const have = new Set((await client.boxEnv(box2)).vars.map((v) => v.name));
2839
3370
  return names2.every((n) => have.has(n)) ? true : "too old";
2840
3371
  } catch (err) {
2841
3372
  const message = err.message;
2842
3373
  return /no route:|too old/.test(message) ? "too old" : message;
2843
3374
  }
2844
3375
  }
2845
- function displayName(box, user) {
2846
- return user !== void 0 && slugOf(box.owner) !== user ? `${slugOf(box.owner)}/${box.name}` : box.name;
3376
+ function displayName(box2, user) {
3377
+ return user !== void 0 && slugOf(box2.owner) !== user ? `${slugOf(box2.owner)}/${box2.name}` : box2.name;
2847
3378
  }
2848
- function describe(box, user) {
2849
- const from = box.source.startsWith("snapshot:") ? ` from snapshot ${shortRef(box.source.slice("snapshot:".length), box.owner)}` : box.source.startsWith("fork:") ? `, a fork of ${shortRef(box.source.slice("fork:".length), box.owner)}` : "";
2850
- return `box ${color.bold(displayName(box, user))} is ${box.status} at ${box.ip}${from}: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`;
3379
+ function describe(box2, user) {
3380
+ const from = box2.source.startsWith("snapshot:") ? ` from snapshot ${shortRef(box2.source.slice("snapshot:".length), box2.owner)}` : box2.source.startsWith("fork:") ? `, a fork of ${shortRef(box2.source.slice("fork:".length), box2.owner)}` : "";
3381
+ return `box ${color.bold(displayName(box2, user))} is ${box2.status} at ${box2.ip}${from}: ${box2.vcpu} vCPU, ${gb(box2.memMib * 1024 ** 2)} RAM, ${gb(box2.diskBytes)} disk`;
2851
3382
  }
2852
3383
  function autoHibernateText(sec, idleCheck) {
2853
3384
  if (!sec) return "never hibernates on its own";
@@ -2892,13 +3423,13 @@ var connectCommand = new Command2("connect").alias("cn").description("open a she
2892
3423
  let owner;
2893
3424
  try {
2894
3425
  const name = nameArg ?? await pickBox(client);
2895
- let box = pickRef(await boxesFor(client, name), name, me(client));
2896
- if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
2897
- cert = await ensureCert(client, void 0, void 0, { owner: box.owner });
2898
- owner = box.owner;
2899
- const wasRunning = box.status === "running";
2900
- if (!wasRunning) box = await wakeUp(client, box, displayName(box, me(client)));
2901
- ep = sshEndpoint(box, client.target, opts.direct);
3426
+ let box2 = pickRef(await boxesFor(client, name), name, me(client));
3427
+ if (!box2) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
3428
+ cert = await ensureCert(client, void 0, void 0, { owner: box2.owner });
3429
+ owner = box2.owner;
3430
+ const wasRunning = box2.status === "running";
3431
+ if (!wasRunning) box2 = await wakeUp(client, box2, displayName(box2, me(client)));
3432
+ ep = sshEndpoint(box2, client.target, opts.direct);
2902
3433
  if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
2903
3434
  else if (opts.direct) await checkDirect(ep);
2904
3435
  } finally {
@@ -2971,14 +3502,14 @@ var execCommand = new Command3("exec").description("run a command in a box and e
2971
3502
  let cert;
2972
3503
  let owner;
2973
3504
  try {
2974
- let box = pickRef(await boxesFor(client, name), name, me(client));
2975
- if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
2976
- if (box.status === "stopped") throw new KvboxError(`box ${name} is stopped (kvbox start ${name})`);
2977
- cert = await ensureCert(client, void 0, void 0, { owner: box.owner });
2978
- owner = box.owner;
2979
- const wasRunning = box.status === "running";
2980
- if (!wasRunning) box = await wakeUp(client, box, displayName(box, me(client)));
2981
- ep = sshEndpoint(box, client.target, opts.direct);
3505
+ let box2 = pickRef(await boxesFor(client, name), name, me(client));
3506
+ if (!box2) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
3507
+ if (box2.status === "stopped") throw new KvboxError(`box ${name} is stopped (kvbox start ${name})`);
3508
+ cert = await ensureCert(client, void 0, void 0, { owner: box2.owner });
3509
+ owner = box2.owner;
3510
+ const wasRunning = box2.status === "running";
3511
+ if (!wasRunning) box2 = await wakeUp(client, box2, displayName(box2, me(client)));
3512
+ ep = sshEndpoint(box2, client.target, opts.direct);
2982
3513
  if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
2983
3514
  else if (opts.direct) await checkDirect(ep);
2984
3515
  } finally {
@@ -3020,22 +3551,22 @@ var forkCommand = new Command4("fork").description("copy a box, running or stopp
3020
3551
  const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
3021
3552
  const client = await clientFor(cmd.optsWithGlobals());
3022
3553
  try {
3023
- const box = await spin(`forking ${source}\u2026`, client.forkMachine(source, {
3554
+ const box2 = await spin(`forking ${source}\u2026`, client.forkMachine(source, {
3024
3555
  ...name !== void 0 ? { name } : {},
3025
3556
  ...opts.size !== void 0 ? { size: opts.size } : {},
3026
3557
  ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
3027
3558
  ...opts.force ? { force: true } : {}
3028
3559
  }));
3029
3560
  if (opts.json) {
3030
- json(box);
3561
+ json(box2);
3031
3562
  return;
3032
3563
  }
3033
3564
  const user = me(client);
3034
- process.stdout.write(`${box.name}
3565
+ process.stdout.write(`${box2.name}
3035
3566
  `);
3036
- info(`${color.green("\u2713")} ${describe(box, user)}`);
3037
- info(` connect with: kvbox connect ${displayName(box, user)}`);
3038
- info(` it ${autoHibernateText(box.autoHibernateSec, box.idleCheck)}; published ports and HTTPS names stay with ${source}`);
3567
+ info(`${color.green("\u2713")} ${describe(box2, user)}`);
3568
+ info(` connect with: kvbox connect ${displayName(box2, user)}`);
3569
+ info(` it ${autoHibernateText(box2.autoHibernateSec, box2.idleCheck)}; published ports and HTTPS names stay with ${source}`);
3039
3570
  } finally {
3040
3571
  await client.close();
3041
3572
  }
@@ -3100,14 +3631,14 @@ function subdomainJson(sub, user) {
3100
3631
  return { box: boxOf(sub, user), subdomain: sub.subdomain, port: sub.port, url: sub.url, routes: sub.routes };
3101
3632
  }
3102
3633
  function httpsRowsOf(sub, user) {
3103
- const box = boxOf(sub, user);
3104
- return [{ box, guestPort: sub.port, proto: "https", url: sub.url }, ...sub.routes.map((r) => ({ box, guestPort: r.port, proto: "https", url: r.url, name: r.name }))];
3634
+ const box2 = boxOf(sub, user);
3635
+ return [{ box: box2, guestPort: sub.port, proto: "https", url: sub.url }, ...sub.routes.map((r) => ({ box: box2, guestPort: r.port, proto: "https", url: r.url, name: r.name }))];
3105
3636
  }
3106
3637
  function requireCloud(client) {
3107
3638
  if (client.target.kind !== "cloud") throw new KvboxError("HTTPS names need the kvbox cloud: kvbox login (this host's own socket has none)");
3108
3639
  }
3109
- function rowsOf(box, user, only) {
3110
- return (box.ports ?? []).filter(only ?? (() => true)).map((f) => ({ box: displayName(box, user), ...f }));
3640
+ function rowsOf(box2, user, only) {
3641
+ return (box2.ports ?? []).filter(only ?? (() => true)).map((f) => ({ box: displayName(box2, user), ...f }));
3111
3642
  }
3112
3643
  function reaches(row, short = false) {
3113
3644
  if (row.address !== void 0) return `${row.address}:${row.hostPort}`;
@@ -3131,51 +3662,51 @@ var getCommand = new Command6("get").description("show one box in full: status,
3131
3662
  const client = await clientFor(cmd.optsWithGlobals());
3132
3663
  try {
3133
3664
  const user = me(client);
3134
- const box = await findBox(client, name);
3135
- const subs = client.target.kind === "cloud" ? await subdomainsOf(client, box) : [];
3665
+ const box2 = await findBox(client, name);
3666
+ const subs = client.target.kind === "cloud" ? await subdomainsOf(client, box2) : [];
3136
3667
  if (opts.json) {
3137
- json({ ...box, ...subs.length > 0 ? { subdomains: subs.map((s) => subdomainJson(s, user)) } : {} });
3668
+ json({ ...box2, ...subs.length > 0 ? { subdomains: subs.map((s) => subdomainJson(s, user)) } : {} });
3138
3669
  return;
3139
3670
  }
3140
- const rows2 = getRows(box, subs, user);
3671
+ const rows2 = getRows(box2, subs, user);
3141
3672
  const width2 = Math.max(...rows2.map(([k]) => k.length));
3142
3673
  for (const [k, v] of rows2) info(`${color.dim(k.padStart(width2))} ${v}`);
3143
3674
  } finally {
3144
3675
  await client.close();
3145
3676
  }
3146
3677
  });
3147
- async function subdomainsOf(client, box) {
3678
+ async function subdomainsOf(client, box2) {
3148
3679
  try {
3149
- const slug = slugOf(box.owner);
3150
- return (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slug);
3680
+ const slug = slugOf(box2.owner);
3681
+ return (await client.listSubdomains()).filter((s) => s.box === box2.name && s.owner === slug);
3151
3682
  } catch (err) {
3152
3683
  warn(`HTTPS name not shown: ${err.message}`);
3153
3684
  return [];
3154
3685
  }
3155
3686
  }
3156
- function getRows(box, subs, user) {
3687
+ function getRows(box2, subs, user) {
3157
3688
  const rows2 = [
3158
- ["name", color.bold(displayName(box, user))],
3159
- ["status", status(box.status)]
3689
+ ["name", color.bold(displayName(box2, user))],
3690
+ ["status", status(box2.status)]
3160
3691
  ];
3161
- if (user !== void 0) rows2.push(["owner", ownerCell(box, user)]);
3162
- if (box.status !== "unknown") {
3163
- rows2.push(["size", `${shape(box.vcpu, box.memMib, box.diskBytes)} ${color.dim(`(${gb(box.diskUsedBytes)} used)`)}`]);
3164
- rows2.push(["address", box.ssh?.host ?? (box.ip === "" ? "-" : box.ip)]);
3165
- rows2.push(["ssh", box.ssh ? `ssh -p ${box.ssh.port} ${box.ssh.user}@${box.ssh.host}` : `kvbox connect ${displayName(box, user)}`]);
3692
+ if (user !== void 0) rows2.push(["owner", ownerCell(box2, user)]);
3693
+ if (box2.status !== "unknown") {
3694
+ rows2.push(["size", `${shape(box2.vcpu, box2.memMib, box2.diskBytes)} ${color.dim(`(${gb(box2.diskUsedBytes)} used)`)}`]);
3695
+ rows2.push(["address", box2.ssh?.host ?? (box2.ip === "" ? "-" : box2.ip)]);
3696
+ rows2.push(["ssh", box2.ssh ? `ssh -p ${box2.ssh.port} ${box2.ssh.user}@${box2.ssh.host}` : `kvbox connect ${displayName(box2, user)}`]);
3166
3697
  }
3167
- if (box.url !== void 0) rows2.push(["connect", `${box.url} ${color.dim("(password shown once, at new)")}`]);
3698
+ if (box2.url !== void 0) rows2.push(["connect", `${box2.url} ${color.dim("(password shown once, at new)")}`]);
3168
3699
  const urls = subs.flatMap((sub) => [`${sub.url} ${color.dim(`(port ${sub.port})`)}`, ...sub.routes.map((r) => `${r.url} ${color.dim(`(port ${r.port})`)}`)]);
3169
3700
  rows2.push(["url", urls.length === 0 ? "-" : urls.join(", ")]);
3170
- const ports = rowsOf(box, user).map((r) => `${r.guestPort}/${r.proto} \u2192 ${reaches(r, true)}`);
3701
+ const ports = rowsOf(box2, user).map((r) => `${r.guestPort}/${r.proto} \u2192 ${reaches(r, true)}`);
3171
3702
  rows2.push(["ports", ports.length === 0 ? "-" : ports.join(", ")]);
3172
- rows2.push(["volumes", box.volumes?.length ? box.volumes.map((v) => `${v.name} ${color.dim(`(${v.sizeGib} GB at ${v.mountPath})`)}`).join(", ") : "-"]);
3173
- const quiet = box.idleCheck === void 0 ? "without network traffic" : `idle by ${box.idleCheck}`;
3174
- rows2.push(["auto-hibernate", box.autoHibernateSec ? `after ${duration(box.autoHibernateSec)} ${quiet}` : "off"]);
3175
- if (!box.autoHibernateSec && box.idleCheck !== void 0) rows2.push(["idle check", `${box.idleCheck} ${color.dim("(used once auto-hibernate is on)")}`]);
3176
- rows2.push(["source", box.source]);
3177
- rows2.push(["base", box.image === void 0 ? box.base : `${box.image} ${box.base}`]);
3178
- rows2.push(["created", `${age(box.createdAt)} ${color.dim(`(${box.createdAt})`)}`]);
3703
+ rows2.push(["volumes", box2.volumes?.length ? box2.volumes.map((v) => `${v.name} ${color.dim(`(${v.sizeGib} GB at ${v.mountPath})`)}`).join(", ") : "-"]);
3704
+ const quiet = box2.idleCheck === void 0 ? "without network traffic" : `idle by ${box2.idleCheck}`;
3705
+ rows2.push(["auto-hibernate", box2.autoHibernateSec ? `after ${duration(box2.autoHibernateSec)} ${quiet}` : "off"]);
3706
+ if (!box2.autoHibernateSec && box2.idleCheck !== void 0) rows2.push(["idle check", `${box2.idleCheck} ${color.dim("(used once auto-hibernate is on)")}`]);
3707
+ rows2.push(["source", box2.source]);
3708
+ rows2.push(["base", box2.image === void 0 ? box2.base : `${box2.image} ${box2.base}`]);
3709
+ rows2.push(["created", `${age(box2.createdAt)} ${color.dim(`(${box2.createdAt})`)}`]);
3179
3710
  return rows2;
3180
3711
  }
3181
3712
 
@@ -3184,8 +3715,8 @@ import { Command as Command7 } from "commander";
3184
3715
  var hibernateCommand = new Command7("hibernate").description("save a box's memory to disk and free its RAM (kvbox wake continues it where it left off)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
3185
3716
  const client = await clientFor(cmd.optsWithGlobals());
3186
3717
  try {
3187
- const box = await spin(`hibernating ${name} (saving its memory to disk)\u2026`, client.hibernateMachine(name));
3188
- if (opts.json) json(box);
3718
+ const box2 = await spin(`hibernating ${name} (saving its memory to disk)\u2026`, client.hibernateMachine(name));
3719
+ if (opts.json) json(box2);
3189
3720
  else info(`${color.green("\u2713")} box ${name} hibernated (memory saved to disk, RAM freed; kvbox wake ${name} continues it where it left off)`);
3190
3721
  } finally {
3191
3722
  await client.close();
@@ -3203,19 +3734,19 @@ var linkCommand = new Command8("link").description("let one box reach a port of
3203
3734
  const port = parseLinkPort(opts.port);
3204
3735
  const client = await clientFor(cmd.optsWithGlobals());
3205
3736
  try {
3206
- const box = await spin(`linking ${from} to ${name}:${port}\u2026`, client.addLink(name, { from, port }));
3737
+ const box2 = await spin(`linking ${from} to ${name}:${port}\u2026`, client.addLink(name, { from, port }));
3207
3738
  const user = me(client);
3208
- const shown = displayName(box, user);
3739
+ const shown = displayName(box2, user);
3209
3740
  if (opts.json) {
3210
3741
  json({ from, box: shown, port });
3211
3742
  return;
3212
3743
  }
3213
3744
  const fromName = from.slice(from.lastIndexOf("/") + 1);
3214
- const link2 = box.links?.find((l) => l.port === port && l.from.slice(l.from.lastIndexOf("/") + 1) === fromName);
3215
- const apart = link2 !== void 0 ? link2.from.includes("/") : from.includes("/") && from.split("/")[0] !== slugOf(box.owner);
3216
- const host = apart ? `${box.name}.${slugOf(box.owner)}.kvbox` : `${box.name}.kvbox`;
3745
+ const link2 = box2.links?.find((l) => l.port === port && l.from.slice(l.from.lastIndexOf("/") + 1) === fromName);
3746
+ const apart = link2 !== void 0 ? link2.from.includes("/") : from.includes("/") && from.split("/")[0] !== slugOf(box2.owner);
3747
+ const host = apart ? `${box2.name}.${slugOf(box2.owner)}.kvbox` : `${box2.name}.kvbox`;
3217
3748
  info(`${color.green("\u2713")} box ${color.bold(from)} can reach ${color.bold(`${host}:${port}`)}`);
3218
- if (box.status !== "running") info(` box ${shown} is ${box.status}: the link opens when it runs`);
3749
+ if (box2.status !== "running") info(` box ${shown} is ${box2.status}: the link opens when it runs`);
3219
3750
  } finally {
3220
3751
  await client.close();
3221
3752
  }
@@ -3232,12 +3763,12 @@ var linksCommand = new Command9("links").description("list the links between box
3232
3763
  const unlisted = name === void 0 || name.includes("/") || user === void 0 ? name : `${client.target.kind === "cloud" ? client.target.org ?? user : user}/${name}`;
3233
3764
  const wanted = picked === void 0 ? unlisted : `${slugOf(picked.owner)}/${picked.name}`;
3234
3765
  const rows2 = machines.flatMap((b) => {
3235
- const box = displayName(b, user);
3236
- const slug = box.includes("/") ? box.split("/")[0] : void 0;
3766
+ const box2 = displayName(b, user);
3767
+ const slug = box2.includes("/") ? box2.split("/")[0] : void 0;
3237
3768
  return (b.links ?? []).map((l) => {
3238
3769
  const source = l.from.includes("/") ? l.from : `${slugOf(b.owner)}/${l.from}`;
3239
3770
  const from = slug !== void 0 && !l.from.includes("/") ? `${slug}/${l.from}` : l.from;
3240
- const row = { from: user !== void 0 && from.startsWith(`${user}/`) ? from.slice(user.length + 1) : from, box, port: l.port };
3771
+ const row = { from: user !== void 0 && from.startsWith(`${user}/`) ? from.slice(user.length + 1) : from, box: box2, port: l.port };
3241
3772
  return { row, ends: [`${slugOf(b.owner)}/${b.name}`, source] };
3242
3773
  });
3243
3774
  }).filter((r) => wanted === void 0 || r.ends.includes(wanted)).map((r) => r.row).sort((a, b) => a.box.localeCompare(b.box) || a.from.localeCompare(b.from) || a.port - b.port);
@@ -3260,8 +3791,8 @@ import { Command as Command10 } from "commander";
3260
3791
  var pauseCommand = new Command10("pause").description("freeze a box in place (memory and processes kept, no CPU used; kvbox resume continues it instantly)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
3261
3792
  const client = await clientFor(cmd.optsWithGlobals());
3262
3793
  try {
3263
- const box = await spin(`pausing ${name}\u2026`, client.pauseMachine(name));
3264
- if (opts.json) json(box);
3794
+ const box2 = await spin(`pausing ${name}\u2026`, client.pauseMachine(name));
3795
+ if (opts.json) json(box2);
3265
3796
  else info(`${color.green("\u2713")} box ${name} is in standby (frozen in place; kvbox resume ${name} continues it)`);
3266
3797
  } finally {
3267
3798
  await client.close();
@@ -3353,16 +3884,16 @@ var claimCommand = new Command11("claim").description(`give a box an HTTPS addre
3353
3884
  const [port] = parsePorts([portText]);
3354
3885
  const user = me(client);
3355
3886
  const found = await findBox(client, name);
3356
- const box = displayName(found, user);
3357
- const sub = await spin(`claiming ${subdomain}\u2026`, client.claimSubdomain(box, { name: subdomain, port }));
3887
+ const box2 = displayName(found, user);
3888
+ const sub = await spin(`claiming ${subdomain}\u2026`, client.claimSubdomain(box2, { name: subdomain, port }));
3358
3889
  if (opts.json) {
3359
3890
  json(subdomainJson(sub, me(client)));
3360
3891
  return;
3361
3892
  }
3362
- info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box)} port ${sub.port}`);
3363
- info(` more ports under it: kvbox vm proxy add ${box} <port> --name <name> \u2192 https://<name>.${sub.url.replace(/^https:\/\//, "")}`);
3364
- info(` another address for this box: kvbox vm proxy claim ${box} <subdomain> --port <port>`);
3365
- if (found.status !== "running") info(` box ${box} is ${found.status}: the address answers once it runs`);
3893
+ info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box2)} port ${sub.port}`);
3894
+ info(` more ports under it: kvbox vm proxy add ${box2} <port> --name <name> \u2192 https://<name>.${sub.url.replace(/^https:\/\//, "")}`);
3895
+ info(` another address for this box: kvbox vm proxy claim ${box2} <subdomain> --port <port>`);
3896
+ if (found.status !== "running") info(` box ${box2} is ${found.status}: the address answers once it runs`);
3366
3897
  } finally {
3367
3898
  await client.close();
3368
3899
  }
@@ -3388,21 +3919,21 @@ var addCommand = new Command12("add").description("publish box ports on the inte
3388
3919
  const user = me(client);
3389
3920
  if (opts.name !== void 0) requireCloud(client);
3390
3921
  const found = await findBox(client, name);
3391
- const box = displayName(found, user);
3922
+ const box2 = displayName(found, user);
3392
3923
  if (opts.name !== void 0) {
3393
3924
  const route = opts.name;
3394
- const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}\u2026`, client.addSubdomainRoute(box, { name: route, port: guestPorts[0] }, opts.sub));
3925
+ const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}\u2026`, client.addSubdomainRoute(box2, { name: route, port: guestPorts[0] }, opts.sub));
3395
3926
  const url = sub.routes.find((r) => r.name === route).url;
3396
3927
  if (opts.json) {
3397
- json({ box, guestPort: guestPorts[0], proto: "https", url, name: route });
3928
+ json({ box: box2, guestPort: guestPorts[0], proto: "https", url, name: route });
3398
3929
  return;
3399
3930
  }
3400
- info(`${color.green("\u2713")} ${color.bold(url)} \u2192 box ${color.bold(box)} port ${guestPorts[0]}`);
3931
+ info(`${color.green("\u2713")} ${color.bold(url)} \u2192 box ${color.bold(box2)} port ${guestPorts[0]}`);
3401
3932
  info(" the first name under a subdomain waits for its certificate, about a minute");
3402
- if (found.status !== "running") info(` box ${box} is ${found.status}: the address answers once it runs`);
3933
+ if (found.status !== "running") info(` box ${box2} is ${found.status}: the address answers once it runs`);
3403
3934
  return;
3404
3935
  }
3405
- const updated = await spin(`publishing ${guestPorts.join(", ")} on ${name}\u2026`, client.addPorts(box, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));
3936
+ const updated = await spin(`publishing ${guestPorts.join(", ")} on ${name}\u2026`, client.addPorts(box2, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));
3406
3937
  const rows2 = rowsOf(updated, user, (f) => f.proto === proto && guestPorts.includes(f.guestPort));
3407
3938
  if (opts.json) {
3408
3939
  json(rows2);
@@ -3456,15 +3987,15 @@ var releaseCommand = new Command14("release").description("give up one of a box'
3456
3987
  const client = await clientFor(cmd.optsWithGlobals());
3457
3988
  try {
3458
3989
  requireCloud(client);
3459
- const box = displayName(await findBox(client, name), me(client));
3460
- if (!await confirm(`Give up ${opts.sub !== void 0 ? `${opts.sub}, one of box ${box}'s HTTPS addresses,` : `box ${box}'s HTTPS address`} and every name under it? Anyone may claim it after.`, opts.yes ?? false)) {
3990
+ const box2 = displayName(await findBox(client, name), me(client));
3991
+ if (!await confirm(`Give up ${opts.sub !== void 0 ? `${opts.sub}, one of box ${box2}'s HTTPS addresses,` : `box ${box2}'s HTTPS address`} and every name under it? Anyone may claim it after.`, opts.yes ?? false)) {
3461
3992
  info("cancelled");
3462
3993
  process.exitCode = 1;
3463
3994
  return;
3464
3995
  }
3465
- const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box, opts.sub));
3996
+ const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box2, opts.sub));
3466
3997
  const names2 = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
3467
- info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names2} no longer reach box ${color.bold(box)}`);
3998
+ info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names2} no longer reach box ${color.bold(box2)}`);
3468
3999
  } finally {
3469
4000
  await client.close();
3470
4001
  }
@@ -3486,19 +4017,19 @@ var rmCommand = new Command15("rm").description("stop publishing box ports, or a
3486
4017
  const client = await clientFor(cmd.optsWithGlobals());
3487
4018
  try {
3488
4019
  if (opts.name !== void 0) requireCloud(client);
3489
- const box = displayName(await findBox(client, name), me(client));
3490
- const question = opts.name !== void 0 ? `Stop serving ${opts.name} under box ${box}'s subdomain?` : `Stop publishing port${guestPorts.length > 1 ? "s" : ""} ${guestPorts.join(", ")} of box ${box}?`;
4020
+ const box2 = displayName(await findBox(client, name), me(client));
4021
+ const question = opts.name !== void 0 ? `Stop serving ${opts.name} under box ${box2}'s subdomain?` : `Stop publishing port${guestPorts.length > 1 ? "s" : ""} ${guestPorts.join(", ")} of box ${box2}?`;
3491
4022
  if (!await confirm(question, opts.yes ?? false)) {
3492
4023
  info("cancelled");
3493
4024
  process.exitCode = 1;
3494
4025
  return;
3495
4026
  }
3496
4027
  if (opts.name !== void 0) {
3497
- const sub = await spin(`freeing ${opts.name} on ${name}\u2026`, client.removeSubdomainRoute(box, opts.name, opts.sub));
3498
- info(`${color.green("\u2713")} ${opts.name}.${sub.url.replace(/^https:\/\//, "")} no longer reaches box ${color.bold(box)}`);
4028
+ const sub = await spin(`freeing ${opts.name} on ${name}\u2026`, client.removeSubdomainRoute(box2, opts.name, opts.sub));
4029
+ info(`${color.green("\u2713")} ${opts.name}.${sub.url.replace(/^https:\/\//, "")} no longer reaches box ${color.bold(box2)}`);
3499
4030
  return;
3500
4031
  }
3501
- await spin(`closing ${guestPorts.join(", ")} on ${name}\u2026`, client.removePorts(box, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));
4032
+ await spin(`closing ${guestPorts.join(", ")} on ${name}\u2026`, client.removePorts(box2, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));
3502
4033
  info(`${color.green("\u2713")} box ${color.bold(name)} no longer publishes ${guestPorts.join(", ")} (${proto})`);
3503
4034
  } finally {
3504
4035
  await client.close();
@@ -3512,13 +4043,13 @@ var setPortCommand = new Command16("set-port").description("point a box's HTTPS
3512
4043
  const client = await clientFor(cmd.optsWithGlobals());
3513
4044
  try {
3514
4045
  requireCloud(client);
3515
- const box = displayName(await findBox(client, name), me(client));
3516
- const sub = await spin(`pointing ${name} at port ${port}\u2026`, client.setSubdomainPort(box, { port }, opts.sub));
4046
+ const box2 = displayName(await findBox(client, name), me(client));
4047
+ const sub = await spin(`pointing ${name} at port ${port}\u2026`, client.setSubdomainPort(box2, { port }, opts.sub));
3517
4048
  if (opts.json) {
3518
4049
  json(subdomainJson(sub, me(client)));
3519
4050
  return;
3520
4051
  }
3521
- info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box)} port ${sub.port}`);
4052
+ info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box2)} port ${sub.port}`);
3522
4053
  } finally {
3523
4054
  await client.close();
3524
4055
  }
@@ -3544,13 +4075,13 @@ var createCommand = new Command18("create").description("make a URL that wakes t
3544
4075
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3545
4076
  try {
3546
4077
  requireCloud2(client);
3547
- const box = displayName(await findBox(client, name), me(client));
3548
- const hook = await client.createBoxHook(box);
4078
+ const box2 = displayName(await findBox(client, name), me(client));
4079
+ const hook = await client.createBoxHook(box2);
3549
4080
  if (opts.json) {
3550
4081
  json(hook);
3551
4082
  return;
3552
4083
  }
3553
- info(`${color.green("\u2713")} hook ${hook.id} wakes box ${color.bold(box)}`);
4084
+ info(`${color.green("\u2713")} hook ${hook.id} wakes box ${color.bold(box2)}`);
3554
4085
  info(` url: ${hook.url}`);
3555
4086
  info(` secret: ${hook.secret} ${color.dim("(shown only now)")}`);
3556
4087
  info("");
@@ -3569,14 +4100,14 @@ var lsCommand3 = new Command19("ls").alias("list").description("list a box's wak
3569
4100
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3570
4101
  try {
3571
4102
  requireCloud2(client);
3572
- const box = displayName(await findBox(client, name), me(client));
3573
- const hooks = await client.boxHooks(box);
4103
+ const box2 = displayName(await findBox(client, name), me(client));
4104
+ const hooks = await client.boxHooks(box2);
3574
4105
  if (opts.json) {
3575
4106
  json(hooks);
3576
4107
  return;
3577
4108
  }
3578
4109
  if (hooks.length === 0) {
3579
- info(`box ${box} has no wake hooks; make one with: kvbox vm hook create ${box}`);
4110
+ info(`box ${box2} has no wake hooks; make one with: kvbox vm hook create ${box2}`);
3580
4111
  return;
3581
4112
  }
3582
4113
  table(hooks.map((h) => ({ id: h.id, url: h.url, "last called": h.lastCalledAt ? age(h.lastCalledAt) : color.dim("never"), by: h.createdBy ?? "-", created: age(h.createdAt) })));
@@ -3591,18 +4122,18 @@ var rmCommand2 = new Command20("rm").alias("remove").description("remove a wake
3591
4122
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3592
4123
  try {
3593
4124
  requireCloud2(client);
3594
- const box = displayName(await findBox(client, name), me(client));
3595
- if (!await confirm(`Remove hook ${id} of box ${box}? Whatever calls its URL stops waking the box.`, opts.yes ?? false)) {
4125
+ const box2 = displayName(await findBox(client, name), me(client));
4126
+ if (!await confirm(`Remove hook ${id} of box ${box2}? Whatever calls its URL stops waking the box.`, opts.yes ?? false)) {
3596
4127
  info("cancelled");
3597
4128
  process.exitCode = 1;
3598
4129
  return;
3599
4130
  }
3600
- const hook = await client.removeBoxHook(box, id);
4131
+ const hook = await client.removeBoxHook(box2, id);
3601
4132
  if (opts.json) {
3602
4133
  json(hook);
3603
4134
  return;
3604
4135
  }
3605
- info(`${color.green("\u2713")} hook ${hook.id} removed; its URL no longer wakes box ${color.bold(box)}`);
4136
+ info(`${color.green("\u2713")} hook ${hook.id} removed; its URL no longer wakes box ${color.bold(box2)}`);
3606
4137
  } finally {
3607
4138
  await client.close();
3608
4139
  }
@@ -3619,7 +4150,7 @@ import { Command as Command25 } from "commander";
3619
4150
  import { Command as Command22 } from "commander";
3620
4151
 
3621
4152
  // src/commands/vm/backup/shared.ts
3622
- import { setTimeout as sleep2 } from "timers/promises";
4153
+ import { setTimeout as sleep3 } from "timers/promises";
3623
4154
  function requireCloud3(client) {
3624
4155
  if (client.target.kind !== "cloud") throw new KvboxError("backups need the kvbox cloud: kvbox login (this host's own socket has none)");
3625
4156
  }
@@ -3641,11 +4172,11 @@ async function untilSettled(ask, what, id, where, opts = {}) {
3641
4172
  if (failed >= tries) throw lostTrack(`could not ask how it is doing: ${err.message}`);
3642
4173
  }
3643
4174
  if (Date.now() >= until2) throw lostTrack("it is taking longer than a backup is given");
3644
- await sleep2(pollMs);
4175
+ await sleep3(pollMs);
3645
4176
  }
3646
4177
  }
3647
- function untilDone(client, box, id, opts = {}) {
3648
- return untilSettled(() => client.boxBackup(box, id), `box ${box}`, id, `kvbox vm backup ls ${box}`, opts);
4178
+ function untilDone(client, box2, id, opts = {}) {
4179
+ return untilSettled(() => client.boxBackup(box2, id), `box ${box2}`, id, `kvbox vm backup ls ${box2}`, opts);
3649
4180
  }
3650
4181
  function sizeLine(b) {
3651
4182
  const data = b.dataBytes === null ? "?" : gb(b.dataBytes);
@@ -3659,23 +4190,23 @@ var createCommand2 = new Command22("create").description("back up a box's disk t
3659
4190
  try {
3660
4191
  requireCloud3(client);
3661
4192
  const found = await findBox(client, name);
3662
- const box = displayName(found, me(client));
3663
- const started = await client.createBoxBackup(box);
4193
+ const box2 = displayName(found, me(client));
4194
+ const started = await client.createBoxBackup(box2);
3664
4195
  if (!opts.wait) {
3665
4196
  if (opts.json) json(started);
3666
4197
  else {
3667
- info(`${color.green("\u2713")} backup ${started.id} of box ${color.bold(box)} started; it runs in the background`);
3668
- info(color.dim(` status: kvbox vm backup ls ${box}`));
4198
+ info(`${color.green("\u2713")} backup ${started.id} of box ${color.bold(box2)} started; it runs in the background`);
4199
+ info(color.dim(` status: kvbox vm backup ls ${box2}`));
3669
4200
  }
3670
4201
  return;
3671
4202
  }
3672
- const done = await spin(`backing up ${box}\u2026`, untilDone(client, box, started.id));
4203
+ const done = await spin(`backing up ${box2}\u2026`, untilDone(client, box2, started.id));
3673
4204
  if (opts.json) json(done);
3674
- if (done.status === "failed") throw new KvboxError(`backup ${done.id} of box ${box} failed: ${done.error ?? "no reason given"}`);
4205
+ if (done.status === "failed") throw new KvboxError(`backup ${done.id} of box ${box2} failed: ${done.error ?? "no reason given"}`);
3675
4206
  if (opts.json) return;
3676
- info(`${color.green("\u2713")} backup ${done.id} of box ${color.bold(box)}: ${sizeLine(done)}`);
4207
+ info(`${color.green("\u2713")} backup ${done.id} of box ${color.bold(box2)}: ${sizeLine(done)}`);
3677
4208
  if ((found.volumes?.length ?? 0) > 0) info(color.dim(` not included: volume${found.volumes.length > 1 ? "s" : ""} ${found.volumes.map((v) => v.name).join(", ")}`));
3678
- info(color.dim(` restore with: kvbox vm backup restore ${box} ${done.id}`));
4209
+ info(color.dim(` restore with: kvbox vm backup restore ${box2} ${done.id}`));
3679
4210
  } finally {
3680
4211
  await client.close();
3681
4212
  }
@@ -3687,21 +4218,21 @@ var lsCommand4 = new Command23("ls").alias("list").description("list backups: ev
3687
4218
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3688
4219
  try {
3689
4220
  requireCloud3(client);
3690
- const box = name === void 0 ? void 0 : displayName(await findBox(client, name), me(client));
3691
- const list = box === void 0 ? await client.listBackups() : await client.boxBackups(box);
4221
+ const box2 = name === void 0 ? void 0 : displayName(await findBox(client, name), me(client));
4222
+ const list = box2 === void 0 ? await client.listBackups() : await client.boxBackups(box2);
3692
4223
  if (opts.json) {
3693
4224
  json(list);
3694
4225
  return;
3695
4226
  }
3696
4227
  if (list.length === 0) {
3697
- info(box === void 0 ? "no backups yet; make one with: kvbox vm backup create <box>" : `box ${box} has no backups; make one with: kvbox vm backup create ${box}`);
4228
+ info(box2 === void 0 ? "no backups yet; make one with: kvbox vm backup create <box>" : `box ${box2} has no backups; make one with: kvbox vm backup create ${box2}`);
3698
4229
  return;
3699
4230
  }
3700
4231
  const anyError = list.some((b) => b.error !== null);
3701
4232
  table(
3702
4233
  list.map((b) => ({
3703
4234
  id: b.id,
3704
- ...box === void 0 ? { box: b.owner === me(client) ? b.box : `${b.owner}/${b.box}` } : {},
4235
+ ...box2 === void 0 ? { box: b.owner === me(client) ? b.box : `${b.owner}/${b.box}` } : {},
3705
4236
  status: b.status === "ready" ? color.green(b.status) : b.status === "failed" ? color.red(b.status) : color.yellow(b.status),
3706
4237
  data: b.dataBytes === null ? "-" : gbShort(b.dataBytes),
3707
4238
  uploaded: b.uploadedBytes === null ? "-" : gbShort(b.uploadedBytes),
@@ -3722,20 +4253,20 @@ var restoreCommand = new Command24("restore").description("put a backup back: th
3722
4253
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
3723
4254
  try {
3724
4255
  requireCloud3(client);
3725
- const box = displayName(await findBox(client, name), me(client));
3726
- const backup = await client.boxBackup(box, id);
3727
- const question = `Restore box ${box} from backup ${backup.id} (${age(backup.createdAt)} ago, ${sizeLine(backup)})? Everything written to its disk since is lost, and a running box restarts.`;
4256
+ const box2 = displayName(await findBox(client, name), me(client));
4257
+ const backup = await client.boxBackup(box2, id);
4258
+ const question = `Restore box ${box2} from backup ${backup.id} (${age(backup.createdAt)} ago, ${sizeLine(backup)})? Everything written to its disk since is lost, and a running box restarts.`;
3728
4259
  if (!await confirm(question, opts.yes ?? false)) {
3729
4260
  info("cancelled");
3730
4261
  process.exitCode = 1;
3731
4262
  return;
3732
4263
  }
3733
- const machine = await spin(`restoring ${box} from ${backup.id}\u2026`, client.restoreBoxBackup(box, id));
4264
+ const machine = await spin(`restoring ${box2} from ${backup.id}\u2026`, client.restoreBoxBackup(box2, id));
3734
4265
  if (opts.json) {
3735
4266
  json(machine);
3736
4267
  return;
3737
4268
  }
3738
- info(`${color.green("\u2713")} box ${color.bold(box)} restored from backup ${backup.id}; it is ${machine.status}`);
4269
+ info(`${color.green("\u2713")} box ${color.bold(box2)} restored from backup ${backup.id}; it is ${machine.status}`);
3739
4270
  } finally {
3740
4271
  await client.close();
3741
4272
  }
@@ -3760,17 +4291,17 @@ var rescaleCommand = new Command26("rescale").description("change a box's vCPUs,
3760
4291
  try {
3761
4292
  const before = pickRef(await boxesFor(client, name), name, me(client));
3762
4293
  if (!before) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
3763
- const box = await spin(`rescaling ${name}\u2026`, client.rescaleMachine(displayName(before, me(client)), body));
4294
+ const box2 = await spin(`rescaling ${name}\u2026`, client.rescaleMachine(displayName(before, me(client)), body));
3764
4295
  if (opts.json) {
3765
- json(box);
4296
+ json(box2);
3766
4297
  return;
3767
4298
  }
3768
- const same = box.vcpu === before.vcpu && box.memMib === before.memMib && box.diskBytes === before.diskBytes;
4299
+ const same = box2.vcpu === before.vcpu && box2.memMib === before.memMib && box2.diskBytes === before.diskBytes;
3769
4300
  if (same) {
3770
4301
  info(`box ${name} already has that shape; nothing changed`);
3771
4302
  return;
3772
4303
  }
3773
- info(`${color.green("\u2713")} ${describe(box)}`);
4304
+ info(`${color.green("\u2713")} ${describe(box2)}`);
3774
4305
  if (before.status === "running") info(" it was restarted: processes that were running are gone, files are intact");
3775
4306
  } finally {
3776
4307
  await client.close();
@@ -3797,8 +4328,8 @@ import { Command as Command27 } from "commander";
3797
4328
  var resumeCommand = new Command27("resume").description("continue a box that is in standby (kvbox pause)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
3798
4329
  const client = await clientFor(cmd.optsWithGlobals());
3799
4330
  try {
3800
- const box = await spin(`resuming ${name}\u2026`, client.resumeMachine(name));
3801
- if (opts.json) json(box);
4331
+ const box2 = await spin(`resuming ${name}\u2026`, client.resumeMachine(name));
4332
+ if (opts.json) json(box2);
3802
4333
  else info(`${color.green("\u2713")} box ${name} resumed`);
3803
4334
  } finally {
3804
4335
  await client.close();
@@ -3810,16 +4341,16 @@ import { Command as Command28 } from "commander";
3810
4341
  var rmCommand3 = new Command28("rm").description("destroy a box (its disk is deleted; snapshots are kept)").argument("<name>", "box name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
3811
4342
  const client = await clientFor(cmd.optsWithGlobals());
3812
4343
  try {
3813
- const box = pickRef(await boxesFor(client, name), name, me(client));
3814
- if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
3815
- const ref = displayName(box, me(client));
4344
+ const box2 = pickRef(await boxesFor(client, name), name, me(client));
4345
+ if (!box2) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
4346
+ const ref = displayName(box2, me(client));
3816
4347
  if (!await confirm(`Destroy box ${ref} and its disk?`, opts.yes ?? false)) {
3817
4348
  info("cancelled");
3818
4349
  process.exitCode = 1;
3819
4350
  return;
3820
4351
  }
3821
4352
  await spin(`destroying ${ref}\u2026`, client.deleteMachine(ref));
3822
- const volumes = box.volumes?.map((v) => v.name) ?? [];
4353
+ const volumes = box2.volumes?.map((v) => v.name) ?? [];
3823
4354
  info(`${color.green("\u2713")} box ${ref} destroyed${volumes.length > 0 ? `; its volume${volumes.length > 1 ? "s" : ""} ${volumes.join(", ")} ${volumes.length > 1 ? "are" : "is"} kept, detached` : ""}`);
3824
4355
  } finally {
3825
4356
  await client.close();
@@ -3916,20 +4447,20 @@ var setCommand = new Command29("set").description("change a box's settings, e.g.
3916
4447
  const found = pickRef(await boxesFor(client, name), name, me(client));
3917
4448
  if (!found) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
3918
4449
  if (swapMib !== void 0 && found.status === "stopped") throw new KvboxError(`box ${name} is stopped; --swap is set up inside the box (kvbox start ${name})`);
3919
- let box = found;
4450
+ let box2 = found;
3920
4451
  if (hostSettings) {
3921
- box = await spin(`updating ${name}\u2026`, client.setMachine(displayName(found, me(client)), { ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {}, ...idleCheck !== void 0 ? { idleCheck } : {} }));
3922
- if (!idleCheckKept(idleCheck, box)) {
4452
+ box2 = await spin(`updating ${name}\u2026`, client.setMachine(displayName(found, me(client)), { ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {}, ...idleCheck !== void 0 ? { idleCheck } : {} }));
4453
+ if (!idleCheckKept(idleCheck, box2)) {
3923
4454
  throw new KvboxError(`box ${name}: its host runs a kvbox-server too old for --idle-check; it needs updating first${autoHibernateSec !== void 0 ? " (--auto-hibernate was applied)" : ""}`);
3924
4455
  }
3925
4456
  }
3926
- const swap = swapMib === void 0 ? void 0 : await setSwap(client, box, name, swapMib, cmd);
4457
+ const swap = swapMib === void 0 ? void 0 : await setSwap(client, box2, name, swapMib, cmd);
3927
4458
  if (opts.json) {
3928
- json(swap === void 0 ? box : { ...box, swap });
4459
+ json(swap === void 0 ? box2 : { ...box2, swap });
3929
4460
  return;
3930
4461
  }
3931
- if (hostSettings) info(`${color.green("\u2713")} box ${color.bold(name)}: ${autoHibernateText(box.autoHibernateSec, box.idleCheck)}`);
3932
- if (idleCheck && !box.autoHibernateSec) info(color.dim(` the idle check is used once auto-hibernate is on: kvbox vm set ${name} --auto-hibernate 10m`));
4462
+ if (hostSettings) info(`${color.green("\u2713")} box ${color.bold(name)}: ${autoHibernateText(box2.autoHibernateSec, box2.idleCheck)}`);
4463
+ if (idleCheck && !box2.autoHibernateSec) info(color.dim(` the idle check is used once auto-hibernate is on: kvbox vm set ${name} --auto-hibernate 10m`));
3933
4464
  if (swap) info(`${color.green("\u2713")} box ${color.bold(name)}: ${swapText(swap)}`);
3934
4465
  } finally {
3935
4466
  await client.close();
@@ -3938,8 +4469,8 @@ var setCommand = new Command29("set").description("change a box's settings, e.g.
3938
4469
  async function setSwap(client, found, name, mib, cmd) {
3939
4470
  const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
3940
4471
  const wasRunning = found.status === "running";
3941
- const box = wasRunning ? found : await wakeUp(client, found, displayName(found, me(client)));
3942
- const ep = sshEndpoint(box, client.target);
4472
+ const box2 = wasRunning ? found : await wakeUp(client, found, displayName(found, me(client)));
4473
+ const ep = sshEndpoint(box2, client.target);
3943
4474
  if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
3944
4475
  const what = mib === 0 ? `removing ${name}'s swap\u2026` : `setting up ${mib >= 1024 ? `${mib / 1024}G` : `${mib}M`} of swap in ${name}\u2026`;
3945
4476
  let result = await spin(what, runSwap(ep, mib));
@@ -3961,8 +4492,8 @@ function swapText(s) {
3961
4492
  const size = s.sizeMib % 1024 === 0 ? `${s.sizeMib / 1024} GB` : `${s.sizeMib} MB`;
3962
4493
  return `${size} swap (${s.usedMib} MB used, zswap ${s.zswap ? "on" : "off"})`;
3963
4494
  }
3964
- function idleCheckKept(asked, box) {
3965
- return asked === void 0 || (box.idleCheck ?? "") === asked;
4495
+ function idleCheckKept(asked, box2) {
4496
+ return asked === void 0 || (box2.idleCheck ?? "") === asked;
3966
4497
  }
3967
4498
  function parseIdleCheck(text2) {
3968
4499
  const t = text2.trim();
@@ -3976,9 +4507,9 @@ import { Command as Command30 } from "commander";
3976
4507
  var startCommand = new Command30("start").description("boot a stopped box again (same name, IP and disk)").argument("<name>", "box name").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
3977
4508
  const client = await clientFor(cmd.optsWithGlobals());
3978
4509
  try {
3979
- const box = await spin(`booting ${name}\u2026`, client.startMachine(name, opts.force ?? false));
3980
- if (opts.json) json(box);
3981
- else info(`${color.green("\u2713")} ${describe(box)}`);
4510
+ const box2 = await spin(`booting ${name}\u2026`, client.startMachine(name, opts.force ?? false));
4511
+ if (opts.json) json(box2);
4512
+ else info(`${color.green("\u2713")} ${describe(box2)}`);
3982
4513
  } finally {
3983
4514
  await client.close();
3984
4515
  }
@@ -3989,8 +4520,8 @@ import { Command as Command31 } from "commander";
3989
4520
  var stopCommand = new Command31("stop").description("shut a box down (its disk is kept; start it again with kvbox start)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
3990
4521
  const client = await clientFor(cmd.optsWithGlobals());
3991
4522
  try {
3992
- const box = await spin(`shutting ${name} down\u2026`, client.stopMachine(name));
3993
- if (opts.json) json(box);
4523
+ const box2 = await spin(`shutting ${name} down\u2026`, client.stopMachine(name));
4524
+ if (opts.json) json(box2);
3994
4525
  else info(`${color.green("\u2713")} box ${name} stopped (disk kept; kvbox start ${name} boots it again)`);
3995
4526
  } finally {
3996
4527
  await client.close();
@@ -4087,16 +4618,16 @@ var updateCommand = new Command34("update").description("move a box onto the cur
4087
4618
  try {
4088
4619
  const before = pickRef(await boxesFor(client, name), name, me(client));
4089
4620
  if (!before) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
4090
- const box = await spin(`updating ${name}\u2026`, client.updateMachine(displayName(before, me(client))));
4621
+ const box2 = await spin(`updating ${name}\u2026`, client.updateMachine(displayName(before, me(client))));
4091
4622
  if (opts.json) {
4092
- json(box);
4623
+ json(box2);
4093
4624
  return;
4094
4625
  }
4095
- if (box.base === before.base) {
4096
- info(`box ${name} is already on base image ${box.base}`);
4626
+ if (box2.base === before.base) {
4627
+ info(`box ${name} is already on base image ${box2.base}`);
4097
4628
  } else {
4098
4629
  const restarted = before.status === "running" ? " (restarted: processes that were running are gone, files are intact)" : "";
4099
- info(`${color.green("\u2713")} box ${color.bold(name)} now runs on base image ${box.base} (was ${before.base})${restarted}`);
4630
+ info(`${color.green("\u2713")} box ${color.bold(name)} now runs on base image ${box2.base} (was ${before.base})${restarted}`);
4100
4631
  }
4101
4632
  } finally {
4102
4633
  await client.close();
@@ -4156,8 +4687,8 @@ import { Command as Command36 } from "commander";
4156
4687
  var wakeCommand = new Command36("wake").description("continue a hibernated box where it left off (same name, IP and disk)").argument("<name>", "box name").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
4157
4688
  const client = await clientFor(cmd.optsWithGlobals());
4158
4689
  try {
4159
- const box = await spin(`waking ${name} (loading its memory from disk)\u2026`, client.wakeMachine(name, opts.force ?? false));
4160
- if (opts.json) json(box);
4690
+ const box2 = await spin(`waking ${name} (loading its memory from disk)\u2026`, client.wakeMachine(name, opts.force ?? false));
4691
+ if (opts.json) json(box2);
4161
4692
  else info(`${color.green("\u2713")} box ${name} is awake, running where it left off`);
4162
4693
  } finally {
4163
4694
  await client.close();
@@ -4172,7 +4703,7 @@ var vmAliases = [newCommand, lsCommand, getCommand, connectCommand, execCommand,
4172
4703
  // src/commands/login.ts
4173
4704
  import { hostname as osHostname2 } from "os";
4174
4705
  import { createInterface as createInterface2 } from "readline/promises";
4175
- import { setTimeout as sleep3 } from "timers/promises";
4706
+ import { setTimeout as sleep4 } from "timers/promises";
4176
4707
  import { Writable } from "stream";
4177
4708
  import { Command as Command38 } from "commander";
4178
4709
 
@@ -4254,7 +4785,7 @@ async function storeLogin(url, res, p) {
4254
4785
  await writeSession(session, p);
4255
4786
  return session;
4256
4787
  }
4257
- var terminalIo = { say: info, sleep: sleep3, open: openBrowser, wait: (message, work) => spin(message, work) };
4788
+ var terminalIo = { say: info, sleep: sleep4, open: openBrowser, wait: (message, work) => spin(message, work) };
4258
4789
  async function runDeviceLogin(url, p = paths(), hostname = osHostname2(), io = terminalIo) {
4259
4790
  const publicKey = await ensureSshKey(p, hostname);
4260
4791
  const client = new ServerClient({ kind: "cloud", url, token: "" }, { autoStart: false });
@@ -4520,13 +5051,13 @@ var lsCommand6 = new Command45("ls").description("list snapshots (yours and your
4520
5051
 
4521
5052
  // src/commands/snapshots/new.ts
4522
5053
  import { Command as Command46 } from "commander";
4523
- var newCommand2 = new Command46("new").description("freeze a running box (memory + disk) into a snapshot; the box keeps running").argument("<box>", "box name").argument("<name>", "snapshot name").option("--replace", "retake a snapshot that exists under this name; the old one stays until the new one is complete").option("--json", "print the snapshot as JSON").action(async (box, name, opts, cmd) => {
5054
+ var newCommand2 = new Command46("new").description("freeze a running box (memory + disk) into a snapshot; the box keeps running").argument("<box>", "box name").argument("<name>", "snapshot name").option("--replace", "retake a snapshot that exists under this name; the old one stays until the new one is complete").option("--json", "print the snapshot as JSON").action(async (box2, name, opts, cmd) => {
4524
5055
  const client = await clientFor(cmd.optsWithGlobals());
4525
5056
  try {
4526
- const req = { box, name, ...opts.replace ? { replace: true } : {} };
4527
- const snap = await spin(`saving snapshot ${name} from box ${box} (memory + disk)\u2026`, client.createSnapshot(req));
5057
+ const req = { box: box2, name, ...opts.replace ? { replace: true } : {} };
5058
+ const snap = await spin(`saving snapshot ${name} from box ${box2} (memory + disk)\u2026`, client.createSnapshot(req));
4528
5059
  if (opts.json) json(snap);
4529
- else info(`${color.green("\u2713")} snapshot ${name} ${opts.replace ? "retaken" : "saved"} from box ${box} (${gb(snap.sizeBytes)} on disk); start a warm clone with: kvbox new --from ${name}`);
5060
+ else info(`${color.green("\u2713")} snapshot ${name} ${opts.replace ? "retaken" : "saved"} from box ${box2} (${gb(snap.sizeBytes)} on disk); start a warm clone with: kvbox new --from ${name}`);
4530
5061
  } finally {
4531
5062
  await client.close();
4532
5063
  }
@@ -4932,7 +5463,7 @@ import { Command as Command58, InvalidArgumentError as InvalidArgumentError2, Op
4932
5463
  // src/commands/deploy/config.ts
4933
5464
  import { readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
4934
5465
  import { isAbsolute, join as join6, normalize, relative as relative2 } from "path";
4935
- import { z as z8 } from "zod";
5466
+ import { z as z12 } from "zod";
4936
5467
 
4937
5468
  // src/commands/deploy/templates/docker.ts
4938
5469
  import { readFile as readFile4 } from "fs/promises";
@@ -5356,21 +5887,21 @@ function detectTemplates(pkg, dir = NO_FACTS) {
5356
5887
  var DEPLOY_AUTO_HIBERNATE_SEC = 3600;
5357
5888
  var CONFIG_FILE = "kvbox.json";
5358
5889
  var BOX_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
5359
- var DeployConfigSchema = z8.object({
5360
- template: z8.enum(TEMPLATE_IDS),
5361
- name: z8.string().regex(BOX_NAME_RE, "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit"),
5890
+ var DeployConfigSchema = z12.object({
5891
+ template: z12.enum(TEMPLATE_IDS),
5892
+ name: z12.string().regex(BOX_NAME_RE, "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit"),
5362
5893
  /** The org whose box it is; absent for the user's own. */
5363
- org: z8.string().regex(ORG_SLUG_RE, "not an org slug").optional(),
5894
+ org: z12.string().regex(ORG_SLUG_RE, "not an org slug").optional(),
5364
5895
  /** The HTTPS name (`<subdomain>.kvbox.app`); absent when deploying to this machine's own host. */
5365
- subdomain: z8.string().check((ctx) => {
5896
+ subdomain: z12.string().check((ctx) => {
5366
5897
  const problem = subdomainProblem(ctx.value);
5367
5898
  if (problem) ctx.issues.push({ code: "custom", message: problem, input: ctx.value });
5368
5899
  }).optional(),
5369
- size: z8.enum(SIZE_NAMES).optional(),
5900
+ size: z12.enum(SIZE_NAMES).optional(),
5370
5901
  /** The build output directory, relative to the app; the template's default when absent. */
5371
- dist: z8.string().optional(),
5902
+ dist: z12.string().optional(),
5372
5903
  /** The port a Next.js app or Node server serves; the template's (3000) when absent. */
5373
- port: z8.number().int().min(1).max(65535).optional()
5904
+ port: z12.number().int().min(1).max(65535).optional()
5374
5905
  });
5375
5906
  var SERVICE_KEY_RE = /^[a-z][a-z0-9-]{0,19}$/;
5376
5907
  var RESERVED_SERVICE_KEYS = ["app", "agent", "init", "volumes"];
@@ -5382,38 +5913,38 @@ var POSTGRES_PORT = 5432;
5382
5913
  var POSTGRES_IMAGE = "postgres:17";
5383
5914
  var POSTGRES_ENV = "DATABASE_URL";
5384
5915
  var IMAGE_RE = /^[a-z0-9][a-z0-9._/:@-]*$/;
5385
- var ServiceSchema = z8.strictObject({
5386
- template: z8.enum([...TEMPLATE_IDS, POSTGRES]),
5916
+ var ServiceSchema = z12.strictObject({
5917
+ template: z12.enum([...TEMPLATE_IDS, POSTGRES]),
5387
5918
  /** The service's directory, relative to the one holding kvbox.json; every template but postgres has one. */
5388
- dir: z8.string().min(1).optional(),
5919
+ dir: z12.string().min(1).optional(),
5389
5920
  /** A postgres service's image, `postgres:17` when absent (`pgvector/pgvector:pg17` for vectors). */
5390
- image: z8.string().regex(IMAGE_RE, "an image name like postgres:17").optional(),
5921
+ image: z12.string().regex(IMAGE_RE, "an image name like postgres:17").optional(),
5391
5922
  /** The volume (a key of `volumes`) a postgres service keeps its data on. */
5392
- volume: z8.string().optional(),
5923
+ volume: z12.string().optional(),
5393
5924
  /** The box variable a postgres service's URL is written to, `DATABASE_URL` when absent. */
5394
- env: z8.string().optional(),
5925
+ env: z12.string().optional(),
5395
5926
  /** 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`. */
5396
- context: z8.string().min(1).optional(),
5397
- dist: z8.string().optional(),
5927
+ context: z12.string().min(1).optional(),
5928
+ dist: z12.string().optional(),
5398
5929
  /**
5399
5930
  * A command run once per deploy in the service's new version (a docker service: in a container of
5400
5931
  * the new image; node, nextjs: in the new source, installed and built), with the box's variables,
5401
5932
  * before it replaces the running one. Migrations, mostly. A failing one stops that service's deploy.
5402
5933
  */
5403
- release: z8.string().optional(),
5934
+ release: z12.string().optional(),
5404
5935
  /** The box port of a service with its own server; the template's (3000) when absent. */
5405
- port: z8.number().int().min(1).max(65535).optional(),
5936
+ port: z12.number().int().min(1).max(65535).optional(),
5406
5937
  /** The URL paths that go to this service, each with everything under it; the prefix is kept. */
5407
- paths: z8.array(z8.string().regex(ROUTE_RE, "a path like / or /api, no trailing slash")).min(1).optional()
5938
+ paths: z12.array(z12.string().regex(ROUTE_RE, "a path like / or /api, no trailing slash")).min(1).optional()
5408
5939
  });
5409
- var StackConfigSchema = z8.strictObject({
5940
+ var StackConfigSchema = z12.strictObject({
5410
5941
  name: DeployConfigSchema.shape.name.optional(),
5411
5942
  org: DeployConfigSchema.shape.org,
5412
5943
  subdomain: DeployConfigSchema.shape.subdomain,
5413
5944
  size: DeployConfigSchema.shape.size,
5414
5945
  /** The stack's volumes, name to size ("10GB"): made for its box and attached to it on the first deploy that needs one. */
5415
- volumes: z8.record(z8.string(), z8.string()).optional(),
5416
- services: z8.record(z8.string(), ServiceSchema)
5946
+ volumes: z12.record(z12.string(), z12.string()).optional(),
5947
+ services: z12.record(z12.string(), ServiceSchema)
5417
5948
  });
5418
5949
  function volumeGib(text2) {
5419
5950
  const mib = parseMib(text2);
@@ -5645,14 +6176,14 @@ async function findOrCreate(client, config) {
5645
6176
  const user = me(client);
5646
6177
  const slug = config.org ?? user;
5647
6178
  const named = (await client.listMachines()).filter((b) => b.name === config.name);
5648
- let box = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
6179
+ let box2 = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
5649
6180
  let created = false;
5650
- if (!box) {
5651
- 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 }));
6181
+ if (!box2) {
6182
+ box2 = 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 }));
5652
6183
  created = true;
5653
- info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);
6184
+ info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box2.vcpu} vCPU, ${gb(box2.memMib * 1024 ** 2)} RAM, ${gb(box2.diskBytes)} disk`);
5654
6185
  }
5655
- return { box, ref: displayName(box, user), created };
6186
+ return { box: box2, ref: displayName(box2, user), created };
5656
6187
  }
5657
6188
  async function existingAddresses(client, config) {
5658
6189
  const slug = config.org ?? me(client);
@@ -5666,8 +6197,8 @@ async function refuseOtherAddress(client, config) {
5666
6197
  `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>`
5667
6198
  );
5668
6199
  }
5669
- async function address(client, box, ref, config, port) {
5670
- const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
6200
+ async function address(client, box2, ref, config, port) {
6201
+ const subs = (await client.listSubdomains()).filter((s) => s.box === box2.name && s.owner === slugOf(box2.owner));
5671
6202
  const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
5672
6203
  if (have) {
5673
6204
  if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
@@ -5870,7 +6401,7 @@ async function deployStack(d) {
5870
6401
  if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, { ...config, name: config.name });
5871
6402
  let saved = config;
5872
6403
  if (JSON.stringify(saved) !== JSON.stringify(d.stack)) await writeConfig(dir, saved);
5873
- const box = { name: config.name, org: config.org, subdomain: config.subdomain, size: config.size };
6404
+ const box2 = { name: config.name, org: config.org, subdomain: config.subdomain, size: config.size };
5874
6405
  const all = [];
5875
6406
  for (const service of picked) {
5876
6407
  if (service.postgres) continue;
@@ -5887,7 +6418,7 @@ async function deployStack(d) {
5887
6418
  all.push({ service, template, built, size: await shipping.measure(built.outDir, built.exclude) });
5888
6419
  }
5889
6420
  info("");
5890
- const { box: found, ref, created } = await findOrCreate(client, box);
6421
+ const { box: found, ref, created } = await findOrCreate(client, box2);
5891
6422
  const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
5892
6423
  const wasRunning = !created && found.status === "running";
5893
6424
  const machine = created || wasRunning ? found : await wakeUp(client, found, ref);
@@ -5927,7 +6458,7 @@ ${front.output.trim()}`);
5927
6458
  const missing = picked.length < services.length ? await neverShipped(ep, services.filter((s) => !picked.includes(s))) : [];
5928
6459
  let url = `http://${machine.ip}`;
5929
6460
  if (cloud) {
5930
- const got = await address(client, machine, ref, box, FRONT_PORT);
6461
+ const got = await address(client, machine, ref, box2, FRONT_PORT);
5931
6462
  url = got.url;
5932
6463
  if (got.subdomain !== saved.subdomain) await writeConfig(dir, { ...saved, subdomain: got.subdomain });
5933
6464
  }
@@ -6143,14 +6674,14 @@ async function settle(d) {
6143
6674
  const volumes = { ...stack.volumes };
6144
6675
  const services = { ...stack.services };
6145
6676
  for (const key of open.volumes) {
6146
- let volume = volumeNameFor(name, volumes, accountVolumes);
6677
+ let volume2 = volumeNameFor(name, volumes, accountVolumes);
6147
6678
  let gib = `${VOLUME_GIB}GB`;
6148
6679
  if (ask) {
6149
- 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 });
6680
+ volume2 = await text(`Volume for ${key}'s data`, { default: volume2, 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 });
6150
6681
  gib = await text("Volume size", { default: gib, validate: (a) => volumeGib(a) === void 0 ? "whole GB, like 10GB" : void 0 });
6151
6682
  }
6152
- volumes[volume] = gib;
6153
- services[key] = { ...services[key], volume };
6683
+ volumes[volume2] = gib;
6684
+ services[key] = { ...services[key], volume: volume2 };
6154
6685
  }
6155
6686
  if (ask) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
6156
6687
  `);
@@ -6165,20 +6696,20 @@ async function settle(d) {
6165
6696
  };
6166
6697
  }
6167
6698
  var VOLUME_GIB = 10;
6168
- function defaultVolumes(box, stackVolumes, account, keys) {
6699
+ function defaultVolumes(box2, stackVolumes, account, keys) {
6169
6700
  const taken = { ...stackVolumes };
6170
6701
  return keys.map((key) => {
6171
- const v = volumeNameFor(box, taken, account);
6702
+ const v = volumeNameFor(box2, taken, account);
6172
6703
  taken[v] = `${VOLUME_GIB}GB`;
6173
6704
  return [key, v];
6174
6705
  });
6175
6706
  }
6176
- function volumeNameFor(box, taken, account = /* @__PURE__ */ new Set()) {
6707
+ function volumeNameFor(box2, taken, account = /* @__PURE__ */ new Set()) {
6177
6708
  const free = (n) => taken[n] === void 0 && !account.has(n);
6178
- const base = `${box.slice(0, 9).replace(/-+$/, "")}-db`;
6709
+ const base = `${box2.slice(0, 9).replace(/-+$/, "")}-db`;
6179
6710
  if (free(base)) return base;
6180
6711
  for (let i = 2; ; i++) {
6181
- const n = `${box.slice(0, 8).replace(/-+$/, "")}-db${i}`;
6712
+ const n = `${box2.slice(0, 8).replace(/-+$/, "")}-db${i}`;
6182
6713
  if (free(n)) return n;
6183
6714
  }
6184
6715
  }
@@ -6223,22 +6754,22 @@ var deployCommand = new Command58("deploy").description("put the app in this dir
6223
6754
  const { box: found, ref, created } = await findOrCreate(client, config);
6224
6755
  const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
6225
6756
  const wasRunning = !created && found.status === "running";
6226
- const box = created || wasRunning ? found : await wakeUp(client, found, ref);
6227
- const ep = sshEndpoint(box, client.target);
6757
+ const box2 = created || wasRunning ? found : await wakeUp(client, found, ref);
6758
+ const ep = sshEndpoint(box2, client.target);
6228
6759
  if (!wasRunning) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(ep));
6229
6760
  const port = config.port ?? template.port;
6230
6761
  const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port), built.exclude);
6231
6762
  const there = built.boxBuild ? "installing and building there" : "installing there";
6232
6763
  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`;
6233
6764
  let result = await spin(doing, shipIt);
6234
- if (result.status === SSH_FAILED3 && await renewAfterRefusal(client, cert, box.owner)) {
6765
+ if (result.status === SSH_FAILED3 && await renewAfterRefusal(client, cert, box2.owner)) {
6235
6766
  info("renewed your SSH certificate, trying again\u2026");
6236
6767
  result = await spin(doing, shipIt);
6237
6768
  }
6238
6769
  refuseFailedShip(result, { ref, template, port, built });
6239
- let url = `http://${box.ip}${port === 80 ? "" : `:${port}`}`;
6770
+ let url = `http://${box2.ip}${port === 80 ? "" : `:${port}`}`;
6240
6771
  if (cloud) {
6241
- const got = await address(client, box, ref, config, port);
6772
+ const got = await address(client, box2, ref, config, port);
6242
6773
  url = got.url;
6243
6774
  if (got.subdomain !== config.subdomain) await writeConfig(dir, { ...config, subdomain: got.subdomain, ...built.dist !== void 0 && built.dist !== config.dist ? { dist: built.dist } : {} });
6244
6775
  }
@@ -6353,23 +6884,23 @@ import { Command as Command69 } from "commander";
6353
6884
 
6354
6885
  // src/commands/volume/attach.ts
6355
6886
  import { Command as Command59 } from "commander";
6356
- function describeMount(machine, volume, box) {
6357
- const path = machine.volumes?.find((v) => volume === v.name || volume.endsWith(`/${v.name}`))?.mountPath ?? volumeMountPath(volume.slice(volume.lastIndexOf("/") + 1));
6358
- return machine.status === "running" ? ` the box was restarted; the volume is at ${path} inside it` : ` box ${box} is ${machine.status}; the volume is at ${path} once it runs`;
6887
+ function describeMount(machine, volume2, box2) {
6888
+ const path = machine.volumes?.find((v) => volume2 === v.name || volume2.endsWith(`/${v.name}`))?.mountPath ?? volumeMountPath(volume2.slice(volume2.lastIndexOf("/") + 1));
6889
+ return machine.status === "running" ? ` the box was restarted; the volume is at ${path} inside it` : ` box ${box2} is ${machine.status}; the volume is at ${path} once it runs`;
6359
6890
  }
6360
6891
  var attachCommand = new Command59("attach").description("attach a volume to a box at /mnt/<volume> (a running box is restarted to take it)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (picked from a list when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
6361
6892
  if (volumeArg === void 0 || boxArg === void 0) askOrUsage("give the volume and the box: kvbox volume attach <volume> <box>");
6362
6893
  const client = await clientFor(cmd.optsWithGlobals());
6363
6894
  try {
6364
- const volume = volumeArg ?? (await pickVolume(client, (v) => v.attachedTo === null, "no volume is free to attach (kvbox volume ls); make one with kvbox volume new")).ref;
6365
- const box = boxArg ?? await pickBox(client);
6366
- const machine = await spin(`attaching volume ${volume} to box ${box} (a running box is restarted)\u2026`, client.attachVolume(volume, { box }));
6895
+ const volume2 = volumeArg ?? (await pickVolume(client, (v) => v.attachedTo === null, "no volume is free to attach (kvbox volume ls); make one with kvbox volume new")).ref;
6896
+ const box2 = boxArg ?? await pickBox(client);
6897
+ const machine = await spin(`attaching volume ${volume2} to box ${box2} (a running box is restarted)\u2026`, client.attachVolume(volume2, { box: box2 }));
6367
6898
  if (opts.json) {
6368
6899
  json(machine);
6369
6900
  return;
6370
6901
  }
6371
- info(`${color.green("\u2713")} volume ${volume} attached to box ${box}`);
6372
- info(describeMount(machine, volume, box));
6902
+ info(`${color.green("\u2713")} volume ${volume2} attached to box ${box2}`);
6903
+ info(describeMount(machine, volume2, box2));
6373
6904
  } finally {
6374
6905
  await client.close();
6375
6906
  }
@@ -6380,25 +6911,25 @@ import { Command as Command63 } from "commander";
6380
6911
 
6381
6912
  // src/commands/volume/backup/create.ts
6382
6913
  import { Command as Command60 } from "commander";
6383
- var createCommand4 = new Command60("create").description("back up a volume's disk to the kvbox cloud (encrypted)").argument("<volume>", "volume name").option("--wait", "stay until the backup is ready (by default it runs in the background)").option("--json", "print the backup as JSON").action(async (volume, opts, cmd) => {
6914
+ var createCommand4 = new Command60("create").description("back up a volume's disk to the kvbox cloud (encrypted)").argument("<volume>", "volume name").option("--wait", "stay until the backup is ready (by default it runs in the background)").option("--json", "print the backup as JSON").action(async (volume2, opts, cmd) => {
6384
6915
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
6385
6916
  try {
6386
6917
  requireCloud3(client);
6387
- const started = await client.createVolumeBackup(volume);
6918
+ const started = await client.createVolumeBackup(volume2);
6388
6919
  if (!opts.wait) {
6389
6920
  if (opts.json) json(started);
6390
6921
  else {
6391
- info(`${color.green("\u2713")} backup ${started.id} of volume ${color.bold(volume)} started; it runs in the background`);
6392
- info(color.dim(` status: kvbox volume backup ls ${volume}`));
6922
+ info(`${color.green("\u2713")} backup ${started.id} of volume ${color.bold(volume2)} started; it runs in the background`);
6923
+ info(color.dim(` status: kvbox volume backup ls ${volume2}`));
6393
6924
  }
6394
6925
  return;
6395
6926
  }
6396
- const done = await spin(`backing up volume ${volume}\u2026`, untilSettled(() => client.volumeBackup(volume, started.id), `volume ${volume}`, started.id, `kvbox volume backup ls ${volume}`));
6927
+ const done = await spin(`backing up volume ${volume2}\u2026`, untilSettled(() => client.volumeBackup(volume2, started.id), `volume ${volume2}`, started.id, `kvbox volume backup ls ${volume2}`));
6397
6928
  if (opts.json) json(done);
6398
- if (done.status === "failed") throw new KvboxError(`backup ${done.id} of volume ${volume} failed: ${done.error ?? "no reason given"}`);
6929
+ if (done.status === "failed") throw new KvboxError(`backup ${done.id} of volume ${volume2} failed: ${done.error ?? "no reason given"}`);
6399
6930
  if (opts.json) return;
6400
- info(`${color.green("\u2713")} backup ${done.id} of volume ${color.bold(volume)}: ${sizeLine(done)}`);
6401
- info(color.dim(` restore with: kvbox volume backup restore ${volume} ${done.id}`));
6931
+ info(`${color.green("\u2713")} backup ${done.id} of volume ${color.bold(volume2)}: ${sizeLine(done)}`);
6932
+ info(color.dim(` restore with: kvbox volume backup restore ${volume2} ${done.id}`));
6402
6933
  } finally {
6403
6934
  await client.close();
6404
6935
  }
@@ -6406,24 +6937,24 @@ var createCommand4 = new Command60("create").description("back up a volume's dis
6406
6937
 
6407
6938
  // src/commands/volume/backup/ls.ts
6408
6939
  import { Command as Command61 } from "commander";
6409
- var lsCommand9 = new Command61("ls").alias("list").description("list volume backups: every volume's, or one volume's").argument("[volume]", "volume name (default: every volume)").option("--json", "print as JSON").action(async (volume, opts, cmd) => {
6940
+ var lsCommand9 = new Command61("ls").alias("list").description("list volume backups: every volume's, or one volume's").argument("[volume]", "volume name (default: every volume)").option("--json", "print as JSON").action(async (volume2, opts, cmd) => {
6410
6941
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
6411
6942
  try {
6412
6943
  requireCloud3(client);
6413
- const list = volume === void 0 ? await client.listVolumeBackups() : await client.volumeBackups(volume);
6944
+ const list = volume2 === void 0 ? await client.listVolumeBackups() : await client.volumeBackups(volume2);
6414
6945
  if (opts.json) {
6415
6946
  json(list);
6416
6947
  return;
6417
6948
  }
6418
6949
  if (list.length === 0) {
6419
- info(volume === void 0 ? "no volume backups yet; make one with: kvbox volume backup create <volume>" : `volume ${volume} has no backups; make one with: kvbox volume backup create ${volume}`);
6950
+ info(volume2 === void 0 ? "no volume backups yet; make one with: kvbox volume backup create <volume>" : `volume ${volume2} has no backups; make one with: kvbox volume backup create ${volume2}`);
6420
6951
  return;
6421
6952
  }
6422
6953
  const anyError = list.some((b) => b.error !== null);
6423
6954
  table(
6424
6955
  list.map((b) => ({
6425
6956
  id: b.id,
6426
- ...volume === void 0 ? { volume: b.owner === me(client) ? b.volume : `${b.owner}/${b.volume}` } : {},
6957
+ ...volume2 === void 0 ? { volume: b.owner === me(client) ? b.volume : `${b.owner}/${b.volume}` } : {},
6427
6958
  status: b.status === "ready" ? color.green(b.status) : b.status === "failed" ? color.red(b.status) : color.yellow(b.status),
6428
6959
  data: b.dataBytes === null ? "-" : gbShort(b.dataBytes),
6429
6960
  uploaded: b.uploadedBytes === null ? "-" : gbShort(b.uploadedBytes),
@@ -6440,23 +6971,23 @@ var lsCommand9 = new Command61("ls").alias("list").description("list volume back
6440
6971
 
6441
6972
  // src/commands/volume/backup/restore.ts
6442
6973
  import { Command as Command62 } from "commander";
6443
- var restoreCommand2 = new Command62("restore").description("put a backup back: the volume's data becomes the backup's (a running box holding it restarts)").argument("<volume>", "volume name").argument("<id>", "the backup's id (kvbox volume backup ls <volume>)").option("-y, --yes", "do not ask for confirmation").option("--json", "print the volume as JSON").action(async (volume, id, opts, cmd) => {
6974
+ var restoreCommand2 = new Command62("restore").description("put a backup back: the volume's data becomes the backup's (a running box holding it restarts)").argument("<volume>", "volume name").argument("<id>", "the backup's id (kvbox volume backup ls <volume>)").option("-y, --yes", "do not ask for confirmation").option("--json", "print the volume as JSON").action(async (volume2, id, opts, cmd) => {
6444
6975
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
6445
6976
  try {
6446
6977
  requireCloud3(client);
6447
- const backup = await client.volumeBackup(volume, id);
6448
- const question = `Restore volume ${volume} from backup ${backup.id} (${age(backup.createdAt)} ago, ${sizeLine(backup)})? Everything written to it since is lost, and a running box that holds it restarts.`;
6978
+ const backup = await client.volumeBackup(volume2, id);
6979
+ const question = `Restore volume ${volume2} from backup ${backup.id} (${age(backup.createdAt)} ago, ${sizeLine(backup)})? Everything written to it since is lost, and a running box that holds it restarts.`;
6449
6980
  if (!await confirm(question, opts.yes ?? false)) {
6450
6981
  info("cancelled");
6451
6982
  process.exitCode = 1;
6452
6983
  return;
6453
6984
  }
6454
- const restored = await spin(`restoring volume ${volume} from ${backup.id}\u2026`, client.restoreVolumeBackup(volume, id));
6985
+ const restored = await spin(`restoring volume ${volume2} from ${backup.id}\u2026`, client.restoreVolumeBackup(volume2, id));
6455
6986
  if (opts.json) {
6456
6987
  json(restored);
6457
6988
  return;
6458
6989
  }
6459
- info(`${color.green("\u2713")} volume ${color.bold(volume)} restored from backup ${backup.id}${restored.attachedTo ? color.dim(` (box ${restored.attachedTo} was restarted if it was running)`) : ""}`);
6990
+ info(`${color.green("\u2713")} volume ${color.bold(volume2)} restored from backup ${backup.id}${restored.attachedTo ? color.dim(` (box ${restored.attachedTo} was restarted if it was running)`) : ""}`);
6460
6991
  } finally {
6461
6992
  await client.close();
6462
6993
  }
@@ -6521,21 +7052,21 @@ var detachCommand = new Command65("detach").description("detach a volume from a
6521
7052
  if (volumeArg === void 0) askOrUsage("give the volume: kvbox volume detach <volume> [box]");
6522
7053
  const client = await clientFor(cmd.optsWithGlobals());
6523
7054
  try {
6524
- let volume = volumeArg;
6525
- let box = boxArg;
6526
- if (volume === void 0 || box === void 0) {
6527
- const found = volume === void 0 ? await pickVolume(client, (v) => v.attachedTo !== null, "no volume is attached to a box (kvbox volume ls)") : pickRef(await spin("finding the volume\u2026", client.listVolumes()), volume, me(client), "volume");
6528
- if (!found) throw new KvboxError(`volume ${volume}: not found (kvbox volume ls)`);
6529
- if (found.attachedTo === null) throw new KvboxError(`volume ${volume}: not attached to a box`);
6530
- volume ??= refOf(found, me(client));
6531
- box ??= refOf({ name: found.attachedTo, owner: found.owner }, me(client));
7055
+ let volume2 = volumeArg;
7056
+ let box2 = boxArg;
7057
+ if (volume2 === void 0 || box2 === void 0) {
7058
+ const found = volume2 === void 0 ? await pickVolume(client, (v) => v.attachedTo !== null, "no volume is attached to a box (kvbox volume ls)") : pickRef(await spin("finding the volume\u2026", client.listVolumes()), volume2, me(client), "volume");
7059
+ if (!found) throw new KvboxError(`volume ${volume2}: not found (kvbox volume ls)`);
7060
+ if (found.attachedTo === null) throw new KvboxError(`volume ${volume2}: not attached to a box`);
7061
+ volume2 ??= refOf(found, me(client));
7062
+ box2 ??= refOf({ name: found.attachedTo, owner: found.owner }, me(client));
6532
7063
  }
6533
- const machine = await spin(`detaching volume ${volume} from box ${box} (a running box is restarted)\u2026`, client.detachVolume(volume, { box }));
7064
+ const machine = await spin(`detaching volume ${volume2} from box ${box2} (a running box is restarted)\u2026`, client.detachVolume(volume2, { box: box2 }));
6534
7065
  if (opts.json) {
6535
7066
  json(machine);
6536
7067
  return;
6537
7068
  }
6538
- info(`${color.green("\u2713")} volume ${volume} detached from box ${box}; its data is kept${machine.status === "running" ? " (the box was restarted)" : ""}`);
7069
+ info(`${color.green("\u2713")} volume ${volume2} detached from box ${box2}; its data is kept${machine.status === "running" ? " (the box was restarted)" : ""}`);
6539
7070
  } finally {
6540
7071
  await client.close();
6541
7072
  }
@@ -6996,7 +7527,7 @@ function timeoutOf(value) {
6996
7527
  if (sec > MAX_CRON_COMMAND_TIMEOUT_SEC) throw new KvboxError(`--timeout ${value}: a command may run for ${MAX_CRON_COMMAND_TIMEOUT_SEC / 60} minutes at most`);
6997
7528
  return sec;
6998
7529
  }
6999
- var addCommand3 = new Command84("add").description("add a trigger: on a schedule, call a port of a box or run a command in it").argument("<service>", "cron service name").argument("<box>", "the box it acts on").argument("<expr>", 'cron expression in quotes, five fields: "0 6 * * *" is every day at 06:00').option("--port <n>", "call this port, the one your app listens on in the box").option("--path <path>", "with --port: path and query to request (default: /)").option("--method <method>", `with --port: HTTP method, ${CRON_METHODS.join(" or ")} (default: POST)`).option("--run <command>", 'or run this command in the box, in quotes: "node ~/app/embed.js"').option("--timeout <duration>", `with --run: stop the command after this long (90s, 10m, 1h; default: ${DEFAULT_CRON_COMMAND_TIMEOUT_SEC / 60}m)`).option("--tz <zone>", "time zone the schedule is read in, like Europe/Bucharest", "UTC").option("--json", "print as JSON").action(async (service, box, expr, opts, cmd) => {
7530
+ var addCommand3 = new Command84("add").description("add a trigger: on a schedule, call a port of a box or run a command in it").argument("<service>", "cron service name").argument("<box>", "the box it acts on").argument("<expr>", 'cron expression in quotes, five fields: "0 6 * * *" is every day at 06:00').option("--port <n>", "call this port, the one your app listens on in the box").option("--path <path>", "with --port: path and query to request (default: /)").option("--method <method>", `with --port: HTTP method, ${CRON_METHODS.join(" or ")} (default: POST)`).option("--run <command>", 'or run this command in the box, in quotes: "node ~/app/embed.js"').option("--timeout <duration>", `with --run: stop the command after this long (90s, 10m, 1h; default: ${DEFAULT_CRON_COMMAND_TIMEOUT_SEC / 60}m)`).option("--tz <zone>", "time zone the schedule is read in, like Europe/Bucharest", "UTC").option("--json", "print as JSON").action(async (service, box2, expr, opts, cmd) => {
7000
7531
  let action;
7001
7532
  if (opts.run !== void 0) {
7002
7533
  if (opts.port !== void 0 || opts.path !== void 0 || opts.method !== void 0) throw new KvboxError("a trigger runs a command or calls a port: use --run, or --port with --path and --method, not both");
@@ -7009,7 +7540,7 @@ var addCommand3 = new Command84("add").description("add a trigger: on a schedule
7009
7540
  }
7010
7541
  const client = await cronClient(cmd);
7011
7542
  try {
7012
- const trigger = await client.addCronTrigger(service, { box, expr, timezone: opts.tz, ...action });
7543
+ const trigger = await client.addCronTrigger(service, { box: box2, expr, timezone: opts.tz, ...action });
7013
7544
  if (opts.json) {
7014
7545
  json(trigger);
7015
7546
  return;
@@ -7135,7 +7666,7 @@ var runsCommand = new Command90("runs").aliases(["logs"]).description("show how
7135
7666
  }))
7136
7667
  );
7137
7668
  const last = runs.find((r) => r.output !== null);
7138
- if (last) info(color.dim(`A command's output stays in the box, one file per run; the newest: kvbox exec <box> -- cat ${last.output}`));
7669
+ if (last) info(color.dim(`A command's output stays in the box; the newest: kvbox exec <box> -- cat ${last.output}`));
7139
7670
  } finally {
7140
7671
  await client.close();
7141
7672
  }
@@ -7157,7 +7688,7 @@ import { Command as Command105 } from "commander";
7157
7688
 
7158
7689
  // src/commands/managed/create.ts
7159
7690
  import { Command as Command94 } from "commander";
7160
- import { setTimeout as sleep4 } from "timers/promises";
7691
+ import { setTimeout as sleep5 } from "timers/promises";
7161
7692
 
7162
7693
  // src/commands/managed/shared.ts
7163
7694
  import "commander";
@@ -7259,7 +7790,7 @@ var createCommand9 = (spec) => {
7259
7790
  const made = await spin(`creating ${spec.title} database ${name}\u2026`, client.createManaged(spec.kind, req));
7260
7791
  const shown = shownName3(made, me(client));
7261
7792
  const ready = await spin(`starting ${spec.title}\u2026`, async () => {
7262
- for (const until2 = Date.now() + READY_WAIT_MS; Date.now() < until2; await sleep4(READY_STEP_MS)) {
7793
+ for (const until2 = Date.now() + READY_WAIT_MS; Date.now() < until2; await sleep5(READY_STEP_MS)) {
7263
7794
  const now = await client.getManaged(spec.kind, shown).catch(() => void 0);
7264
7795
  if (now?.health?.ready && now.health.accepting) return true;
7265
7796
  }
@@ -7312,16 +7843,16 @@ var infoCommand3 = (spec) => new Command96("info").alias("get").description("sho
7312
7843
 
7313
7844
  // src/commands/managed/link.ts
7314
7845
  import { Command as Command97 } from "commander";
7315
- var linkCommand2 = (spec) => new Command97("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) => {
7846
+ var linkCommand2 = (spec) => new Command97("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, box2, opts, cmd) => {
7316
7847
  const client = await managedClient(cmd);
7317
7848
  try {
7318
- const m = await spin(`linking ${box} to ${name}\u2026`, client.linkManaged(spec.kind, name, box));
7849
+ const m = await spin(`linking ${box2} to ${name}\u2026`, client.linkManaged(spec.kind, name, box2));
7319
7850
  if (opts.json) {
7320
7851
  json(m);
7321
7852
  return;
7322
7853
  }
7323
- info(`${color.green("\u2713")} box ${box} can reach database ${name}`);
7324
- info(` inside ${box}: ${m.urls.private} ${color.dim(`(the password: kvbox ${spec.command} password ${name})`)}`);
7854
+ info(`${color.green("\u2713")} box ${box2} can reach database ${name}`);
7855
+ info(` inside ${box2}: ${m.urls.private} ${color.dim(`(the password: kvbox ${spec.command} password ${name})`)}`);
7325
7856
  } finally {
7326
7857
  await client.close();
7327
7858
  }
@@ -7445,12 +7976,12 @@ var stopCommand2 = (spec) => new Command103("stop").description("shut a database
7445
7976
 
7446
7977
  // src/commands/managed/unlink.ts
7447
7978
  import { Command as Command104 } from "commander";
7448
- var unlinkCommand2 = (spec) => new Command104("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) => {
7979
+ var unlinkCommand2 = (spec) => new Command104("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, box2, opts, cmd) => {
7449
7980
  const client = await managedClient(cmd);
7450
7981
  try {
7451
- const m = await spin(`unlinking ${box} from ${name}\u2026`, client.unlinkManaged(spec.kind, name, box));
7982
+ const m = await spin(`unlinking ${box2} from ${name}\u2026`, client.unlinkManaged(spec.kind, name, box2));
7452
7983
  if (opts.json) json(m);
7453
- else info(`${color.green("\u2713")} box ${box} no longer reaches database ${name}`);
7984
+ else info(`${color.green("\u2713")} box ${box2} no longer reaches database ${name}`);
7454
7985
  } finally {
7455
7986
  await client.close();
7456
7987
  }
@@ -7491,15 +8022,15 @@ function reach(boxes, verb) {
7491
8022
  return boxes === 1 ? `1 box ${verb}s it when it next starts` : `${boxes} boxes ${verb} it when they next start`;
7492
8023
  }
7493
8024
  async function findBox2(client, name) {
7494
- const box = pickRef(await boxesFor(client, name), name, me(client));
7495
- if (!box) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
7496
- return { box, ref: displayName(box, me(client)) };
8025
+ const box2 = pickRef(await boxesFor(client, name), name, me(client));
8026
+ if (!box2) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
8027
+ return { box: box2, ref: displayName(box2, me(client)) };
7497
8028
  }
7498
8029
  function boxReach(running, verb) {
7499
8030
  return running ? `it ${verb} it when it next starts (kvbox stop, kvbox start)` : `it ${verb} it when it starts`;
7500
8031
  }
7501
- function firstBootHint(box, name) {
7502
- if (box.image === "postgres" && /^POSTGRES_(USER|PASSWORD|DB)$/.test(name)) {
8032
+ function firstBootHint(box2, name) {
8033
+ if (box2.image === "postgres" && /^POSTGRES_(USER|PASSWORD|DB)$/.test(name)) {
7503
8034
  return `${name} is read once, when the box first boots: the database keeps the user, password and database it was made with (change them with psql in the box)`;
7504
8035
  }
7505
8036
  return void 0;
@@ -7510,9 +8041,9 @@ var lsCommand16 = new Command107("ls").alias("list").description("list the varia
7510
8041
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
7511
8042
  try {
7512
8043
  if (opts.box !== void 0) {
7513
- const { box, ref } = await findBox2(client, opts.box);
8044
+ const { box: box2, ref } = await findBox2(client, opts.box);
7514
8045
  const own = await client.boxEnv(ref);
7515
- const slug = slugOf(box.owner);
8046
+ const slug = slugOf(box2.owner);
7516
8047
  const theirs = client.target.kind === "cloud" ? await client.listEnv(slug === me(client) ? void 0 : slug) : [];
7517
8048
  const mine = new Set(own.vars.map((v) => v.name));
7518
8049
  const inherited = theirs.filter((v) => !mine.has(v.name));
@@ -7655,18 +8186,18 @@ var addCommand4 = new Command111("add").description("serve a box at a domain of
7655
8186
  try {
7656
8187
  requireCloud5(client);
7657
8188
  const user = me(client);
7658
- const box = displayName(await findBox(client, name), user);
7659
- const d = await spin(`adding ${domain}\u2026`, client.addDomain(box, { domain, ...port !== void 0 ? { port } : {} }));
8189
+ const box2 = displayName(await findBox(client, name), user);
8190
+ const d = await spin(`adding ${domain}\u2026`, client.addDomain(box2, { domain, ...port !== void 0 ? { port } : {} }));
7660
8191
  if (opts.json) {
7661
8192
  json(domainJson(d, user));
7662
8193
  return;
7663
8194
  }
7664
8195
  if (d.status === "live") {
7665
- info(`${color.green("\u2713")} ${color.bold(d.url)} \u2192 box ${color.bold(box)} port ${d.port}`);
8196
+ info(`${color.green("\u2713")} ${color.bold(d.url)} \u2192 box ${color.bold(box2)} port ${d.port}`);
7666
8197
  info(" the certificate is made on the first visit, which can take a few seconds");
7667
8198
  return;
7668
8199
  }
7669
- info(`${color.green("\u2713")} ${domain} added for box ${color.bold(box)} port ${d.port}, waiting for its DNS`);
8200
+ info(`${color.green("\u2713")} ${domain} added for box ${color.bold(box2)} port ${d.port}, waiting for its DNS`);
7670
8201
  const zone = zoneOf(domain);
7671
8202
  info(`
7672
8203
  At the company that runs the DNS of ${zone}, add:
@@ -7722,14 +8253,14 @@ var rmCommand15 = new Command113("rm").alias("remove").description("stop serving
7722
8253
  requireCloud5(client);
7723
8254
  const found = (await client.listDomains()).find((d) => d.domain === domain);
7724
8255
  if (!found) throw new KvboxError(`domain ${domain}: not found (kvbox domain ls)`);
7725
- const box = boxOf2(found, me(client));
7726
- if (!await confirm(`Stop serving box ${box} at ${domain}?`, opts.yes ?? false)) {
8256
+ const box2 = boxOf2(found, me(client));
8257
+ if (!await confirm(`Stop serving box ${box2} at ${domain}?`, opts.yes ?? false)) {
7727
8258
  info("cancelled");
7728
8259
  process.exitCode = 1;
7729
8260
  return;
7730
8261
  }
7731
8262
  await spin(`removing ${domain}\u2026`, client.removeDomain(`${found.owner}/${found.box}`, domain));
7732
- info(`${color.green("\u2713")} ${domain} no longer serves box ${box} (you can remove its DNS record)`);
8263
+ info(`${color.green("\u2713")} ${domain} no longer serves box ${box2} (you can remove its DNS record)`);
7733
8264
  } finally {
7734
8265
  await client.close();
7735
8266
  }