@kvbox/cli 0.5.39 → 0.5.41
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 +301 -120
- package/dist/kvbox.js.map +1 -1
- package/package.json +1 -1
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
|
|
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.
|
|
167
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.41" : void 0);
|
|
168
168
|
|
|
169
169
|
// src/commands/vm/index.ts
|
|
170
170
|
import { Command as Command37 } from "commander";
|
|
@@ -919,8 +919,11 @@ var VolumeEventsResponseSchema = z2.object({
|
|
|
919
919
|
events: z2.array(VolumeEventRowSchema),
|
|
920
920
|
next: z2.number().int()
|
|
921
921
|
});
|
|
922
|
+
var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
|
|
923
|
+
var ApiErrorCodeSchema = z2.enum(API_ERROR_CODES);
|
|
922
924
|
var ApiErrorSchema = z2.object({
|
|
923
|
-
error: z2.string()
|
|
925
|
+
error: z2.string(),
|
|
926
|
+
code: ApiErrorCodeSchema.optional()
|
|
924
927
|
});
|
|
925
928
|
var DEFAULT_CLOUD_URL = "https://api.kvbox.sh";
|
|
926
929
|
var ACTIVATED_BY = ["card", "admin"];
|
|
@@ -1332,24 +1335,25 @@ var ServerClient = class {
|
|
|
1332
1335
|
removeBoxHook(name, id) {
|
|
1333
1336
|
return this.call("DELETE", `/machines/${encodeURIComponent(name)}/hooks/${encodeURIComponent(id)}`, WakeHookSchema);
|
|
1334
1337
|
}
|
|
1335
|
-
/** HTTPS names (#31), the control plane's only:
|
|
1338
|
+
/** HTTPS names (#31), the control plane's only: claim another subdomain for the box (up to MAX_BOX_SUBDOMAINS). */
|
|
1336
1339
|
claimSubdomain(name, req) {
|
|
1337
1340
|
return this.call("PUT", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema, req);
|
|
1338
1341
|
}
|
|
1339
|
-
|
|
1340
|
-
|
|
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);
|
|
1341
1345
|
}
|
|
1342
|
-
releaseSubdomain(name) {
|
|
1343
|
-
return this.call("DELETE",
|
|
1346
|
+
releaseSubdomain(name, sub) {
|
|
1347
|
+
return this.call("DELETE", subdomainPath(name, "", sub), SubdomainSchema);
|
|
1344
1348
|
}
|
|
1345
|
-
/** `<route>.<sub>`: a named port under the box's
|
|
1346
|
-
addSubdomainRoute(name, req) {
|
|
1347
|
-
return this.call("POST",
|
|
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);
|
|
1348
1352
|
}
|
|
1349
|
-
removeSubdomainRoute(name, route) {
|
|
1350
|
-
return this.call("DELETE",
|
|
1353
|
+
removeSubdomainRoute(name, route, sub) {
|
|
1354
|
+
return this.call("DELETE", subdomainPath(name, `/routes/${encodeURIComponent(route)}`, sub), SubdomainSchema);
|
|
1351
1355
|
}
|
|
1352
|
-
/** Every readable box's
|
|
1356
|
+
/** Every readable box's subdomains, one entry each. */
|
|
1353
1357
|
listSubdomains() {
|
|
1354
1358
|
return this.call("GET", "/subdomains", z3.array(SubdomainSchema));
|
|
1355
1359
|
}
|
|
@@ -1575,8 +1579,8 @@ async function checkDirect(ep) {
|
|
|
1575
1579
|
}
|
|
1576
1580
|
var NOT_A_HOST_HINT = "kvbox-server is not installed, so this machine is not a kvbox host. Set it up with install-server.sh, or log in to the cloud with: kvbox login";
|
|
1577
1581
|
async function lastErrorLine(logPath, from = 0) {
|
|
1578
|
-
const { readFile:
|
|
1579
|
-
const text2 = (await
|
|
1582
|
+
const { readFile: readFile9 } = await import("fs/promises");
|
|
1583
|
+
const text2 = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
|
|
1580
1584
|
const lines = text2.trimEnd().split("\n").slice(-20).reverse();
|
|
1581
1585
|
return lines.find((l) => l.startsWith("error: "))?.slice("error: ".length);
|
|
1582
1586
|
}
|
|
@@ -1635,6 +1639,9 @@ async function serving(p, timeoutMs, check) {
|
|
|
1635
1639
|
}
|
|
1636
1640
|
throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
|
|
1637
1641
|
}
|
|
1642
|
+
function subdomainPath(box, path, sub) {
|
|
1643
|
+
return `/machines/${encodeURIComponent(box)}/subdomain${path}${sub !== void 0 ? `?sub=${encodeURIComponent(sub)}` : ""}`;
|
|
1644
|
+
}
|
|
1638
1645
|
|
|
1639
1646
|
// src/prompt.ts
|
|
1640
1647
|
import { createInterface } from "readline/promises";
|
|
@@ -2246,28 +2253,28 @@ var getCommand = new Command6("get").description("show one box in full: status,
|
|
|
2246
2253
|
try {
|
|
2247
2254
|
const user = me(client);
|
|
2248
2255
|
const box = await findBox(client, name);
|
|
2249
|
-
const
|
|
2256
|
+
const subs = client.target.kind === "cloud" ? await subdomainsOf(client, box) : [];
|
|
2250
2257
|
if (opts.json) {
|
|
2251
|
-
json({ ...box, ...
|
|
2258
|
+
json({ ...box, ...subs.length > 0 ? { subdomains: subs.map((s) => subdomainJson(s, user)) } : {} });
|
|
2252
2259
|
return;
|
|
2253
2260
|
}
|
|
2254
|
-
const rows2 = getRows(box,
|
|
2261
|
+
const rows2 = getRows(box, subs, user);
|
|
2255
2262
|
const width2 = Math.max(...rows2.map(([k]) => k.length));
|
|
2256
2263
|
for (const [k, v] of rows2) info(`${color.dim(k.padStart(width2))} ${v}`);
|
|
2257
2264
|
} finally {
|
|
2258
2265
|
await client.close();
|
|
2259
2266
|
}
|
|
2260
2267
|
});
|
|
2261
|
-
async function
|
|
2268
|
+
async function subdomainsOf(client, box) {
|
|
2262
2269
|
try {
|
|
2263
2270
|
const slug = slugOf(box.owner);
|
|
2264
|
-
return (await client.listSubdomains()).
|
|
2271
|
+
return (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slug);
|
|
2265
2272
|
} catch (err) {
|
|
2266
2273
|
warn(`HTTPS name not shown: ${err.message}`);
|
|
2267
|
-
return
|
|
2274
|
+
return [];
|
|
2268
2275
|
}
|
|
2269
2276
|
}
|
|
2270
|
-
function getRows(box,
|
|
2277
|
+
function getRows(box, subs, user) {
|
|
2271
2278
|
const rows2 = [
|
|
2272
2279
|
["name", color.bold(displayName(box, user))],
|
|
2273
2280
|
["status", status(box.status)]
|
|
@@ -2279,7 +2286,8 @@ function getRows(box, sub, user) {
|
|
|
2279
2286
|
rows2.push(["ssh", box.ssh ? `ssh -p ${box.ssh.port} ${box.ssh.user}@${box.ssh.host}` : `kvbox connect ${displayName(box, user)}`]);
|
|
2280
2287
|
}
|
|
2281
2288
|
if (box.url !== void 0) rows2.push(["connect", `${box.url} ${color.dim("(password shown once, at new)")}`]);
|
|
2282
|
-
|
|
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(", ")]);
|
|
2283
2291
|
const ports = rowsOf(box, user).map((r) => `${r.guestPort}/${r.proto} \u2192 ${reaches(r, true)}`);
|
|
2284
2292
|
rows2.push(["ports", ports.length === 0 ? "-" : ports.join(", ")]);
|
|
2285
2293
|
rows2.push(["volumes", box.volumes?.length ? box.volumes.map((v) => `${v.name} ${color.dim(`(${v.sizeGib} GB at ${v.mountPath})`)}`).join(", ") : "-"]);
|
|
@@ -2387,6 +2395,7 @@ import { Command as Command11 } from "commander";
|
|
|
2387
2395
|
// ../shared/src/names.ts
|
|
2388
2396
|
import { createHmac } from "crypto";
|
|
2389
2397
|
var DEFAULT_PROXY_DOMAIN = "kvbox.app";
|
|
2398
|
+
var MAX_BOX_SUBDOMAINS = 5;
|
|
2390
2399
|
var LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
2391
2400
|
var RESERVED_SUBDOMAINS = /* @__PURE__ */ new Set([
|
|
2392
2401
|
"admin",
|
|
@@ -2452,7 +2461,7 @@ function assertDomain(text2, proxyDomain) {
|
|
|
2452
2461
|
}
|
|
2453
2462
|
|
|
2454
2463
|
// src/commands/vm/proxy/claim.ts
|
|
2455
|
-
var claimCommand = new Command11("claim").description(
|
|
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) => {
|
|
2456
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>");
|
|
2457
2466
|
if (subArg !== void 0) assertSubdomain(subArg);
|
|
2458
2467
|
if (opts.port !== void 0) parsePorts([opts.port]);
|
|
@@ -2473,6 +2482,7 @@ var claimCommand = new Command11("claim").description("give a box its HTTPS addr
|
|
|
2473
2482
|
}
|
|
2474
2483
|
info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box)} port ${sub.port}`);
|
|
2475
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>`);
|
|
2476
2486
|
if (found.status !== "running") info(` box ${box} is ${found.status}: the address answers once it runs`);
|
|
2477
2487
|
} finally {
|
|
2478
2488
|
await client.close();
|
|
@@ -2484,12 +2494,14 @@ import { Command as Command17 } from "commander";
|
|
|
2484
2494
|
|
|
2485
2495
|
// src/commands/vm/proxy/add.ts
|
|
2486
2496
|
import { Command as Command12 } from "commander";
|
|
2487
|
-
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) => {
|
|
2488
2498
|
const guestPorts = parsePorts(portTexts);
|
|
2489
2499
|
if (opts.name !== void 0) {
|
|
2490
2500
|
assertRouteName(opts.name);
|
|
2491
2501
|
if (guestPorts.length !== 1) throw new KvboxError("--name publishes one port: kvbox vm proxy add <box> <port> --name <name>");
|
|
2492
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>");
|
|
2493
2505
|
}
|
|
2494
2506
|
const proto = opts.udp ? "udp" : "tcp";
|
|
2495
2507
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
@@ -2500,7 +2512,7 @@ var addCommand = new Command12("add").description("publish box ports on the inte
|
|
|
2500
2512
|
const box = displayName(found, user);
|
|
2501
2513
|
if (opts.name !== void 0) {
|
|
2502
2514
|
const route = opts.name;
|
|
2503
|
-
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));
|
|
2504
2516
|
const url = sub.routes.find((r) => r.name === route).url;
|
|
2505
2517
|
if (opts.json) {
|
|
2506
2518
|
json({ box, guestPort: guestPorts[0], proto: "https", url, name: route });
|
|
@@ -2526,7 +2538,7 @@ var addCommand = new Command12("add").description("publish box ports on the inte
|
|
|
2526
2538
|
|
|
2527
2539
|
// src/commands/vm/proxy/ls.ts
|
|
2528
2540
|
import { Command as Command13 } from "commander";
|
|
2529
|
-
async function
|
|
2541
|
+
async function subdomainsOf2(client) {
|
|
2530
2542
|
try {
|
|
2531
2543
|
return await client.listSubdomains();
|
|
2532
2544
|
} catch (err) {
|
|
@@ -2540,7 +2552,7 @@ var lsCommand2 = new Command13("ls").description("list the box ports published o
|
|
|
2540
2552
|
const user = me(client);
|
|
2541
2553
|
const [boxes, subs] = await Promise.all([
|
|
2542
2554
|
name === void 0 ? client.listMachines() : findBox(client, name).then((b) => [b]),
|
|
2543
|
-
client.target.kind === "cloud" ?
|
|
2555
|
+
client.target.kind === "cloud" ? subdomainsOf2(client) : []
|
|
2544
2556
|
]);
|
|
2545
2557
|
const shown = new Set(boxes.map((b) => displayName(b, user)));
|
|
2546
2558
|
const https = subs.flatMap((s) => httpsRowsOf(s, user)).filter((r) => shown.has(r.box));
|
|
@@ -2561,17 +2573,17 @@ var lsCommand2 = new Command13("ls").description("list the box ports published o
|
|
|
2561
2573
|
|
|
2562
2574
|
// src/commands/vm/proxy/release.ts
|
|
2563
2575
|
import { Command as Command14 } from "commander";
|
|
2564
|
-
var releaseCommand = new Command14("release").description("give up a box's HTTPS
|
|
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) => {
|
|
2565
2577
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
2566
2578
|
try {
|
|
2567
2579
|
requireCloud(client);
|
|
2568
2580
|
const box = displayName(await findBox(client, name), me(client));
|
|
2569
|
-
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)) {
|
|
2570
2582
|
info("cancelled");
|
|
2571
2583
|
process.exitCode = 1;
|
|
2572
2584
|
return;
|
|
2573
2585
|
}
|
|
2574
|
-
const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box));
|
|
2586
|
+
const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box, opts.sub));
|
|
2575
2587
|
const names2 = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
|
|
2576
2588
|
info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names2} no longer reach box ${color.bold(box)}`);
|
|
2577
2589
|
} finally {
|
|
@@ -2581,10 +2593,12 @@ var releaseCommand = new Command14("release").description("give up a box's HTTPS
|
|
|
2581
2593
|
|
|
2582
2594
|
// src/commands/vm/proxy/rm.ts
|
|
2583
2595
|
import { Command as Command15 } from "commander";
|
|
2584
|
-
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) => {
|
|
2585
2597
|
if (opts.name !== void 0) {
|
|
2586
2598
|
assertRouteName(opts.name);
|
|
2587
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>");
|
|
2588
2602
|
} else if (portTexts.length === 0) {
|
|
2589
2603
|
throw new KvboxError("which ports? kvbox vm proxy rm <box> <port...>, or --name <name> for an HTTPS name");
|
|
2590
2604
|
}
|
|
@@ -2601,7 +2615,7 @@ var rmCommand = new Command15("rm").description("stop publishing box ports, or a
|
|
|
2601
2615
|
return;
|
|
2602
2616
|
}
|
|
2603
2617
|
if (opts.name !== void 0) {
|
|
2604
|
-
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));
|
|
2605
2619
|
info(`${color.green("\u2713")} ${opts.name}.${sub.url.replace(/^https:\/\//, "")} no longer reaches box ${color.bold(box)}`);
|
|
2606
2620
|
return;
|
|
2607
2621
|
}
|
|
@@ -2614,13 +2628,13 @@ var rmCommand = new Command15("rm").description("stop publishing box ports, or a
|
|
|
2614
2628
|
|
|
2615
2629
|
// src/commands/vm/proxy/set-port.ts
|
|
2616
2630
|
import { Command as Command16 } from "commander";
|
|
2617
|
-
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) => {
|
|
2618
2632
|
const [port] = parsePorts([portText]);
|
|
2619
2633
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
2620
2634
|
try {
|
|
2621
2635
|
requireCloud(client);
|
|
2622
2636
|
const box = displayName(await findBox(client, name), me(client));
|
|
2623
|
-
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));
|
|
2624
2638
|
if (opts.json) {
|
|
2625
2639
|
json(subdomainJson(sub, me(client)));
|
|
2626
2640
|
return;
|
|
@@ -3824,6 +3838,7 @@ var PricingSchema = z4.object({
|
|
|
3824
3838
|
volumeGibHour: z4.number().nonnegative().default(0),
|
|
3825
3839
|
diskIncludedGib: z4.number().int().nonnegative().default(0)
|
|
3826
3840
|
});
|
|
3841
|
+
var PriceListSchema = PricingSchema.extend({ welcomeCredit: z4.number().nonnegative() });
|
|
3827
3842
|
var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
|
|
3828
3843
|
function costOf(t, pricing) {
|
|
3829
3844
|
return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;
|
|
@@ -4024,28 +4039,18 @@ function creditRow(b, me2) {
|
|
|
4024
4039
|
}
|
|
4025
4040
|
|
|
4026
4041
|
// src/commands/deploy/index.ts
|
|
4027
|
-
import { readFile as
|
|
4042
|
+
import { access as access4, readFile as readFile8 } from "fs/promises";
|
|
4028
4043
|
import { basename, resolve as resolve2 } from "path";
|
|
4029
4044
|
import { Command as Command61, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
|
|
4030
4045
|
|
|
4031
4046
|
// src/commands/deploy/config.ts
|
|
4032
|
-
import { readFile as
|
|
4033
|
-
import { join as
|
|
4047
|
+
import { readFile as readFile7, writeFile as writeFile4 } from "fs/promises";
|
|
4048
|
+
import { join as join6 } from "path";
|
|
4034
4049
|
import { z as z5 } from "zod";
|
|
4035
4050
|
|
|
4036
|
-
// src/commands/deploy/templates/
|
|
4037
|
-
import {
|
|
4051
|
+
// src/commands/deploy/templates/docker.ts
|
|
4052
|
+
import { readFile as readFile6 } from "fs/promises";
|
|
4038
4053
|
import { join as join2 } from "path";
|
|
4039
|
-
async function packageManager(dir) {
|
|
4040
|
-
const has = (f) => access(join2(dir, f)).then(() => true, () => false);
|
|
4041
|
-
if (await has("pnpm-lock.yaml")) return "pnpm";
|
|
4042
|
-
if (await has("yarn.lock")) return "yarn";
|
|
4043
|
-
if (await has("bun.lockb") || await has("bun.lock")) return "bun";
|
|
4044
|
-
return "npm";
|
|
4045
|
-
}
|
|
4046
|
-
function runScript(pm, script) {
|
|
4047
|
-
return pm === "yarn" ? [script] : ["run", script];
|
|
4048
|
-
}
|
|
4049
4054
|
|
|
4050
4055
|
// src/commands/deploy/templates/server.ts
|
|
4051
4056
|
var APP_DIR = "/srv/app/current";
|
|
@@ -4053,6 +4058,7 @@ var SERVICE = "kvbox-app";
|
|
|
4053
4058
|
var START_WAIT_SEC = 30;
|
|
4054
4059
|
var APP_NOT_LISTENING = 4;
|
|
4055
4060
|
var LOG_MARKER = "--- kvbox-app log ---";
|
|
4061
|
+
var DROP_CONTAINER = `if systemctl is-active --quiet docker && docker inspect ${SERVICE} >/dev/null 2>&1; then docker rm -f ${SERVICE} >/dev/null 2>&1 || true; docker rmi ${SERVICE} >/dev/null 2>&1 || true; sudo -n systemctl disable --quiet docker 2>/dev/null || true; fi`;
|
|
4056
4062
|
function commands(pm) {
|
|
4057
4063
|
switch (pm) {
|
|
4058
4064
|
case "pnpm":
|
|
@@ -4107,6 +4113,8 @@ function serverRemote(opts) {
|
|
|
4107
4113
|
`mv /srv/app/.incoming ${APP_DIR}`,
|
|
4108
4114
|
"sudo -n systemctl daemon-reload",
|
|
4109
4115
|
`sudo -n systemctl enable --quiet ${SERVICE}`,
|
|
4116
|
+
// A box that switched from the Docker template: its container holds the same box port.
|
|
4117
|
+
DROP_CONTAINER,
|
|
4110
4118
|
`sudo -n systemctl restart ${SERVICE}`,
|
|
4111
4119
|
"rm -rf /srv/app/.old",
|
|
4112
4120
|
// bash's /dev/tcp: no curl or nc in the image needed.
|
|
@@ -4119,6 +4127,81 @@ function serverRemote(opts) {
|
|
|
4119
4127
|
].join("\n");
|
|
4120
4128
|
}
|
|
4121
4129
|
|
|
4130
|
+
// src/commands/deploy/templates/docker.ts
|
|
4131
|
+
var CONTAINER = "kvbox-app";
|
|
4132
|
+
var BUILD_LOG_LINES = 60;
|
|
4133
|
+
function exposedPort(dockerfile) {
|
|
4134
|
+
const m = /^\s*EXPOSE\s+(\d+)/im.exec(dockerfile);
|
|
4135
|
+
return m ? Number(m[1]) : void 0;
|
|
4136
|
+
}
|
|
4137
|
+
var dockerTemplate = {
|
|
4138
|
+
id: "docker",
|
|
4139
|
+
label: "Docker",
|
|
4140
|
+
hint: "built from the Dockerfile in the box, run as a container on $PORT (3000)",
|
|
4141
|
+
size: "s",
|
|
4142
|
+
port: 3e3,
|
|
4143
|
+
customPort: true,
|
|
4144
|
+
listens: "The container must listen on the port its Dockerfile EXPOSEs (or on PORT, 3000, without one)",
|
|
4145
|
+
logs: `docker logs ${CONTAINER}`,
|
|
4146
|
+
detect(_pkg, dir) {
|
|
4147
|
+
return dir.dockerfile;
|
|
4148
|
+
},
|
|
4149
|
+
/** No local build: the box does it. The Dockerfile is read for its EXPOSE port only. */
|
|
4150
|
+
async build(ctx) {
|
|
4151
|
+
const dockerfile = await readFile6(join2(ctx.dir, "Dockerfile"), "utf8").catch(() => void 0);
|
|
4152
|
+
if (dockerfile === void 0) throw new KvboxError(`${ctx.dir}: no Dockerfile; the Docker template builds the image from it`);
|
|
4153
|
+
const containerPort = exposedPort(dockerfile);
|
|
4154
|
+
return { outDir: ctx.dir, exclude: ["node_modules", ".git"], pm: "npm", what: "the source", ...containerPort !== void 0 ? { containerPort } : {} };
|
|
4155
|
+
},
|
|
4156
|
+
remote(built, port) {
|
|
4157
|
+
return dockerRemote(port, built.containerPort ?? port);
|
|
4158
|
+
}
|
|
4159
|
+
};
|
|
4160
|
+
function dockerRemote(port, containerPort) {
|
|
4161
|
+
return [
|
|
4162
|
+
"set -eo pipefail",
|
|
4163
|
+
"test -d /srv/app -a -w /srv/app || exit 3",
|
|
4164
|
+
"command -v docker >/dev/null || exit 3",
|
|
4165
|
+
"rm -rf /srv/app/.incoming /srv/app/.old",
|
|
4166
|
+
"mkdir -p /srv/app/.incoming",
|
|
4167
|
+
"tar -xf - -C /srv/app/.incoming",
|
|
4168
|
+
"cd /srv/app/.incoming",
|
|
4169
|
+
// Plain progress, not -q: a failed RUN step then shows its own output (npm's error, say), which
|
|
4170
|
+
// quiet mode drops; the last lines are enough and are what the CLI prints on a failure.
|
|
4171
|
+
`docker build --progress=plain -t ${CONTAINER} . 2>&1 | tail -n ${BUILD_LOG_LINES}`,
|
|
4172
|
+
"cd /",
|
|
4173
|
+
`if [ -e ${APP_DIR} ]; then mv ${APP_DIR} /srv/app/.old; fi`,
|
|
4174
|
+
`mv /srv/app/.incoming ${APP_DIR}`,
|
|
4175
|
+
"rm -rf /srv/app/.old",
|
|
4176
|
+
"sudo -n systemctl enable --quiet docker",
|
|
4177
|
+
// A box that switched from the Next.js or Node template: its service holds the same box port.
|
|
4178
|
+
`sudo -n systemctl disable --now --quiet ${SERVICE} 2>/dev/null || true`,
|
|
4179
|
+
`docker rm -f ${CONTAINER} >/dev/null 2>&1 || true`,
|
|
4180
|
+
`docker run -d --name ${CONTAINER} --restart unless-stopped -p ${port}:${containerPort} -e PORT=${containerPort} ${CONTAINER} >/dev/null`,
|
|
4181
|
+
"docker image prune -f >/dev/null",
|
|
4182
|
+
"i=0",
|
|
4183
|
+
`until ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ${CONTAINER} 2>/dev/null) && [ -n "$ip" ] && timeout 1 bash -c "</dev/tcp/$ip/${containerPort}" 2>/dev/null; do`,
|
|
4184
|
+
" i=$((i+1))",
|
|
4185
|
+
` if [ "$i" -ge ${START_WAIT_SEC} ] || [ "$(docker inspect -f '{{.State.Running}}' ${CONTAINER} 2>/dev/null)" != true ]; then echo '${LOG_MARKER}'; docker logs --tail 20 ${CONTAINER} 2>&1 || true; exit ${APP_NOT_LISTENING}; fi`,
|
|
4186
|
+
" sleep 1",
|
|
4187
|
+
"done"
|
|
4188
|
+
].join("\n");
|
|
4189
|
+
}
|
|
4190
|
+
|
|
4191
|
+
// src/commands/deploy/templates/pm.ts
|
|
4192
|
+
import { access } from "fs/promises";
|
|
4193
|
+
import { join as join3 } from "path";
|
|
4194
|
+
async function packageManager(dir) {
|
|
4195
|
+
const has = (f) => access(join3(dir, f)).then(() => true, () => false);
|
|
4196
|
+
if (await has("pnpm-lock.yaml")) return "pnpm";
|
|
4197
|
+
if (await has("yarn.lock")) return "yarn";
|
|
4198
|
+
if (await has("bun.lockb") || await has("bun.lock")) return "bun";
|
|
4199
|
+
return "npm";
|
|
4200
|
+
}
|
|
4201
|
+
function runScript(pm, script) {
|
|
4202
|
+
return pm === "yarn" ? [script] : ["run", script];
|
|
4203
|
+
}
|
|
4204
|
+
|
|
4122
4205
|
// src/commands/deploy/templates/nextjs.ts
|
|
4123
4206
|
var nextjsTemplate = {
|
|
4124
4207
|
id: "nextjs",
|
|
@@ -4174,7 +4257,7 @@ var nodeTemplate = {
|
|
|
4174
4257
|
// src/commands/deploy/templates/react.ts
|
|
4175
4258
|
import { spawn as spawn5 } from "child_process";
|
|
4176
4259
|
import { access as access2 } from "fs/promises";
|
|
4177
|
-
import { join as
|
|
4260
|
+
import { join as join4 } from "path";
|
|
4178
4261
|
var OUT_DIRS = ["dist", "build"];
|
|
4179
4262
|
async function runBuild(dir, pm) {
|
|
4180
4263
|
const args = runScript(pm, "build");
|
|
@@ -4205,47 +4288,72 @@ var reactTemplate = {
|
|
|
4205
4288
|
await runBuild(ctx.dir, pm);
|
|
4206
4289
|
const candidates = ctx.dist !== void 0 ? [ctx.dist] : OUT_DIRS;
|
|
4207
4290
|
for (const dist of candidates) {
|
|
4208
|
-
const outDir =
|
|
4209
|
-
if (await access2(
|
|
4291
|
+
const outDir = join4(ctx.dir, dist);
|
|
4292
|
+
if (await access2(join4(outDir, "index.html")).then(() => true, () => false)) return { outDir, dist, exclude: [], pm, what: `${dist}/` };
|
|
4210
4293
|
}
|
|
4211
4294
|
throw new KvboxError(
|
|
4212
4295
|
`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`
|
|
4213
4296
|
);
|
|
4214
4297
|
},
|
|
4215
|
-
|
|
4216
|
-
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
|
|
4220
|
-
|
|
4221
|
-
|
|
4222
|
-
|
|
4223
|
-
|
|
4224
|
-
|
|
4225
|
-
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
|
|
4232
|
-
|
|
4233
|
-
|
|
4234
|
-
|
|
4235
|
-
|
|
4236
|
-
|
|
4298
|
+
remote: nginxRemote
|
|
4299
|
+
};
|
|
4300
|
+
function nginxRemote() {
|
|
4301
|
+
return [
|
|
4302
|
+
"set -e",
|
|
4303
|
+
"test -e /etc/nginx/sites-enabled/kvbox-app || exit 3",
|
|
4304
|
+
"rm -rf /srv/app/.incoming /srv/app/.old",
|
|
4305
|
+
"mkdir -p /srv/app/.incoming",
|
|
4306
|
+
"tar -xf - -C /srv/app/.incoming",
|
|
4307
|
+
"chmod -R a+rX /srv/app/.incoming",
|
|
4308
|
+
"if [ -e /srv/app/dist ]; then mv /srv/app/dist /srv/app/.old; fi",
|
|
4309
|
+
"mv /srv/app/.incoming /srv/app/dist",
|
|
4310
|
+
"rm -rf /srv/app/.old",
|
|
4311
|
+
// A box that switched from the Docker template: its container would keep running (and its RAM) for nothing.
|
|
4312
|
+
DROP_CONTAINER,
|
|
4313
|
+
"sudo -n systemctl enable --now --quiet nginx",
|
|
4314
|
+
"sudo -n systemctl reload nginx"
|
|
4315
|
+
].join("\n");
|
|
4316
|
+
}
|
|
4317
|
+
|
|
4318
|
+
// src/commands/deploy/templates/static.ts
|
|
4319
|
+
import { access as access3 } from "fs/promises";
|
|
4320
|
+
import { join as join5 } from "path";
|
|
4321
|
+
var EXCLUDE = ["node_modules", ".git", "kvbox.json"];
|
|
4322
|
+
var staticTemplate = {
|
|
4323
|
+
id: "static",
|
|
4324
|
+
label: "Static site",
|
|
4325
|
+
hint: "plain HTML, CSS and JS: shipped as is, served by nginx in the box",
|
|
4326
|
+
size: "xs",
|
|
4327
|
+
port: 80,
|
|
4328
|
+
/** 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. */
|
|
4329
|
+
detect(pkg, dir) {
|
|
4330
|
+
return dir.indexHtml && typeof pkg?.scripts?.["build"] !== "string";
|
|
4331
|
+
},
|
|
4332
|
+
async build(ctx) {
|
|
4333
|
+
const dist = ctx.dist;
|
|
4334
|
+
const outDir = dist !== void 0 ? join5(ctx.dir, dist) : ctx.dir;
|
|
4335
|
+
if (!await access3(join5(outDir, "index.html")).then(() => true, () => false)) {
|
|
4336
|
+
throw new KvboxError(
|
|
4337
|
+
`${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`
|
|
4338
|
+
);
|
|
4339
|
+
}
|
|
4340
|
+
const pm = ctx.pkg !== void 0 ? await packageManager(ctx.dir) : "npm";
|
|
4341
|
+
return { outDir, ...dist !== void 0 ? { dist } : {}, exclude: EXCLUDE, pm, what: dist !== void 0 ? `${dist}/` : "the directory" };
|
|
4342
|
+
},
|
|
4343
|
+
remote: nginxRemote
|
|
4237
4344
|
};
|
|
4238
4345
|
|
|
4239
4346
|
// src/commands/deploy/templates/index.ts
|
|
4240
|
-
var TEMPLATES = [reactTemplate, nextjsTemplate, nodeTemplate];
|
|
4347
|
+
var TEMPLATES = [dockerTemplate, reactTemplate, nextjsTemplate, nodeTemplate, staticTemplate];
|
|
4241
4348
|
var TEMPLATE_IDS = TEMPLATES.map((t) => t.id);
|
|
4242
4349
|
function templateById(id) {
|
|
4243
4350
|
const t = TEMPLATES.find((x) => x.id === id);
|
|
4244
4351
|
if (!t) throw new Error(`no template ${id}`);
|
|
4245
4352
|
return t;
|
|
4246
4353
|
}
|
|
4247
|
-
|
|
4248
|
-
|
|
4354
|
+
var NO_FACTS = { indexHtml: false, dockerfile: false };
|
|
4355
|
+
function detectTemplates(pkg, dir = NO_FACTS) {
|
|
4356
|
+
return TEMPLATES.filter((t) => t.detect(pkg, dir));
|
|
4249
4357
|
}
|
|
4250
4358
|
|
|
4251
4359
|
// src/commands/deploy/config.ts
|
|
@@ -4269,10 +4377,10 @@ var DeployConfigSchema = z5.object({
|
|
|
4269
4377
|
port: z5.number().int().min(1).max(65535).optional()
|
|
4270
4378
|
});
|
|
4271
4379
|
async function readConfig(dir) {
|
|
4272
|
-
const path =
|
|
4380
|
+
const path = join6(dir, CONFIG_FILE);
|
|
4273
4381
|
let raw;
|
|
4274
4382
|
try {
|
|
4275
|
-
raw = await
|
|
4383
|
+
raw = await readFile7(path, "utf8");
|
|
4276
4384
|
} catch (err) {
|
|
4277
4385
|
if (err.code === "ENOENT") return void 0;
|
|
4278
4386
|
throw err;
|
|
@@ -4291,7 +4399,7 @@ async function readConfig(dir) {
|
|
|
4291
4399
|
return parsed.data;
|
|
4292
4400
|
}
|
|
4293
4401
|
async function writeConfig(dir, config) {
|
|
4294
|
-
await writeFile4(
|
|
4402
|
+
await writeFile4(join6(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
|
|
4295
4403
|
}
|
|
4296
4404
|
function nameFromDir(dirName) {
|
|
4297
4405
|
const slug = dirName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 12).replace(/-+$/, "");
|
|
@@ -4304,7 +4412,7 @@ function subdomainFor(name) {
|
|
|
4304
4412
|
// src/commands/deploy/ship.ts
|
|
4305
4413
|
import { spawn as spawn6 } from "child_process";
|
|
4306
4414
|
import { readdir, stat as stat2 } from "fs/promises";
|
|
4307
|
-
import { join as
|
|
4415
|
+
import { join as join7 } from "path";
|
|
4308
4416
|
var IMAGE_TOO_OLD = 3;
|
|
4309
4417
|
var SSH_FAILED3 = 255;
|
|
4310
4418
|
async function measure(dir, exclude = []) {
|
|
@@ -4312,7 +4420,7 @@ async function measure(dir, exclude = []) {
|
|
|
4312
4420
|
const walk = async (d) => {
|
|
4313
4421
|
for (const entry of await readdir(d, { withFileTypes: true })) {
|
|
4314
4422
|
if (exclude.includes(entry.name)) continue;
|
|
4315
|
-
const path =
|
|
4423
|
+
const path = join7(d, entry.name);
|
|
4316
4424
|
if (entry.isDirectory()) await walk(path);
|
|
4317
4425
|
else if (entry.isFile()) {
|
|
4318
4426
|
total.files += 1;
|
|
@@ -4355,9 +4463,10 @@ async function ship(ep, dir, remote, exclude = []) {
|
|
|
4355
4463
|
var shipping = { ship, measure, waitForSsh };
|
|
4356
4464
|
|
|
4357
4465
|
// src/commands/deploy/index.ts
|
|
4358
|
-
var deployCommand = new Command61("deploy").description("put the app in this directory (React, Next.js or a
|
|
4466
|
+
var deployCommand = new Command61("deploy").description("put the app in this directory (React, Next.js, a Node server, a Dockerfile or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the box port of a Next.js app, Node server or container (default 3000; saved to kvbox.json)", parsePort).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
|
|
4359
4467
|
const dir = resolve2(dirArg ?? ".");
|
|
4360
4468
|
const pkg = await readPackageJson(dir);
|
|
4469
|
+
const facts = { indexHtml: await exists(resolve2(dir, "index.html")), dockerfile: await exists(resolve2(dir, "Dockerfile")) };
|
|
4361
4470
|
const saved = await readConfig(dir);
|
|
4362
4471
|
const globals = cmd.optsWithGlobals();
|
|
4363
4472
|
const orgFlag = orgOption(globals);
|
|
@@ -4366,7 +4475,7 @@ var deployCommand = new Command61("deploy").description("put the app in this dir
|
|
|
4366
4475
|
try {
|
|
4367
4476
|
const cloud = client.target.kind === "cloud";
|
|
4368
4477
|
if (!cloud && org !== void 0) throw new KvboxError("--org needs a control plane: kvbox login, or drop --org");
|
|
4369
|
-
const { config, template, fresh } = await settle(dir, pkg, saved, opts, orgFlag, cloud);
|
|
4478
|
+
const { config, template, fresh } = await settle(dir, pkg, facts, saved, opts, orgFlag, cloud);
|
|
4370
4479
|
if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, config);
|
|
4371
4480
|
await writeConfig(dir, config);
|
|
4372
4481
|
if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
|
|
@@ -4400,8 +4509,9 @@ ${result.output.trim()}` : ""}`, SSH_FAILED3);
|
|
|
4400
4509
|
}
|
|
4401
4510
|
if (result.status === APP_NOT_LISTENING) {
|
|
4402
4511
|
const log = result.output.split(LOG_MARKER)[1]?.trim();
|
|
4512
|
+
const where = built.containerPort !== void 0 && built.containerPort !== port ? `the container's port ${built.containerPort} (box port ${port})` : `port ${port}`;
|
|
4403
4513
|
throw new KvboxError(
|
|
4404
|
-
`the app did not answer on
|
|
4514
|
+
`the app did not answer on ${where} within ${START_WAIT_SEC} s: it crashed, or listens on another port. ${template.listens ?? `It must listen on process.env.PORT (${port})`}${template.customPort ? ", or say its port with --port" : ""}. Its log: kvbox exec ${ref} -- ${template.logs ?? "journalctl -u kvbox-app"}${log ? `
|
|
4405
4515
|
last lines:
|
|
4406
4516
|
${log}` : ""}`
|
|
4407
4517
|
);
|
|
@@ -4435,16 +4545,17 @@ function parsePort(v) {
|
|
|
4435
4545
|
if (portProblem(v)) throw new InvalidArgumentError2("expected a port, 1-65535");
|
|
4436
4546
|
return Number(v);
|
|
4437
4547
|
}
|
|
4548
|
+
var exists = (path) => access4(path).then(() => true, () => false);
|
|
4438
4549
|
async function readPackageJson(dir) {
|
|
4439
4550
|
try {
|
|
4440
|
-
return JSON.parse(await
|
|
4551
|
+
return JSON.parse(await readFile8(resolve2(dir, "package.json"), "utf8"));
|
|
4441
4552
|
} catch (err) {
|
|
4442
4553
|
if (err.code === "ENOENT") return void 0;
|
|
4443
4554
|
throw new KvboxError(`${resolve2(dir, "package.json")}: ${err.message}`);
|
|
4444
4555
|
}
|
|
4445
4556
|
}
|
|
4446
|
-
async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
|
|
4447
|
-
const detected =
|
|
4557
|
+
async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
|
|
4558
|
+
const [detected, ...also] = detectTemplates(pkg, facts);
|
|
4448
4559
|
if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
|
|
4449
4560
|
if (opts.sub !== void 0) assertSubdomain(opts.sub);
|
|
4450
4561
|
const renamed = saved !== void 0 && (opts.name !== void 0 && opts.name !== saved.name || orgFlag !== void 0 && orgFlag !== saved.org);
|
|
@@ -4475,10 +4586,13 @@ async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
|
|
|
4475
4586
|
`);
|
|
4476
4587
|
let templateId = defaults.template;
|
|
4477
4588
|
if (open.template && ask) {
|
|
4478
|
-
const initial =
|
|
4479
|
-
templateId = await select("Template", TEMPLATES.map((t) => ({ value: t.id, label: t.label, hint: t === detected ? `${t.hint} \xB7 detected` : t.hint })), initial);
|
|
4589
|
+
const initial = TEMPLATES.indexOf(detected ?? templateById("react"));
|
|
4590
|
+
templateId = await select("Template", TEMPLATES.map((t) => ({ value: t.id, label: t.label, hint: t === detected ? `${t.hint} \xB7 detected${also.length ? `, also ${also.map((a) => a.label).join(", ")}` : ""}` : t.hint })), initial);
|
|
4480
4591
|
}
|
|
4481
|
-
if (
|
|
4592
|
+
if (open.template && !ask && detected !== void 0 && also.length > 0 && templateId === detected.id) {
|
|
4593
|
+
info(` ${detected.label} detected: deploying with it. The app is also ${also.map((a) => `${a.label} (--template ${a.id})`).join(", ")}; say so to use that instead.`);
|
|
4594
|
+
}
|
|
4595
|
+
if (templateId === void 0) throw new KvboxError(`could not tell what kind of app ${dir} is (no Dockerfile, 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("|")}`);
|
|
4482
4596
|
const template = templateById(templateId);
|
|
4483
4597
|
let name = defaults.name;
|
|
4484
4598
|
if (open.name && ask) name = await text("Box name", { default: defaults.name, validate: (a) => BOX_NAME_RE.test(a) ? void 0 : NAME_RULE });
|
|
@@ -4529,22 +4643,23 @@ async function findOrCreate(client, config) {
|
|
|
4529
4643
|
}
|
|
4530
4644
|
return { box, ref: displayName(box, user), created };
|
|
4531
4645
|
}
|
|
4532
|
-
async function
|
|
4646
|
+
async function existingAddresses(client, config) {
|
|
4533
4647
|
const slug = config.org ?? me(client);
|
|
4534
|
-
return (await client.listSubdomains()).
|
|
4648
|
+
return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
|
|
4535
4649
|
}
|
|
4536
4650
|
async function refuseOtherAddress(client, config) {
|
|
4537
|
-
const have = await
|
|
4538
|
-
if (
|
|
4651
|
+
const have = await existingAddresses(client, config);
|
|
4652
|
+
if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
|
|
4539
4653
|
const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
|
|
4540
4654
|
throw new KvboxError(
|
|
4541
|
-
`box ${ref} already
|
|
4655
|
+
`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>`
|
|
4542
4656
|
);
|
|
4543
4657
|
}
|
|
4544
4658
|
async function address(client, box, ref, config, port) {
|
|
4545
|
-
const
|
|
4659
|
+
const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
|
|
4660
|
+
const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
|
|
4546
4661
|
if (have) {
|
|
4547
|
-
if (have.port !== port) await client.setSubdomainPort(ref, { port });
|
|
4662
|
+
if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
|
|
4548
4663
|
return { url: have.url, subdomain: have.subdomain };
|
|
4549
4664
|
}
|
|
4550
4665
|
const wanted = config.subdomain ?? subdomainFor(config.name);
|
|
@@ -4977,25 +5092,12 @@ var rmCommand9 = new Command74("rm").alias("remove").description("stop serving a
|
|
|
4977
5092
|
var domainCommand = new Command75("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand10).addCommand(rmCommand9);
|
|
4978
5093
|
for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
|
|
4979
5094
|
|
|
4980
|
-
// src/
|
|
4981
|
-
|
|
4982
|
-
|
|
4983
|
-
|
|
4984
|
-
|
|
4985
|
-
|
|
4986
|
-
program.addCommand(envCommand);
|
|
4987
|
-
program.addCommand(domainCommand);
|
|
4988
|
-
program.addCommand(serverCommand);
|
|
4989
|
-
program.addCommand(loginCommand);
|
|
4990
|
-
program.addCommand(logoutCommand);
|
|
4991
|
-
program.addCommand(whoamiCommand);
|
|
4992
|
-
program.addCommand(orgCommand);
|
|
4993
|
-
program.addCommand(usageCommand2);
|
|
4994
|
-
program.addCommand(creditCommand);
|
|
4995
|
-
program.addCommand(deployCommand);
|
|
4996
|
-
for (const cmd of vmAliases) program.addCommand(cmd);
|
|
4997
|
-
return program;
|
|
4998
|
-
}
|
|
5095
|
+
// src/commands/update.ts
|
|
5096
|
+
import { spawn as spawn7 } from "child_process";
|
|
5097
|
+
import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
5098
|
+
import { tmpdir } from "os";
|
|
5099
|
+
import { join as join8 } from "path";
|
|
5100
|
+
import { Command as Command76 } from "commander";
|
|
4999
5101
|
|
|
5000
5102
|
// src/update.ts
|
|
5001
5103
|
import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
|
|
@@ -5003,7 +5105,11 @@ import { dirname } from "path";
|
|
|
5003
5105
|
var REGISTRY_URL = "https://registry.npmjs.org/@kvbox/cli/latest";
|
|
5004
5106
|
var CHECK_EVERY_MS = 24 * 60 * 60 * 1e3;
|
|
5005
5107
|
var FETCH_TIMEOUT_MS = 1500;
|
|
5006
|
-
var UPDATE_COMMAND = "
|
|
5108
|
+
var UPDATE_COMMAND = "kvbox update";
|
|
5109
|
+
var suppressed = false;
|
|
5110
|
+
function suppressUpdateNotice() {
|
|
5111
|
+
suppressed = true;
|
|
5112
|
+
}
|
|
5007
5113
|
function isNewer(a, b) {
|
|
5008
5114
|
const pa = parse(a);
|
|
5009
5115
|
const pb = parse(b);
|
|
@@ -5069,6 +5175,7 @@ function enabled() {
|
|
|
5069
5175
|
function startUpdateCheck() {
|
|
5070
5176
|
if (!enabled()) return Promise.resolve();
|
|
5071
5177
|
process.on("exit", () => {
|
|
5178
|
+
if (suppressed) return;
|
|
5072
5179
|
const state = readUpdateState();
|
|
5073
5180
|
const notice = state ? updateNotice(state.latest) : null;
|
|
5074
5181
|
if (notice) process.stderr.write(notice);
|
|
@@ -5076,6 +5183,80 @@ function startUpdateCheck() {
|
|
|
5076
5183
|
return refreshUpdateState();
|
|
5077
5184
|
}
|
|
5078
5185
|
|
|
5186
|
+
// src/commands/update.ts
|
|
5187
|
+
var INSTALL_BASE = "https://kvbox.sh";
|
|
5188
|
+
function installerFor(platform, base = INSTALL_BASE) {
|
|
5189
|
+
const root = base.replace(/\/+$/, "");
|
|
5190
|
+
if (platform === "win32") {
|
|
5191
|
+
const url = `${root}/install.ps1`;
|
|
5192
|
+
return {
|
|
5193
|
+
url,
|
|
5194
|
+
cmd: "powershell.exe",
|
|
5195
|
+
args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${url} | iex`]
|
|
5196
|
+
};
|
|
5197
|
+
}
|
|
5198
|
+
return { url: `${root}/install.sh`, cmd: "bash", args: ["{script}"] };
|
|
5199
|
+
}
|
|
5200
|
+
async function download(url) {
|
|
5201
|
+
let res;
|
|
5202
|
+
try {
|
|
5203
|
+
res = await fetch(url, { signal: AbortSignal.timeout(3e4) });
|
|
5204
|
+
} catch (err) {
|
|
5205
|
+
throw new KvboxError(`could not download ${url}: ${err.message}`);
|
|
5206
|
+
}
|
|
5207
|
+
if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
|
|
5208
|
+
const body = await res.text();
|
|
5209
|
+
if (!body.startsWith("#!")) throw new KvboxError(`${url} did not return a shell script`);
|
|
5210
|
+
return body;
|
|
5211
|
+
}
|
|
5212
|
+
function run(cmd, args) {
|
|
5213
|
+
return new Promise((resolve3, reject) => {
|
|
5214
|
+
const child = spawn7(cmd, args, { stdio: "inherit" });
|
|
5215
|
+
child.on("error", (err) => reject(new KvboxError(`could not run ${cmd}: ${err.message}`)));
|
|
5216
|
+
child.on("exit", (code, signal) => resolve3(code ?? (signal ? 1 : 0)));
|
|
5217
|
+
});
|
|
5218
|
+
}
|
|
5219
|
+
var selfUpdateCommand = new Command76("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
|
|
5220
|
+
suppressUpdateNotice();
|
|
5221
|
+
const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
|
|
5222
|
+
let code;
|
|
5223
|
+
if (process.platform === "win32") {
|
|
5224
|
+
code = await run(inst.cmd, inst.args);
|
|
5225
|
+
} else {
|
|
5226
|
+
const script = await download(inst.url);
|
|
5227
|
+
const dir = mkdtempSync(join8(tmpdir(), "kvbox-update-"));
|
|
5228
|
+
const file = join8(dir, "install.sh");
|
|
5229
|
+
try {
|
|
5230
|
+
writeFileSync2(file, script, { mode: 448 });
|
|
5231
|
+
code = await run(inst.cmd, inst.args.map((a) => a === "{script}" ? file : a));
|
|
5232
|
+
} finally {
|
|
5233
|
+
rmSync(dir, { recursive: true, force: true });
|
|
5234
|
+
}
|
|
5235
|
+
}
|
|
5236
|
+
if (code !== 0) throw new KvboxError(`the installer failed (exit ${code})`, code);
|
|
5237
|
+
});
|
|
5238
|
+
|
|
5239
|
+
// src/program.ts
|
|
5240
|
+
function buildProgram() {
|
|
5241
|
+
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();
|
|
5242
|
+
program.addCommand(vmCommand);
|
|
5243
|
+
program.addCommand(snapshotsCommand);
|
|
5244
|
+
program.addCommand(volumeCommand);
|
|
5245
|
+
program.addCommand(envCommand);
|
|
5246
|
+
program.addCommand(domainCommand);
|
|
5247
|
+
program.addCommand(serverCommand);
|
|
5248
|
+
program.addCommand(loginCommand);
|
|
5249
|
+
program.addCommand(logoutCommand);
|
|
5250
|
+
program.addCommand(whoamiCommand);
|
|
5251
|
+
program.addCommand(orgCommand);
|
|
5252
|
+
program.addCommand(usageCommand2);
|
|
5253
|
+
program.addCommand(creditCommand);
|
|
5254
|
+
program.addCommand(deployCommand);
|
|
5255
|
+
program.addCommand(selfUpdateCommand);
|
|
5256
|
+
for (const cmd of vmAliases) program.addCommand(cmd);
|
|
5257
|
+
return program;
|
|
5258
|
+
}
|
|
5259
|
+
|
|
5079
5260
|
// src/index.ts
|
|
5080
5261
|
var updateCheck = startUpdateCheck();
|
|
5081
5262
|
try {
|