@kvbox/cli 0.5.46 → 0.5.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kvbox.js CHANGED
@@ -164,7 +164,7 @@ function versionOf(srcFileUrl, injected) {
164
164
  }
165
165
 
166
166
  // src/version.ts
167
- var VERSION = versionOf(import.meta.url, true ? "0.5.46" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.47" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command37 } from "commander";
@@ -1632,17 +1632,17 @@ function sshArgs(ep, p = paths()) {
1632
1632
  async function waitForSsh(ep, timeoutMs = 3e4) {
1633
1633
  const { connect } = await import("net");
1634
1634
  const deadline = Date.now() + timeoutMs;
1635
- const attempt = () => new Promise((resolve3) => {
1635
+ const attempt = () => new Promise((resolve4) => {
1636
1636
  const sock = connect({ host: ep.host, port: ep.port, timeout: 1e3 });
1637
1637
  sock.once("connect", () => {
1638
1638
  sock.destroy();
1639
- resolve3(true);
1639
+ resolve4(true);
1640
1640
  });
1641
1641
  sock.once("timeout", () => {
1642
1642
  sock.destroy();
1643
- resolve3(false);
1643
+ resolve4(false);
1644
1644
  });
1645
- sock.once("error", () => resolve3(false));
1645
+ sock.once("error", () => resolve4(false));
1646
1646
  });
1647
1647
  while (Date.now() < deadline) {
1648
1648
  if (await attempt()) return;
@@ -1657,8 +1657,8 @@ async function checkDirect(ep) {
1657
1657
  }
1658
1658
  var NOT_A_HOST_HINT = "kvbox-server is not installed, so this machine is not a kvbox host. Set it up with install-server.sh, or log in to the cloud with: kvbox login";
1659
1659
  async function lastErrorLine(logPath, from = 0) {
1660
- const { readFile: readFile8 } = await import("fs/promises");
1661
- const text2 = (await readFile8(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
1660
+ const { readFile: readFile9 } = await import("fs/promises");
1661
+ const text2 = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
1662
1662
  for (const line of text2.trimEnd().split("\n").slice(-20).reverse()) {
1663
1663
  const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
1664
1664
  if (m?.[1] !== void 0) return m[1];
@@ -1787,7 +1787,7 @@ async function select(message, choices, initial = 0) {
1787
1787
  render();
1788
1788
  let done = false;
1789
1789
  try {
1790
- return await new Promise((resolve3, reject) => {
1790
+ return await new Promise((resolve4, reject) => {
1791
1791
  const onData = (chunk) => {
1792
1792
  for (const key of keysIn(chunk)) {
1793
1793
  if (isUp(key)) index = (index - 1 + choices.length) % choices.length;
@@ -1795,7 +1795,7 @@ async function select(message, choices, initial = 0) {
1795
1795
  else if (key === ENTER || key === "\n") {
1796
1796
  inp.off("data", onData);
1797
1797
  done = true;
1798
- resolve3(choices[index].value);
1798
+ resolve4(choices[index].value);
1799
1799
  return;
1800
1800
  } else if (key === CTRL_C || key === CTRL_D) {
1801
1801
  inp.off("data", onData);
@@ -1845,13 +1845,13 @@ async function hiddenText(message) {
1845
1845
  let chars = [];
1846
1846
  let done = false;
1847
1847
  try {
1848
- return await new Promise((resolve3, reject) => {
1848
+ return await new Promise((resolve4, reject) => {
1849
1849
  const onData = (chunk) => {
1850
1850
  for (const key of keysIn(chunk)) {
1851
1851
  if (key === ENTER || key === "\n") {
1852
1852
  inp.off("data", onData);
1853
1853
  done = true;
1854
- resolve3(chars.join(""));
1854
+ resolve4(chars.join(""));
1855
1855
  return;
1856
1856
  }
1857
1857
  if (key === CTRL_C || key === CTRL_D) {
@@ -2163,12 +2163,12 @@ async function runSsh(ssh, opts) {
2163
2163
  timedOut = true;
2164
2164
  child.kill("SIGTERM");
2165
2165
  }, opts.timeout * 1e3);
2166
- const status2 = await new Promise((resolve3, reject) => {
2166
+ const status2 = await new Promise((resolve4, reject) => {
2167
2167
  child.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
2168
2168
  child.once("close", (code, signal) => {
2169
- if (timedOut) resolve3(TIMEOUT_EXIT);
2170
- else if (code !== null) resolve3(code);
2171
- else resolve3(signal === "SIGINT" ? 130 : 1);
2169
+ if (timedOut) resolve4(TIMEOUT_EXIT);
2170
+ else if (code !== null) resolve4(code);
2171
+ else resolve4(signal === "SIGINT" ? 130 : 1);
2172
2172
  });
2173
2173
  }).finally(() => clearTimeout(timer));
2174
2174
  return { status: status2, chunks, timedOut };
@@ -3102,9 +3102,9 @@ function runSwap(ep, mib) {
3102
3102
  const chunks = [];
3103
3103
  child.stdout.on("data", (c2) => chunks.push(c2));
3104
3104
  child.stderr.on("data", (c2) => chunks.push(c2));
3105
- return new Promise((resolve3, reject) => {
3105
+ return new Promise((resolve4, reject) => {
3106
3106
  child.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
3107
- child.once("close", (code) => resolve3({ status: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
3107
+ child.once("close", (code) => resolve4({ status: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
3108
3108
  });
3109
3109
  }
3110
3110
 
@@ -3961,18 +3961,18 @@ var redeemCommand = new Command53("redeem").description("redeem a promo code for
3961
3961
  });
3962
3962
 
3963
3963
  // src/commands/deploy/index.ts
3964
- import { access as access4, readFile as readFile7 } from "fs/promises";
3965
- import { basename, resolve as resolve2 } from "path";
3964
+ import { access as access5, readFile as readFile8 } from "fs/promises";
3965
+ import { basename as basename2, resolve as resolve3 } from "path";
3966
3966
  import { Command as Command54, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
3967
3967
 
3968
3968
  // src/commands/deploy/config.ts
3969
3969
  import { readFile as readFile6, writeFile as writeFile4 } from "fs/promises";
3970
- import { join as join6 } from "path";
3970
+ import { isAbsolute, join as join6, normalize, relative as relative2 } from "path";
3971
3971
  import { z as z5 } from "zod";
3972
3972
 
3973
3973
  // src/commands/deploy/templates/docker.ts
3974
3974
  import { readFile as readFile5 } from "fs/promises";
3975
- import { join as join2 } from "path";
3975
+ import { join as join2, relative, sep } from "path";
3976
3976
 
3977
3977
  // src/commands/deploy/templates/server.ts
3978
3978
  var APP_DIR = "/srv/app/current";
@@ -3993,16 +3993,21 @@ function commands(pm) {
3993
3993
  return { setup: [], install: "if [ -f package-lock.json ]; then npm ci; else npm install; fi", build: "npm run build", start: "npm run start" };
3994
3994
  }
3995
3995
  }
3996
+ var DROP_SINGLE = `sudo -n systemctl disable --now --quiet ${SERVICE} 2>/dev/null || true
3997
+ ${DROP_CONTAINER}`;
3996
3998
  function serverRemote(opts) {
3997
3999
  const c2 = commands(opts.pm);
4000
+ const root = opts.target?.root ?? "/srv/app";
4001
+ const appDir = opts.target ? `${root}/current` : APP_DIR;
4002
+ const service = opts.target?.unit ?? SERVICE;
3998
4003
  const unit = [
3999
4004
  "[Unit]",
4000
- "Description=kvbox deploy: the app in " + APP_DIR,
4005
+ "Description=kvbox deploy: the app in " + appDir,
4001
4006
  "After=network.target",
4002
4007
  "",
4003
4008
  "[Service]",
4004
4009
  "User=kvbox",
4005
- `WorkingDirectory=${APP_DIR}`,
4010
+ `WorkingDirectory=${appDir}`,
4006
4011
  // PORT on the command line: the proxied address points at it, and nothing in the environment
4007
4012
  // file below may move the app off it (env's PORT, say, copied from a .env).
4008
4013
  `ExecStart=/usr/bin/env PORT=${opts.port} ${c2.start}`,
@@ -4018,32 +4023,34 @@ function serverRemote(opts) {
4018
4023
  return [
4019
4024
  "set -e",
4020
4025
  "test -d /srv/app -a -w /srv/app || exit 3",
4021
- "rm -rf /srv/app/.incoming /srv/app/.old",
4022
- "mkdir -p /srv/app/.incoming",
4023
- "tar -xf - -C /srv/app/.incoming",
4024
- "cd /srv/app/.incoming",
4026
+ `rm -rf ${root}/.incoming ${root}/.old`,
4027
+ `mkdir -p ${root}/.incoming`,
4028
+ `tar -xf - -C ${root}/.incoming`,
4029
+ `cd ${root}/.incoming`,
4025
4030
  // Not NODE_ENV=production here: the install would skip devDependencies, which the build needs (TypeScript, Tailwind).
4026
4031
  `export ${["CI=1", ...opts.env ?? []].join(" ")}`,
4027
4032
  ...c2.setup,
4028
4033
  c2.install,
4029
4034
  ...opts.build ? [c2.build] : [],
4030
4035
  "cd /",
4031
- `sudo -n tee /etc/systemd/system/${SERVICE}.service >/dev/null <<'UNIT'`,
4036
+ // Before the unit is written: in a stack the single deploy's unit is the one being dropped.
4037
+ ...opts.target ? [DROP_SINGLE] : [],
4038
+ `sudo -n tee /etc/systemd/system/${service}.service >/dev/null <<'UNIT'`,
4032
4039
  ...unit,
4033
4040
  "UNIT",
4034
- `if [ -e ${APP_DIR} ]; then mv ${APP_DIR} /srv/app/.old; fi`,
4035
- `mv /srv/app/.incoming ${APP_DIR}`,
4041
+ `if [ -e ${appDir} ]; then mv ${appDir} ${root}/.old; fi`,
4042
+ `mv ${root}/.incoming ${appDir}`,
4036
4043
  "sudo -n systemctl daemon-reload",
4037
- `sudo -n systemctl enable --quiet ${SERVICE}`,
4044
+ `sudo -n systemctl enable --quiet ${service}`,
4038
4045
  // A box that switched from the Docker template: its container holds the same box port.
4039
- DROP_CONTAINER,
4040
- `sudo -n systemctl restart ${SERVICE}`,
4041
- "rm -rf /srv/app/.old",
4046
+ ...opts.target ? [] : [DROP_CONTAINER],
4047
+ `sudo -n systemctl restart ${service}`,
4048
+ `rm -rf ${root}/.old`,
4042
4049
  // bash's /dev/tcp: no curl or nc in the image needed.
4043
4050
  "i=0",
4044
4051
  `until timeout 1 bash -c '</dev/tcp/127.0.0.1/${opts.port}' 2>/dev/null; do`,
4045
4052
  " i=$((i+1))",
4046
- ` if [ "$i" -ge ${START_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${SERVICE} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
4053
+ ` if [ "$i" -ge ${START_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${service} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
4047
4054
  " sleep 1",
4048
4055
  "done"
4049
4056
  ].join("\n");
@@ -4073,9 +4080,14 @@ var dockerTemplate = {
4073
4080
  const dockerfile = await readFile5(join2(ctx.dir, "Dockerfile"), "utf8").catch(() => void 0);
4074
4081
  if (dockerfile === void 0) throw new KvboxError(`${ctx.dir}: no Dockerfile; the Docker template builds the image from it`);
4075
4082
  const containerPort = exposedPort(dockerfile);
4083
+ if (ctx.context !== void 0 && ctx.context !== ctx.dir) {
4084
+ const dockerfilePath = relative(ctx.context, join2(ctx.dir, "Dockerfile")).split(sep).join("/");
4085
+ return { outDir: ctx.context, exclude: ["node_modules", ".git", ".venv"], pm: "npm", what: "the build context", dockerfile: dockerfilePath, ...containerPort !== void 0 ? { containerPort } : {} };
4086
+ }
4076
4087
  return { outDir: ctx.dir, exclude: ["node_modules", ".git"], pm: "npm", what: "the source", ...containerPort !== void 0 ? { containerPort } : {} };
4077
4088
  },
4078
- remote(built, port) {
4089
+ remote(built, port, target) {
4090
+ if (target) return dockerServiceRemote(port, target, built.dockerfile);
4079
4091
  return dockerRemote(port, built.containerPort ?? port);
4080
4092
  }
4081
4093
  };
@@ -4109,6 +4121,61 @@ function dockerRemote(port, containerPort) {
4109
4121
  "done"
4110
4122
  ].join("\n");
4111
4123
  }
4124
+ var BOX_ENV_PLAIN = "/home/kvbox/.ssh/environment";
4125
+ function dockerServiceRemote(port, target, dockerfile) {
4126
+ const image = target.unit;
4127
+ const unit = [
4128
+ "[Unit]",
4129
+ `Description=kvbox deploy: the container ${image}`,
4130
+ "After=docker.service network-online.target",
4131
+ "Requires=docker.service",
4132
+ "",
4133
+ "[Service]",
4134
+ // A box that never had a variable has no file yet, and docker refuses a missing --env-file.
4135
+ `ExecStartPre=/bin/sh -c '[ -e ${BOX_ENV_PLAIN} ] || install -m 600 -o kvbox -g kvbox /dev/null ${BOX_ENV_PLAIN}'`,
4136
+ `ExecStartPre=-/usr/bin/docker rm -f ${image}`,
4137
+ `ExecStart=/usr/bin/docker run --rm --name ${image} --network host --env-file ${BOX_ENV_PLAIN} -e PORT=${port} ${image}`,
4138
+ `ExecStop=/usr/bin/docker stop ${image}`,
4139
+ "Restart=always",
4140
+ "RestartSec=2",
4141
+ "",
4142
+ "[Install]",
4143
+ "WantedBy=multi-user.target"
4144
+ ];
4145
+ const root = target.root;
4146
+ return [
4147
+ "set -eo pipefail",
4148
+ "test -d /srv/app -a -w /srv/app || exit 3",
4149
+ "command -v docker >/dev/null || exit 3",
4150
+ `rm -rf ${root}/.incoming ${root}/.old`,
4151
+ `mkdir -p ${root}/.incoming`,
4152
+ `tar -xf - -C ${root}/.incoming`,
4153
+ `cd ${root}/.incoming`,
4154
+ // Quoted: the path is the user's `dir`, which may hold a space.
4155
+ `docker build --progress=plain${dockerfile !== void 0 ? ` -f '${dockerfile.replaceAll("'", `'\\''`)}'` : ""} -t ${image} . 2>&1 | tail -n ${BUILD_LOG_LINES}`,
4156
+ "cd /",
4157
+ // The single deploy's app or container would hold its port and RAM beside the services.
4158
+ DROP_SINGLE,
4159
+ `sudo -n tee /etc/systemd/system/${target.unit}.service >/dev/null <<'UNIT'`,
4160
+ ...unit,
4161
+ "UNIT",
4162
+ `if [ -e ${root}/current ]; then mv ${root}/current ${root}/.old; fi`,
4163
+ `mv ${root}/.incoming ${root}/current`,
4164
+ `rm -rf ${root}/.old`,
4165
+ "sudo -n systemctl daemon-reload",
4166
+ "sudo -n systemctl enable --quiet docker",
4167
+ `sudo -n systemctl enable --quiet ${target.unit}`,
4168
+ `sudo -n systemctl restart ${target.unit}`,
4169
+ "docker image prune -f >/dev/null",
4170
+ // The box's network: the port is the box's own, and nothing but the app answers on it.
4171
+ "i=0",
4172
+ `until timeout 1 bash -c '</dev/tcp/127.0.0.1/${port}' 2>/dev/null; do`,
4173
+ " i=$((i+1))",
4174
+ ` if [ "$i" -ge ${START_WAIT_SEC} ] || ! systemctl is-active --quiet ${target.unit}; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${target.unit} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
4175
+ " sleep 1",
4176
+ "done"
4177
+ ].join("\n");
4178
+ }
4112
4179
 
4113
4180
  // src/commands/deploy/templates/pm.ts
4114
4181
  import { access } from "fs/promises";
@@ -4144,8 +4211,8 @@ var nextjsTemplate = {
4144
4211
  const pm = await packageManager(ctx.dir);
4145
4212
  return { outDir: ctx.dir, exclude: ["node_modules", ".next", ".git"], pm, what: "the source", boxBuild: true };
4146
4213
  },
4147
- remote(built, port) {
4148
- return serverRemote({ pm: built.pm, port, build: true, env: ["NEXT_TELEMETRY_DISABLED=1"] });
4214
+ remote(built, port, target) {
4215
+ return serverRemote({ pm: built.pm, port, build: true, env: ["NEXT_TELEMETRY_DISABLED=1"], ...target ? { target } : {} });
4149
4216
  }
4150
4217
  };
4151
4218
 
@@ -4171,8 +4238,8 @@ var nodeTemplate = {
4171
4238
  const boxBuild = typeof ctx.pkg.scripts["build"] === "string";
4172
4239
  return { outDir: ctx.dir, exclude: ["node_modules", ".git"], pm, what: "the source", boxBuild };
4173
4240
  },
4174
- remote(built, port) {
4175
- return serverRemote({ pm: built.pm, port, build: built.boxBuild === true });
4241
+ remote(built, port, target) {
4242
+ return serverRemote({ pm: built.pm, port, build: built.boxBuild === true, ...target ? { target } : {} });
4176
4243
  }
4177
4244
  };
4178
4245
 
@@ -4184,10 +4251,10 @@ var OUT_DIRS = ["dist", "build"];
4184
4251
  async function runBuild(dir, pm) {
4185
4252
  const args = runScript(pm, "build");
4186
4253
  info(`${color.dim("$")} ${pm} ${args.join(" ")}`);
4187
- const status2 = await new Promise((resolve3, reject) => {
4254
+ const status2 = await new Promise((resolve4, reject) => {
4188
4255
  const child = spawn4(pm, args, { cwd: dir, stdio: ["ignore", process.stderr, process.stderr], shell: process.platform === "win32" });
4189
4256
  child.once("error", (err) => reject(new KvboxError(`could not run ${pm}: ${err.message}`)));
4190
- child.once("close", (code) => resolve3(code ?? 1));
4257
+ child.once("close", (code) => resolve4(code ?? 1));
4191
4258
  });
4192
4259
  if (status2 !== 0) throw new KvboxError(`the build failed (${pm} exited ${status2}); nothing was deployed`);
4193
4260
  }
@@ -4217,9 +4284,23 @@ var reactTemplate = {
4217
4284
  `the build left no ${candidates.join(" or ")}/index.html. The React template ships a directory of static files; set "dist" in kvbox.json to the build output directory, or pick the right template with --template`
4218
4285
  );
4219
4286
  },
4220
- remote: nginxRemote
4287
+ remote: (_built, _port, target) => nginxRemote(target)
4221
4288
  };
4222
- function nginxRemote() {
4289
+ function nginxRemote(target) {
4290
+ if (target) {
4291
+ return [
4292
+ "set -e",
4293
+ "test -d /srv/app -a -w /srv/app || exit 3",
4294
+ DROP_SINGLE,
4295
+ `rm -rf ${target.root}/.incoming ${target.root}/.old`,
4296
+ `mkdir -p ${target.root}/.incoming`,
4297
+ `tar -xf - -C ${target.root}/.incoming`,
4298
+ `chmod -R a+rX ${target.root}/.incoming`,
4299
+ `if [ -e ${target.root}/dist ]; then mv ${target.root}/dist ${target.root}/.old; fi`,
4300
+ `mv ${target.root}/.incoming ${target.root}/dist`,
4301
+ `rm -rf ${target.root}/.old`
4302
+ ].join("\n");
4303
+ }
4223
4304
  return [
4224
4305
  "set -e",
4225
4306
  "test -e /etc/nginx/sites-enabled/kvbox-app || exit 3",
@@ -4262,7 +4343,7 @@ var staticTemplate = {
4262
4343
  const pm = ctx.pkg !== void 0 ? await packageManager(ctx.dir) : "npm";
4263
4344
  return { outDir, ...dist !== void 0 ? { dist } : {}, exclude: EXCLUDE, pm, what: dist !== void 0 ? `${dist}/` : "the directory" };
4264
4345
  },
4265
- remote: nginxRemote
4346
+ remote: (_built, _port, target) => nginxRemote(target)
4266
4347
  };
4267
4348
 
4268
4349
  // src/commands/deploy/templates/index.ts
@@ -4298,7 +4379,134 @@ var DeployConfigSchema = z5.object({
4298
4379
  /** The port a Next.js app or Node server serves; the template's (3000) when absent. */
4299
4380
  port: z5.number().int().min(1).max(65535).optional()
4300
4381
  });
4301
- async function readConfig(dir) {
4382
+ var SERVICE_KEY_RE = /^[a-z][a-z0-9-]{0,19}$/;
4383
+ var RESERVED_SERVICE_KEYS = ["app", "agent", "init", "volumes"];
4384
+ var STATIC_TEMPLATES = ["react", "static"];
4385
+ var FRONT_PORT = 80;
4386
+ var ROUTE_RE = /^\/(?:[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*)?$/;
4387
+ var POSTGRES = "postgres";
4388
+ var POSTGRES_PORT = 5432;
4389
+ var POSTGRES_IMAGE = "postgres:17";
4390
+ var POSTGRES_ENV = "DATABASE_URL";
4391
+ var IMAGE_RE = /^[a-z0-9][a-z0-9._/:@-]*$/;
4392
+ var ServiceSchema = z5.strictObject({
4393
+ template: z5.enum([...TEMPLATE_IDS, POSTGRES]),
4394
+ /** The service's directory, relative to the one holding kvbox.json; every template but postgres has one. */
4395
+ dir: z5.string().min(1).optional(),
4396
+ /** A postgres service's image, `postgres:17` when absent (`pgvector/pgvector:pg17` for vectors). */
4397
+ image: z5.string().regex(IMAGE_RE, "an image name like postgres:17").optional(),
4398
+ /** The volume (a key of `volumes`) a postgres service keeps its data on. */
4399
+ volume: z5.string().optional(),
4400
+ /** The box variable a postgres service's URL is written to, `DATABASE_URL` when absent. */
4401
+ env: z5.string().optional(),
4402
+ /** A docker service's build context, relative to kvbox.json, when it is not `dir` (a monorepo built from its root); the Dockerfile stays in `dir`. */
4403
+ context: z5.string().min(1).optional(),
4404
+ dist: z5.string().optional(),
4405
+ /** The box port of a service with its own server; the template's (3000) when absent. */
4406
+ port: z5.number().int().min(1).max(65535).optional(),
4407
+ /** The URL paths that go to this service, each with everything under it; the prefix is kept. */
4408
+ paths: z5.array(z5.string().regex(ROUTE_RE, "a path like / or /api, no trailing slash")).min(1).optional()
4409
+ });
4410
+ var StackConfigSchema = z5.strictObject({
4411
+ name: DeployConfigSchema.shape.name.optional(),
4412
+ org: DeployConfigSchema.shape.org,
4413
+ subdomain: DeployConfigSchema.shape.subdomain,
4414
+ size: DeployConfigSchema.shape.size,
4415
+ /** The stack's volumes, name to size ("10GB"): made for its box and attached to it on the first deploy that needs one. */
4416
+ volumes: z5.record(z5.string(), z5.string()).optional(),
4417
+ services: z5.record(z5.string(), ServiceSchema)
4418
+ });
4419
+ function volumeGib(text2) {
4420
+ const mib = parseMib(text2);
4421
+ if (mib === void 0 || mib === 0 || mib % 1024 !== 0 || mib / 1024 > MAX_VOLUME_GIB) return void 0;
4422
+ return mib / 1024;
4423
+ }
4424
+ function stackServices(stack, defaultPort, exposed = /* @__PURE__ */ new Map()) {
4425
+ const services = [];
4426
+ const ports = /* @__PURE__ */ new Map();
4427
+ const routes = /* @__PURE__ */ new Map();
4428
+ const entries = Object.entries(stack.services);
4429
+ if (entries.length === 0) throw new KvboxError(`${CONFIG_FILE}: services: at least one service`);
4430
+ for (const [name, size] of Object.entries(stack.volumes ?? {})) {
4431
+ if (!VOLUME_NAME_RE.test(name)) throw new KvboxError(`${CONFIG_FILE}: volumes.${name}: a volume name is ${VOLUME_NAME_RULE}`);
4432
+ if (volumeGib(size) === void 0) throw new KvboxError(`${CONFIG_FILE}: volumes.${name}: ${size} is not a size; write whole GB, like "10GB" (at most ${MAX_VOLUME_GIB})`);
4433
+ }
4434
+ const volumeUsers = /* @__PURE__ */ new Map();
4435
+ const envUsers = /* @__PURE__ */ new Map();
4436
+ for (const [key, config] of entries) {
4437
+ const at = `${CONFIG_FILE}: services.${key}`;
4438
+ if (!SERVICE_KEY_RE.test(key)) throw new KvboxError(`${at}: a service name is 1-20 chars, lowercase letters, digits and '-', starting with a letter`);
4439
+ if (RESERVED_SERVICE_KEYS.includes(key)) throw new KvboxError(`${at}: the name ${key} is taken by kvbox itself; call the service something else (web, api, site)`);
4440
+ const outside = (p) => isAbsolute(p) || p.split(/[\\/]/).includes("..");
4441
+ if (config.template === POSTGRES) {
4442
+ services.push(postgresService(key, config, stack, { volumeUsers, envUsers }, ports));
4443
+ continue;
4444
+ }
4445
+ for (const field of ["image", "volume", "env"]) {
4446
+ if (config[field] !== void 0) throw new KvboxError(`${at}.${field}: only a postgres service has one`);
4447
+ }
4448
+ if (config.dir === void 0) throw new KvboxError(`${at}.dir: the service's directory, relative to ${CONFIG_FILE}`);
4449
+ if (outside(config.dir)) throw new KvboxError(`${at}.dir: a directory inside the project, relative to ${CONFIG_FILE}`);
4450
+ if (config.context !== void 0) {
4451
+ if (config.template !== "docker") throw new KvboxError(`${at}.context: only a docker service has a build context`);
4452
+ if (outside(config.context)) throw new KvboxError(`${at}.context: a directory inside the project, relative to ${CONFIG_FILE}`);
4453
+ const rel = relative2(normalize(config.context), normalize(config.dir));
4454
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new KvboxError(`${at}.context: must hold the service's dir (${config.dir}), where its Dockerfile is`);
4455
+ }
4456
+ const isStatic = STATIC_TEMPLATES.includes(config.template);
4457
+ const paths2 = config.paths ?? [];
4458
+ if (isStatic && config.port !== void 0) throw new KvboxError(`${at}.port: a ${config.template} service has no port of its own; nginx serves its files`);
4459
+ if (isStatic && paths2.length === 0) throw new KvboxError(`${at}.paths: say where the site is served, for example "paths": ["/"]`);
4460
+ let port;
4461
+ if (!isStatic) {
4462
+ const fromExpose = config.port === void 0 ? exposed.get(key) : void 0;
4463
+ port = config.port ?? fromExpose ?? defaultPort(config.template);
4464
+ const instead = `set its own "port" in ${CONFIG_FILE}; the container must listen on it, given as PORT`;
4465
+ if (port === FRONT_PORT) {
4466
+ if (fromExpose !== void 0) throw new KvboxError(`${at}: its Dockerfile EXPOSEs ${FRONT_PORT}, nginx's, the front door of the box; ${instead}`);
4467
+ throw new KvboxError(`${at}.port: ${FRONT_PORT} is nginx's, the front door of the box; pick another`);
4468
+ }
4469
+ const other = ports.get(port);
4470
+ if (other !== void 0) {
4471
+ if (fromExpose !== void 0) throw new KvboxError(`${at}: its Dockerfile EXPOSEs ${port}, which is also ${other}'s; ${instead}`);
4472
+ throw new KvboxError(`${at}.port: ${port} is also ${other}'s; give each service its own "port"`);
4473
+ }
4474
+ ports.set(port, key);
4475
+ }
4476
+ for (const path of paths2) {
4477
+ const other = routes.get(path);
4478
+ if (other !== void 0) throw new KvboxError(`${at}.paths: ${path} is also ${other}'s; a path goes to one service`);
4479
+ routes.set(path, key);
4480
+ }
4481
+ services.push({ key, config, static: isStatic, ...port !== void 0 ? { port } : {}, paths: paths2 });
4482
+ }
4483
+ return services;
4484
+ }
4485
+ function postgresService(key, config, stack, { volumeUsers, envUsers }, ports) {
4486
+ const at = `${CONFIG_FILE}: services.${key}`;
4487
+ for (const field of ["dir", "context", "dist", "paths"]) {
4488
+ if (config[field] !== void 0) throw new KvboxError(`${at}.${field}: a postgres service has none${field === "paths" ? "; it is reached by the other services on 127.0.0.1, never from the internet" : ""}`);
4489
+ }
4490
+ const env = config.env ?? POSTGRES_ENV;
4491
+ const envProblem = envNameProblem(env);
4492
+ if (envProblem !== null) throw new KvboxError(`${at}.env: ${envProblem}`);
4493
+ const envOwner = envUsers.get(env);
4494
+ if (envOwner !== void 0) throw new KvboxError(`${at}.env: ${env} already holds ${envOwner}'s URL; give each database its own "env" (like ${key.toUpperCase().replace(/-/g, "_")}_URL)`);
4495
+ envUsers.set(env, key);
4496
+ if (config.volume !== void 0) {
4497
+ if (stack.volumes?.[config.volume] === void 0) throw new KvboxError(`${at}.volume: no volume ${config.volume} in "volumes"; add it there with its size, like "volumes": { "${config.volume}": "10GB" }`);
4498
+ const other2 = volumeUsers.get(config.volume);
4499
+ if (other2 !== void 0) throw new KvboxError(`${at}.volume: ${config.volume} already holds ${other2}'s data; give each database its own volume`);
4500
+ volumeUsers.set(config.volume, key);
4501
+ }
4502
+ const port = config.port ?? POSTGRES_PORT;
4503
+ if (port === FRONT_PORT) throw new KvboxError(`${at}.port: ${FRONT_PORT} is nginx's, the front door of the box; pick another`);
4504
+ const other = ports.get(port);
4505
+ if (other !== void 0) throw new KvboxError(`${at}.port: ${port} is also ${other}'s; give each service its own "port"`);
4506
+ ports.set(port, key);
4507
+ return { key, config, static: false, port, paths: [], postgres: { image: config.image ?? POSTGRES_IMAGE, env, ...config.volume !== void 0 ? { volume: config.volume } : {} } };
4508
+ }
4509
+ async function readDeployFile(dir) {
4302
4510
  const path = join6(dir, CONFIG_FILE);
4303
4511
  let raw;
4304
4512
  try {
@@ -4313,12 +4521,13 @@ async function readConfig(dir) {
4313
4521
  } catch {
4314
4522
  throw new KvboxError(`${path}: not valid JSON`);
4315
4523
  }
4316
- const parsed = DeployConfigSchema.safeParse(json2);
4524
+ const stack = typeof json2 === "object" && json2 !== null && "services" in json2;
4525
+ const parsed = stack ? StackConfigSchema.safeParse(json2) : DeployConfigSchema.safeParse(json2);
4317
4526
  if (!parsed.success) {
4318
4527
  const issue = parsed.error.issues[0];
4319
4528
  throw new KvboxError(`${path}: ${issue.path.join(".") || "file"}: ${issue.message}`);
4320
4529
  }
4321
- return parsed.data;
4530
+ return stack ? { kind: "stack", config: parsed.data } : { kind: "single", config: parsed.data };
4322
4531
  }
4323
4532
  async function writeConfig(dir, config) {
4324
4533
  await writeFile4(join6(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
@@ -4369,35 +4578,625 @@ async function ship(ep, dir, remote, exclude = []) {
4369
4578
  tar.once("close", (code) => {
4370
4579
  if (code !== 0) ssh.stdin.end();
4371
4580
  });
4372
- const tarDone = new Promise((resolve3) => tar.once("close", () => resolve3()));
4373
- const status2 = await new Promise((resolve3, reject) => {
4581
+ const tarDone = new Promise((resolve4) => tar.once("close", () => resolve4()));
4582
+ const status2 = await new Promise((resolve4, reject) => {
4374
4583
  ssh.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
4375
4584
  ssh.once("close", (code, signal) => {
4376
4585
  tar.stdout.unpipe(ssh.stdin);
4377
4586
  tar.stdout.resume();
4378
4587
  tar.kill();
4379
- resolve3(code ?? (signal === "SIGINT" ? 130 : 1));
4588
+ resolve4(code ?? (signal === "SIGINT" ? 130 : 1));
4380
4589
  });
4381
4590
  });
4382
4591
  await tarDone;
4383
4592
  return { status: status2, output: Buffer.concat(chunks).toString("utf8") };
4384
4593
  }
4385
- var shipping = { ship, measure, waitForSsh };
4594
+ async function run(ep, remote) {
4595
+ const ssh = spawn5("ssh", [...sshArgs(ep), remote], { stdio: ["ignore", "pipe", "pipe"] });
4596
+ const chunks = [];
4597
+ ssh.stdout.on("data", (c2) => chunks.push(c2));
4598
+ ssh.stderr.on("data", (c2) => chunks.push(c2));
4599
+ const status2 = await new Promise((resolve4, reject) => {
4600
+ ssh.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
4601
+ ssh.once("close", (code, signal) => resolve4(code ?? (signal === "SIGINT" ? 130 : 1)));
4602
+ });
4603
+ return { status: status2, output: Buffer.concat(chunks).toString("utf8") };
4604
+ }
4605
+ var shipping = { ship, run, measure, waitForSsh };
4606
+
4607
+ // src/commands/deploy/box.ts
4608
+ var NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
4609
+ function refuseFailedShip(result, ctx) {
4610
+ const { ref, template, port, built, service } = ctx;
4611
+ const app = service ? `service ${service.key}` : "the app";
4612
+ if (result.status === SSH_FAILED3) throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `
4613
+ ${result.output.trim()}` : ""}`, SSH_FAILED3);
4614
+ if (result.status === IMAGE_TOO_OLD) {
4615
+ throw new KvboxError(
4616
+ `box ${ref} runs an image too old for the ${template.label} template (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}) once its host has the new image, or deploy under another name (--name) to get a fresh box`
4617
+ );
4618
+ }
4619
+ if (result.status === APP_NOT_LISTENING) {
4620
+ const log = result.output.split(LOG_MARKER)[1]?.trim();
4621
+ const where = built.containerPort !== void 0 && built.containerPort !== port ? `the container's port ${built.containerPort} (box port ${port})` : `port ${port}`;
4622
+ const fix = service ? `, or say its port with "port" in ${CONFIG_FILE}` : template.customPort ? ", or say its port with --port" : "";
4623
+ const listens = service && template.id === "docker" ? `The container must listen on PORT (${port}), on the box's own network` : template.listens ?? `It must listen on process.env.PORT (${port})`;
4624
+ throw new KvboxError(
4625
+ `${app} did not answer on ${service ? `port ${port}` : where} within ${START_WAIT_SEC} s: it crashed, or listens on another port. ${listens}${fix}. Its log: kvbox exec ${ref} -- ${service ? `journalctl -u ${service.unit}` : template.logs ?? "journalctl -u kvbox-app"}${log ? `
4626
+ last lines:
4627
+ ${log}` : ""}`
4628
+ );
4629
+ }
4630
+ if (result.status !== 0) throw new KvboxError(`deploying ${service ? `service ${service.key} ` : ""}to ${ref} failed (exit ${result.status}):
4631
+ ${result.output.trim()}`);
4632
+ }
4633
+ async function findOrCreate(client, config) {
4634
+ const user = me(client);
4635
+ const slug = config.org ?? user;
4636
+ const named = (await client.listMachines()).filter((b) => b.name === config.name);
4637
+ let box = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
4638
+ let created = false;
4639
+ if (!box) {
4640
+ box = await spin(`booting a new box ${config.name}\u2026`, client.createMachine({ name: config.name, ...config.size !== void 0 ? { size: config.size } : {}, autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));
4641
+ created = true;
4642
+ info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);
4643
+ }
4644
+ return { box, ref: displayName(box, user), created };
4645
+ }
4646
+ async function existingAddresses(client, config) {
4647
+ const slug = config.org ?? me(client);
4648
+ return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
4649
+ }
4650
+ async function refuseOtherAddress(client, config) {
4651
+ const have = await existingAddresses(client, config);
4652
+ if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
4653
+ const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
4654
+ throw new KvboxError(
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>`
4656
+ );
4657
+ }
4658
+ async function address(client, box, ref, config, port) {
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];
4661
+ if (have) {
4662
+ if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
4663
+ return { url: have.url, subdomain: have.subdomain };
4664
+ }
4665
+ const wanted = config.subdomain ?? subdomainFor(config.name);
4666
+ try {
4667
+ const sub = await spin(`claiming https://${wanted}.kvbox.app\u2026`, client.claimSubdomain(ref, { name: wanted, port }));
4668
+ return { url: sub.url, subdomain: sub.subdomain };
4669
+ } catch (err) {
4670
+ if (!(err instanceof KvboxError)) throw err;
4671
+ throw new KvboxError(`${err.message}
4672
+ the app is on box ${ref} but has no address yet: pick another with kvbox deploy --sub <name> (saved to ${CONFIG_FILE})`);
4673
+ }
4674
+ }
4675
+
4676
+ // src/commands/deploy/stack.ts
4677
+ import { access as access4, readFile as readFile7 } from "fs/promises";
4678
+ import { basename, join as join8, resolve as resolve2 } from "path";
4679
+
4680
+ // src/commands/deploy/postgres.ts
4681
+ import { randomBytes } from "crypto";
4682
+ var POSTGRES_USER = "kvbox";
4683
+ var POSTGRES_DB = "app";
4684
+ var ENV_MISSING = 6;
4685
+ var VOLUME_NOT_MOUNTED = 7;
4686
+ var DB_NOT_READY = 8;
4687
+ var URL_OTHER_PORT = 9;
4688
+ var URL_FOREIGN = 10;
4689
+ var OTHER_DATA = 11;
4690
+ var DB_WAIT_SEC = 90;
4691
+ var AGENT = "/usr/local/sbin/kvbox-agent";
4692
+ var ENV_WAIT_SEC = 60;
4693
+ function newPassword() {
4694
+ return randomBytes(24).toString("hex");
4695
+ }
4696
+ function postgresUrl(password, port) {
4697
+ return `postgres://${POSTGRES_USER}:${password}@127.0.0.1:${port}/${POSTGRES_DB}`;
4698
+ }
4699
+ function postgresRemote(o) {
4700
+ const { root, unit } = o.target;
4701
+ const mount = `/mnt/${o.volume}`;
4702
+ const key = o.target.root.split("/").pop();
4703
+ const data = `${mount}/${key}`;
4704
+ const envFile = `${root}/current/postgres.env`;
4705
+ const unitText = [
4706
+ "[Unit]",
4707
+ `Description=kvbox deploy: the database ${unit}`,
4708
+ "After=docker.service kvbox-volumes.service network-online.target",
4709
+ "Requires=docker.service",
4710
+ "",
4711
+ "[Service]",
4712
+ `ExecStartPre=/usr/bin/mountpoint -q ${mount}`,
4713
+ `ExecStartPre=-/usr/bin/docker rm -f ${unit}`,
4714
+ `ExecStart=/usr/bin/docker run --rm --name ${unit} --network host --env-file ${envFile} -e POSTGRES_USER=${POSTGRES_USER} -e POSTGRES_DB=${POSTGRES_DB} -e PGDATA=/kvbox-data/pgdata -v ${data}:/kvbox-data ${o.image} -c listen_addresses=127.0.0.1 -c port=${o.port}`,
4715
+ `ExecStop=/usr/bin/docker stop ${unit}`,
4716
+ "Restart=always",
4717
+ "RestartSec=2",
4718
+ "",
4719
+ "[Install]",
4720
+ "WantedBy=multi-user.target"
4721
+ ];
4722
+ return [
4723
+ "set -eo pipefail",
4724
+ "test -d /srv/app -a -w /srv/app || exit 3",
4725
+ "command -v docker >/dev/null || exit 3",
4726
+ // The host hands a booting box its variables a few seconds after it starts. Only an agent that marks
4727
+ // it (base v0.12.0+) is waited for: on an older image the file never comes, and every deploy would stall.
4728
+ `if grep -qs env-ready ${AGENT}; then i=0; until [ -e /run/kvbox/env-ready ] || [ "$i" -ge ${ENV_WAIT_SEC} ]; do i=$((i+1)); sleep 1; done; fi`,
4729
+ `url=$(sed -n 's/^${o.env}=//p' ${BOX_ENV_PLAIN} 2>/dev/null | head -n 1 || true)`,
4730
+ `[ -n "$url" ] || exit ${ENV_MISSING}`,
4731
+ // Only a URL this CLI made, for this port, is the database's: never a value set for something else.
4732
+ `pw=\${url#postgres://${POSTGRES_USER}:}`,
4733
+ "pw=${pw%%@*}",
4734
+ `case "$pw" in ''|*[!0-9a-f]*) exit ${URL_FOREIGN} ;; esac`,
4735
+ `case "$url" in "${postgresUrl("$pw", o.port)}") ;; "postgres://${POSTGRES_USER}:$pw@127.0.0.1:"*"/${POSTGRES_DB}") exit ${URL_OTHER_PORT} ;; *) exit ${URL_FOREIGN} ;; esac`,
4736
+ `mountpoint -q ${mount} || exit ${VOLUME_NOT_MOUNTED}`,
4737
+ `mkdir -p ${root}/current`,
4738
+ // One database per volume: another service's data there is a renamed service, never started empty beside it.
4739
+ // Its pgdata (mode 700, postgres's) is seen from the folder above, which is this user's.
4740
+ `for f in ${mount}/*/pgdata; do [ -d "$f" ] || continue; o=\${f#${mount}/}; o=\${o%%/*}; [ "$o" = ${key} ] || { echo "$o"; exit ${OTHER_DATA}; }; done`,
4741
+ `mkdir -p ${data}`,
4742
+ `(umask 077; printf 'POSTGRES_PASSWORD=%s\\n' "$pw" > ${envFile})`,
4743
+ `docker image inspect ${o.image} >/dev/null 2>&1 || docker pull -q ${o.image} >/dev/null`,
4744
+ DROP_SINGLE,
4745
+ `cat > ${root}/.unit <<'UNIT'`,
4746
+ ...unitText,
4747
+ "UNIT",
4748
+ "changed=0",
4749
+ `if ! cmp -s ${root}/.unit /etc/systemd/system/${unit}.service; then sudo -n cp ${root}/.unit /etc/systemd/system/${unit}.service; sudo -n systemctl daemon-reload; changed=1; fi`,
4750
+ `rm -f ${root}/.unit`,
4751
+ "sudo -n systemctl enable --quiet docker",
4752
+ `sudo -n systemctl enable --quiet ${unit}`,
4753
+ `if [ "$changed" = 1 ] || ! systemctl is-active --quiet ${unit}; then sudo -n systemctl restart ${unit}; fi`,
4754
+ // Ready on TCP, not only on its socket: during the first start's initdb it listens on no port.
4755
+ "i=0",
4756
+ `until docker exec ${unit} pg_isready -q -h 127.0.0.1 -p ${o.port} 2>/dev/null; do`,
4757
+ " i=$((i+1))",
4758
+ ` if [ "$i" -ge ${DB_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${unit} -n 20 --no-pager -o cat || true; exit ${DB_NOT_READY}; fi`,
4759
+ " sleep 1",
4760
+ "done",
4761
+ // The box's password is the one that counts, whatever the data was made with (a new box on an old volume).
4762
+ // Over the local socket (trust in the image), whose name carries the port: without -p it is 5432's.
4763
+ `docker exec ${unit} psql -q -p ${o.port} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c "ALTER ROLE ${POSTGRES_USER} PASSWORD '$pw'" >/dev/null`
4764
+ ].join("\n");
4765
+ }
4766
+
4767
+ // src/commands/deploy/nginx.ts
4768
+ var STACK_SITE = "kvbox-stack";
4769
+ var SITE_REFUSED = 5;
4770
+ var NO_PREVIOUS_SITE = "--- kvbox: no previous stack site ---";
4771
+ var PROXY = (port) => [
4772
+ `proxy_pass http://127.0.0.1:${port};`,
4773
+ "proxy_http_version 1.1;",
4774
+ "proxy_set_header Host $http_host;",
4775
+ "proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
4776
+ "proxy_set_header X-Forwarded-Proto $kvbox_proto;",
4777
+ // WebSocket, and streamed answers (server-sent events) as they are written.
4778
+ "proxy_set_header Upgrade $http_upgrade;",
4779
+ "proxy_set_header Connection $kvbox_connection;",
4780
+ "proxy_buffering off;",
4781
+ "proxy_read_timeout 3600s;"
4782
+ ];
4783
+ var block2 = (head, body) => [` ${head} {`, ...body.map((l) => ` ${l}`), " }", ""];
4784
+ function locations(service, path) {
4785
+ const dist = `/srv/app/${service.key}/dist`;
4786
+ if (service.static) {
4787
+ if (path === "/") return block2("location /", [`root ${dist};`, "try_files $uri $uri/ /index.html;"]);
4788
+ return [...block2(`location = ${path}`, [`return 301 ${path}/;`]), ...block2(`location ${path}/`, [`alias ${dist}/;`, `try_files $uri $uri/ ${path}/index.html;`])];
4789
+ }
4790
+ const proxy = PROXY(service.port);
4791
+ if (path === "/") return block2("location /", proxy);
4792
+ return [...block2(`location = ${path}`, proxy), ...block2(`location ${path}/`, proxy)];
4793
+ }
4794
+ function stackSite(services) {
4795
+ const routed = services.flatMap((s) => s.paths.map((path) => ({ service: s, path })));
4796
+ const root = routed.find((r) => r.path === "/");
4797
+ return [
4798
+ "# Written by kvbox deploy from kvbox.json; the next deploy writes it again.",
4799
+ "map $http_upgrade $kvbox_connection {",
4800
+ " default upgrade;",
4801
+ " '' close;",
4802
+ "}",
4803
+ "map $http_x_forwarded_proto $kvbox_proto {",
4804
+ " default $http_x_forwarded_proto;",
4805
+ " '' $scheme;",
4806
+ "}",
4807
+ "server {",
4808
+ " listen 80 default_server;",
4809
+ " listen [::]:80 default_server;",
4810
+ " server_name _;",
4811
+ " index index.html;",
4812
+ // The app behind a path decides how much it takes.
4813
+ " client_max_body_size 0;",
4814
+ "",
4815
+ " gzip on;",
4816
+ " gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;",
4817
+ "",
4818
+ ...routed.flatMap((r) => locations(r.service, r.path)),
4819
+ // No service at the top: say so instead of nginx's own welcome page.
4820
+ ...root ? [] : block2("location /", ["return 404;"]),
4821
+ "}",
4822
+ ""
4823
+ ].join("\n");
4824
+ }
4825
+ function frontRemote(site) {
4826
+ const available = `/etc/nginx/sites-available/${STACK_SITE}`;
4827
+ const enabled2 = `/etc/nginx/sites-enabled/${STACK_SITE}`;
4828
+ return [
4829
+ "set -e",
4830
+ "command -v nginx >/dev/null || exit 3",
4831
+ `if [ -e ${available} ]; then sudo -n cp -f ${available} ${available}.old; fi`,
4832
+ `sudo -n tee ${available} >/dev/null <<'KVBOX_SITE'`,
4833
+ site,
4834
+ "KVBOX_SITE",
4835
+ `sudo -n ln -sf ${available} ${enabled2}`,
4836
+ "sudo -n rm -f /etc/nginx/sites-enabled/kvbox-app",
4837
+ "if ! sudo -n nginx -t 2>&1; then",
4838
+ ` if [ -e ${available}.old ]; then sudo -n mv -f ${available}.old ${available}; else echo '${NO_PREVIOUS_SITE}'; sudo -n rm -f ${available} ${enabled2}; sudo -n ln -sf /etc/nginx/sites-available/kvbox-app /etc/nginx/sites-enabled/kvbox-app; fi`,
4839
+ ` exit ${SITE_REFUSED}`,
4840
+ "fi",
4841
+ `sudo -n rm -f ${available}.old`,
4842
+ "sudo -n systemctl enable --now --quiet nginx",
4843
+ "sudo -n systemctl reload nginx"
4844
+ ].join("\n");
4845
+ }
4846
+
4847
+ // src/commands/deploy/stack.ts
4848
+ var STACK_SIZE = "s";
4849
+ var exists = (path) => access4(path).then(() => true, () => false);
4850
+ async function deployStack(d) {
4851
+ const { dir, opts, client, cloud } = d;
4852
+ if (opts.template !== void 0 || opts.port !== void 0) throw new KvboxError(`--template and --port are one app's; with several services each says its own in ${CONFIG_FILE}`);
4853
+ const exposed = await exposedPorts(dir, d.stack);
4854
+ const portOf = (template) => templateById(template).port;
4855
+ pick(stackServices(d.stack, portOf, exposed), opts.only);
4856
+ const config = await settle(d);
4857
+ const services = stackServices(config, portOf, exposed);
4858
+ const picked = pick(services, opts.only);
4859
+ if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, { ...config, name: config.name });
4860
+ let saved = config;
4861
+ if (JSON.stringify(saved) !== JSON.stringify(d.stack)) await writeConfig(dir, saved);
4862
+ const box = { name: config.name, org: config.org, subdomain: config.subdomain, size: config.size };
4863
+ const all = [];
4864
+ for (const service of picked) {
4865
+ if (service.postgres) continue;
4866
+ const template = templateById(service.config.template);
4867
+ const serviceDir = resolve2(dir, service.config.dir);
4868
+ if (!await exists(serviceDir)) throw new KvboxError(`${CONFIG_FILE}: services.${service.key}.dir: no directory ${serviceDir}`);
4869
+ info(`${color.bold("Building")} ${color.cyan(service.key)} ${color.dim(`(${template.label})`)}`);
4870
+ const context = service.config.context !== void 0 ? resolve2(dir, service.config.context) : void 0;
4871
+ const built = await template.build({ dir: serviceDir, pkg: await readPackageJson(serviceDir), dist: service.config.dist, ...context !== void 0 ? { context } : {} });
4872
+ if (built.dist !== void 0 && built.dist !== service.config.dist) {
4873
+ saved = { ...saved, services: { ...saved.services, [service.key]: { ...saved.services[service.key], dist: built.dist } } };
4874
+ await writeConfig(dir, saved);
4875
+ }
4876
+ all.push({ service, template, built, size: await shipping.measure(built.outDir, built.exclude) });
4877
+ }
4878
+ info("");
4879
+ const { box: found, ref, created } = await findOrCreate(client, box);
4880
+ const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
4881
+ const wasRunning = !created && found.status === "running";
4882
+ const machine = created || wasRunning ? found : await wakeUp(client, found, ref);
4883
+ const ep = sshEndpoint(machine, client.target);
4884
+ if (!wasRunning) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(ep));
4885
+ let renewed = false;
4886
+ const renewOnce = async () => {
4887
+ if (renewed || !await renewAfterRefusal(client, cert, machine.owner)) return false;
4888
+ renewed = true;
4889
+ info("renewed your SSH certificate, trying again\u2026");
4890
+ return true;
4891
+ };
4892
+ const databases = picked.filter((s) => s.postgres);
4893
+ if (databases.length > 0) await deployDatabases({ client, ref, owner: machine.owner, name: machine.name, ep, volumes: config.volumes ?? {}, databases, renewOnce });
4894
+ for (const { service, template, built, size } of all) {
4895
+ const target = { root: `/srv/app/${service.key}`, unit: `kvbox-${service.key}` };
4896
+ const port = service.port ?? FRONT_PORT;
4897
+ const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port, target), built.exclude);
4898
+ const there = service.static ? "" : template.id === "docker" ? " and building the image there, a minute or two" : built.boxBuild ? " and installing and building there, a minute or two" : " and installing there, a minute or two";
4899
+ const doing = `${service.key}: shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}${there}\u2026`;
4900
+ let result = await spin(doing, shipIt);
4901
+ if (result.status === SSH_FAILED3 && await renewOnce()) result = await spin(doing, shipIt);
4902
+ refuseFailedShip(result, { ref, template, port, built, ...service.static ? {} : { service: { key: service.key, unit: target.unit } } });
4903
+ }
4904
+ const front = await spin(`pointing the box's front door at ${services.length === 1 ? "the service" : `the ${services.length} services`}\u2026`, shipping.run(ep, frontRemote(stackSite(services))));
4905
+ if (front.status === IMAGE_TOO_OLD) throw new KvboxError(`box ${ref} has no nginx: its image is too old (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}), or deploy under another name (--name) to get a fresh box`);
4906
+ if (front.status === SITE_REFUSED) {
4907
+ const first = front.output.includes(NO_PREVIOUS_SITE);
4908
+ const after = first ? "this was the box's first stack, so there are no previous routes to keep, and any single app it ran was stopped for the services: its address answers nothing until a deploy whose routes nginx takes" : "the previous ones keep serving";
4909
+ throw new KvboxError(`nginx in box ${ref} refused the routes made from ${CONFIG_FILE}; ${after}. The services themselves were deployed.
4910
+ ${front.output.replace(NO_PREVIOUS_SITE, "").trim()}`);
4911
+ }
4912
+ if (front.status !== 0) throw new KvboxError(`setting up nginx in box ${ref} failed (exit ${front.status}):
4913
+ ${front.output.trim()}`);
4914
+ const missing = picked.length < services.length ? await neverShipped(ep, services.filter((s) => !picked.includes(s))) : [];
4915
+ let url = `http://${machine.ip}`;
4916
+ if (cloud) {
4917
+ const got = await address(client, machine, ref, box, FRONT_PORT);
4918
+ url = got.url;
4919
+ if (got.subdomain !== saved.subdomain) await writeConfig(dir, { ...saved, subdomain: got.subdomain });
4920
+ }
4921
+ if (opts.json) {
4922
+ json({
4923
+ box: ref,
4924
+ created,
4925
+ url,
4926
+ services: [
4927
+ ...databases.map((s) => ({ key: s.key, template: POSTGRES, image: s.postgres.image, volume: s.postgres.volume, env: s.postgres.env, port: s.port, paths: [] })),
4928
+ ...all.map(({ service, template, built, size }) => ({
4929
+ key: service.key,
4930
+ template: template.id,
4931
+ files: size.files,
4932
+ bytes: size.bytes,
4933
+ ...built.dist !== void 0 ? { dist: built.dist } : {},
4934
+ ...service.port !== void 0 ? { port: service.port } : {},
4935
+ paths: service.paths
4936
+ }))
4937
+ ],
4938
+ ...missing.length > 0 ? { missing: missing.map((s) => s.key) } : {}
4939
+ });
4940
+ return;
4941
+ }
4942
+ process.stdout.write(`${url}
4943
+ `);
4944
+ info(`${color.green("\u2713")} ${color.bold(config.name)} is live at ${color.bold(url)}`);
4945
+ info(` box ${ref}${created ? " (new)" : ""}`);
4946
+ for (const s of databases) {
4947
+ const vol = s.postgres.volume;
4948
+ info(` ${color.cyan(s.key)} \xB7 Postgres ${s.postgres.image} \xB7 port ${s.port} \xB7 data on volume ${vol} (${config.volumes?.[vol] ?? "?"}) \xB7 URL in ${s.postgres.env}`);
4949
+ }
4950
+ for (const { service, template, size } of all) {
4951
+ const where = service.paths.length > 0 ? service.paths.join(", ") : "no path, reached by the other services only";
4952
+ info(` ${color.cyan(service.key)} \xB7 ${template.label} \xB7 ${where}${service.port !== void 0 ? ` \xB7 port ${service.port}` : ""} \xB7 ${size.files} files, ${gb(size.bytes)}`);
4953
+ }
4954
+ for (const s of missing) {
4955
+ const where = s.postgres ? `no database, and no service gets ${s.postgres.env},` : s.paths.length > 0 ? `${s.paths.join(", ")} answer${s.paths.length === 1 ? "s" : ""} nothing` : "nothing runs";
4956
+ warn(` ! ${s.key} was never deployed to this box: ${where} until kvbox deploy --only ${s.key} (or a full kvbox deploy)`);
4957
+ }
4958
+ const at = d.dirArg !== void 0 ? ` ${d.dirArg}` : "";
4959
+ info(` redeploy: kvbox deploy${at} one service: kvbox deploy${at} --only <service>`);
4960
+ }
4961
+ async function exposedPorts(dir, stack) {
4962
+ const ports = /* @__PURE__ */ new Map();
4963
+ for (const [key, s] of Object.entries(stack.services)) {
4964
+ if (s.template !== "docker" || s.port !== void 0 || s.dir === void 0) continue;
4965
+ const text2 = await readFile7(resolve2(dir, s.dir, "Dockerfile"), "utf8").catch(() => void 0);
4966
+ const port = text2 !== void 0 ? exposedPort(text2) : void 0;
4967
+ if (port !== void 0) ports.set(key, port);
4968
+ }
4969
+ return ports;
4970
+ }
4971
+ async function deployDatabases(d) {
4972
+ const { client, ref } = d;
4973
+ let stale = false;
4974
+ const own = new Set((await client.boxEnv(ref)).vars.map((v) => v.name));
4975
+ for (const s of d.databases) {
4976
+ const pg = s.postgres;
4977
+ if (own.has(pg.env)) continue;
4978
+ await spin(`${s.key}: making a password, its URL in the box variable ${pg.env} (secret)\u2026`, client.setBoxEnv(ref, pg.env, { value: postgresUrl(newPassword(), s.port), secret: true }));
4979
+ stale = true;
4980
+ }
4981
+ let restarted = false;
4982
+ const slug = slugOf(d.owner);
4983
+ const existing = (await client.listVolumes()).filter((v) => slugOf(v.owner) === slug);
4984
+ for (const s of d.databases) {
4985
+ const name = s.postgres.volume;
4986
+ const have = existing.find((v) => v.name === name);
4987
+ if (have?.attachedTo === d.name) continue;
4988
+ if (have && have.attachedTo !== null) throw new KvboxError(`volume ${name} (in ${CONFIG_FILE} for ${s.key}) is attached to box ${have.attachedTo}. Detach it there (kvbox volume detach ${name} ${have.attachedTo}), or name another volume for ${s.key}`);
4989
+ if (have?.host !== void 0) {
4990
+ const boxHost = (await client.listMachines()).find((m) => m.name === d.name && slugOf(m.owner) === slug)?.host;
4991
+ if (boxHost !== void 0 && boxHost !== have.host) {
4992
+ throw new KvboxError(
4993
+ `volume ${name} (${s.key}'s data) is on host ${have.host} and box ${ref} on host ${boxHost}: a volume attaches only to a box on its own host, and its data cannot move yet. Deploy to a box on ${have.host} (one that is still there, --name), or name another volume for ${s.key} in ${CONFIG_FILE} for a new, empty database`
4994
+ );
4995
+ }
4996
+ }
4997
+ if (!have) {
4998
+ const sizeGib = volumeGib(d.volumes[name]);
4999
+ await spin(`${s.key}: making volume ${name} (${sizeGib} GB) for box ${ref}\u2026`, client.createVolume({ name, sizeGib, box: ref }));
5000
+ }
5001
+ await spin(`${s.key}: attaching volume ${name} to box ${ref} (the box restarts once)\u2026`, client.attachVolume(name, { box: ref }));
5002
+ restarted = true;
5003
+ }
5004
+ const restart = async (why) => {
5005
+ info(`restarting box ${ref} so ${why}`);
5006
+ await spin(`restarting box ${ref}\u2026`, async () => {
5007
+ await client.stopMachine(ref);
5008
+ await client.startMachine(ref);
5009
+ });
5010
+ restarted = true;
5011
+ };
5012
+ if (stale && !restarted) await restart("it gets the new database URL");
5013
+ if (restarted) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
5014
+ for (const s of d.databases) {
5015
+ const pg = s.postgres;
5016
+ const script = postgresRemote({ target: { root: `/srv/app/${s.key}`, unit: `kvbox-${s.key}` }, image: pg.image, volume: pg.volume, env: pg.env, port: s.port });
5017
+ const doing = `${s.key}: starting ${pg.image} with its data on volume ${pg.volume} (the first start takes a while)\u2026`;
5018
+ const runScript2 = async () => {
5019
+ const result2 = await spin(doing, shipping.run(d.ep, script));
5020
+ return result2.status === SSH_FAILED3 && await d.renewOnce() ? spin(doing, shipping.run(d.ep, script)) : result2;
5021
+ };
5022
+ let result = await runScript2();
5023
+ if (result.status === ENV_MISSING && !restarted) {
5024
+ await restart(`it gets ${pg.env}`);
5025
+ await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
5026
+ result = await runScript2();
5027
+ }
5028
+ if (result.status === URL_OTHER_PORT) {
5029
+ await spin(`${s.key}: the database moved to port ${s.port}; a new URL in ${pg.env} (secret)\u2026`, client.setBoxEnv(ref, pg.env, { value: postgresUrl(newPassword(), s.port), secret: true }));
5030
+ await restart(`it gets ${pg.env} for port ${s.port}`);
5031
+ await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
5032
+ result = await runScript2();
5033
+ }
5034
+ refuseFailedDatabase(result, s, ref);
5035
+ }
5036
+ }
5037
+ function refuseFailedDatabase(result, s, ref) {
5038
+ const pg = s.postgres;
5039
+ const unit = `kvbox-${s.key}`;
5040
+ switch (result.status) {
5041
+ case 0:
5042
+ return;
5043
+ case SSH_FAILED3:
5044
+ throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `
5045
+ ${result.output.trim()}` : ""}`, SSH_FAILED3);
5046
+ case IMAGE_TOO_OLD:
5047
+ throw new KvboxError(`box ${ref} runs an image too old for a database service (base v0.9.1 or newer). Update the box (kvbox vm update ${ref}), or deploy under another name (--name) to get a fresh box`);
5048
+ case ENV_MISSING:
5049
+ throw new KvboxError(`box ${ref} has not got the variable ${pg.env} although it is set (kvbox env ls --box ${ref}). Restart the box (kvbox stop ${ref} && kvbox start ${ref}) and deploy again`);
5050
+ case VOLUME_NOT_MOUNTED:
5051
+ throw new KvboxError(`volume ${pg.volume} is attached to box ${ref} but not mounted at /mnt/${pg.volume}: the box's image is too old for volumes (base v0.9.1 or newer, kvbox vm update ${ref}), or the box needs a restart. The database was not started, so nothing was written to the box's own disk`);
5052
+ case URL_FOREIGN:
5053
+ throw new KvboxError(`box ${ref}'s variable ${pg.env} holds something other than ${s.key}'s URL (another database?), so ${s.key} was not started. Name another variable for ${s.key} ("env" in ${CONFIG_FILE}), or remove it (kvbox env rm ${pg.env} --box ${ref}) and deploy again`);
5054
+ case URL_OTHER_PORT:
5055
+ throw new KvboxError(`box ${ref} still has ${s.key}'s URL for another port after a restart. Restart the box (kvbox stop ${ref} && kvbox start ${ref}) and deploy again`);
5056
+ case OTHER_DATA: {
5057
+ const other = result.output.trim().split("\n").at(-1);
5058
+ throw new KvboxError(
5059
+ `volume ${pg.volume} holds the database of service ${other}, not ${s.key}'s (a renamed service?), so ${s.key} was not started. To keep that data as ${s.key}'s: kvbox exec ${ref} -- 'sudo systemctl disable --now kvbox-${other}; sudo mv /mnt/${pg.volume}/${other} /mnt/${pg.volume}/${s.key}', then deploy again. Otherwise give ${s.key} another volume`
5060
+ );
5061
+ }
5062
+ case DB_NOT_READY: {
5063
+ const log = result.output.split(LOG_MARKER)[1]?.trim();
5064
+ throw new KvboxError(`${s.key}: ${pg.image} did not answer on port ${s.port} within ${DB_WAIT_SEC} s. Its log: kvbox exec ${ref} -- journalctl -u ${unit}${log ? `
5065
+ last lines:
5066
+ ${log}` : ""}`);
5067
+ }
5068
+ default:
5069
+ throw new KvboxError(`starting ${s.key} in ${ref} failed (exit ${result.status}):
5070
+ ${result.output.trim()}`);
5071
+ }
5072
+ }
5073
+ async function neverShipped(ep, services) {
5074
+ if (services.length === 0) return [];
5075
+ const checks = services.map((s) => `[ -e /srv/app/${s.key}/${s.static ? "dist" : "current"} ] || echo ${s.key}`);
5076
+ const result = await shipping.run(ep, checks.join("\n"));
5077
+ if (result.status !== 0) return [];
5078
+ const keys = new Set(result.output.split("\n").map((l) => l.trim()));
5079
+ return services.filter((s) => keys.has(s.key));
5080
+ }
5081
+ function pick(services, only) {
5082
+ if (only === void 0) return services;
5083
+ for (const key of only) {
5084
+ if (!services.some((s) => s.key === key)) throw new KvboxError(`--only ${key}: no such service in ${CONFIG_FILE} (it has ${services.map((s) => s.key).join(", ")})`);
5085
+ }
5086
+ return services.filter((s) => only.includes(s.key));
5087
+ }
5088
+ async function settle(d) {
5089
+ const { stack, opts, orgFlag, cloud } = d;
5090
+ if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
5091
+ if (opts.sub !== void 0) assertSubdomain(opts.sub);
5092
+ const renamed = stack.name !== void 0 && (opts.name !== void 0 && opts.name !== stack.name || orgFlag !== void 0 && orgFlag !== stack.org);
5093
+ const savedSub = renamed ? void 0 : stack.subdomain;
5094
+ const defaults = { name: opts.name ?? stack.name ?? nameFromDir(basename(d.dir)), size: opts.size ?? stack.size ?? STACK_SIZE };
5095
+ const open = {
5096
+ name: opts.name === void 0 && stack.name === void 0,
5097
+ subdomain: cloud && opts.sub === void 0 && savedSub === void 0,
5098
+ size: opts.size === void 0 && stack.size === void 0,
5099
+ // Only for the databases this run deploys: one left out by --only is asked when it is deployed.
5100
+ volumes: Object.entries(stack.services).filter(([key, s]) => s.template === POSTGRES && s.volume === void 0 && (opts.only === void 0 || opts.only.includes(key))).map(([key]) => key)
5101
+ };
5102
+ const anyOpen = open.name || open.subdomain || open.size || open.volumes.length > 0;
5103
+ const accountVolumes = open.volumes.length > 0 ? new Set((await d.client.listVolumes()).map((v) => v.name)) : /* @__PURE__ */ new Set();
5104
+ if (anyOpen && !opts.yes && !interactive()) {
5105
+ throw new KvboxError(
5106
+ `kvbox deploy asks a few questions the first time, and this is not a terminal. Pass -y to take the defaults (box ${defaults.name}${cloud ? `, https://${opts.sub ?? savedSub ?? subdomainFor(defaults.name)}.kvbox.app` : ""}, size ${defaults.size}${defaultVolumes(defaults.name, stack.volumes ?? {}, accountVolumes, open.volumes).map(([key, v]) => `, a ${VOLUME_GIB} GB volume ${v} for ${key}`).join("")}), or answer with --name${cloud ? ", --sub" : ""} and --size, or in ${CONFIG_FILE}`
5107
+ );
5108
+ }
5109
+ const ask = anyOpen && !opts.yes;
5110
+ if (ask) info(`${color.bold("kvbox deploy")} ${color.dim(d.dir)} ${color.dim(`\xB7 ${Object.keys(stack.services).length} services`)}
5111
+ `);
5112
+ let name = defaults.name;
5113
+ if (open.name && ask) name = await text("Box name", { default: defaults.name, validate: (a) => BOX_NAME_RE.test(a) ? void 0 : NAME_RULE });
5114
+ let subdomain = opts.sub ?? savedSub ?? (cloud ? subdomainFor(name) : void 0);
5115
+ if (open.subdomain && ask) {
5116
+ subdomain = await text("Address", {
5117
+ default: subdomainFor(name),
5118
+ validate: (a) => {
5119
+ const problem = subdomainProblem(a);
5120
+ return problem ? `that name ${problem}` : void 0;
5121
+ }
5122
+ });
5123
+ info(` ${color.dim(`https://${subdomain}.kvbox.app`)}`);
5124
+ }
5125
+ let size = defaults.size;
5126
+ if (open.size && ask) {
5127
+ size = await select("Box size", SIZE_NAMES.map((s) => ({ value: s, label: s, hint: `${SIZES[s].vcpu} vCPU, ${SIZES[s].memMib / 1024} GB RAM, ${SIZES[s].diskGib} GB disk` })), SIZE_NAMES.indexOf(STACK_SIZE));
5128
+ }
5129
+ const volumes = { ...stack.volumes };
5130
+ const services = { ...stack.services };
5131
+ for (const key of open.volumes) {
5132
+ let volume = volumeNameFor(name, volumes, accountVolumes);
5133
+ let gib = `${VOLUME_GIB}GB`;
5134
+ if (ask) {
5135
+ volume = await text(`Volume for ${key}'s data`, { default: volume, validate: (a) => !VOLUME_NAME_RE.test(a) ? VOLUME_NAME_RULE : volumes[a] !== void 0 ? "already a volume of this stack" : accountVolumes.has(a) ? `already a volume of yours, another box's data; to reuse it on purpose, name it in ${CONFIG_FILE}` : void 0 });
5136
+ gib = await text("Volume size", { default: gib, validate: (a) => volumeGib(a) === void 0 ? "whole GB, like 10GB" : void 0 });
5137
+ }
5138
+ volumes[volume] = gib;
5139
+ services[key] = { ...services[key], volume };
5140
+ }
5141
+ if (ask) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
5142
+ `);
5143
+ const org = orgFlag ?? stack.org;
5144
+ return {
5145
+ name,
5146
+ ...org !== void 0 ? { org } : {},
5147
+ ...subdomain !== void 0 ? { subdomain } : {},
5148
+ size,
5149
+ ...Object.keys(volumes).length > 0 ? { volumes } : {},
5150
+ services
5151
+ };
5152
+ }
5153
+ var VOLUME_GIB = 10;
5154
+ function defaultVolumes(box, stackVolumes, account, keys) {
5155
+ const taken = { ...stackVolumes };
5156
+ return keys.map((key) => {
5157
+ const v = volumeNameFor(box, taken, account);
5158
+ taken[v] = `${VOLUME_GIB}GB`;
5159
+ return [key, v];
5160
+ });
5161
+ }
5162
+ function volumeNameFor(box, taken, account = /* @__PURE__ */ new Set()) {
5163
+ const free = (n) => taken[n] === void 0 && !account.has(n);
5164
+ const base = `${box.slice(0, 9).replace(/-+$/, "")}-db`;
5165
+ if (free(base)) return base;
5166
+ for (let i = 2; ; i++) {
5167
+ const n = `${box.slice(0, 8).replace(/-+$/, "")}-db${i}`;
5168
+ if (free(n)) return n;
5169
+ }
5170
+ }
5171
+ async function readPackageJson(dir) {
5172
+ try {
5173
+ return JSON.parse(await readFile7(join8(dir, "package.json"), "utf8"));
5174
+ } catch (err) {
5175
+ if (err.code === "ENOENT") return void 0;
5176
+ throw new KvboxError(`${join8(dir, "package.json")}: ${err.message}`);
5177
+ }
5178
+ }
4386
5179
 
4387
5180
  // src/commands/deploy/index.ts
4388
- var deployCommand = new Command54("deploy").description("put the app in this directory (React, Next.js, a Node server, a Dockerfile or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the box port of a Next.js app, Node server or container (default 3000; saved to kvbox.json)", parsePort).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
4389
- const dir = resolve2(dirArg ?? ".");
4390
- const pkg = await readPackageJson(dir);
4391
- const facts = { indexHtml: await exists(resolve2(dir, "index.html")), dockerfile: await exists(resolve2(dir, "Dockerfile")) };
4392
- const saved = await readConfig(dir);
5181
+ var deployCommand = new Command54("deploy").description("put the app in this directory (React, Next.js, a Node server, a Dockerfile or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the box port of a Next.js app, Node server or container (default 3000; saved to kvbox.json)", parsePort).option("--only <service>", "with several services in kvbox.json: deploy this one only (repeatable)", (v, all) => [...all ?? [], v]).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
5182
+ const dir = resolve3(dirArg ?? ".");
5183
+ const pkg = await readPackageJson2(dir);
5184
+ const facts = { indexHtml: await exists2(resolve3(dir, "index.html")), dockerfile: await exists2(resolve3(dir, "Dockerfile")) };
5185
+ const file = await readDeployFile(dir);
5186
+ const saved = file?.kind === "single" ? file.config : void 0;
4393
5187
  const globals = cmd.optsWithGlobals();
4394
5188
  const orgFlag = orgOption(globals);
4395
- const org = orgFlag ?? saved?.org;
5189
+ const org = orgFlag ?? file?.config.org;
4396
5190
  const client = await clientFor({ ...globals.local ? { local: true } : {}, ...org !== void 0 ? { org } : {} });
4397
5191
  try {
4398
5192
  const cloud = client.target.kind === "cloud";
4399
5193
  if (!cloud && org !== void 0) throw new KvboxError("--org needs a control plane: kvbox login, or drop --org");
4400
- const { config, template, fresh } = await settle(dir, pkg, facts, saved, opts, orgFlag, cloud);
5194
+ if (file?.kind === "stack") {
5195
+ await deployStack({ dir, dirArg, stack: file.config, opts, orgFlag, client, cloud });
5196
+ return;
5197
+ }
5198
+ if (opts.only !== void 0) throw new KvboxError(`--only picks a service of a ${CONFIG_FILE} with "services"; this one describes a single app`);
5199
+ const { config, template, fresh } = await settle2(dir, pkg, facts, saved, opts, orgFlag, cloud);
4401
5200
  if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, config);
4402
5201
  await writeConfig(dir, config);
4403
5202
  if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
@@ -4422,24 +5221,7 @@ var deployCommand = new Command54("deploy").description("put the app in this dir
4422
5221
  info("renewed your SSH certificate, trying again\u2026");
4423
5222
  result = await spin(doing, shipIt);
4424
5223
  }
4425
- if (result.status === SSH_FAILED3) throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `
4426
- ${result.output.trim()}` : ""}`, SSH_FAILED3);
4427
- if (result.status === IMAGE_TOO_OLD) {
4428
- throw new KvboxError(
4429
- `box ${ref} runs an image too old for the ${template.label} template (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}) once its host has the new image, or deploy under another name (--name) to get a fresh box`
4430
- );
4431
- }
4432
- if (result.status === APP_NOT_LISTENING) {
4433
- const log = result.output.split(LOG_MARKER)[1]?.trim();
4434
- const where = built.containerPort !== void 0 && built.containerPort !== port ? `the container's port ${built.containerPort} (box port ${port})` : `port ${port}`;
4435
- throw new KvboxError(
4436
- `the app did not answer on ${where} within ${START_WAIT_SEC} s: it crashed, or listens on another port. ${template.listens ?? `It must listen on process.env.PORT (${port})`}${template.customPort ? ", or say its port with --port" : ""}. Its log: kvbox exec ${ref} -- ${template.logs ?? "journalctl -u kvbox-app"}${log ? `
4437
- last lines:
4438
- ${log}` : ""}`
4439
- );
4440
- }
4441
- if (result.status !== 0) throw new KvboxError(`deploying to ${ref} failed (exit ${result.status}):
4442
- ${result.output.trim()}`);
5224
+ refuseFailedShip(result, { ref, template, port, built });
4443
5225
  let url = `http://${box.ip}${port === 80 ? "" : `:${port}`}`;
4444
5226
  if (cloud) {
4445
5227
  const got = await address(client, box, ref, config, port);
@@ -4467,16 +5249,16 @@ function parsePort(v) {
4467
5249
  if (portProblem(v)) throw new InvalidArgumentError2("expected a port, 1-65535");
4468
5250
  return Number(v);
4469
5251
  }
4470
- var exists = (path) => access4(path).then(() => true, () => false);
4471
- async function readPackageJson(dir) {
5252
+ var exists2 = (path) => access5(path).then(() => true, () => false);
5253
+ async function readPackageJson2(dir) {
4472
5254
  try {
4473
- return JSON.parse(await readFile7(resolve2(dir, "package.json"), "utf8"));
5255
+ return JSON.parse(await readFile8(resolve3(dir, "package.json"), "utf8"));
4474
5256
  } catch (err) {
4475
5257
  if (err.code === "ENOENT") return void 0;
4476
- throw new KvboxError(`${resolve2(dir, "package.json")}: ${err.message}`);
5258
+ throw new KvboxError(`${resolve3(dir, "package.json")}: ${err.message}`);
4477
5259
  }
4478
5260
  }
4479
- async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
5261
+ async function settle2(dir, pkg, facts, saved, opts, orgFlag, cloud) {
4480
5262
  const [detected, ...also] = detectTemplates(pkg, facts);
4481
5263
  if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
4482
5264
  if (opts.sub !== void 0) assertSubdomain(opts.sub);
@@ -4484,7 +5266,7 @@ async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
4484
5266
  const savedSub = renamed ? void 0 : saved?.subdomain;
4485
5267
  const defaults = {
4486
5268
  template: opts.template ?? saved?.template ?? detected?.id,
4487
- name: opts.name ?? saved?.name ?? nameFromDir(basename(dir)),
5269
+ name: opts.name ?? saved?.name ?? nameFromDir(basename2(dir)),
4488
5270
  subdomain: opts.sub ?? savedSub,
4489
5271
  size: opts.size ?? saved?.size
4490
5272
  };
@@ -4551,49 +5333,6 @@ async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
4551
5333
  };
4552
5334
  return { config, template, fresh };
4553
5335
  }
4554
- var NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
4555
- async function findOrCreate(client, config) {
4556
- const user = me(client);
4557
- const slug = config.org ?? user;
4558
- const named = (await client.listMachines()).filter((b) => b.name === config.name);
4559
- let box = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
4560
- let created = false;
4561
- if (!box) {
4562
- box = await spin(`booting a new box ${config.name}\u2026`, client.createMachine({ name: config.name, ...config.size !== void 0 ? { size: config.size } : {}, autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));
4563
- created = true;
4564
- info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);
4565
- }
4566
- return { box, ref: displayName(box, user), created };
4567
- }
4568
- async function existingAddresses(client, config) {
4569
- const slug = config.org ?? me(client);
4570
- return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
4571
- }
4572
- async function refuseOtherAddress(client, config) {
4573
- const have = await existingAddresses(client, config);
4574
- if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
4575
- const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
4576
- throw new KvboxError(
4577
- `box ${ref} already has ${MAX_BOX_SUBDOMAINS} addresses (${have.map((s) => s.subdomain).join(", ")}), none of them ${config.subdomain}. Deploy to one: kvbox deploy --sub <name>. Or free one: kvbox vm proxy release ${ref} --sub <name>`
4578
- );
4579
- }
4580
- async function address(client, box, ref, config, port) {
4581
- const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
4582
- const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
4583
- if (have) {
4584
- if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
4585
- return { url: have.url, subdomain: have.subdomain };
4586
- }
4587
- const wanted = config.subdomain ?? subdomainFor(config.name);
4588
- try {
4589
- const sub = await spin(`claiming https://${wanted}.kvbox.app\u2026`, client.claimSubdomain(ref, { name: wanted, port }));
4590
- return { url: sub.url, subdomain: sub.subdomain };
4591
- } catch (err) {
4592
- if (!(err instanceof KvboxError)) throw err;
4593
- throw new KvboxError(`${err.message}
4594
- the app is on box ${ref} but has no address yet: pick another with kvbox deploy --sub <name> (saved to ${CONFIG_FILE})`);
4595
- }
4596
- }
4597
5336
 
4598
5337
  // src/commands/volume/index.ts
4599
5338
  import { Command as Command60 } from "commander";
@@ -5018,7 +5757,7 @@ for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in thi
5018
5757
  import { spawn as spawn6 } from "child_process";
5019
5758
  import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
5020
5759
  import { tmpdir } from "os";
5021
- import { join as join8 } from "path";
5760
+ import { join as join9 } from "path";
5022
5761
  import { Command as Command69 } from "commander";
5023
5762
 
5024
5763
  // src/update.ts
@@ -5131,11 +5870,11 @@ async function download(url) {
5131
5870
  if (!body.startsWith("#!")) throw new KvboxError(`${url} did not return a shell script`);
5132
5871
  return body;
5133
5872
  }
5134
- function run(cmd, args) {
5135
- return new Promise((resolve3, reject) => {
5873
+ function run2(cmd, args) {
5874
+ return new Promise((resolve4, reject) => {
5136
5875
  const child = spawn6(cmd, args, { stdio: "inherit" });
5137
5876
  child.on("error", (err) => reject(new KvboxError(`could not run ${cmd}: ${err.message}`)));
5138
- child.on("exit", (code, signal) => resolve3(code ?? (signal ? 1 : 0)));
5877
+ child.on("exit", (code, signal) => resolve4(code ?? (signal ? 1 : 0)));
5139
5878
  });
5140
5879
  }
5141
5880
  var selfUpdateCommand = new Command69("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
@@ -5143,14 +5882,14 @@ var selfUpdateCommand = new Command69("update").description("update kvbox to the
5143
5882
  const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
5144
5883
  let code;
5145
5884
  if (process.platform === "win32") {
5146
- code = await run(inst.cmd, inst.args);
5885
+ code = await run2(inst.cmd, inst.args);
5147
5886
  } else {
5148
5887
  const script = await download(inst.url);
5149
- const dir = mkdtempSync(join8(tmpdir(), "kvbox-update-"));
5150
- const file = join8(dir, "install.sh");
5888
+ const dir = mkdtempSync(join9(tmpdir(), "kvbox-update-"));
5889
+ const file = join9(dir, "install.sh");
5151
5890
  try {
5152
5891
  writeFileSync2(file, script, { mode: 448 });
5153
- code = await run(inst.cmd, inst.args.map((a) => a === "{script}" ? file : a));
5892
+ code = await run2(inst.cmd, inst.args.map((a) => a === "{script}" ? file : a));
5154
5893
  } finally {
5155
5894
  rmSync(dir, { recursive: true, force: true });
5156
5895
  }