@kvbox/cli 0.5.38 → 0.5.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kvbox.js CHANGED
@@ -149,7 +149,7 @@ async function spin(message, work, opts = {}) {
149
149
  }
150
150
 
151
151
  // src/program.ts
152
- import { Command as Command76 } from "commander";
152
+ import { Command as Command77 } from "commander";
153
153
 
154
154
  // ../shared/src/version.ts
155
155
  import { createRequire } from "module";
@@ -164,7 +164,7 @@ function versionOf(srcFileUrl, injected) {
164
164
  }
165
165
 
166
166
  // src/version.ts
167
- var VERSION = versionOf(import.meta.url, true ? "0.5.38" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.40" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command37 } from "commander";
@@ -391,8 +391,8 @@ async function ensureCert(client, p = paths(), now = Date.now(), opts = {}) {
391
391
  if (!session) return "local";
392
392
  const expires = session.sshCertExpires ? new Date(session.sshCertExpires).getTime() : 0;
393
393
  const onDisk = await readFile2(p.sshCert, "utf8").then(() => true, () => false);
394
- const names = opts.owner === void 0 || (session.sshCertPrincipals ?? []).includes(opts.owner);
395
- if (onDisk && expires - now > RENEW_BEFORE_MS && names && !opts.force) return "kept";
394
+ const names2 = opts.owner === void 0 || (session.sshCertPrincipals ?? []).includes(opts.owner);
395
+ if (onDisk && expires - now > RENEW_BEFORE_MS && names2 && !opts.force) return "kept";
396
396
  const publicKey = await readFile2(`${p.sshKey}.pub`, "utf8").catch(() => null);
397
397
  if (publicKey === null) throw new KvboxError(`could not renew your SSH certificate: no key at ${p.sshKey}.pub; run: kvbox login`);
398
398
  let signed;
@@ -587,6 +587,8 @@ var MachineSchema = z2.object({
587
587
  * links to, and a volume attaches to, only a box on the same host.
588
588
  */
589
589
  host: z2.string().optional(),
590
+ /** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
591
+ country: z2.string().optional(),
590
592
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
591
593
  autoHibernateSec: z2.number().int().positive().optional(),
592
594
  /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
@@ -684,6 +686,11 @@ var CreateMachineRequest = z2.object({
684
686
  * control plane reads it; a host has one place to put a box.
685
687
  */
686
688
  near: z2.string().optional(),
689
+ /**
690
+ * Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
691
+ * `@kvbox/shared/country`. Only the control plane reads it.
692
+ */
693
+ country: z2.string().optional(),
687
694
  /** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
688
695
  image: z2.string().optional(),
689
696
  /** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
@@ -912,8 +919,11 @@ var VolumeEventsResponseSchema = z2.object({
912
919
  events: z2.array(VolumeEventRowSchema),
913
920
  next: z2.number().int()
914
921
  });
922
+ var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
923
+ var ApiErrorCodeSchema = z2.enum(API_ERROR_CODES);
915
924
  var ApiErrorSchema = z2.object({
916
- error: z2.string()
925
+ error: z2.string(),
926
+ code: ApiErrorCodeSchema.optional()
917
927
  });
918
928
  var DEFAULT_CLOUD_URL = "https://api.kvbox.sh";
919
929
  var ACTIVATED_BY = ["card", "admin"];
@@ -1067,7 +1077,9 @@ var HostJoinRequestSchema = z2.object({
1067
1077
  name: z2.string().min(1),
1068
1078
  url: z2.string().url(),
1069
1079
  fingerprint: z2.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
1070
- publicAddress: z2.string().min(1)
1080
+ publicAddress: z2.string().min(1),
1081
+ /** Where the host is (`kvbox server join --country`): a code or an English name. */
1082
+ country: z2.string().optional()
1071
1083
  });
1072
1084
  var HostJoinResponseSchema = z2.object({
1073
1085
  hostSecret: z2.string(),
@@ -1079,8 +1091,12 @@ var CloudHostSchema = z2.object({
1079
1091
  publicAddress: z2.string(),
1080
1092
  joinedAt: z2.string(),
1081
1093
  lastSeenAt: z2.string().nullable(),
1082
- capacity: CapacitySchema.nullable()
1094
+ capacity: CapacitySchema.nullable(),
1095
+ /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
1096
+ country: z2.string().nullable()
1083
1097
  });
1098
+ var HostPatchRequest = z2.object({ country: z2.string().nullable() });
1099
+ var CountrySchema = z2.object({ code: z2.string(), name: z2.string() });
1084
1100
 
1085
1101
  // src/kvm.ts
1086
1102
  import { accessSync, constants, readFileSync, statSync } from "fs";
@@ -1319,24 +1335,25 @@ var ServerClient = class {
1319
1335
  removeBoxHook(name, id) {
1320
1336
  return this.call("DELETE", `/machines/${encodeURIComponent(name)}/hooks/${encodeURIComponent(id)}`, WakeHookSchema);
1321
1337
  }
1322
- /** HTTPS names (#31), the control plane's only: the box's subdomain, claimed for its default port. */
1338
+ /** HTTPS names (#31), the control plane's only: claim another subdomain for the box (up to MAX_BOX_SUBDOMAINS). */
1323
1339
  claimSubdomain(name, req) {
1324
1340
  return this.call("PUT", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema, req);
1325
1341
  }
1326
- setSubdomainPort(name, req) {
1327
- return this.call("POST", `/machines/${encodeURIComponent(name)}/subdomain/port`, SubdomainSchema, req);
1342
+ /** `sub` names which of the box's subdomains; left out, the box's only one (several: an error). */
1343
+ setSubdomainPort(name, req, sub) {
1344
+ return this.call("POST", subdomainPath(name, "/port", sub), SubdomainSchema, req);
1328
1345
  }
1329
- releaseSubdomain(name) {
1330
- return this.call("DELETE", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema);
1346
+ releaseSubdomain(name, sub) {
1347
+ return this.call("DELETE", subdomainPath(name, "", sub), SubdomainSchema);
1331
1348
  }
1332
- /** `<route>.<sub>`: a named port under the box's subdomain. */
1333
- addSubdomainRoute(name, req) {
1334
- return this.call("POST", `/machines/${encodeURIComponent(name)}/subdomain/routes`, SubdomainSchema, req);
1349
+ /** `<route>.<sub>`: a named port under one of the box's subdomains. */
1350
+ addSubdomainRoute(name, req, sub) {
1351
+ return this.call("POST", subdomainPath(name, "/routes", sub), SubdomainSchema, req);
1335
1352
  }
1336
- removeSubdomainRoute(name, route) {
1337
- return this.call("DELETE", `/machines/${encodeURIComponent(name)}/subdomain/routes/${encodeURIComponent(route)}`, SubdomainSchema);
1353
+ removeSubdomainRoute(name, route, sub) {
1354
+ return this.call("DELETE", subdomainPath(name, `/routes/${encodeURIComponent(route)}`, sub), SubdomainSchema);
1338
1355
  }
1339
- /** Every readable box's subdomain. */
1356
+ /** Every readable box's subdomains, one entry each. */
1340
1357
  listSubdomains() {
1341
1358
  return this.call("GET", "/subdomains", z3.array(SubdomainSchema));
1342
1359
  }
@@ -1622,6 +1639,9 @@ async function serving(p, timeoutMs, check) {
1622
1639
  }
1623
1640
  throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
1624
1641
  }
1642
+ function subdomainPath(box, path, sub) {
1643
+ return `/machines/${encodeURIComponent(box)}/subdomain${path}${sub !== void 0 ? `?sub=${encodeURIComponent(sub)}` : ""}`;
1644
+ }
1625
1645
 
1626
1646
  // src/prompt.ts
1627
1647
  import { createInterface } from "readline/promises";
@@ -1835,6 +1855,39 @@ function envValueProblem(value) {
1835
1855
  return null;
1836
1856
  }
1837
1857
 
1858
+ // ../shared/src/country.ts
1859
+ var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
1860
+ var NOT_COUNTRIES = /* @__PURE__ */ new Set(["EU", "EZ", "UN", "QO", "XA", "XB", "ZZ"]);
1861
+ var ALIASES = { usa: "US", america: "US", uk: "GB", britain: "GB", england: "GB", holland: "NL" };
1862
+ var fold = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z]/g, "");
1863
+ var byName;
1864
+ function nameIndex() {
1865
+ if (byName) return byName;
1866
+ byName = new Map(Object.entries(ALIASES));
1867
+ for (let a = 65; a <= 90; a++) {
1868
+ for (let b = 65; b <= 90; b++) {
1869
+ const code = String.fromCharCode(a, b);
1870
+ const name = countryName(code);
1871
+ if (name !== void 0 && canonical(code) === code) byName.set(fold(name), code);
1872
+ }
1873
+ }
1874
+ return byName;
1875
+ }
1876
+ function canonical(code) {
1877
+ return /-([A-Z]{2})$/.exec(Intl.getCanonicalLocales(`und-${code}`)[0] ?? "")?.[1] ?? code;
1878
+ }
1879
+ function countryName(code) {
1880
+ if (!/^[A-Z]{2}$/.test(code) || NOT_COUNTRIES.has(code)) return void 0;
1881
+ return names.of(code);
1882
+ }
1883
+ function parseCountry(input) {
1884
+ const t = input.trim();
1885
+ const upper = t.toUpperCase();
1886
+ const code = countryName(upper) !== void 0 ? canonical(upper) : nameIndex().get(fold(t));
1887
+ if (code !== void 0) return code;
1888
+ throw new KvboxError(`unknown country "${input}": give its name or its two-letter code, e.g. RO or US`);
1889
+ }
1890
+
1838
1891
  // ../shared/src/duration.ts
1839
1892
  var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
1840
1893
  function parseDuration(text2) {
@@ -1846,10 +1899,16 @@ function parseDuration(text2) {
1846
1899
  }
1847
1900
 
1848
1901
  // src/commands/vm/new.ts
1849
- var newCommand = new Command("new").description("boot a new box from an image (the base one, or e.g. postgres) or a snapshot").argument("[name]", "box name (box1, box2, \u2026 when omitted)").addOption(new Option("-s, --size <size>", "box size (default: server config, s)").choices(SIZE_NAMES)).option("-b, --base <image>", "the image to boot: base (default) or one the host has, e.g. postgres").option("-e, --env <NAME=value>", "a variable of the box's own, over yours (repeatable; change later with kvbox env set --box)", collect, []).option("-f, --from <snapshot>", "start from a snapshot instead of an image").option("--near <box>", "put it on the same host as this box, so the two can be linked (kvbox vm link)").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
1902
+ var newCommand = new Command("new").description("boot a new box from an image (the base one, or e.g. postgres) or a snapshot").argument("[name]", "box name (box1, box2, \u2026 when omitted)").addOption(new Option("-s, --size <size>", "box size (default: server config, s)").choices(SIZE_NAMES)).option("-b, --base <image>", "the image to boot: base (default) or one the host has, e.g. postgres").option("-e, --env <NAME=value>", "a variable of the box's own, over yours (repeatable; change later with kvbox env set --box)", collect, []).option("-f, --from <snapshot>", "start from a snapshot instead of an image").option("--near <box>", "put it on the same host as this box, so the two can be linked (kvbox vm link)").option("--country <country>", "put it on a host in this country, a name or a code, e.g. romania or US").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
1850
1903
  const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
1851
1904
  const env = parseEnvFlags(opts.env);
1905
+ const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
1906
+ if (country !== void 0 && opts.from !== void 0) throw new KvboxError("--country cannot be given with --from: a snapshot is restored on its own host");
1852
1907
  const client = await clientFor(cmd.optsWithGlobals());
1908
+ if (country !== void 0 && client.target.kind !== "cloud") {
1909
+ await client.close();
1910
+ throw new KvboxError("--country picks a host through the control plane; this machine is the only host here (kvbox login first)");
1911
+ }
1853
1912
  try {
1854
1913
  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`;
1855
1914
  const box = await spin(what, client.createMachine({
@@ -1859,6 +1918,7 @@ var newCommand = new Command("new").description("boot a new box from an image (t
1859
1918
  ...opts.base !== void 0 ? { image: opts.base } : {},
1860
1919
  ...env.length > 0 ? { env } : {},
1861
1920
  ...opts.near !== void 0 ? { near: opts.near } : {},
1921
+ ...country !== void 0 ? { country } : {},
1862
1922
  ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
1863
1923
  ...opts.force ? { force: true } : {}
1864
1924
  }));
@@ -1895,10 +1955,10 @@ var newCommand = new Command("new").description("boot a new box from an image (t
1895
1955
  await client.close();
1896
1956
  }
1897
1957
  });
1898
- async function keptVars(client, box, names) {
1958
+ async function keptVars(client, box, names2) {
1899
1959
  try {
1900
1960
  const have = new Set((await client.boxEnv(box)).vars.map((v) => v.name));
1901
- return names.every((n) => have.has(n)) ? true : "too old";
1961
+ return names2.every((n) => have.has(n)) ? true : "too old";
1902
1962
  } catch (err) {
1903
1963
  const message = err.message;
1904
1964
  return /no route:|too old/.test(message) ? "too old" : message;
@@ -2140,12 +2200,13 @@ var lsCommand = new Command5("ls").description("list boxes with status and addre
2140
2200
  await client.close();
2141
2201
  }
2142
2202
  });
2203
+ var hostCell = (b) => b.host === void 0 ? "-" : b.country === void 0 ? b.host : `${b.host} ${color.dim(`(${b.country})`)}`;
2143
2204
  function lsRows(boxes, cloud) {
2144
2205
  return boxes.map((b) => ({
2145
2206
  ...cloud ? { owner: ownerCell(b, cloud.me) } : {},
2146
2207
  name: boxName(b.name),
2147
2208
  status: status(b.status),
2148
- ...cloud?.showHost ? { host: b.host ?? "-" } : {},
2209
+ ...cloud?.showHost ? { host: hostCell(b) } : {},
2149
2210
  address: addressOf(b),
2150
2211
  size: b.status === "unknown" ? "-" : `${shape(b.vcpu, b.memMib, b.diskBytes)} ${color.dim(`(${gbShort(b.diskUsedBytes)} used)`)}`,
2151
2212
  created: age(b.createdAt),
@@ -2192,28 +2253,28 @@ var getCommand = new Command6("get").description("show one box in full: status,
2192
2253
  try {
2193
2254
  const user = me(client);
2194
2255
  const box = await findBox(client, name);
2195
- const sub = client.target.kind === "cloud" ? await subdomainOf(client, box) : void 0;
2256
+ const subs = client.target.kind === "cloud" ? await subdomainsOf(client, box) : [];
2196
2257
  if (opts.json) {
2197
- json({ ...box, ...sub ? { subdomain: subdomainJson(sub, user) } : {} });
2258
+ json({ ...box, ...subs.length > 0 ? { subdomains: subs.map((s) => subdomainJson(s, user)) } : {} });
2198
2259
  return;
2199
2260
  }
2200
- const rows2 = getRows(box, sub, user);
2261
+ const rows2 = getRows(box, subs, user);
2201
2262
  const width2 = Math.max(...rows2.map(([k]) => k.length));
2202
2263
  for (const [k, v] of rows2) info(`${color.dim(k.padStart(width2))} ${v}`);
2203
2264
  } finally {
2204
2265
  await client.close();
2205
2266
  }
2206
2267
  });
2207
- async function subdomainOf(client, box) {
2268
+ async function subdomainsOf(client, box) {
2208
2269
  try {
2209
2270
  const slug = slugOf(box.owner);
2210
- return (await client.listSubdomains()).find((s) => s.box === box.name && s.owner === slug);
2271
+ return (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slug);
2211
2272
  } catch (err) {
2212
2273
  warn(`HTTPS name not shown: ${err.message}`);
2213
- return void 0;
2274
+ return [];
2214
2275
  }
2215
2276
  }
2216
- function getRows(box, sub, user) {
2277
+ function getRows(box, subs, user) {
2217
2278
  const rows2 = [
2218
2279
  ["name", color.bold(displayName(box, user))],
2219
2280
  ["status", status(box.status)]
@@ -2225,7 +2286,8 @@ function getRows(box, sub, user) {
2225
2286
  rows2.push(["ssh", box.ssh ? `ssh -p ${box.ssh.port} ${box.ssh.user}@${box.ssh.host}` : `kvbox connect ${displayName(box, user)}`]);
2226
2287
  }
2227
2288
  if (box.url !== void 0) rows2.push(["connect", `${box.url} ${color.dim("(password shown once, at new)")}`]);
2228
- rows2.push(["url", sub ? [`${sub.url} ${color.dim(`(port ${sub.port})`)}`, ...sub.routes.map((r) => `${r.url} ${color.dim(`(port ${r.port})`)}`)].join(", ") : "-"]);
2289
+ const urls = subs.flatMap((sub) => [`${sub.url} ${color.dim(`(port ${sub.port})`)}`, ...sub.routes.map((r) => `${r.url} ${color.dim(`(port ${r.port})`)}`)]);
2290
+ rows2.push(["url", urls.length === 0 ? "-" : urls.join(", ")]);
2229
2291
  const ports = rowsOf(box, user).map((r) => `${r.guestPort}/${r.proto} \u2192 ${reaches(r, true)}`);
2230
2292
  rows2.push(["ports", ports.length === 0 ? "-" : ports.join(", ")]);
2231
2293
  rows2.push(["volumes", box.volumes?.length ? box.volumes.map((v) => `${v.name} ${color.dim(`(${v.sizeGib} GB at ${v.mountPath})`)}`).join(", ") : "-"]);
@@ -2333,6 +2395,7 @@ import { Command as Command11 } from "commander";
2333
2395
  // ../shared/src/names.ts
2334
2396
  import { createHmac } from "crypto";
2335
2397
  var DEFAULT_PROXY_DOMAIN = "kvbox.app";
2398
+ var MAX_BOX_SUBDOMAINS = 5;
2336
2399
  var LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
2337
2400
  var RESERVED_SUBDOMAINS = /* @__PURE__ */ new Set([
2338
2401
  "admin",
@@ -2398,7 +2461,7 @@ function assertDomain(text2, proxyDomain) {
2398
2461
  }
2399
2462
 
2400
2463
  // src/commands/vm/proxy/claim.ts
2401
- var claimCommand = new Command11("claim").description("give a box its HTTPS address, https://<subdomain>.kvbox.app, serving one of its ports").argument("[box]", "box name (picked from a list when left out)").argument("[subdomain]", "3-63 lowercase letters, digits and '-'; must be free (asked for when left out)").option("--port <port>", "the box port the address serves (asked for when left out)").option("--json", "print the subdomain as JSON").action(async (nameArg, subArg, opts, cmd) => {
2464
+ var claimCommand = new Command11("claim").description(`give a box an HTTPS address, https://<subdomain>.kvbox.app, serving one of its ports (up to ${MAX_BOX_SUBDOMAINS} per box)`).argument("[box]", "box name (picked from a list when left out)").argument("[subdomain]", "3-63 lowercase letters, digits and '-'; must be free (asked for when left out)").option("--port <port>", "the box port the address serves (asked for when left out)").option("--json", "print the subdomain as JSON").action(async (nameArg, subArg, opts, cmd) => {
2402
2465
  if (nameArg === void 0 || subArg === void 0 || opts.port === void 0) askOrUsage("give the box, the subdomain and the port: kvbox vm proxy claim <box> <subdomain> --port <port>");
2403
2466
  if (subArg !== void 0) assertSubdomain(subArg);
2404
2467
  if (opts.port !== void 0) parsePorts([opts.port]);
@@ -2419,6 +2482,7 @@ var claimCommand = new Command11("claim").description("give a box its HTTPS addr
2419
2482
  }
2420
2483
  info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box)} port ${sub.port}`);
2421
2484
  info(` more ports under it: kvbox vm proxy add ${box} <port> --name <name> \u2192 https://<name>.${sub.url.replace(/^https:\/\//, "")}`);
2485
+ info(` another address for this box: kvbox vm proxy claim ${box} <subdomain> --port <port>`);
2422
2486
  if (found.status !== "running") info(` box ${box} is ${found.status}: the address answers once it runs`);
2423
2487
  } finally {
2424
2488
  await client.close();
@@ -2430,12 +2494,14 @@ import { Command as Command17 } from "commander";
2430
2494
 
2431
2495
  // src/commands/vm/proxy/add.ts
2432
2496
  import { Command as Command12 } from "commander";
2433
- var addCommand = new Command12("add").description("publish box ports on the internet; each gets a random public port, or an HTTPS name with --name").argument("<box>", "box name").argument("<port...>", "ports inside the box, e.g. 3000 8080").option("--udp", "UDP instead of TCP").option("--name <name>", "serve the port at https://<name>.<subdomain>.kvbox.app (one port; needs kvbox vm proxy claim first)").option("--json", "print the new forwards as JSON").action(async (name, portTexts, opts, cmd) => {
2497
+ var addCommand = new Command12("add").description("publish box ports on the internet; each gets a random public port, or an HTTPS name with --name").argument("<box>", "box name").argument("<port...>", "ports inside the box, e.g. 3000 8080").option("--udp", "UDP instead of TCP").option("--name <name>", "serve the port at https://<name>.<subdomain>.kvbox.app (one port; needs kvbox vm proxy claim first)").option("--sub <subdomain>", "with --name: which of the box's subdomains it goes under (needed when it has more than one)").option("--json", "print the new forwards as JSON").action(async (name, portTexts, opts, cmd) => {
2434
2498
  const guestPorts = parsePorts(portTexts);
2435
2499
  if (opts.name !== void 0) {
2436
2500
  assertRouteName(opts.name);
2437
2501
  if (guestPorts.length !== 1) throw new KvboxError("--name publishes one port: kvbox vm proxy add <box> <port> --name <name>");
2438
2502
  if (opts.udp) throw new KvboxError("--name serves HTTPS, which is TCP: drop --udp");
2503
+ } else if (opts.sub !== void 0) {
2504
+ throw new KvboxError("--sub goes with --name: kvbox vm proxy add <box> <port> --name <name> --sub <subdomain>");
2439
2505
  }
2440
2506
  const proto = opts.udp ? "udp" : "tcp";
2441
2507
  const client = await clientFor(cmd.optsWithGlobals());
@@ -2446,7 +2512,7 @@ var addCommand = new Command12("add").description("publish box ports on the inte
2446
2512
  const box = displayName(found, user);
2447
2513
  if (opts.name !== void 0) {
2448
2514
  const route = opts.name;
2449
- const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}\u2026`, client.addSubdomainRoute(box, { name: route, port: guestPorts[0] }));
2515
+ const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}\u2026`, client.addSubdomainRoute(box, { name: route, port: guestPorts[0] }, opts.sub));
2450
2516
  const url = sub.routes.find((r) => r.name === route).url;
2451
2517
  if (opts.json) {
2452
2518
  json({ box, guestPort: guestPorts[0], proto: "https", url, name: route });
@@ -2472,7 +2538,7 @@ var addCommand = new Command12("add").description("publish box ports on the inte
2472
2538
 
2473
2539
  // src/commands/vm/proxy/ls.ts
2474
2540
  import { Command as Command13 } from "commander";
2475
- async function subdomainsOf(client) {
2541
+ async function subdomainsOf2(client) {
2476
2542
  try {
2477
2543
  return await client.listSubdomains();
2478
2544
  } catch (err) {
@@ -2486,7 +2552,7 @@ var lsCommand2 = new Command13("ls").description("list the box ports published o
2486
2552
  const user = me(client);
2487
2553
  const [boxes, subs] = await Promise.all([
2488
2554
  name === void 0 ? client.listMachines() : findBox(client, name).then((b) => [b]),
2489
- client.target.kind === "cloud" ? subdomainsOf(client) : []
2555
+ client.target.kind === "cloud" ? subdomainsOf2(client) : []
2490
2556
  ]);
2491
2557
  const shown = new Set(boxes.map((b) => displayName(b, user)));
2492
2558
  const https = subs.flatMap((s) => httpsRowsOf(s, user)).filter((r) => shown.has(r.box));
@@ -2507,19 +2573,19 @@ var lsCommand2 = new Command13("ls").description("list the box ports published o
2507
2573
 
2508
2574
  // src/commands/vm/proxy/release.ts
2509
2575
  import { Command as Command14 } from "commander";
2510
- var releaseCommand = new Command14("release").description("give up a box's HTTPS address and every name under it").argument("<box>", "box name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2576
+ var releaseCommand = new Command14("release").description("give up one of a box's HTTPS addresses and every name under it").argument("<box>", "box name").option("--sub <subdomain>", "which of the box's subdomains (needed when it has more than one)").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2511
2577
  const client = await clientFor(cmd.optsWithGlobals());
2512
2578
  try {
2513
2579
  requireCloud(client);
2514
2580
  const box = displayName(await findBox(client, name), me(client));
2515
- if (!await confirm(`Give up box ${box}'s HTTPS address and every name under it? Anyone may claim it after.`, opts.yes ?? false)) {
2581
+ 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)) {
2516
2582
  info("cancelled");
2517
2583
  process.exitCode = 1;
2518
2584
  return;
2519
2585
  }
2520
- const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box));
2521
- const names = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
2522
- info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names} no longer reach box ${color.bold(box)}`);
2586
+ const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box, opts.sub));
2587
+ const names2 = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
2588
+ info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names2} no longer reach box ${color.bold(box)}`);
2523
2589
  } finally {
2524
2590
  await client.close();
2525
2591
  }
@@ -2527,10 +2593,12 @@ var releaseCommand = new Command14("release").description("give up a box's HTTPS
2527
2593
 
2528
2594
  // src/commands/vm/proxy/rm.ts
2529
2595
  import { Command as Command15 } from "commander";
2530
- var rmCommand = new Command15("rm").description("stop publishing box ports, or an HTTPS name with --name").argument("<box>", "box name").argument("[port...]", "ports inside the box, as given to add").option("--udp", "the UDP forwards of those ports").option("--name <name>", "the HTTPS name to free (kvbox vm proxy release frees the whole subdomain)").option("-y, --yes", "do not ask for confirmation").action(async (name, portTexts, opts, cmd) => {
2596
+ var rmCommand = new Command15("rm").description("stop publishing box ports, or an HTTPS name with --name").argument("<box>", "box name").argument("[port...]", "ports inside the box, as given to add").option("--udp", "the UDP forwards of those ports").option("--name <name>", "the HTTPS name to free (kvbox vm proxy release frees the whole subdomain)").option("--sub <subdomain>", "with --name: which of the box's subdomains the name is under (needed when it has more than one)").option("-y, --yes", "do not ask for confirmation").action(async (name, portTexts, opts, cmd) => {
2531
2597
  if (opts.name !== void 0) {
2532
2598
  assertRouteName(opts.name);
2533
2599
  if (portTexts.length > 0) throw new KvboxError("--name frees a name, not ports: kvbox vm proxy rm <box> --name <name>");
2600
+ } else if (opts.sub !== void 0) {
2601
+ throw new KvboxError("--sub goes with --name: kvbox vm proxy rm <box> --name <name> --sub <subdomain>");
2534
2602
  } else if (portTexts.length === 0) {
2535
2603
  throw new KvboxError("which ports? kvbox vm proxy rm <box> <port...>, or --name <name> for an HTTPS name");
2536
2604
  }
@@ -2547,7 +2615,7 @@ var rmCommand = new Command15("rm").description("stop publishing box ports, or a
2547
2615
  return;
2548
2616
  }
2549
2617
  if (opts.name !== void 0) {
2550
- const sub = await spin(`freeing ${opts.name} on ${name}\u2026`, client.removeSubdomainRoute(box, opts.name));
2618
+ const sub = await spin(`freeing ${opts.name} on ${name}\u2026`, client.removeSubdomainRoute(box, opts.name, opts.sub));
2551
2619
  info(`${color.green("\u2713")} ${opts.name}.${sub.url.replace(/^https:\/\//, "")} no longer reaches box ${color.bold(box)}`);
2552
2620
  return;
2553
2621
  }
@@ -2560,13 +2628,13 @@ var rmCommand = new Command15("rm").description("stop publishing box ports, or a
2560
2628
 
2561
2629
  // src/commands/vm/proxy/set-port.ts
2562
2630
  import { Command as Command16 } from "commander";
2563
- var setPortCommand = new Command16("set-port").description("point a box's HTTPS address at another of its ports").argument("<box>", "box name").argument("<port>", "the box port https://<subdomain>.kvbox.app serves from now on").option("--json", "print the subdomain as JSON").action(async (name, portText, opts, cmd) => {
2631
+ var setPortCommand = new Command16("set-port").description("point a box's HTTPS address at another of its ports").argument("<box>", "box name").argument("<port>", "the box port https://<subdomain>.kvbox.app serves from now on").option("--sub <subdomain>", "which of the box's subdomains (needed when it has more than one)").option("--json", "print the subdomain as JSON").action(async (name, portText, opts, cmd) => {
2564
2632
  const [port] = parsePorts([portText]);
2565
2633
  const client = await clientFor(cmd.optsWithGlobals());
2566
2634
  try {
2567
2635
  requireCloud(client);
2568
2636
  const box = displayName(await findBox(client, name), me(client));
2569
- const sub = await spin(`pointing ${name} at port ${port}\u2026`, client.setSubdomainPort(box, { port }));
2637
+ const sub = await spin(`pointing ${name} at port ${port}\u2026`, client.setSubdomainPort(box, { port }, opts.sub));
2570
2638
  if (opts.json) {
2571
2639
  json(subdomainJson(sub, me(client)));
2572
2640
  return;
@@ -3279,10 +3347,11 @@ function runKvboxServer(args) {
3279
3347
  }
3280
3348
 
3281
3349
  // src/commands/server/join.ts
3282
- var joinCommand = new Command38("join").description("put this machine behind a control plane (needs a one-time token minted there) and restart its server").argument("<control-plane-url>", "the control plane, e.g. https://api.kvbox.sh").requiredOption("--token <token>", "one-time join token from the control plane").option("--advertise <host-or-ip>", "address the control plane reaches this machine at (default: its default-route address)").option("--name <name>", "how the control plane lists this machine (default: hostname)").action(async (url, opts) => {
3350
+ var joinCommand = new Command38("join").description("put this machine behind a control plane (needs a one-time token minted there) and restart its server").argument("<control-plane-url>", "the control plane, e.g. https://api.kvbox.sh").requiredOption("--token <token>", "one-time join token from the control plane").option("--advertise <host-or-ip>", "address the control plane reaches this machine at (default: its default-route address)").option("--name <name>", "how the control plane lists this machine (default: hostname)").option("--country <country>", "where this machine is, a name or a code (romania, US); kvbox new --country places boxes by it").action(async (url, opts) => {
3283
3351
  const args = ["join", url, "--token", opts.token];
3284
3352
  if (opts.advertise !== void 0) args.push("--advertise", opts.advertise);
3285
3353
  if (opts.name !== void 0) args.push("--name", opts.name);
3354
+ if (opts.country !== void 0) args.push("--country", opts.country);
3286
3355
  for (const line of (await runKvboxServer(args)).split("\n")) info(line);
3287
3356
  const pid = await spin("restarting kvbox-server\u2026", restartLocalServer(paths()));
3288
3357
  info(`kvbox-server restarted (pid ${pid}); it answers the control plane now`);
@@ -3769,6 +3838,7 @@ var PricingSchema = z4.object({
3769
3838
  volumeGibHour: z4.number().nonnegative().default(0),
3770
3839
  diskIncludedGib: z4.number().int().nonnegative().default(0)
3771
3840
  });
3841
+ var PriceListSchema = PricingSchema.extend({ welcomeCredit: z4.number().nonnegative() });
3772
3842
  var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
3773
3843
  function costOf(t, pricing) {
3774
3844
  return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;
@@ -3969,13 +4039,13 @@ function creditRow(b, me2) {
3969
4039
  }
3970
4040
 
3971
4041
  // src/commands/deploy/index.ts
3972
- import { readFile as readFile7 } from "fs/promises";
4042
+ import { access as access4, readFile as readFile7 } from "fs/promises";
3973
4043
  import { basename, resolve as resolve2 } from "path";
3974
4044
  import { Command as Command61, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
3975
4045
 
3976
4046
  // src/commands/deploy/config.ts
3977
4047
  import { readFile as readFile6, writeFile as writeFile4 } from "fs/promises";
3978
- import { join as join4 } from "path";
4048
+ import { join as join5 } from "path";
3979
4049
  import { z as z5 } from "zod";
3980
4050
 
3981
4051
  // src/commands/deploy/templates/pm.ts
@@ -4157,40 +4227,62 @@ var reactTemplate = {
4157
4227
  `the build left no ${candidates.join(" or ")}/index.html. The React template ships a directory of static files; set "dist" in kvbox.json to the build output directory, or pick the right template with --template`
4158
4228
  );
4159
4229
  },
4160
- /**
4161
- * The archive lands in a staging directory, which then becomes /srv/app/dist in one move; the
4162
- * old site is kept beside it until the new one is in place, so a failed step never leaves nginx
4163
- * without a root and a visitor never sees a half-copied site. Files get read permission for
4164
- * nginx's user, whatever umask the build ran under. /srv/app is the kvbox user's (image v0.8.0+);
4165
- * the missing site file means an older image.
4166
- */
4167
- remote() {
4168
- return [
4169
- "set -e",
4170
- "test -e /etc/nginx/sites-enabled/kvbox-app || exit 3",
4171
- "rm -rf /srv/app/.incoming /srv/app/.old",
4172
- "mkdir -p /srv/app/.incoming",
4173
- "tar -xf - -C /srv/app/.incoming",
4174
- "chmod -R a+rX /srv/app/.incoming",
4175
- "if [ -e /srv/app/dist ]; then mv /srv/app/dist /srv/app/.old; fi",
4176
- "mv /srv/app/.incoming /srv/app/dist",
4177
- "rm -rf /srv/app/.old",
4178
- "sudo -n systemctl enable --now --quiet nginx",
4179
- "sudo -n systemctl reload nginx"
4180
- ].join("\n");
4181
- }
4230
+ remote: nginxRemote
4231
+ };
4232
+ function nginxRemote() {
4233
+ return [
4234
+ "set -e",
4235
+ "test -e /etc/nginx/sites-enabled/kvbox-app || exit 3",
4236
+ "rm -rf /srv/app/.incoming /srv/app/.old",
4237
+ "mkdir -p /srv/app/.incoming",
4238
+ "tar -xf - -C /srv/app/.incoming",
4239
+ "chmod -R a+rX /srv/app/.incoming",
4240
+ "if [ -e /srv/app/dist ]; then mv /srv/app/dist /srv/app/.old; fi",
4241
+ "mv /srv/app/.incoming /srv/app/dist",
4242
+ "rm -rf /srv/app/.old",
4243
+ "sudo -n systemctl enable --now --quiet nginx",
4244
+ "sudo -n systemctl reload nginx"
4245
+ ].join("\n");
4246
+ }
4247
+
4248
+ // src/commands/deploy/templates/static.ts
4249
+ import { access as access3 } from "fs/promises";
4250
+ import { join as join4 } from "path";
4251
+ var EXCLUDE = ["node_modules", ".git", "kvbox.json"];
4252
+ var staticTemplate = {
4253
+ id: "static",
4254
+ label: "Static site",
4255
+ hint: "plain HTML, CSS and JS: shipped as is, served by nginx in the box",
4256
+ size: "xs",
4257
+ port: 80,
4258
+ /** An index.html at the top and nothing to build; a project with a `build` script is one of the others, or says --template static. */
4259
+ detect(pkg, dir) {
4260
+ return dir.indexHtml && typeof pkg?.scripts?.["build"] !== "string";
4261
+ },
4262
+ async build(ctx) {
4263
+ const dist = ctx.dist;
4264
+ const outDir = dist !== void 0 ? join4(ctx.dir, dist) : ctx.dir;
4265
+ if (!await access3(join4(outDir, "index.html")).then(() => true, () => false)) {
4266
+ throw new KvboxError(
4267
+ `${outDir} has no index.html. The static template ships a directory of files as it is; set "dist" in kvbox.json to the folder that holds the site, or pick another template with --template`
4268
+ );
4269
+ }
4270
+ const pm = ctx.pkg !== void 0 ? await packageManager(ctx.dir) : "npm";
4271
+ return { outDir, ...dist !== void 0 ? { dist } : {}, exclude: EXCLUDE, pm, what: dist !== void 0 ? `${dist}/` : "the directory" };
4272
+ },
4273
+ remote: nginxRemote
4182
4274
  };
4183
4275
 
4184
4276
  // src/commands/deploy/templates/index.ts
4185
- var TEMPLATES = [reactTemplate, nextjsTemplate, nodeTemplate];
4277
+ var TEMPLATES = [reactTemplate, nextjsTemplate, nodeTemplate, staticTemplate];
4186
4278
  var TEMPLATE_IDS = TEMPLATES.map((t) => t.id);
4187
4279
  function templateById(id) {
4188
4280
  const t = TEMPLATES.find((x) => x.id === id);
4189
4281
  if (!t) throw new Error(`no template ${id}`);
4190
4282
  return t;
4191
4283
  }
4192
- function detectTemplate(pkg) {
4193
- return TEMPLATES.find((t) => t.detect(pkg));
4284
+ function detectTemplate(pkg, dir = { indexHtml: false }) {
4285
+ return TEMPLATES.find((t) => t.detect(pkg, dir));
4194
4286
  }
4195
4287
 
4196
4288
  // src/commands/deploy/config.ts
@@ -4214,7 +4306,7 @@ var DeployConfigSchema = z5.object({
4214
4306
  port: z5.number().int().min(1).max(65535).optional()
4215
4307
  });
4216
4308
  async function readConfig(dir) {
4217
- const path = join4(dir, CONFIG_FILE);
4309
+ const path = join5(dir, CONFIG_FILE);
4218
4310
  let raw;
4219
4311
  try {
4220
4312
  raw = await readFile6(path, "utf8");
@@ -4236,7 +4328,7 @@ async function readConfig(dir) {
4236
4328
  return parsed.data;
4237
4329
  }
4238
4330
  async function writeConfig(dir, config) {
4239
- await writeFile4(join4(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
4331
+ await writeFile4(join5(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
4240
4332
  }
4241
4333
  function nameFromDir(dirName) {
4242
4334
  const slug = dirName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 12).replace(/-+$/, "");
@@ -4249,7 +4341,7 @@ function subdomainFor(name) {
4249
4341
  // src/commands/deploy/ship.ts
4250
4342
  import { spawn as spawn6 } from "child_process";
4251
4343
  import { readdir, stat as stat2 } from "fs/promises";
4252
- import { join as join5 } from "path";
4344
+ import { join as join6 } from "path";
4253
4345
  var IMAGE_TOO_OLD = 3;
4254
4346
  var SSH_FAILED3 = 255;
4255
4347
  async function measure(dir, exclude = []) {
@@ -4257,7 +4349,7 @@ async function measure(dir, exclude = []) {
4257
4349
  const walk = async (d) => {
4258
4350
  for (const entry of await readdir(d, { withFileTypes: true })) {
4259
4351
  if (exclude.includes(entry.name)) continue;
4260
- const path = join5(d, entry.name);
4352
+ const path = join6(d, entry.name);
4261
4353
  if (entry.isDirectory()) await walk(path);
4262
4354
  else if (entry.isFile()) {
4263
4355
  total.files += 1;
@@ -4300,9 +4392,10 @@ async function ship(ep, dir, remote, exclude = []) {
4300
4392
  var shipping = { ship, measure, waitForSsh };
4301
4393
 
4302
4394
  // src/commands/deploy/index.ts
4303
- var deployCommand = new Command61("deploy").description("put the app in this directory (React, Next.js or a Node server) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the port a Next.js app or Node server listens on (default 3000; saved to kvbox.json)", parsePort).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
4395
+ var deployCommand = new Command61("deploy").description("put the app in this directory (React, Next.js, a Node server or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the port a Next.js app or Node server listens on (default 3000; saved to kvbox.json)", parsePort).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
4304
4396
  const dir = resolve2(dirArg ?? ".");
4305
4397
  const pkg = await readPackageJson(dir);
4398
+ const facts = { indexHtml: await access4(resolve2(dir, "index.html")).then(() => true, () => false) };
4306
4399
  const saved = await readConfig(dir);
4307
4400
  const globals = cmd.optsWithGlobals();
4308
4401
  const orgFlag = orgOption(globals);
@@ -4311,7 +4404,7 @@ var deployCommand = new Command61("deploy").description("put the app in this dir
4311
4404
  try {
4312
4405
  const cloud = client.target.kind === "cloud";
4313
4406
  if (!cloud && org !== void 0) throw new KvboxError("--org needs a control plane: kvbox login, or drop --org");
4314
- const { config, template, fresh } = await settle(dir, pkg, saved, opts, orgFlag, cloud);
4407
+ const { config, template, fresh } = await settle(dir, pkg, facts, saved, opts, orgFlag, cloud);
4315
4408
  if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, config);
4316
4409
  await writeConfig(dir, config);
4317
4410
  if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
@@ -4388,8 +4481,8 @@ async function readPackageJson(dir) {
4388
4481
  throw new KvboxError(`${resolve2(dir, "package.json")}: ${err.message}`);
4389
4482
  }
4390
4483
  }
4391
- async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
4392
- const detected = detectTemplate(pkg);
4484
+ async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
4485
+ const detected = detectTemplate(pkg, facts);
4393
4486
  if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
4394
4487
  if (opts.sub !== void 0) assertSubdomain(opts.sub);
4395
4488
  const renamed = saved !== void 0 && (opts.name !== void 0 && opts.name !== saved.name || orgFlag !== void 0 && orgFlag !== saved.org);
@@ -4423,7 +4516,7 @@ async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
4423
4516
  const initial = detected ? TEMPLATES.indexOf(detected) : 0;
4424
4517
  templateId = await select("Template", TEMPLATES.map((t) => ({ value: t.id, label: t.label, hint: t === detected ? `${t.hint} \xB7 detected` : t.hint })), initial);
4425
4518
  }
4426
- if (templateId === void 0) throw new KvboxError(`could not tell what kind of app ${dir} is (no package.json of a Vite, Create React App or Next.js project, or of a server on Express, Fastify, Koa, Hono or NestJS): say it with --template ${TEMPLATE_IDS.join("|")}`);
4519
+ if (templateId === void 0) throw new KvboxError(`could not tell what kind of app ${dir} is (no package.json of a Vite, Create React App or Next.js project, or of a server on Express, Fastify, Koa, Hono or NestJS, and no index.html): say it with --template ${TEMPLATE_IDS.join("|")}`);
4427
4520
  const template = templateById(templateId);
4428
4521
  let name = defaults.name;
4429
4522
  if (open.name && ask) name = await text("Box name", { default: defaults.name, validate: (a) => BOX_NAME_RE.test(a) ? void 0 : NAME_RULE });
@@ -4474,22 +4567,23 @@ async function findOrCreate(client, config) {
4474
4567
  }
4475
4568
  return { box, ref: displayName(box, user), created };
4476
4569
  }
4477
- async function existingAddress(client, config) {
4570
+ async function existingAddresses(client, config) {
4478
4571
  const slug = config.org ?? me(client);
4479
- return (await client.listSubdomains()).find((s) => s.box === config.name && s.owner === slug);
4572
+ return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
4480
4573
  }
4481
4574
  async function refuseOtherAddress(client, config) {
4482
- const have = await existingAddress(client, config);
4483
- if (!have || have.subdomain === config.subdomain) return;
4575
+ const have = await existingAddresses(client, config);
4576
+ if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
4484
4577
  const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
4485
4578
  throw new KvboxError(
4486
- `box ${ref} already answers at ${have.url}, not ${config.subdomain}. To keep the address: kvbox deploy --sub ${have.subdomain}. To move it: kvbox vm proxy release ${ref}, then deploy again`
4579
+ `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>`
4487
4580
  );
4488
4581
  }
4489
4582
  async function address(client, box, ref, config, port) {
4490
- const have = (await client.listSubdomains()).find((s) => s.box === box.name && s.owner === slugOf(box.owner));
4583
+ const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
4584
+ const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
4491
4585
  if (have) {
4492
- if (have.port !== port) await client.setSubdomainPort(ref, { port });
4586
+ if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
4493
4587
  return { url: have.url, subdomain: have.subdomain };
4494
4588
  }
4495
4589
  const wanted = config.subdomain ?? subdomainFor(config.name);
@@ -4729,19 +4823,19 @@ var lsCommand9 = new Command68("ls").alias("list").description("list the variabl
4729
4823
 
4730
4824
  // src/commands/env/rm.ts
4731
4825
  import { Command as Command69 } from "commander";
4732
- var rmCommand8 = new Command69("rm").alias("remove").description("remove variables; boxes lose them when they next start").argument("<names...>", "variable names").option("-y, --yes", "do not ask for confirmation").option("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names, opts, cmd) => {
4826
+ var rmCommand8 = new Command69("rm").alias("remove").description("remove variables; boxes lose them when they next start").argument("<names...>", "variable names").option("-y, --yes", "do not ask for confirmation").option("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names2, opts, cmd) => {
4733
4827
  const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
4734
4828
  try {
4735
4829
  const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
4736
4830
  const owner = target === void 0 ? requireCloud4(client) : `box ${target.ref}`;
4737
- if (!await confirm(`Remove ${names.join(", ")} from ${owner}'s variables?`, opts.yes ?? false)) {
4831
+ if (!await confirm(`Remove ${names2.join(", ")} from ${owner}'s variables?`, opts.yes ?? false)) {
4738
4832
  info("cancelled");
4739
4833
  process.exitCode = 1;
4740
4834
  return;
4741
4835
  }
4742
4836
  const changes = [];
4743
4837
  const failed = [];
4744
- for (const name of names) {
4838
+ for (const name of names2) {
4745
4839
  try {
4746
4840
  if (target !== void 0) {
4747
4841
  const c2 = await spin(`removing ${name}\u2026`, client.removeBoxEnv(target.ref, name));
@@ -4922,25 +5016,12 @@ var rmCommand9 = new Command74("rm").alias("remove").description("stop serving a
4922
5016
  var domainCommand = new Command75("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand10).addCommand(rmCommand9);
4923
5017
  for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
4924
5018
 
4925
- // src/program.ts
4926
- function buildProgram() {
4927
- const program = new Command76("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
4928
- program.addCommand(vmCommand);
4929
- program.addCommand(snapshotsCommand);
4930
- program.addCommand(volumeCommand);
4931
- program.addCommand(envCommand);
4932
- program.addCommand(domainCommand);
4933
- program.addCommand(serverCommand);
4934
- program.addCommand(loginCommand);
4935
- program.addCommand(logoutCommand);
4936
- program.addCommand(whoamiCommand);
4937
- program.addCommand(orgCommand);
4938
- program.addCommand(usageCommand2);
4939
- program.addCommand(creditCommand);
4940
- program.addCommand(deployCommand);
4941
- for (const cmd of vmAliases) program.addCommand(cmd);
4942
- return program;
4943
- }
5019
+ // src/commands/update.ts
5020
+ import { spawn as spawn7 } from "child_process";
5021
+ import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
5022
+ import { tmpdir } from "os";
5023
+ import { join as join7 } from "path";
5024
+ import { Command as Command76 } from "commander";
4944
5025
 
4945
5026
  // src/update.ts
4946
5027
  import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
@@ -4948,7 +5029,11 @@ import { dirname } from "path";
4948
5029
  var REGISTRY_URL = "https://registry.npmjs.org/@kvbox/cli/latest";
4949
5030
  var CHECK_EVERY_MS = 24 * 60 * 60 * 1e3;
4950
5031
  var FETCH_TIMEOUT_MS = 1500;
4951
- var UPDATE_COMMAND = "npm install -g @kvbox/cli";
5032
+ var UPDATE_COMMAND = "kvbox update";
5033
+ var suppressed = false;
5034
+ function suppressUpdateNotice() {
5035
+ suppressed = true;
5036
+ }
4952
5037
  function isNewer(a, b) {
4953
5038
  const pa = parse(a);
4954
5039
  const pb = parse(b);
@@ -5014,6 +5099,7 @@ function enabled() {
5014
5099
  function startUpdateCheck() {
5015
5100
  if (!enabled()) return Promise.resolve();
5016
5101
  process.on("exit", () => {
5102
+ if (suppressed) return;
5017
5103
  const state = readUpdateState();
5018
5104
  const notice = state ? updateNotice(state.latest) : null;
5019
5105
  if (notice) process.stderr.write(notice);
@@ -5021,6 +5107,80 @@ function startUpdateCheck() {
5021
5107
  return refreshUpdateState();
5022
5108
  }
5023
5109
 
5110
+ // src/commands/update.ts
5111
+ var INSTALL_BASE = "https://kvbox.sh";
5112
+ function installerFor(platform, base = INSTALL_BASE) {
5113
+ const root = base.replace(/\/+$/, "");
5114
+ if (platform === "win32") {
5115
+ const url = `${root}/install.ps1`;
5116
+ return {
5117
+ url,
5118
+ cmd: "powershell.exe",
5119
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${url} | iex`]
5120
+ };
5121
+ }
5122
+ return { url: `${root}/install.sh`, cmd: "bash", args: ["{script}"] };
5123
+ }
5124
+ async function download(url) {
5125
+ let res;
5126
+ try {
5127
+ res = await fetch(url, { signal: AbortSignal.timeout(3e4) });
5128
+ } catch (err) {
5129
+ throw new KvboxError(`could not download ${url}: ${err.message}`);
5130
+ }
5131
+ if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
5132
+ const body = await res.text();
5133
+ if (!body.startsWith("#!")) throw new KvboxError(`${url} did not return a shell script`);
5134
+ return body;
5135
+ }
5136
+ function run(cmd, args) {
5137
+ return new Promise((resolve3, reject) => {
5138
+ const child = spawn7(cmd, args, { stdio: "inherit" });
5139
+ child.on("error", (err) => reject(new KvboxError(`could not run ${cmd}: ${err.message}`)));
5140
+ child.on("exit", (code, signal) => resolve3(code ?? (signal ? 1 : 0)));
5141
+ });
5142
+ }
5143
+ var selfUpdateCommand = new Command76("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
5144
+ suppressUpdateNotice();
5145
+ const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
5146
+ let code;
5147
+ if (process.platform === "win32") {
5148
+ code = await run(inst.cmd, inst.args);
5149
+ } else {
5150
+ const script = await download(inst.url);
5151
+ const dir = mkdtempSync(join7(tmpdir(), "kvbox-update-"));
5152
+ const file = join7(dir, "install.sh");
5153
+ try {
5154
+ writeFileSync2(file, script, { mode: 448 });
5155
+ code = await run(inst.cmd, inst.args.map((a) => a === "{script}" ? file : a));
5156
+ } finally {
5157
+ rmSync(dir, { recursive: true, force: true });
5158
+ }
5159
+ }
5160
+ if (code !== 0) throw new KvboxError(`the installer failed (exit ${code})`, code);
5161
+ });
5162
+
5163
+ // src/program.ts
5164
+ function buildProgram() {
5165
+ const program = new Command77("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
5166
+ program.addCommand(vmCommand);
5167
+ program.addCommand(snapshotsCommand);
5168
+ program.addCommand(volumeCommand);
5169
+ program.addCommand(envCommand);
5170
+ program.addCommand(domainCommand);
5171
+ program.addCommand(serverCommand);
5172
+ program.addCommand(loginCommand);
5173
+ program.addCommand(logoutCommand);
5174
+ program.addCommand(whoamiCommand);
5175
+ program.addCommand(orgCommand);
5176
+ program.addCommand(usageCommand2);
5177
+ program.addCommand(creditCommand);
5178
+ program.addCommand(deployCommand);
5179
+ program.addCommand(selfUpdateCommand);
5180
+ for (const cmd of vmAliases) program.addCommand(cmd);
5181
+ return program;
5182
+ }
5183
+
5024
5184
  // src/index.ts
5025
5185
  var updateCheck = startUpdateCheck();
5026
5186
  try {