cloudler 0.0.2 → 0.0.3

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.
Files changed (2) hide show
  1. package/dist/cloudler.js +1091 -662
  2. package/package.json +1 -1
package/dist/cloudler.js CHANGED
@@ -6354,15 +6354,15 @@ var require_parser = __commonJS({
6354
6354
  var node_process = __require("process");
6355
6355
  var cst = require_cst();
6356
6356
  var lexer = require_lexer();
6357
- function includesToken(list3, type) {
6358
- for (let i = 0; i < list3.length; ++i)
6359
- if (list3[i].type === type)
6357
+ function includesToken(list2, type) {
6358
+ for (let i = 0; i < list2.length; ++i)
6359
+ if (list2[i].type === type)
6360
6360
  return true;
6361
6361
  return false;
6362
6362
  }
6363
- function findNonEmptyIndex(list3) {
6364
- for (let i = 0; i < list3.length; ++i) {
6365
- switch (list3[i].type) {
6363
+ function findNonEmptyIndex(list2) {
6364
+ for (let i = 0; i < list2.length; ++i) {
6365
+ switch (list2[i].type) {
6366
6366
  case "space":
6367
6367
  case "comment":
6368
6368
  case "newline":
@@ -8156,6 +8156,516 @@ var require_cjs = __commonJS({
8156
8156
  }
8157
8157
  });
8158
8158
 
8159
+ // ../../packages/schema/src/env-inputs.ts
8160
+ var import_yaml = __toESM(require_dist(), 1);
8161
+
8162
+ // ../../packages/schema/src/portler-syntax.ts
8163
+ function isObject(v) {
8164
+ return Boolean(v) && typeof v === "object" && !Array.isArray(v);
8165
+ }
8166
+ var OLD_POSTGRES = {
8167
+ volumes: ["@${self.name}-data:/var/lib/postgresql/data"]
8168
+ };
8169
+ var BUILT_IN_PRESETS = {
8170
+ postgres: {
8171
+ image: "postgres:${version}-alpine",
8172
+ port: 5432,
8173
+ volumes: ["@${self.name}-data:/var/lib/postgresql"],
8174
+ versions: {
8175
+ "18": {},
8176
+ "17": OLD_POSTGRES,
8177
+ "16": OLD_POSTGRES,
8178
+ "15": OLD_POSTGRES,
8179
+ "14": OLD_POSTGRES
8180
+ },
8181
+ env: {
8182
+ POSTGRES_USER: { default: "postgres" },
8183
+ POSTGRES_PASSWORD: { default: "postgres", secret: true },
8184
+ POSTGRES_DB: { default: "app" }
8185
+ },
8186
+ healthcheck: { type: "tcp", timeout_ms: 12e4 },
8187
+ exports: {
8188
+ database_url: "postgres://${env.POSTGRES_USER}:${env.POSTGRES_PASSWORD}@${self.address}/${env.POSTGRES_DB}"
8189
+ }
8190
+ },
8191
+ mysql: {
8192
+ image: "mysql:${version}",
8193
+ port: 3306,
8194
+ volumes: ["@${self.name}-data:/var/lib/mysql"],
8195
+ versions: { "9.7": {}, "8.4": {}, "8.0": {} },
8196
+ env: {
8197
+ MYSQL_ROOT_PASSWORD: { default: "mysql", secret: true },
8198
+ MYSQL_DATABASE: { default: "app" },
8199
+ MYSQL_USER: { default: "app" },
8200
+ MYSQL_PASSWORD: { default: "app", secret: true }
8201
+ },
8202
+ healthcheck: { type: "tcp", timeout_ms: 18e4 },
8203
+ exports: {
8204
+ database_url: "mysql://${env.MYSQL_USER}:${env.MYSQL_PASSWORD}@${self.address}/${env.MYSQL_DATABASE}"
8205
+ }
8206
+ },
8207
+ redis: {
8208
+ image: "redis:${version}-alpine",
8209
+ port: 6379,
8210
+ volumes: ["@${self.name}-data:/data"],
8211
+ versions: { "8": {}, "7": {} },
8212
+ healthcheck: { type: "tcp" },
8213
+ exports: { redis_url: "redis://${self.address}" }
8214
+ }
8215
+ };
8216
+ var ENTRY_KEYS = ["value", "default", "required", "secret", "description", "generate"];
8217
+ function scalar(v) {
8218
+ return v === null || ["string", "number", "boolean"].includes(typeof v);
8219
+ }
8220
+ function text(v) {
8221
+ return v === null ? "" : String(v);
8222
+ }
8223
+ function readEntry(key, raw) {
8224
+ if (scalar(raw)) return { value: text(raw) };
8225
+ if (!isObject(raw)) throw new Error("Invalid environment entry");
8226
+ const invalid = (why) => new Error(`Invalid environment entry ${key}: ${why}`);
8227
+ for (const k of Object.keys(raw))
8228
+ if (!ENTRY_KEYS.includes(k))
8229
+ throw invalid(`unknown key "${k}"; allowed keys: ${ENTRY_KEYS.join(", ")}`);
8230
+ if (raw.value !== void 0 && raw.default !== void 0)
8231
+ throw invalid("it cannot set both value and default");
8232
+ for (const k of ["value", "default"])
8233
+ if (raw[k] !== void 0 && !scalar(raw[k]))
8234
+ throw invalid(`${k} must be a string, number or boolean`);
8235
+ const required5 = raw.required ?? void 0;
8236
+ if (required5 !== void 0 && typeof required5 !== "boolean" && required5 !== "prod")
8237
+ throw invalid('required must be true, false or "prod"');
8238
+ const secret2 = raw.secret ?? void 0;
8239
+ if (secret2 !== void 0 && typeof secret2 !== "boolean")
8240
+ throw invalid("secret must be true or false");
8241
+ if ((raw.description ?? void 0) !== void 0 && typeof raw.description !== "string")
8242
+ throw invalid("description must be a string");
8243
+ const generate = raw.generate ?? void 0;
8244
+ if (generate !== void 0 && typeof generate !== "boolean")
8245
+ throw invalid("generate must be true or false");
8246
+ if (generate === true && raw.value !== void 0)
8247
+ throw invalid("it cannot set both value and generate");
8248
+ if (generate === true && secret2 === false)
8249
+ throw invalid("a generated value is always secret; remove secret: false");
8250
+ return {
8251
+ ...raw.value !== void 0 ? { value: text(raw.value) } : {},
8252
+ ...raw.default !== void 0 ? { value: text(raw.default), isDefault: true } : {},
8253
+ ...required5 === void 0 ? {} : { required: required5 },
8254
+ // isSecretEntry makes a generated entry secret; stored here, a higher generate: false would keep it.
8255
+ ...secret2 === void 0 ? {} : { secret: secret2 },
8256
+ ...generate === void 0 ? {} : { generate },
8257
+ ...typeof raw.description === "string" ? { description: raw.description } : {}
8258
+ };
8259
+ }
8260
+ function readEnvLayer(v, label = "env") {
8261
+ if (v === void 0 || v === null) return {};
8262
+ if (!isObject(v)) throw new Error(`${label} must be a mapping`);
8263
+ const layer = /* @__PURE__ */ Object.create(null);
8264
+ for (const [key, raw] of Object.entries(v)) {
8265
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
8266
+ throw new Error("Invalid environment entry");
8267
+ layer[key] = readEntry(key, raw);
8268
+ }
8269
+ return layer;
8270
+ }
8271
+ function mergeEnvLayers(...layers) {
8272
+ const merged = /* @__PURE__ */ Object.create(null);
8273
+ for (const layer of layers)
8274
+ for (const [key, upper] of Object.entries(layer)) {
8275
+ const lower = merged[key] ?? {};
8276
+ const required5 = upper.required ?? lower.required;
8277
+ const generate = upper.generate ?? lower.generate;
8278
+ const secret2 = upper.secret ?? lower.secret;
8279
+ const description = upper.description ?? lower.description;
8280
+ const base = upper.generate === true && upper.value === void 0 && !lower.isDefault ? {} : lower;
8281
+ const source = upper.value !== void 0 ? upper : base;
8282
+ merged[key] = {
8283
+ ...source.value === void 0 ? {} : { value: source.value },
8284
+ ...source.isDefault ? { isDefault: true } : {},
8285
+ ...source.presetDefault ? { presetDefault: true } : {},
8286
+ ...required5 === void 0 ? {} : { required: required5 },
8287
+ ...secret2 === void 0 ? {} : { secret: secret2 },
8288
+ ...generate === void 0 ? {} : { generate },
8289
+ ...description === void 0 ? {} : { description }
8290
+ };
8291
+ }
8292
+ return merged;
8293
+ }
8294
+ function requiredEnvKeys(entries) {
8295
+ return Object.entries(entries).filter(
8296
+ ([, e]) => e.required === "prod" || isGenerated(e) || isSecretEntry(e) && e.isDefault === true
8297
+ ).map(([key]) => key);
8298
+ }
8299
+ function isSecretEntry(entry) {
8300
+ return entry.generate === true || entry.secret === true;
8301
+ }
8302
+ function isGenerated(entry) {
8303
+ return entry.generate === true && (entry.value === void 0 || entry.isDefault === true);
8304
+ }
8305
+ function fillPlaceholders(v, values) {
8306
+ if (typeof v === "string")
8307
+ return Object.entries(values).reduce(
8308
+ (s, [name4, value]) => s.replaceAll(`\${${name4}}`, () => value),
8309
+ v
8310
+ );
8311
+ if (Array.isArray(v)) return v.map((x) => fillPlaceholders(x, values));
8312
+ if (isObject(v))
8313
+ return Object.fromEntries(
8314
+ Object.entries(v).map(([k, x]) => [k, fillPlaceholders(x, values)])
8315
+ );
8316
+ return v;
8317
+ }
8318
+ var BUILT_IN_PROPERTIES = /* @__PURE__ */ new Set([
8319
+ "url",
8320
+ "local_url",
8321
+ "localUrl",
8322
+ "port",
8323
+ "host",
8324
+ "url_host",
8325
+ "urlHost",
8326
+ "protocol",
8327
+ "desired_port",
8328
+ "desiredPort",
8329
+ "container",
8330
+ "container_name",
8331
+ "containerName",
8332
+ "image",
8333
+ "name",
8334
+ "address",
8335
+ "address_host",
8336
+ "address_port"
8337
+ ]);
8338
+ function readExports(v, name4) {
8339
+ if (v === void 0 || v === null) return {};
8340
+ const field = `services.${name4}.exports`;
8341
+ if (!isObject(v)) throw new Error(`${field} must be a mapping of name: template`);
8342
+ const out = /* @__PURE__ */ Object.create(null);
8343
+ for (const [key, template] of Object.entries(v)) {
8344
+ if (!/^[a-z][a-z0-9_]*$/.test(key))
8345
+ throw new Error(`${field}.${key}: export names use lowercase letters, digits and "_", starting with a letter`);
8346
+ if (BUILT_IN_PROPERTIES.has(key))
8347
+ throw new Error(`${field}.${key} would hide the built-in "${key}" property; pick another name`);
8348
+ if (typeof template !== "string" && typeof template !== "number")
8349
+ throw new Error(`${field}.${key} must be a string template`);
8350
+ out[key] = String(template);
8351
+ }
8352
+ return out;
8353
+ }
8354
+ function applyPreset(raw, name4) {
8355
+ const { use, ...own2 } = raw;
8356
+ if (use === void 0 || use === null)
8357
+ return { service: own2, env: {}, exports: readExports(raw.exports, name4) };
8358
+ const field = `services.${name4}.use`;
8359
+ if (typeof use !== "string" || !use.trim())
8360
+ throw new Error(`${field} must be a preset name`);
8361
+ const known = Object.keys(BUILT_IN_PRESETS);
8362
+ if (use.includes("/") || /\.ya?ml(@|$)/.test(use))
8363
+ throw new Error(
8364
+ `${field}: Cloudler only receives portler.yml, so it cannot read preset files. Use a built-in preset (${known.join(", ")}), or write the keys on the service.`
8365
+ );
8366
+ const at = use.lastIndexOf("@");
8367
+ const target = at > 0 ? use.slice(0, at) : use;
8368
+ const version3 = at > 0 ? use.slice(at + 1) : void 0;
8369
+ if (!Object.hasOwn(BUILT_IN_PRESETS, target))
8370
+ throw new Error(`${field}: there is no built-in preset "${target}". Built-in presets: ${known.join(", ")}.`);
8371
+ const { versions, ...keys } = BUILT_IN_PRESETS[target];
8372
+ const listed = Object.keys(versions).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
8373
+ if (version3 === void 0)
8374
+ throw new Error(
8375
+ `${field}: preset "${target}" needs a version, for example "${target}@${listed[0]}". Versions: ${listed.join(", ")}. Cloudler does not pick one, because a data volume may not open with a different version.`
8376
+ );
8377
+ if (!Object.hasOwn(versions, version3))
8378
+ throw new Error(`${field}: preset "${target}" has no version "${version3}". Versions: ${listed.join(", ")}.`);
8379
+ const preset = fillPlaceholders(
8380
+ { ...keys, ...versions[version3] },
8381
+ { version: version3, "self.name": name4 }
8382
+ );
8383
+ const { env, exports: presetExports, ...presetKeys } = preset;
8384
+ if (own2.exports !== void 0 && own2.exports !== null && !isObject(own2.exports))
8385
+ throw new Error(`services.${name4}.exports must be a mapping of name: template`);
8386
+ const presetEnv = readEnvLayer(env, `preset ${use} env`);
8387
+ for (const entry of Object.values(presetEnv))
8388
+ if (!isSecretEntry(entry)) entry.presetDefault = true;
8389
+ return {
8390
+ service: { ...presetKeys, ...own2 },
8391
+ env: presetEnv,
8392
+ exports: readExports({ ...presetExports, ...own2.exports }, name4)
8393
+ };
8394
+ }
8395
+ function ownHealthcheck(health, name4) {
8396
+ if (!isObject(health) || typeof health.url !== "string") return health;
8397
+ return { ...health, url: health.url.replaceAll("${self.", `\${${name4}.`) };
8398
+ }
8399
+ var REFERENCE = /\$\{([A-Za-z0-9_-]+)\.([A-Za-z0-9_]+)\}/g;
8400
+ var BARE_REFERENCE = /^([A-Za-z0-9_-]+)\.([A-Za-z0-9_]+)$/;
8401
+ var ADDRESS_PROPERTIES = /* @__PURE__ */ new Set(["address", "address_host", "address_port"]);
8402
+ var LOCAL_URL = /* @__PURE__ */ new Set(["local_url", "localUrl"]);
8403
+ function expandOne(service, property, scope) {
8404
+ const { owner, targets, exportOf } = scope;
8405
+ if (service === "env" && exportOf !== void 0 && !targets.env) {
8406
+ const exporter = exportOf.split(".", 1)[0];
8407
+ const values = targets[exporter].env;
8408
+ if (!Object.hasOwn(values, property))
8409
+ throw new Error(`Export ${exportOf} reads env.${property}, but service ${exporter} has no env value for ${property}`);
8410
+ const value = values[property];
8411
+ if (!scope.isLiteral(property))
8412
+ return expandReferences(value, { ...scope, owner: exporter, exportOf: void 0, noExports: true });
8413
+ if (value.includes("${"))
8414
+ throw new Error(
8415
+ `Export ${exportOf} reads env.${property}, and its deployment value contains "\${", which the generated config cannot keep as text. Supply a value without "\${".`
8416
+ );
8417
+ return value;
8418
+ }
8419
+ const publicValue = service === "proxy" && property !== "address_host" && scope.publicUrl !== void 0 ? publicProxyReference(property, scope.publicUrl) : void 0;
8420
+ if (publicValue !== void 0)
8421
+ return scope.publicProxy ? scope.publicProxy(`\${proxy.${property}}`, publicValue) : publicValue;
8422
+ if (LOCAL_URL.has(property))
8423
+ throw new Error(`Service ${owner}: a value reads ${property}, which only Portler 0.5 knows. In production it is the same as url; use url.`);
8424
+ const name4 = service === "self" && !targets.self ? owner : service;
8425
+ const target = targets[name4];
8426
+ if (target) {
8427
+ if (property === "name") return name4;
8428
+ if (ADDRESS_PROPERTIES.has(property) && target.port !== void 0) {
8429
+ if (property === "address_host") return name4;
8430
+ if (property === "address_port") return String(target.port);
8431
+ return `${name4}:${target.port}`;
8432
+ }
8433
+ if (Object.hasOwn(target.exports, property)) {
8434
+ const exportName = `${name4}.${property}`;
8435
+ if (exportOf !== void 0)
8436
+ throw new Error(`Export ${exportOf} cannot use another export (${exportName})`);
8437
+ if (scope.noExports)
8438
+ throw new Error(`An export cannot read an env value that uses an export (${exportName})`);
8439
+ scope.onExport?.();
8440
+ return expandReferences(target.exports[property], { ...scope, owner: name4, exportOf: exportName });
8441
+ }
8442
+ }
8443
+ return `\${${name4}.${property}}`;
8444
+ }
8445
+ function expandReferences(value, scope) {
8446
+ const bare = BARE_REFERENCE.exec(value);
8447
+ if (bare) {
8448
+ const [, service, property] = bare;
8449
+ const { targets, owner, exportOf } = scope;
8450
+ const self = service === "self" && !targets.self;
8451
+ const env = service === "env" && exportOf !== void 0 && !targets.env;
8452
+ const target = targets[self ? owner : service];
8453
+ if (self || env || service === "proxy" && property !== "address_host" && scope.publicUrl !== void 0 && publicProxyReference(property, scope.publicUrl) !== void 0 || LOCAL_URL.has(property) || // An export (or the env it reads) can embed a bare built-in reference in other text;
8454
+ // keep its syntax for the downstream resolver (`prefix-${env.P}` with P: db.port).
8455
+ (scope.exportOf !== void 0 || scope.noExports) && readsAsReference(value, targets) || target && (property === "name" || ADDRESS_PROPERTIES.has(property) || Object.hasOwn(target.exports, property)))
8456
+ return expandOne(service, property, scope);
8457
+ return value;
8458
+ }
8459
+ return value.replace(
8460
+ REFERENCE,
8461
+ (_whole, service, property) => expandOne(service, property, scope)
8462
+ );
8463
+ }
8464
+ var PROXY_HOST = /* @__PURE__ */ new Set(["host", "url_host", "urlHost", "address_host"]);
8465
+ function publicProxyReference(property, publicUrl) {
8466
+ const url2 = new URL(publicUrl);
8467
+ if (property === "url") return url2.origin;
8468
+ if (property === "protocol") return url2.protocol.slice(0, -1);
8469
+ if (PROXY_HOST.has(property)) return url2.hostname;
8470
+ return void 0;
8471
+ }
8472
+ function expandWithPublicProxy(value, scope) {
8473
+ if (value.includes("\0")) throw new Error("An env value contains a NUL character, which no process environment can hold");
8474
+ const publics = [];
8475
+ const template = expandReferences(value, {
8476
+ ...scope,
8477
+ publicProxy: (reference, publicValue) => `\0${publics.push([reference, publicValue]) - 1}\0`
8478
+ });
8479
+ const fill = (pick2) => template.replace(/\0(\d+)\0/g, (_, i) => publics[Number(i)][pick2]);
8480
+ const expanded = fill(1);
8481
+ const references = (text4) => [...text4.matchAll(REFERENCE)].map((m) => m[0]).join("\n");
8482
+ return readsAsReference(expanded, scope.targets) || references(expanded) !== references(template) ? fill(0) : expanded;
8483
+ }
8484
+ function readsAsReference(value, services) {
8485
+ const bare = BARE_REFERENCE.exec(value);
8486
+ if (!bare || bare[1] === "env") return false;
8487
+ const [, service, property] = bare;
8488
+ return service === "self" || service === "proxy" || BUILT_IN_PROPERTIES.has(property) || Object.hasOwn(services, service) && services[service].port !== void 0;
8489
+ }
8490
+ function referenceDiagnosticSecrets(value, targets) {
8491
+ const bare = BARE_REFERENCE.exec(value);
8492
+ if (bare && !readsAsReference(value, targets)) return [];
8493
+ const references = bare ? [bare] : [...value.matchAll(REFERENCE)];
8494
+ return references.flatMap(([, service, property]) => {
8495
+ const unknownService = service !== "proxy" && !Object.hasOwn(targets, service);
8496
+ const unknownProperty = !BUILT_IN_PROPERTIES.has(property) && !Object.hasOwn(targets[service]?.exports ?? {}, property);
8497
+ if (!unknownService && !unknownProperty) return [];
8498
+ return [
8499
+ `${service}.${property}`,
8500
+ ...unknownService ? [service] : [],
8501
+ ...unknownProperty ? [property] : []
8502
+ ];
8503
+ });
8504
+ }
8505
+ function isReferencesOnly(written, targets, owner) {
8506
+ const isPublic = (service, property) => BUILT_IN_PROPERTIES.has(property) && (service === "proxy" || Boolean(targets[service === "self" && !targets.self ? owner : service]));
8507
+ const bare = BARE_REFERENCE.exec(written);
8508
+ if (bare) return isPublic(bare[1], bare[2]);
8509
+ const references = [...written.matchAll(REFERENCE)];
8510
+ return references.length > 0 && written.replace(REFERENCE, "") === "" && references.every((m) => isPublic(m[1], m[2]));
8511
+ }
8512
+
8513
+ // ../../packages/schema/src/env-inputs.ts
8514
+ function mapping(v, label) {
8515
+ if (!v || typeof v !== "object" || Array.isArray(v))
8516
+ throw new Error(`${label} must be a mapping`);
8517
+ return v;
8518
+ }
8519
+ function stringList(v) {
8520
+ if (v === void 0) return [];
8521
+ const a = typeof v === "string" ? [v] : v;
8522
+ if (!Array.isArray(a) || a.some((x) => typeof x !== "string"))
8523
+ throw new Error("Expected a list of strings");
8524
+ return a;
8525
+ }
8526
+ function parsePortlerYaml(config2) {
8527
+ try {
8528
+ return (0, import_yaml.parse)(config2, {
8529
+ maxAliasCount: 0,
8530
+ customTags: (tags) => tags.filter((t) => typeof t === "string" || !["HEX", "OCT"].includes(t.format ?? ""))
8531
+ });
8532
+ } catch {
8533
+ throw new Error("Portler configuration is not valid YAML. Check syntax and indentation.");
8534
+ }
8535
+ }
8536
+ function dockerOverride(service) {
8537
+ const d = service.docker;
8538
+ if (d === void 0 || d === true) return {};
8539
+ if (typeof d === "string") return { image: d };
8540
+ return mapping(d, "docker");
8541
+ }
8542
+ function serviceEnvDeclarations(root, prod, presetEnv, service, serviceProd) {
8543
+ const prodEnv = readEnvLayer(prod.env);
8544
+ const docker = dockerOverride(service);
8545
+ const serviceProdEnv = readEnvLayer(serviceProd.env);
8546
+ const own2 = mergeEnvLayers(
8547
+ presetEnv,
8548
+ readEnvLayer(service.env ?? service.environment),
8549
+ readEnvLayer(docker.env ?? docker.environment),
8550
+ serviceProdEnv
8551
+ );
8552
+ const entries = mergeEnvLayers(mergeEnvLayers(readEnvLayer(root.env), prodEnv), own2);
8553
+ const requirements = /* @__PURE__ */ new Set([
8554
+ ...stringList(prod.require),
8555
+ ...stringList(serviceProd.require),
8556
+ ...requiredEnvKeys(entries)
8557
+ ]);
8558
+ for (const [k, v] of Object.entries(prodEnv))
8559
+ if (v.value === "" && !own2[k]?.value) requirements.add(k);
8560
+ for (const [k, v] of Object.entries(serviceProdEnv))
8561
+ if (v.value === "") requirements.add(k);
8562
+ return { entries, requirements };
8563
+ }
8564
+ function deploymentInputs(config2) {
8565
+ const root = mapping(parsePortlerYaml(config2), "config");
8566
+ const all = mapping(root.services, "services");
8567
+ const prod = root.prod === void 0 ? {} : mapping(root.prod, "prod");
8568
+ const selected = prod.services === void 0 ? Object.keys(all) : stringList(prod.services);
8569
+ const inputs = /* @__PURE__ */ new Map();
8570
+ for (const name4 of selected) {
8571
+ if (!Object.hasOwn(all, name4)) throw new Error(`prod.services names unknown service "${name4}"`);
8572
+ const preset = applyPreset(mapping(all[name4], `services.${name4}`), name4);
8573
+ const s = preset.service;
8574
+ const sp = s.prod === void 0 ? {} : mapping(s.prod, `services.${name4}.prod`);
8575
+ const { entries, requirements } = serviceEnvDeclarations(root, prod, preset.env, s, sp);
8576
+ const injected = s.port === void 0 ? [] : stringList(s.port_env ?? s.portEnv);
8577
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(entries), ...requirements])) {
8578
+ const entry = entries[key] ?? {};
8579
+ const generated = isGenerated(entry);
8580
+ const input2 = inputs.get(key) ?? { key, required: false, generated: false, secret: false, configured: false, services: [] };
8581
+ input2.generated ||= generated;
8582
+ input2.required ||= !generated && (requirements.has(key) || entry.required === true && !entry.value && !injected.includes(key));
8583
+ input2.secret ||= isSecretEntry(entry);
8584
+ input2.configured ||= !requirements.has(key) && entry.value !== void 0;
8585
+ input2.description ??= entry.description;
8586
+ input2.services.push(name4);
8587
+ inputs.set(key, input2);
8588
+ }
8589
+ }
8590
+ const rank = (i) => i.required ? 0 : i.generated ? 1 : 2;
8591
+ return [...inputs.values()].map((i) => i.generated ? { ...i, required: false } : i).sort((a, b) => rank(a) - rank(b) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
8592
+ }
8593
+ function generatedEnvKeys(config2) {
8594
+ return deploymentInputs(config2).filter((i) => i.generated).map((i) => i.key);
8595
+ }
8596
+ function withGeneratedPlaceholders(config2, environment) {
8597
+ let keys;
8598
+ try {
8599
+ keys = generatedEnvKeys(config2);
8600
+ } catch {
8601
+ return environment;
8602
+ }
8603
+ const filled = { ...environment };
8604
+ for (const key of keys) if (!Object.hasOwn(filled, key) || !filled[key]) filled[key] = "0".repeat(64);
8605
+ return filled;
8606
+ }
8607
+
8608
+ // src/env-input.ts
8609
+ var KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
8610
+ function parseEnvFile(text4, path) {
8611
+ if (text4.trimStart().startsWith("{")) {
8612
+ try {
8613
+ return JSON.parse(text4);
8614
+ } catch {
8615
+ throw new Error(`Cannot read --env-file ${path}: invalid JSON (values redacted)`);
8616
+ }
8617
+ }
8618
+ const env = {};
8619
+ for (const [i, raw] of text4.split(/\r?\n/).entries()) {
8620
+ const line = raw.trim();
8621
+ if (!line || line.startsWith("#")) continue;
8622
+ const pair = splitPair(line.replace(/^export\s+/, ""));
8623
+ const value = pair && dotenvValue(pair[1].trim());
8624
+ if (!pair || value === void 0) throw new Error(`Cannot read --env-file ${path}: line ${i + 1} is not KEY=VALUE (values redacted)`);
8625
+ env[pair[0]] = value;
8626
+ }
8627
+ return env;
8628
+ }
8629
+ function dotenvValue(text4) {
8630
+ const quoted = /^(["'])((?:\\.|(?!\1).)*)\1\s*(?:#.*)?$/.exec(text4);
8631
+ if (quoted)
8632
+ return quoted[1] === "'" ? quoted[2] : quoted[2].replace(/\\([n"\\])/g, (_m, c) => c === "n" ? "\n" : c);
8633
+ if (/^["']/.test(text4)) return void 0;
8634
+ return text4.startsWith("#") ? "" : text4.replace(/\s+#.*$/, "");
8635
+ }
8636
+ function parseEnvFlags(flags) {
8637
+ const env = {};
8638
+ for (const [i, flag] of flags.entries()) {
8639
+ const pair = splitPair(flag);
8640
+ if (!pair) throw new Error(`--env number ${i + 1} is not KEY=VALUE (value redacted)`);
8641
+ env[pair[0]] = pair[1];
8642
+ }
8643
+ return env;
8644
+ }
8645
+ function splitPair(text4) {
8646
+ const at = text4.indexOf("=");
8647
+ if (at < 1) return void 0;
8648
+ const key = text4.slice(0, at).trim();
8649
+ return KEY.test(key) ? [key, text4.slice(at + 1)] : void 0;
8650
+ }
8651
+ function describeInputs(config2, supplied, saved2) {
8652
+ let inputs;
8653
+ try {
8654
+ inputs = deploymentInputs(config2);
8655
+ } catch {
8656
+ return { lines: [], missing: [] };
8657
+ }
8658
+ const lines = [];
8659
+ const missing = [];
8660
+ for (const input2 of inputs.filter((i) => i.required || i.generated || i.description)) {
8661
+ const given = Object.hasOwn(supplied, input2.key);
8662
+ const state = given && supplied[input2.key] ? "supplied" : given && !input2.generated ? input2.required ? "MISSING" : "empty" : saved2?.has(input2.key) ? "saved" : input2.generated ? "generated by Cloudler" : input2.required ? saved2 === void 0 ? "required" : "MISSING" : "optional";
8663
+ if (state === "MISSING") missing.push(input2.key);
8664
+ lines.push(` ${input2.key}: ${state}${input2.description ? ` \xB7 ${input2.description.replace(/\s+/g, " ")}` : ""}`);
8665
+ }
8666
+ return { lines, missing };
8667
+ }
8668
+
8159
8669
  // src/index.ts
8160
8670
  import { parseArgs } from "node:util";
8161
8671
  import { readFile as readFile4 } from "node:fs/promises";
@@ -8359,7 +8869,7 @@ __export(external_exports, {
8359
8869
  optional: () => optional,
8360
8870
  output: () => output,
8361
8871
  overwrite: () => _overwrite,
8362
- parse: () => parse2,
8872
+ parse: () => parse3,
8363
8873
  parseAsync: () => parseAsync2,
8364
8874
  partialRecord: () => partialRecord,
8365
8875
  pipe: () => pipe,
@@ -8711,7 +9221,7 @@ __export(core_exports2, {
8711
9221
  memoizer: () => memoizer,
8712
9222
  mergeValues: () => mergeValues,
8713
9223
  meta: () => meta,
8714
- parse: () => parse,
9224
+ parse: () => parse2,
8715
9225
  parseAsync: () => parseAsync,
8716
9226
  parseURLObject: () => parseURLObject,
8717
9227
  prettifyError: () => prettifyError,
@@ -8785,7 +9295,7 @@ __export(util_exports, {
8785
9295
  hexToUint8Array: () => hexToUint8Array,
8786
9296
  hide: () => hide,
8787
9297
  installLazyProp: () => installLazyProp,
8788
- isObject: () => isObject,
9298
+ isObject: () => isObject2,
8789
9299
  isPlainObject: () => isPlainObject,
8790
9300
  issue: () => issue,
8791
9301
  joinValues: () => joinValues,
@@ -9010,7 +9520,7 @@ function slugify(input2) {
9010
9520
  }
9011
9521
  var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {
9012
9522
  };
9013
- function isObject(data) {
9523
+ function isObject2(data) {
9014
9524
  return typeof data === "object" && data !== null && !Array.isArray(data);
9015
9525
  }
9016
9526
  var allowsEval = /* @__PURE__ */ cached(() => {
@@ -9029,7 +9539,7 @@ var allowsEval = /* @__PURE__ */ cached(() => {
9029
9539
  }
9030
9540
  });
9031
9541
  function isPlainObject(o) {
9032
- if (isObject(o) === false)
9542
+ if (isObject2(o) === false)
9033
9543
  return false;
9034
9544
  const ctor = o.constructor;
9035
9545
  if (ctor === void 0)
@@ -9037,7 +9547,7 @@ function isPlainObject(o) {
9037
9547
  if (typeof ctor !== "function")
9038
9548
  return true;
9039
9549
  const prot = ctor.prototype;
9040
- if (isObject(prot) === false)
9550
+ if (isObject2(prot) === false)
9041
9551
  return false;
9042
9552
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
9043
9553
  return false;
@@ -9931,7 +10441,7 @@ var _parse = (_Err) => {
9931
10441
  };
9932
10442
  return fn;
9933
10443
  };
9934
- var parse = /* @__PURE__ */ _parse($ZodRealError);
10444
+ var parse2 = /* @__PURE__ */ _parse($ZodRealError);
9935
10445
  var _parseAsync = (_Err) => {
9936
10446
  const fn = async (schema, value, _ctx, params) => {
9937
10447
  const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
@@ -11723,7 +12233,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
11723
12233
  }
11724
12234
  return propValues;
11725
12235
  });
11726
- const isObject4 = isObject;
12236
+ const isObject4 = isObject2;
11727
12237
  const catchall = def.catchall;
11728
12238
  let value;
11729
12239
  const memo2 = globalConfig.memoizer;
@@ -11867,7 +12377,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
11867
12377
  return doc.compile();
11868
12378
  };
11869
12379
  let fastpass;
11870
- const isObject4 = isObject;
12380
+ const isObject4 = isObject2;
11871
12381
  const jit = !globalConfig.jitless;
11872
12382
  const allowsEval2 = allowsEval;
11873
12383
  const fastEnabled = jit && allowsEval2.value;
@@ -12084,7 +12594,7 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
12084
12594
  const disc = cached(() => discriminatorMap(def));
12085
12595
  inst._zod.parse = (payload, ctx) => {
12086
12596
  const input2 = payload.value;
12087
- if (!isObject(input2)) {
12597
+ if (!isObject2(input2)) {
12088
12598
  payload.issues.push({
12089
12599
  code: "invalid_type",
12090
12600
  expected: "object",
@@ -13084,10 +13594,10 @@ var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
13084
13594
  throw new Error("implement() must be called with a function");
13085
13595
  }
13086
13596
  return Object.defineProperty(function(...args) {
13087
- const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;
13597
+ const parsedArgs = inst._def.input ? parse2(inst._def.input, args) : args;
13088
13598
  const result = Reflect.apply(func, this, parsedArgs);
13089
13599
  if (inst._def.output) {
13090
- return parse(inst._def.output, result);
13600
+ return parse2(inst._def.output, result);
13091
13601
  }
13092
13602
  return result;
13093
13603
  }, "_zod", { value: inst._zod, enumerable: false });
@@ -24366,8 +24876,8 @@ var contributors = {
24366
24876
  function aggregateChecks(schema) {
24367
24877
  const agg = {};
24368
24878
  const def = schema._zod.def;
24369
- const list3 = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
24370
- for (const ch of list3)
24879
+ const list2 = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
24880
+ for (const ch of list2)
24371
24881
  contributors[ch._zod.def.check]?.(agg, ch._zod.def);
24372
24882
  const bag = schema._zod.bag;
24373
24883
  if (bag.minimum !== void 0)
@@ -25394,7 +25904,7 @@ var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, void 0
25394
25904
  });
25395
25905
 
25396
25906
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/parse.js
25397
- var parse2 = /* @__PURE__ */ _parse(ZodRealError);
25907
+ var parse3 = /* @__PURE__ */ _parse(ZodRealError);
25398
25908
  var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
25399
25909
  var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
25400
25910
  var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
@@ -25531,7 +26041,7 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
25531
26041
  util_exports.own(this, "~standard", value);
25532
26042
  },
25533
26043
  parse: function _parse2(data, params) {
25534
- return parse2(this, data, params, { callee: _parse2 });
26044
+ return parse3(this, data, params, { callee: _parse2 });
25535
26045
  },
25536
26046
  parseAsync: async function _parseAsync2(data, params) {
25537
26047
  return await parseAsync2(this, data, params, { callee: _parseAsync2 });
@@ -27922,6 +28432,9 @@ var deploymentManifestSchema = external_exports.object({
27922
28432
  kind: external_exports.enum(["release", "preview"]),
27923
28433
  name: external_exports.string().min(1),
27924
28434
  version: external_exports.string().min(1),
28435
+ // Release channel an update check follows: "stable" for vX.Y.Z releases, "nightly" for
28436
+ // the rolling nightly prerelease. Absent on previews, prereleases and older bundles.
28437
+ channel: external_exports.enum(["stable", "nightly"]).optional(),
27925
28438
  createdAt: external_exports.iso.datetime(),
27926
28439
  source: external_exports.union([localSourceSchema, githubSourceSchema]),
27927
28440
  portler: external_exports.object({
@@ -27967,7 +28480,9 @@ var PROXY_PORT_MAX = 29999;
27967
28480
  var ipv43 = external_exports.string().trim().refine(isIPv4, "Expected an IPv4 address");
27968
28481
  var PORTLER_SERVICE_PORT_MIN = 51e3;
27969
28482
  var PORTLER_SERVICE_PORT_MAX = 59999;
27970
- var port = external_exports.number().int().min(1).max(65535).refine(
28483
+ var PORT_NUMBER = "Enter a whole number from 1 to 65535";
28484
+ var portNumber = (min = 1, minMessage = PORT_NUMBER) => external_exports.number({ error: PORT_NUMBER }).int(PORT_NUMBER).min(min, minMessage).max(65535, PORT_NUMBER);
28485
+ var port = portNumber().refine(
27971
28486
  (n) => n < PORTLER_SERVICE_PORT_MIN || n > PORTLER_SERVICE_PORT_MAX,
27972
28487
  `Ports ${PORTLER_SERVICE_PORT_MIN}-${PORTLER_SERVICE_PORT_MAX} are used by Portler for app services`
27973
28488
  );
@@ -27981,8 +28496,8 @@ var ranges = [
27981
28496
  { from: PORTLER_SERVICE_PORT_MIN, to: PORTLER_SERVICE_PORT_MAX, what: "Portler's app services" }
27982
28497
  ];
27983
28498
  var appPortsSchema = external_exports.object({
27984
- from: external_exports.number().int().min(1024, "App ports start at 1024 or higher").max(65535),
27985
- to: external_exports.number().int().min(1024).max(65535)
28499
+ from: portNumber(1024, "App ports start at 1024 or higher"),
28500
+ to: portNumber(1024, "App ports start at 1024 or higher")
27986
28501
  }).refine((r) => r.from <= r.to, { path: ["to"], message: "The last app port must not be below the first" }).refine((r) => r.to - r.from < APP_PORTS_MAX, {
27987
28502
  path: ["to"],
27988
28503
  message: `At most ${APP_PORTS_MAX} app ports`
@@ -28047,10 +28562,11 @@ var remoteSettingsSchema = external_exports.object({
28047
28562
  // frps cannot bind its control and HTTPS sockets to the same port.
28048
28563
  message: "The control port and HTTPS port must be different"
28049
28564
  });
28565
+ var gatewayName = external_exports.string().trim().min(1, "Give the gateway a name").max(100, "Use at most 100 characters for the name");
28050
28566
  var createGatewayRequestSchema = external_exports.discriminatedUnion("type", [
28051
28567
  external_exports.object({
28052
28568
  type: external_exports.literal("internal"),
28053
- name: external_exports.string().trim().min(1).max(100),
28569
+ name: gatewayName,
28054
28570
  computeId: external_exports.uuid(),
28055
28571
  settings: createInternalSettingsSchema.default({
28056
28572
  bindAddress: "127.0.0.1",
@@ -28059,19 +28575,19 @@ var createGatewayRequestSchema = external_exports.discriminatedUnion("type", [
28059
28575
  }),
28060
28576
  external_exports.object({
28061
28577
  type: external_exports.literal("ports"),
28062
- name: external_exports.string().trim().min(1).max(100),
28578
+ name: gatewayName,
28063
28579
  computeId: external_exports.uuid(),
28064
28580
  settings: portsSettingsSchema
28065
28581
  }),
28066
28582
  external_exports.object({
28067
28583
  type: external_exports.literal("cloudflare_tunnel"),
28068
- name: external_exports.string().trim().min(1).max(100),
28584
+ name: gatewayName,
28069
28585
  computeId: external_exports.uuid(),
28070
28586
  domainId: external_exports.uuid()
28071
28587
  }),
28072
28588
  external_exports.object({
28073
28589
  type: external_exports.literal("remote"),
28074
- name: external_exports.string().trim().min(1).max(100),
28590
+ name: gatewayName,
28075
28591
  computeId: external_exports.uuid(),
28076
28592
  settings: remoteSettingsSchema
28077
28593
  })
@@ -28088,10 +28604,10 @@ var exposureSchema = external_exports.object({
28088
28604
  port
28089
28605
  });
28090
28606
  var exposuresSchema = external_exports.array(exposureSchema).max(20).refine(
28091
- (list3) => new Set(list3.map((e) => `${e.protocol}/${e.port}`)).size === list3.length,
28607
+ (list2) => new Set(list2.map((e) => `${e.protocol}/${e.port}`)).size === list2.length,
28092
28608
  "Each public port and protocol can be used once"
28093
28609
  ).refine(
28094
- (list3) => new Set(list3.map((e) => `${e.service}/${e.protocol}`)).size === list3.length,
28610
+ (list2) => new Set(list2.map((e) => `${e.service}/${e.protocol}`)).size === list2.length,
28095
28611
  "Expose each service once per protocol"
28096
28612
  );
28097
28613
  var previewLimitSchema = external_exports.number().int().min(0).max(100).nullable();
@@ -28143,6 +28659,22 @@ function gatewayPublicUrl(type, settings, hostname3) {
28143
28659
  const httpsPort = type === "cloudflare_tunnel" ? 443 : settings.httpsPort ?? 443;
28144
28660
  return `https://${hostname3}${httpsPort === 443 ? "" : `:${httpsPort}`}`;
28145
28661
  }
28662
+ var DEFAULT_RELAY_PORT = 7100;
28663
+ var reachable = (a) => a !== "0.0.0.0" && a !== "localhost" && !a.endsWith(".localhost") && (/^[\d.]+$/.test(a) ? isIPv4(a) && !a.startsWith("127.") : true);
28664
+ var relaySettingsSchema = external_exports.object({
28665
+ /** An address of the gateway machine; the relay listens there. */
28666
+ address: ipv43.refine(reachable, "Use an address other machines can reach, not 0.0.0.0 or a loopback address"),
28667
+ port: port.default(DEFAULT_RELAY_PORT),
28668
+ /** Where app machines connect instead, when the relay is behind NAT or a port forward: an IP or DNS name. */
28669
+ publicAddress: hostnameSchema.refine(reachable, "Use an address other machines can reach, not 0.0.0.0 or a loopback address").nullable().optional(),
28670
+ publicPort: portNumber().nullable().optional()
28671
+ });
28672
+ var gatewaySharingRequestSchema = external_exports.object({
28673
+ computeIds: external_exports.array(external_exports.uuid()).max(50),
28674
+ relay: relaySettingsSchema.optional(),
28675
+ /** The list the caller started from; refused with 409 when it changed since. */
28676
+ previous: external_exports.array(external_exports.uuid()).max(50).optional()
28677
+ });
28146
28678
  var MAX_BUSY_PORTS = 2e3;
28147
28679
  var busyPortsSchema = external_exports.array(external_exports.object({ address: external_exports.string().max(45), port: external_exports.number().int().min(1).max(65535) })).max(MAX_BUSY_PORTS);
28148
28680
 
@@ -28155,14 +28687,17 @@ var publicUrlSchema = external_exports.string().max(2048).refine((value) => {
28155
28687
  return false;
28156
28688
  }
28157
28689
  }, "Expected an http(s) origin without path, credentials, query or fragment (no trailing slash)").transform((value) => new URL(value).origin);
28158
- var environmentSchema = external_exports.record(external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), external_exports.string().max(16384)).refine(
28690
+ var environmentValueSchema = external_exports.string().max(16384).refine((v) => !v.includes("\0") && v.isWellFormed(), "Environment values cannot contain NUL or broken Unicode");
28691
+ var environmentSchema = external_exports.record(external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), environmentValueSchema).refine(
28159
28692
  (v) => Object.keys(v).length <= 200 && JSON.stringify(v).length <= 131072,
28160
28693
  "Environment too large"
28161
28694
  );
28695
+ var environmentPatchSchema = external_exports.record(external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), environmentValueSchema.nullable()).refine((v) => Object.keys(v).length <= 200, "Environment too large");
28162
28696
  var deployRequestSchema = external_exports.object({
28163
28697
  manifest: deploymentManifestSchema,
28164
28698
  config: external_exports.string().min(1).max(262144),
28165
28699
  environment: environmentSchema.optional(),
28700
+ environmentPatch: environmentPatchSchema.optional(),
28166
28701
  confirmed: external_exports.literal(true)
28167
28702
  });
28168
28703
  var softwareKindSchema = external_exports.enum(["own", "self-hosted"]);
@@ -28197,6 +28732,11 @@ var createSoftwareFieldsSchema = deployRequestSchema.extend({
28197
28732
  });
28198
28733
  var createSoftwareRequestSchema = createSoftwareFieldsSchema.refine(...oneAddress);
28199
28734
  var softwareAddressSchema = external_exports.object({ ...addressFields, confirmed: external_exports.literal(true) }).refine(...oneAddress);
28735
+ var addSoftwareGatewaySchema = external_exports.object({ gatewayId: external_exports.uuid(), ...addressFields, exposures: exposuresSchema.default([]), confirmed: external_exports.literal(true) }).refine(...oneAddress);
28736
+ var softwareGatewayChangeSchema = external_exports.union([
28737
+ external_exports.object({ active: external_exports.boolean() }),
28738
+ external_exports.object({ primary: external_exports.literal(true), confirmed: external_exports.literal(true) })
28739
+ ]);
28200
28740
  var previewRequestSchema = deployRequestSchema.extend({
28201
28741
  name: previewNameSchema.optional(),
28202
28742
  computeId: external_exports.uuid().optional(),
@@ -28242,7 +28782,8 @@ var softwareTokenRequestSchema = external_exports.object({
28242
28782
 
28243
28783
  // ../../packages/schema/src/control-groups.ts
28244
28784
  var name = external_exports.string().trim().min(1).max(100);
28245
- var controlServerUrlSchema = external_exports.url({ protocol: /^https?$/ }).max(300).transform((value) => new URL(value).origin);
28785
+ var PLAIN_HOST = /^(?:[a-z0-9_-]+\.)*[a-z0-9_-]+\.?$|^\[[0-9a-f:.]+\]$/i;
28786
+ var controlServerUrlSchema = external_exports.url({ protocol: /^https?$/ }).max(300).refine((value) => URL.canParse(value) && PLAIN_HOST.test(new URL(value).hostname), "The host name may only contain letters, digits, dots, hyphens and underscores").transform((value) => new URL(value).origin);
28246
28787
  var createControlGroupRequestSchema = external_exports.object({
28247
28788
  name,
28248
28789
  // The group's first server.
@@ -28276,13 +28817,15 @@ var authModeSchema = external_exports.enum(["multi", "single"]);
28276
28817
  var computeAgentModeSchema = external_exports.enum(["host", "docker", "k8s"]);
28277
28818
  var computeStatusSchema = external_exports.enum(["pending", "online", "offline"]);
28278
28819
  var name3 = external_exports.string().trim().min(1).max(100);
28820
+ var jsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value ?? null)).length;
28279
28821
  var agentDetails = {
28280
28822
  version: external_exports.string().max(100).optional(),
28281
28823
  hostname: external_exports.string().max(255).optional(),
28282
28824
  platform: external_exports.string().max(100).optional(),
28283
28825
  arch: external_exports.string().max(100).optional(),
28284
- capabilities: external_exports.array(external_exports.string().max(100)).optional(),
28285
- systemInfo: external_exports.unknown().optional()
28826
+ capabilities: external_exports.array(external_exports.string().max(100)).max(50).optional(),
28827
+ // Stored and read with every agent request: the same bound as an uplink compute report.
28828
+ systemInfo: external_exports.unknown().refine((v) => jsonBytes(v) <= 16384, "systemInfo is too large").optional()
28286
28829
  };
28287
28830
  var updateComputeRequestSchema = external_exports.object({ name: name3 });
28288
28831
  var createEnrollmentTokenRequestSchema = external_exports.object({
@@ -28304,15 +28847,16 @@ var agentHeartbeatRequestSchema = external_exports.object({
28304
28847
  protocolVersion: external_exports.number().int().positive().optional(),
28305
28848
  ...agentDetails
28306
28849
  });
28307
- var session = { sessionId: external_exports.string() };
28850
+ var session = { sessionId: external_exports.string().max(100) };
28851
+ var terminalData = external_exports.string().max(1 << 20).default("");
28308
28852
  var agentMessageSchema = external_exports.discriminatedUnion("type", [
28309
28853
  external_exports.object({ type: external_exports.literal("terminal.started"), ...session }),
28310
- external_exports.object({ type: external_exports.literal("terminal.output"), ...session, data: external_exports.string().default("") }),
28854
+ external_exports.object({ type: external_exports.literal("terminal.output"), ...session, data: terminalData }),
28311
28855
  external_exports.object({ type: external_exports.literal("terminal.error"), ...session, error: external_exports.string().default("Unknown terminal error") }),
28312
28856
  external_exports.object({ type: external_exports.literal("terminal.exit"), ...session, code: external_exports.number().nullable().default(null) })
28313
28857
  ]);
28314
28858
  var terminalClientMessageSchema = external_exports.discriminatedUnion("type", [
28315
- external_exports.object({ type: external_exports.literal("terminal.input"), ...session, data: external_exports.string().default("") }),
28859
+ external_exports.object({ type: external_exports.literal("terminal.input"), ...session, data: terminalData }),
28316
28860
  external_exports.object({
28317
28861
  type: external_exports.literal("terminal.resize"),
28318
28862
  ...session,
@@ -28323,431 +28867,124 @@ var terminalClientMessageSchema = external_exports.discriminatedUnion("type", [
28323
28867
  ]);
28324
28868
 
28325
28869
  // ../../packages/schema/src/images.ts
28326
- var IMAGE_CACHE_NAMESPACE = "cloudler";
28327
- var IMAGE_PUSH_USERNAME = "cloudler-push";
28328
- var IMAGE_PUSH_TOKEN_PREFIX = "climg_";
28329
- var IMAGE_GRANT_TTL_MS = 60 * 6e4;
28330
- var IMAGE_PUSH_ID_HEADER = "cloudler-push-id";
28331
- var uuid3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
28332
- var servicePattern = /^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/;
28333
- var imageDigestPattern = /^sha256:[a-f0-9]{64}$/;
28334
- function isCacheServiceName(service) {
28335
- return service.length <= 128 && servicePattern.test(service);
28336
- }
28337
- function cacheRepository(rootId, service) {
28338
- if (!uuid3.test(rootId)) throw new Error("Invalid image cache namespace");
28339
- if (!isCacheServiceName(service))
28340
- throw new Error(`Service "${service}" cannot be an image name: use lowercase letters, digits and . _ -`);
28341
- return `${IMAGE_CACHE_NAMESPACE}/${rootId}/${service}`;
28342
- }
28343
- function parseCacheRepository(name4) {
28344
- const parts = name4.split("/");
28345
- if (parts.length !== 3 || parts[0] !== IMAGE_CACHE_NAMESPACE) return null;
28346
- const [, rootId, service] = parts;
28347
- return uuid3.test(rootId) && isCacheServiceName(service) ? { rootId, service } : null;
28348
- }
28349
- function parseCacheImage(repository) {
28350
- const slash = repository.indexOf("/");
28351
- if (slash < 0) return null;
28352
- const parsed = parseCacheRepository(repository.slice(slash + 1));
28353
- return parsed && { host: repository.slice(0, slash).toLowerCase(), ...parsed };
28354
- }
28355
- function imageRepository(image) {
28356
- const name4 = image.split("@")[0];
28357
- const tag = name4.indexOf(":", name4.lastIndexOf("/") + 1);
28358
- return tag < 0 ? name4 : name4.slice(0, tag);
28359
- }
28360
- function foreignCacheImage(images, rootId) {
28361
- for (const image of images) {
28362
- const cached2 = parseCacheImage(imageRepository(image).toLowerCase());
28363
- if (cached2 && cached2.rootId !== rootId) return image;
28364
- }
28365
- return null;
28366
- }
28367
- function cacheImageByTag(image) {
28368
- return !!parseCacheImage(imageRepository(image).toLowerCase()) && !/@sha256:[a-f0-9]{64}$/.test(image);
28369
- }
28370
- function platformForArch(arch2) {
28371
- if (arch2 === "x64" || arch2 === "amd64") return "linux/amd64";
28372
- if (arch2 === "arm64" || arch2 === "aarch64") return "linux/arm64";
28373
- return null;
28374
- }
28375
- var imageGrantRequestSchema = external_exports.object({
28376
- preview: previewNameSchema.optional(),
28377
- computeId: external_exports.uuid().optional(),
28378
- gatewayId: external_exports.uuid().optional(),
28379
- // `--platform`: a new preview goes to an allowed machine of this CPU.
28380
- platform: external_exports.enum(["linux/amd64", "linux/arm64"]).optional()
28381
- }).strict();
28382
- var imageReservationRequestSchema = external_exports.object({ computeId: external_exports.uuid(), rootId: external_exports.uuid().optional() });
28383
- var imageGrantSchema = external_exports.object({
28384
- /** Namespace (main software id). For a reservation, pass it as `id` when creating the software. */
28385
- rootId: external_exports.uuid(),
28386
- /** Registry host (host[:port]) used in image refs; hosts pull from it. */
28387
- registry: external_exports.string().min(1).max(260),
28388
- /** Origin the CLI uploads to (its /v2/ API). */
28389
- pushUrl: external_exports.url(),
28390
- username: external_exports.literal(IMAGE_PUSH_USERNAME),
28391
- token: external_exports.string().startsWith(IMAGE_PUSH_TOKEN_PREFIX),
28392
- expiresAt: external_exports.iso.datetime(),
28393
- /** Build for this platform: the target machine's CPU. Null when unknown. */
28394
- platform: external_exports.enum(["linux/amd64", "linux/arm64"]).nullable(),
28395
- /** The cache's size limit in bytes. */
28396
- maxBytes: external_exports.number().int().positive(),
28397
- /** A preview build's machine: deploy the preview there, so the image fits its CPU. */
28398
- computeId: external_exports.uuid().optional()
28399
- });
28400
- var imageCacheEntrySchema = external_exports.object({
28401
- service: external_exports.string(),
28402
- digest: external_exports.string().regex(imageDigestPattern),
28403
- /** Manifest plus every blob it references. Shared layers count in each image. */
28404
- bytes: external_exports.number().int().nonnegative(),
28405
- pushedAt: external_exports.iso.datetime(),
28406
- /** Releases of the app or its previews that pin this image. */
28407
- usedBy: external_exports.array(external_exports.object({ softwareId: external_exports.string(), releaseId: external_exports.string(), version: external_exports.string() })).default([])
28408
- });
28409
- var imageCacheUsageSchema = external_exports.object({
28410
- /** Bytes on disk for this namespace; shared layers count once. */
28411
- bytes: external_exports.number().int().nonnegative(),
28412
- /** The whole cache on this control server. */
28413
- totalBytes: external_exports.number().int().nonnegative(),
28414
- maxBytes: external_exports.number().int().positive(),
28415
- images: external_exports.array(imageCacheEntrySchema),
28416
- /** Registry host the images are pulled from. */
28417
- registry: external_exports.string()
28418
- });
28419
- function formatBytes(n) {
28420
- if (n < 1024) return `${n} B`;
28421
- const units = ["KB", "MB", "GB", "TB"];
28422
- let value = n / 1024, i = 0;
28423
- while (value >= 1024 && i < units.length - 1) {
28424
- value /= 1024;
28425
- i++;
28426
- }
28427
- return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[i]}`;
28428
- }
28429
-
28430
- // src/build.ts
28431
- import { spawn } from "node:child_process";
28432
- import { createHash as createHash2, randomUUID } from "node:crypto";
28433
- import { createReadStream, createWriteStream } from "node:fs";
28434
- import { mkdtemp, readFile, realpath, rm, stat, open as open2 } from "node:fs/promises";
28435
- import { tmpdir, arch } from "node:os";
28436
- import { basename, dirname, relative, resolve, join } from "node:path";
28437
- import { pipeline } from "node:stream/promises";
28438
- import { createGzip } from "node:zlib";
28439
-
28440
- // ../../packages/schema/src/docker-config.ts
28441
- var import_yaml = __toESM(require_dist(), 1);
28442
- import { createHash } from "node:crypto";
28443
-
28444
- // ../../packages/schema/src/portler-syntax.ts
28445
- function isObject2(v) {
28446
- return Boolean(v) && typeof v === "object" && !Array.isArray(v);
28447
- }
28448
- var OLD_POSTGRES = {
28449
- volumes: ["@${self.name}-data:/var/lib/postgresql/data"]
28450
- };
28451
- var BUILT_IN_PRESETS = {
28452
- postgres: {
28453
- image: "postgres:${version}-alpine",
28454
- port: 5432,
28455
- volumes: ["@${self.name}-data:/var/lib/postgresql"],
28456
- versions: {
28457
- "18": {},
28458
- "17": OLD_POSTGRES,
28459
- "16": OLD_POSTGRES,
28460
- "15": OLD_POSTGRES,
28461
- "14": OLD_POSTGRES
28462
- },
28463
- env: {
28464
- POSTGRES_USER: { default: "postgres" },
28465
- POSTGRES_PASSWORD: { default: "postgres", secret: true },
28466
- POSTGRES_DB: { default: "app" }
28467
- },
28468
- healthcheck: { type: "tcp", timeout_ms: 12e4 },
28469
- exports: {
28470
- database_url: "postgres://${env.POSTGRES_USER}:${env.POSTGRES_PASSWORD}@${self.address}/${env.POSTGRES_DB}"
28471
- }
28472
- },
28473
- mysql: {
28474
- image: "mysql:${version}",
28475
- port: 3306,
28476
- volumes: ["@${self.name}-data:/var/lib/mysql"],
28477
- versions: { "9.7": {}, "8.4": {}, "8.0": {} },
28478
- env: {
28479
- MYSQL_ROOT_PASSWORD: { default: "mysql", secret: true },
28480
- MYSQL_DATABASE: { default: "app" },
28481
- MYSQL_USER: { default: "app" },
28482
- MYSQL_PASSWORD: { default: "app", secret: true }
28483
- },
28484
- healthcheck: { type: "tcp", timeout_ms: 18e4 },
28485
- exports: {
28486
- database_url: "mysql://${env.MYSQL_USER}:${env.MYSQL_PASSWORD}@${self.address}/${env.MYSQL_DATABASE}"
28487
- }
28488
- },
28489
- redis: {
28490
- image: "redis:${version}-alpine",
28491
- port: 6379,
28492
- volumes: ["@${self.name}-data:/data"],
28493
- versions: { "8": {}, "7": {} },
28494
- healthcheck: { type: "tcp" },
28495
- exports: { redis_url: "redis://${self.address}" }
28496
- }
28497
- };
28498
- var ENTRY_KEYS = ["value", "default", "required", "secret", "description"];
28499
- function scalar(v) {
28500
- return v === null || ["string", "number", "boolean"].includes(typeof v);
28501
- }
28502
- function text(v) {
28503
- return v === null ? "" : String(v);
28504
- }
28505
- function readEntry(key, raw) {
28506
- if (scalar(raw)) return { value: text(raw) };
28507
- if (!isObject2(raw)) throw new Error("Invalid environment entry");
28508
- const invalid = (why) => new Error(`Invalid environment entry ${key}: ${why}`);
28509
- for (const k of Object.keys(raw))
28510
- if (!ENTRY_KEYS.includes(k))
28511
- throw invalid(`unknown key "${k}"; allowed keys: ${ENTRY_KEYS.join(", ")}`);
28512
- if (raw.value !== void 0 && raw.default !== void 0)
28513
- throw invalid("it cannot set both value and default");
28514
- for (const k of ["value", "default"])
28515
- if (raw[k] !== void 0 && !scalar(raw[k]))
28516
- throw invalid(`${k} must be a string, number or boolean`);
28517
- const required5 = raw.required ?? void 0;
28518
- if (required5 !== void 0 && typeof required5 !== "boolean" && required5 !== "prod")
28519
- throw invalid('required must be true, false or "prod"');
28520
- const secret2 = raw.secret ?? void 0;
28521
- if (secret2 !== void 0 && typeof secret2 !== "boolean")
28522
- throw invalid("secret must be true or false");
28523
- if ((raw.description ?? void 0) !== void 0 && typeof raw.description !== "string")
28524
- throw invalid("description must be a string");
28525
- return {
28526
- ...raw.value !== void 0 ? { value: text(raw.value) } : {},
28527
- ...raw.default !== void 0 ? { value: text(raw.default), isDefault: true } : {},
28528
- ...required5 === void 0 ? {} : { required: required5 },
28529
- ...secret2 === void 0 ? {} : { secret: secret2 }
28530
- };
28870
+ var IMAGE_CACHE_NAMESPACE = "cloudler";
28871
+ var IMAGE_PUSH_USERNAME = "cloudler-push";
28872
+ var IMAGE_PUSH_TOKEN_PREFIX = "climg_";
28873
+ var IMAGE_GRANT_TTL_MS = 60 * 6e4;
28874
+ var IMAGE_PUSH_ID_HEADER = "cloudler-push-id";
28875
+ var uuid3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
28876
+ var servicePattern = /^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/;
28877
+ var imageDigestPattern = /^sha256:[a-f0-9]{64}$/;
28878
+ function isCacheServiceName(service) {
28879
+ return service.length <= 128 && servicePattern.test(service);
28531
28880
  }
28532
- function readEnvLayer(v, label = "env") {
28533
- if (v === void 0 || v === null) return {};
28534
- if (!isObject2(v)) throw new Error(`${label} must be a mapping`);
28535
- const layer = /* @__PURE__ */ Object.create(null);
28536
- for (const [key, raw] of Object.entries(v)) {
28537
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
28538
- throw new Error("Invalid environment entry");
28539
- layer[key] = readEntry(key, raw);
28540
- }
28541
- return layer;
28881
+ function cacheRepository(rootId, service) {
28882
+ if (!uuid3.test(rootId)) throw new Error("Invalid image cache namespace");
28883
+ if (!isCacheServiceName(service))
28884
+ throw new Error(`Service "${service}" cannot be an image name: use lowercase letters, digits and . _ -`);
28885
+ return `${IMAGE_CACHE_NAMESPACE}/${rootId}/${service}`;
28542
28886
  }
28543
- function mergeEnvLayers(...layers) {
28544
- const merged = /* @__PURE__ */ Object.create(null);
28545
- for (const layer of layers)
28546
- for (const [key, upper] of Object.entries(layer)) {
28547
- const lower = merged[key] ?? {};
28548
- const required5 = upper.required ?? lower.required;
28549
- const secret2 = upper.secret ?? lower.secret;
28550
- const source = upper.value !== void 0 ? upper : lower;
28551
- merged[key] = {
28552
- ...source.value === void 0 ? {} : { value: source.value },
28553
- ...source.isDefault ? { isDefault: true } : {},
28554
- ...source.presetDefault ? { presetDefault: true } : {},
28555
- ...required5 === void 0 ? {} : { required: required5 },
28556
- ...secret2 === void 0 ? {} : { secret: secret2 }
28557
- };
28558
- }
28559
- return merged;
28887
+ function parseCacheRepository(name4) {
28888
+ const parts = name4.split("/");
28889
+ if (parts.length !== 3 || parts[0] !== IMAGE_CACHE_NAMESPACE) return null;
28890
+ const [, rootId, service] = parts;
28891
+ return uuid3.test(rootId) && isCacheServiceName(service) ? { rootId, service } : null;
28560
28892
  }
28561
- function requiredEnvKeys(entries) {
28562
- return Object.entries(entries).filter(
28563
- ([, e]) => e.required === "prod" || e.secret === true && e.isDefault === true
28564
- ).map(([key]) => key);
28893
+ function parseCacheImage(repository) {
28894
+ const slash = repository.indexOf("/");
28895
+ if (slash < 0) return null;
28896
+ const parsed = parseCacheRepository(repository.slice(slash + 1));
28897
+ return parsed && { host: repository.slice(0, slash).toLowerCase(), ...parsed };
28565
28898
  }
28566
- function fillPlaceholders(v, values) {
28567
- if (typeof v === "string")
28568
- return Object.entries(values).reduce(
28569
- (s, [name4, value]) => s.replaceAll(`\${${name4}}`, () => value),
28570
- v
28571
- );
28572
- if (Array.isArray(v)) return v.map((x) => fillPlaceholders(x, values));
28573
- if (isObject2(v))
28574
- return Object.fromEntries(
28575
- Object.entries(v).map(([k, x]) => [k, fillPlaceholders(x, values)])
28576
- );
28577
- return v;
28899
+ function imageRepository(image) {
28900
+ const name4 = image.split("@")[0];
28901
+ const tag = name4.indexOf(":", name4.lastIndexOf("/") + 1);
28902
+ return tag < 0 ? name4 : name4.slice(0, tag);
28578
28903
  }
28579
- var BUILT_IN_PROPERTIES = /* @__PURE__ */ new Set([
28580
- "url",
28581
- "local_url",
28582
- "localUrl",
28583
- "port",
28584
- "host",
28585
- "url_host",
28586
- "urlHost",
28587
- "protocol",
28588
- "desired_port",
28589
- "desiredPort",
28590
- "container",
28591
- "container_name",
28592
- "containerName",
28593
- "image",
28594
- "name",
28595
- "address",
28596
- "address_host",
28597
- "address_port"
28598
- ]);
28599
- function readExports(v, name4) {
28600
- if (v === void 0 || v === null) return {};
28601
- const field = `services.${name4}.exports`;
28602
- if (!isObject2(v)) throw new Error(`${field} must be a mapping of name: template`);
28603
- const out = /* @__PURE__ */ Object.create(null);
28604
- for (const [key, template] of Object.entries(v)) {
28605
- if (!/^[a-z][a-z0-9_]*$/.test(key))
28606
- throw new Error(`${field}.${key}: export names use lowercase letters, digits and "_", starting with a letter`);
28607
- if (BUILT_IN_PROPERTIES.has(key))
28608
- throw new Error(`${field}.${key} would hide the built-in "${key}" property; pick another name`);
28609
- if (typeof template !== "string" && typeof template !== "number")
28610
- throw new Error(`${field}.${key} must be a string template`);
28611
- out[key] = String(template);
28904
+ function foreignCacheImage(images, rootId) {
28905
+ for (const image of images) {
28906
+ const cached2 = parseCacheImage(imageRepository(image).toLowerCase());
28907
+ if (cached2 && cached2.rootId !== rootId) return image;
28612
28908
  }
28613
- return out;
28614
- }
28615
- function applyPreset(raw, name4) {
28616
- const { use, ...own2 } = raw;
28617
- if (use === void 0 || use === null)
28618
- return { service: own2, env: {}, exports: readExports(raw.exports, name4) };
28619
- const field = `services.${name4}.use`;
28620
- if (typeof use !== "string" || !use.trim())
28621
- throw new Error(`${field} must be a preset name`);
28622
- const known = Object.keys(BUILT_IN_PRESETS);
28623
- if (use.includes("/") || /\.ya?ml(@|$)/.test(use))
28624
- throw new Error(
28625
- `${field}: Cloudler only receives portler.yml, so it cannot read preset files. Use a built-in preset (${known.join(", ")}), or write the keys on the service.`
28626
- );
28627
- const at = use.lastIndexOf("@");
28628
- const target = at > 0 ? use.slice(0, at) : use;
28629
- const version3 = at > 0 ? use.slice(at + 1) : void 0;
28630
- if (!Object.hasOwn(BUILT_IN_PRESETS, target))
28631
- throw new Error(`${field}: there is no built-in preset "${target}". Built-in presets: ${known.join(", ")}.`);
28632
- const { versions, ...keys } = BUILT_IN_PRESETS[target];
28633
- const listed = Object.keys(versions).sort((a, b) => b.localeCompare(a, void 0, { numeric: true }));
28634
- if (version3 === void 0)
28635
- throw new Error(
28636
- `${field}: preset "${target}" needs a version, for example "${target}@${listed[0]}". Versions: ${listed.join(", ")}. Cloudler does not pick one, because a data volume may not open with a different version.`
28637
- );
28638
- if (!Object.hasOwn(versions, version3))
28639
- throw new Error(`${field}: preset "${target}" has no version "${version3}". Versions: ${listed.join(", ")}.`);
28640
- const preset = fillPlaceholders(
28641
- { ...keys, ...versions[version3] },
28642
- { version: version3, "self.name": name4 }
28643
- );
28644
- const { env, exports: presetExports, ...presetKeys } = preset;
28645
- if (own2.exports !== void 0 && own2.exports !== null && !isObject2(own2.exports))
28646
- throw new Error(`services.${name4}.exports must be a mapping of name: template`);
28647
- const presetEnv = readEnvLayer(env, `preset ${use} env`);
28648
- for (const entry of Object.values(presetEnv))
28649
- if (entry.secret !== true) entry.presetDefault = true;
28650
- return {
28651
- service: { ...presetKeys, ...own2 },
28652
- env: presetEnv,
28653
- exports: readExports({ ...presetExports, ...own2.exports }, name4)
28654
- };
28909
+ return null;
28655
28910
  }
28656
- function ownHealthcheck(health, name4) {
28657
- if (!isObject2(health) || typeof health.url !== "string") return health;
28658
- return { ...health, url: health.url.replaceAll("${self.", `\${${name4}.`) };
28911
+ function cacheImageByTag(image) {
28912
+ return !!parseCacheImage(imageRepository(image).toLowerCase()) && !/@sha256:[a-f0-9]{64}$/.test(image);
28659
28913
  }
28660
- var REFERENCE = /\$\{([A-Za-z0-9_-]+)\.([A-Za-z0-9_]+)\}/g;
28661
- var BARE_REFERENCE = /^([A-Za-z0-9_-]+)\.([A-Za-z0-9_]+)$/;
28662
- var ADDRESS_PROPERTIES = /* @__PURE__ */ new Set(["address", "address_host", "address_port"]);
28663
- var LOCAL_URL = /* @__PURE__ */ new Set(["local_url", "localUrl"]);
28664
- function expandOne(service, property, scope) {
28665
- const { owner, targets, exportOf } = scope;
28666
- if (service === "env" && exportOf !== void 0 && !targets.env) {
28667
- const exporter = exportOf.split(".", 1)[0];
28668
- const values = targets[exporter].env;
28669
- if (!Object.hasOwn(values, property))
28670
- throw new Error(`Export ${exportOf} reads env.${property}, but service ${exporter} has no env value for ${property}`);
28671
- const value = values[property];
28672
- if (!scope.isLiteral(property))
28673
- return expandReferences(value, { ...scope, owner: exporter, exportOf: void 0, noExports: true });
28674
- if (value.includes("${"))
28675
- throw new Error(
28676
- `Export ${exportOf} reads env.${property}, and its deployment value contains "\${", which the generated config cannot keep as text. Supply a value without "\${".`
28677
- );
28678
- return value;
28679
- }
28680
- if (LOCAL_URL.has(property))
28681
- throw new Error(`Service ${owner}: a value reads ${property}, which only Portler 0.5 knows. In production it is the same as url; use url.`);
28682
- const name4 = service === "self" && !targets.self ? owner : service;
28683
- const target = targets[name4];
28684
- if (target) {
28685
- if (property === "name") return name4;
28686
- if (ADDRESS_PROPERTIES.has(property) && target.port !== void 0) {
28687
- if (property === "address_host") return name4;
28688
- if (property === "address_port") return String(target.port);
28689
- return `${name4}:${target.port}`;
28690
- }
28691
- if (Object.hasOwn(target.exports, property)) {
28692
- const exportName = `${name4}.${property}`;
28693
- if (exportOf !== void 0)
28694
- throw new Error(`Export ${exportOf} cannot use another export (${exportName})`);
28695
- if (scope.noExports)
28696
- throw new Error(`An export cannot read an env value that uses an export (${exportName})`);
28697
- scope.onExport?.();
28698
- return expandReferences(target.exports[property], { ...scope, owner: name4, exportOf: exportName });
28699
- }
28700
- }
28701
- return `\${${name4}.${property}}`;
28914
+ function platformForArch(arch2) {
28915
+ if (arch2 === "x64" || arch2 === "amd64") return "linux/amd64";
28916
+ if (arch2 === "arm64" || arch2 === "aarch64") return "linux/arm64";
28917
+ return null;
28702
28918
  }
28703
- function expandReferences(value, scope) {
28704
- const bare = BARE_REFERENCE.exec(value);
28705
- if (bare) {
28706
- const [, service, property] = bare;
28707
- const { targets, owner, exportOf } = scope;
28708
- const self = service === "self" && !targets.self;
28709
- const env = service === "env" && exportOf !== void 0 && !targets.env;
28710
- const target = targets[self ? owner : service];
28711
- if (self || env || LOCAL_URL.has(property) || // An export (or the env it reads) can embed a bare built-in reference in other text;
28712
- // keep its syntax for the downstream resolver (`prefix-${env.P}` with P: db.port).
28713
- (scope.exportOf !== void 0 || scope.noExports) && readsAsReference(value, targets) || target && (property === "name" || ADDRESS_PROPERTIES.has(property) || Object.hasOwn(target.exports, property)))
28714
- return expandOne(service, property, scope);
28715
- return value;
28919
+ var imageGrantRequestSchema = external_exports.object({
28920
+ preview: previewNameSchema.optional(),
28921
+ computeId: external_exports.uuid().optional(),
28922
+ gatewayId: external_exports.uuid().optional(),
28923
+ // `--platform`: a new preview goes to an allowed machine of this CPU.
28924
+ platform: external_exports.enum(["linux/amd64", "linux/arm64"]).optional()
28925
+ }).strict();
28926
+ var imageReservationRequestSchema = external_exports.object({ computeId: external_exports.uuid(), rootId: external_exports.uuid().optional() });
28927
+ var imageGrantSchema = external_exports.object({
28928
+ /** Namespace (main software id). For a reservation, pass it as `id` when creating the software. */
28929
+ rootId: external_exports.uuid(),
28930
+ /** Registry host (host[:port]) used in image refs; hosts pull from it. */
28931
+ registry: external_exports.string().min(1).max(260),
28932
+ /** Origin the CLI uploads to (its /v2/ API). */
28933
+ pushUrl: external_exports.url(),
28934
+ username: external_exports.literal(IMAGE_PUSH_USERNAME),
28935
+ token: external_exports.string().startsWith(IMAGE_PUSH_TOKEN_PREFIX),
28936
+ expiresAt: external_exports.iso.datetime(),
28937
+ /** Build for this platform: the target machine's CPU. Null when unknown. */
28938
+ platform: external_exports.enum(["linux/amd64", "linux/arm64"]).nullable(),
28939
+ /** The cache's size limit in bytes. */
28940
+ maxBytes: external_exports.number().int().positive(),
28941
+ /** A preview build's machine: deploy the preview there, so the image fits its CPU. */
28942
+ computeId: external_exports.uuid().optional()
28943
+ });
28944
+ var imageCacheEntrySchema = external_exports.object({
28945
+ service: external_exports.string(),
28946
+ digest: external_exports.string().regex(imageDigestPattern),
28947
+ /** Manifest plus every blob it references. Shared layers count in each image. */
28948
+ bytes: external_exports.number().int().nonnegative(),
28949
+ pushedAt: external_exports.iso.datetime(),
28950
+ /** Releases of the app or its previews that pin this image. */
28951
+ usedBy: external_exports.array(external_exports.object({ softwareId: external_exports.string(), releaseId: external_exports.string(), version: external_exports.string() })).default([])
28952
+ });
28953
+ var imageCacheUsageSchema = external_exports.object({
28954
+ /** Bytes on disk for this namespace; shared layers count once. */
28955
+ bytes: external_exports.number().int().nonnegative(),
28956
+ /** The whole cache on this control server. */
28957
+ totalBytes: external_exports.number().int().nonnegative(),
28958
+ maxBytes: external_exports.number().int().positive(),
28959
+ images: external_exports.array(imageCacheEntrySchema),
28960
+ /** Registry host the images are pulled from. */
28961
+ registry: external_exports.string()
28962
+ });
28963
+ function formatBytes(n) {
28964
+ if (n < 1024) return `${n} B`;
28965
+ const units = ["KB", "MB", "GB", "TB"];
28966
+ let value = n / 1024, i = 0;
28967
+ while (value >= 1024 && i < units.length - 1) {
28968
+ value /= 1024;
28969
+ i++;
28716
28970
  }
28717
- return value.replace(
28718
- REFERENCE,
28719
- (_whole, service, property) => expandOne(service, property, scope)
28720
- );
28721
- }
28722
- function readsAsReference(value, services) {
28723
- const bare = BARE_REFERENCE.exec(value);
28724
- if (!bare || bare[1] === "env") return false;
28725
- const [, service, property] = bare;
28726
- return service === "self" || service === "proxy" || BUILT_IN_PROPERTIES.has(property) || Object.hasOwn(services, service) && services[service].port !== void 0;
28727
- }
28728
- function referenceDiagnosticSecrets(value, targets) {
28729
- const bare = BARE_REFERENCE.exec(value);
28730
- if (bare && !readsAsReference(value, targets)) return [];
28731
- const references = bare ? [bare] : [...value.matchAll(REFERENCE)];
28732
- return references.flatMap(([, service, property]) => {
28733
- const unknownService = service !== "proxy" && !Object.hasOwn(targets, service);
28734
- const unknownProperty = !BUILT_IN_PROPERTIES.has(property) && !Object.hasOwn(targets[service]?.exports ?? {}, property);
28735
- if (!unknownService && !unknownProperty) return [];
28736
- return [
28737
- `${service}.${property}`,
28738
- ...unknownService ? [service] : [],
28739
- ...unknownProperty ? [property] : []
28740
- ];
28741
- });
28742
- }
28743
- function isReferencesOnly(written, targets, owner) {
28744
- const isPublic = (service, property) => BUILT_IN_PROPERTIES.has(property) && (service === "proxy" || Boolean(targets[service === "self" && !targets.self ? owner : service]));
28745
- const bare = BARE_REFERENCE.exec(written);
28746
- if (bare) return isPublic(bare[1], bare[2]);
28747
- const references = [...written.matchAll(REFERENCE)];
28748
- return references.length > 0 && written.replace(REFERENCE, "") === "" && references.every((m) => isPublic(m[1], m[2]));
28971
+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[i]}`;
28749
28972
  }
28750
28973
 
28974
+ // src/build.ts
28975
+ import { spawn } from "node:child_process";
28976
+ import { createHash as createHash2, randomUUID } from "node:crypto";
28977
+ import { createReadStream, createWriteStream } from "node:fs";
28978
+ import { mkdtemp, readFile, realpath, rm, stat, open as open2 } from "node:fs/promises";
28979
+ import { tmpdir, arch } from "node:os";
28980
+ import { basename, dirname, relative, resolve, join } from "node:path";
28981
+ import { pipeline } from "node:stream/promises";
28982
+ import { createGzip } from "node:zlib";
28983
+
28984
+ // ../../packages/schema/src/docker-config.ts
28985
+ var import_yaml2 = __toESM(require_dist(), 1);
28986
+ import { createHash } from "node:crypto";
28987
+
28751
28988
  // ../../packages/schema/src/portler.ts
28752
28989
  var PORTLER_MIN_VERSION = "0.3.2";
28753
28990
  var PORTLER_MAX_MINOR = "0.5";
@@ -28773,13 +29010,6 @@ function object2(v, label) {
28773
29010
  throw new Error(`${label} must be a mapping`);
28774
29011
  return v;
28775
29012
  }
28776
- function list(v) {
28777
- if (v === void 0) return [];
28778
- const a = typeof v === "string" ? [v] : v;
28779
- if (!Array.isArray(a) || a.some((x) => typeof x !== "string"))
28780
- throw new Error("Expected a list of strings");
28781
- return a;
28782
- }
28783
29013
  function isHostControlKey(key) {
28784
29014
  return (
28785
29015
  // __proto__: Portler drops this key without a word, on 0.3.2 and 0.4.
@@ -28789,19 +29019,10 @@ function isHostControlKey(key) {
28789
29019
  );
28790
29020
  }
28791
29021
  function productionServices(config2) {
28792
- let document;
28793
- try {
28794
- document = (0, import_yaml.parse)(config2, {
28795
- maxAliasCount: 0,
28796
- customTags: (tags) => tags.filter((t) => typeof t === "string" || !["HEX", "OCT"].includes(t.format ?? ""))
28797
- });
28798
- } catch {
28799
- throw new Error("Portler configuration is not valid YAML. Check syntax and indentation.");
28800
- }
28801
- const root = object2(document, "config");
29022
+ const root = object2(parsePortlerYaml(config2), "config");
28802
29023
  const all = object2(root.services, "services");
28803
29024
  const prod = root.prod === void 0 ? {} : object2(root.prod, "prod");
28804
- const selected = prod.services === void 0 ? Object.keys(all) : list(prod.services);
29025
+ const selected = prod.services === void 0 ? Object.keys(all) : stringList(prod.services);
28805
29026
  if (!selected.length || new Set(selected).size !== selected.length)
28806
29027
  throw new Error("Select at least one unique service");
28807
29028
  return {
@@ -28829,6 +29050,8 @@ function compileDockerConfig(input2, options = {}) {
28829
29050
  exposuresSchema.parse(ingress.exposures);
28830
29051
  if (!Number.isInteger(ingress.proxyPort) || ingress.proxyPort < 1024 || ingress.proxyPort > 65535)
28831
29052
  throw new Error("Invalid loopback proxy port");
29053
+ for (const alias of ingress.aliases ?? [])
29054
+ if (!/^[a-z0-9.-]{1,253}$/.test(alias)) throw new Error("Invalid gateway host name");
28832
29055
  }
28833
29056
  environmentSchema.parse(input2.environment);
28834
29057
  if (Object.keys(input2.environment).some(isHostControlKey))
@@ -28837,25 +29060,12 @@ function compileDockerConfig(input2, options = {}) {
28837
29060
  throw new Error("Invalid software identity");
28838
29061
  if (input2.manifest.portler.minVersion && newerMinor(input2.manifest.portler.minVersion))
28839
29062
  throw new Error(`Manifest requires newer Portler than supported ${PORTLER_MAX_MINOR}.x`);
28840
- let document;
28841
- try {
28842
- document = (0, import_yaml.parse)(input2.config, {
28843
- maxAliasCount: 0,
28844
- customTags: (tags) => tags.filter((t) => typeof t === "string" || !["HEX", "OCT"].includes(t.format ?? ""))
28845
- });
28846
- } catch {
28847
- throw new Error(
28848
- "Portler configuration is not valid YAML. Check syntax and indentation."
28849
- );
28850
- }
28851
- const root = object2(document, "config");
29063
+ const root = object2(parsePortlerYaml(input2.config), "config");
28852
29064
  const all = object2(root.services, "services");
28853
29065
  const prod = root.prod === void 0 ? {} : object2(root.prod, "prod");
28854
- const selected = prod.services === void 0 ? Object.keys(all) : list(prod.services);
29066
+ const selected = prod.services === void 0 ? Object.keys(all) : stringList(prod.services);
28855
29067
  if (!selected.length || new Set(selected).size !== selected.length)
28856
29068
  throw new Error("Select at least one unique service");
28857
- const prodEnv = readEnvLayer(prod.env);
28858
- const rootEnv = mergeEnvLayers(readEnvLayer(root.env), prodEnv);
28859
29069
  const services = /* @__PURE__ */ Object.create(null);
28860
29070
  const images = [];
28861
29071
  const containerNames = /* @__PURE__ */ new Set();
@@ -28874,9 +29084,7 @@ function compileDockerConfig(input2, options = {}) {
28874
29084
  const preset = applyPreset(object2(all[name4], `services.${name4}`), name4);
28875
29085
  const s = preset.service;
28876
29086
  const sp = s.prod === void 0 ? {} : object2(s.prod, "service prod");
28877
- let d = {};
28878
- if (s.docker !== void 0)
28879
- d = typeof s.docker === "string" ? { image: s.docker } : s.docker === true ? {} : object2(s.docker, "docker");
29087
+ const d = dockerOverride(s);
28880
29088
  if (s.port !== void 0 && (typeof s.port !== "number" || !Number.isInteger(s.port) || s.port < 1 || s.port > 65535))
28881
29089
  throw new Error(`Service ${name4}: invalid container port`);
28882
29090
  if (s.transport !== void 0 && !TRANSPORTS.includes(s.transport))
@@ -28887,13 +29095,15 @@ function compileDockerConfig(input2, options = {}) {
28887
29095
  const pin = input2.manifest.images[name4];
28888
29096
  const build = d.build ?? d.dockerfile ?? s.build ?? s.dockerfile;
28889
29097
  const image = pin?.ref ?? d.image ?? s.image;
28890
- if (!image || typeof image !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._/:@-]+$/.test(image))
29098
+ if (!image || typeof image !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._/:@-]+$/.test(image) || // `..` would leave the repository's own path in registry requests; tags and digests never
29099
+ // start with a dot either.
29100
+ /(?:^|[/:@])\./.test(image))
28891
29101
  throw new Error(`Service ${name4} needs a Docker image or manifest pin`);
28892
29102
  if (build && !pin)
28893
29103
  throw new Error(
28894
29104
  `Service ${name4} needs a manifest image pin; host builds are forbidden`
28895
29105
  );
28896
- const volumes = list(d.volumes ?? s.volumes);
29106
+ const volumes = stringList(d.volumes ?? s.volumes);
28897
29107
  for (const mount of volumes) {
28898
29108
  if (!/^@[a-zA-Z0-9][a-zA-Z0-9_.-]*:\/(?!.*(?:\.\.|docker\.sock))[^:\s]+(?::(?:ro|rw))?$/.test(
28899
29109
  mount
@@ -28908,24 +29118,8 @@ function compileDockerConfig(input2, options = {}) {
28908
29118
  throw new Error("Volume names collide after Docker normalization");
28909
29119
  volumeNames.set(normalized, raw);
28910
29120
  }
28911
- const serviceProdEnv = readEnvLayer(sp.env);
28912
- const se = mergeEnvLayers(
28913
- preset.env,
28914
- readEnvLayer(s.env ?? s.environment),
28915
- readEnvLayer(d.env ?? d.environment),
28916
- serviceProdEnv
28917
- );
28918
- const entries = mergeEnvLayers(rootEnv, se);
29121
+ const { entries, requirements } = serviceEnvDeclarations(root, prod, preset.env, s, sp);
28919
29122
  nonEmpty.set(name4, Object.keys(entries).filter((key) => entries[key].required === true));
28920
- const requirements = /* @__PURE__ */ new Set([
28921
- ...list(prod.require),
28922
- ...list(sp.require),
28923
- ...requiredEnvKeys(entries)
28924
- ]);
28925
- for (const [k, v] of Object.entries(prodEnv))
28926
- if (v.value === "" && !se[k]?.value) requirements.add(k);
28927
- for (const [k, v] of Object.entries(serviceProdEnv))
28928
- if (v.value === "") requirements.add(k);
28929
29123
  for (const key of requirements)
28930
29124
  if (!options.environmentUnknown && (!Object.hasOwn(input2.environment, key) || !input2.environment[key]))
28931
29125
  throw new Error(`Service ${name4} requires ${key} in production`);
@@ -28941,7 +29135,7 @@ function compileDockerConfig(input2, options = {}) {
28941
29135
  else if (entry.value !== void 0) effective[key] = entry.value;
28942
29136
  for (const key of requirements) effective[key] = options.environmentUnknown ? "set" : input2.environment[key];
28943
29137
  for (const [key, entry] of Object.entries(entries))
28944
- if (entry.secret === true) explicitSecrets.add(`${name4}/${key}`);
29138
+ if (isSecretEntry(entry)) explicitSecrets.add(`${name4}/${key}`);
28945
29139
  for (const [key, entry] of Object.entries(entries))
28946
29140
  if (entry.presetDefault && !Object.hasOwn(input2.environment, key))
28947
29141
  publicValues.add(`${name4}/${key}`);
@@ -28970,6 +29164,9 @@ function compileDockerConfig(input2, options = {}) {
28970
29164
  const containerCommand = d.command !== void 0 ? d.command : s.docker !== void 0 && !s.image && !s.build ? void 0 : sp.command ?? s.command;
28971
29165
  if (containerCommand !== void 0 && typeof containerCommand !== "string")
28972
29166
  throw new Error(`Service ${name4}: container command must be a string`);
29167
+ for (const key of stringList(s.port_env ?? s.portEnv))
29168
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || isHostControlKey(key))
29169
+ throw new Error(`Service ${name4}: port_env must name a plain environment variable that is not a reserved host runtime control`);
28973
29170
  services[name4] = {
28974
29171
  image,
28975
29172
  volumes,
@@ -28994,7 +29191,7 @@ function compileDockerConfig(input2, options = {}) {
28994
29191
  exports: preset.exports
28995
29192
  };
28996
29193
  if (s.port !== void 0)
28997
- for (const key of list(s.port_env ?? s.portEnv))
29194
+ for (const key of stringList(s.port_env ?? s.portEnv))
28998
29195
  targets[name4].env[key] = String(s.port);
28999
29196
  }
29000
29197
  const isLiteral = (key) => options.environmentUnknown || Object.hasOwn(input2.environment, key);
@@ -29003,13 +29200,14 @@ function compileDockerConfig(input2, options = {}) {
29003
29200
  if (isLiteral(key)) continue;
29004
29201
  if (isReferencesOnly(written, targets, name4))
29005
29202
  publicValues.add(`${name4}/${key}`);
29006
- const expanded = expandReferences(written, {
29203
+ const expanded = expandWithPublicProxy(written, {
29007
29204
  owner: name4,
29008
29205
  targets,
29009
29206
  isLiteral,
29010
29207
  // An export can carry a password even into HOST or a number, so the reading
29011
29208
  // key's name does not make it public.
29012
- onExport: () => explicitSecrets.add(`${name4}/${key}`)
29209
+ onExport: () => explicitSecrets.add(`${name4}/${key}`),
29210
+ publicUrl: input2.publicUrl
29013
29211
  });
29014
29212
  if (expanded !== written && readsAsReference(expanded, targets))
29015
29213
  throw new Error(
@@ -29019,7 +29217,7 @@ function compileDockerConfig(input2, options = {}) {
29019
29217
  }
29020
29218
  for (const [name4, keys] of nonEmpty) {
29021
29219
  const service = services[name4];
29022
- const injected = service.port === void 0 ? [] : list(service.port_env);
29220
+ const injected = service.port === void 0 ? [] : stringList(service.port_env);
29023
29221
  for (const key of keys)
29024
29222
  if (!injected.includes(key) && !service.env[key])
29025
29223
  throw new Error(`Service ${name4} requires ${key} in production`);
@@ -29060,13 +29258,13 @@ function compileDockerConfig(input2, options = {}) {
29060
29258
  host: "127.0.0.1",
29061
29259
  port: port2,
29062
29260
  routes,
29063
- allowed_hosts: [hostname3],
29261
+ allowed_hosts: [.../* @__PURE__ */ new Set([hostname3, ...ingress.aliases ?? []])],
29064
29262
  trusted_proxies: ["127.0.0.1"]
29065
29263
  } : { port: port2, routes, allowed_hosts: [hostname3] }
29066
29264
  };
29067
29265
  return {
29068
29266
  // Portler's YAML reader rejects plain strings folded over lines, which `yaml` writes past 80 columns.
29069
- config: (0, import_yaml.stringify)(generated, { lineWidth: 0 }),
29267
+ config: (0, import_yaml2.stringify)(generated, { lineWidth: 0 }),
29070
29268
  images: [...new Set(images)],
29071
29269
  port: port2,
29072
29270
  proxyHost: generated.host,
@@ -29075,7 +29273,10 @@ function compileDockerConfig(input2, options = {}) {
29075
29273
  // mode/bind keys are exempt: masking "production", "0.0.0.0" or "3000" garbles diagnostics.
29076
29274
  secretValues: Object.entries(services).flatMap(
29077
29275
  ([name4, service]) => Object.entries(service.env).filter(
29078
- ([key, value]) => explicitSecrets.has(`${name4}/${key}`) || !publicValues.has(`${name4}/${key}`) && !PUBLIC_CONFIG_ENV.has(key) && (SECRET_KEY.test(key) || !PUBLIC_SCALAR.test(value))
29276
+ ([key, value]) => (
29277
+ // The agent's own log lines name the public address.
29278
+ !(!isLiteral(key) && [url2.origin, url2.hostname, url2.protocol.slice(0, -1)].includes(value)) && (explicitSecrets.has(`${name4}/${key}`) || !publicValues.has(`${name4}/${key}`) && !PUBLIC_CONFIG_ENV.has(key) && (SECRET_KEY.test(key) || !PUBLIC_SCALAR.test(value)))
29279
+ )
29079
29280
  ).flatMap(([key, value]) => [
29080
29281
  value,
29081
29282
  // Deployment values are literal, never diagnosed as references. Other fragments are masked
@@ -29121,7 +29322,7 @@ function imageJson(bytes) {
29121
29322
  }
29122
29323
  }
29123
29324
  var imageDigest = (bytes) => `sha256:${sha256(bytes)}`;
29124
- function mapping(value, label) {
29325
+ function mapping2(value, label) {
29125
29326
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be a mapping`);
29126
29327
  return value;
29127
29328
  }
@@ -29134,12 +29335,12 @@ function discoverBuilds(config2, projectDir) {
29134
29335
  const raw = docker.build;
29135
29336
  if (!raw) continue;
29136
29337
  if (!isCacheServiceName(name4)) throw new Error(`Service "${name4}" cannot be an image cache name; use lowercase letters, digits and . _ -`);
29137
- const build = typeof raw === "string" ? { context: raw } : mapping(raw, `Service ${name4}: docker.build`);
29338
+ const build = typeof raw === "string" ? { context: raw } : mapping2(raw, `Service ${name4}: docker.build`);
29138
29339
  const context = build.context ?? ".";
29139
29340
  if (typeof context !== "string" || !context || build.dockerfile !== void 0 && typeof build.dockerfile !== "string" || build.target !== void 0 && typeof build.target !== "string")
29140
29341
  throw new Error(`Service ${name4}: invalid Docker build context, dockerfile or target`);
29141
29342
  const args = /* @__PURE__ */ Object.create(null);
29142
- for (const [key, value] of Object.entries(build.args === void 0 ? {} : mapping(build.args, `Service ${name4}: build args`))) {
29343
+ for (const [key, value] of Object.entries(build.args === void 0 ? {} : mapping2(build.args, `Service ${name4}: build args`))) {
29143
29344
  if (!["string", "number", "boolean"].includes(typeof value)) throw new Error(`Service ${name4}: build args must be scalar values`);
29144
29345
  if (String(value).includes("${")) throw new Error(`Service ${name4}: build arg ${key} contains an unresolved reference; local builds cannot resolve \${...} without a running app`);
29145
29346
  args[key] = String(value);
@@ -29341,11 +29542,12 @@ async function localManifest(input2) {
29341
29542
  const directory = dirname(configPath);
29342
29543
  let root, commit, ref;
29343
29544
  let dirty = true;
29545
+ const git = (...args) => command("git", ["-c", "safe.bareRepository=explicit", "-c", "core.fsmonitor=false", ...args], { cwd: directory });
29344
29546
  try {
29345
- root = await command("git", ["rev-parse", "--show-toplevel"], { cwd: directory });
29346
- commit = await command("git", ["rev-parse", "HEAD"], { cwd: directory });
29347
- ref = await command("git", ["branch", "--show-current"], { cwd: directory }) || void 0;
29348
- dirty = !!await command("git", ["status", "--porcelain", "--untracked-files=normal"], { cwd: directory });
29547
+ root = await git("rev-parse", "--show-toplevel");
29548
+ commit = await git("rev-parse", "HEAD");
29549
+ ref = await git("branch", "--show-current") || void 0;
29550
+ dirty = !!await git("status", "--porcelain", "--untracked-files=normal");
29349
29551
  } catch {
29350
29552
  }
29351
29553
  return deploymentManifestSchema.parse({ schemaVersion: 1, kind: input2.preview ? "preview" : "release", name: input2.name || basename(directory), version: input2.version, createdAt: (input2.now ?? /* @__PURE__ */ new Date()).toISOString(), source: { kind: "local", ...commit ? { commit } : {}, ...ref ? { ref } : {}, dirty }, portler: { path: root ? relative(root, configPath) : basename(configPath), config: input2.config, sha256: sha256(input2.config) }, images: input2.images });
@@ -29377,7 +29579,7 @@ function checkConfig(config2, configPath, builds, preview, check2) {
29377
29579
  const manifest = deploymentManifestSchema.parse({ schemaVersion: 1, kind: preview ? "preview" : "release", name: productionServices(config2).name || basename(dirname(configPath)), version: "check", createdAt: (/* @__PURE__ */ new Date()).toISOString(), source: { kind: "local", dirty: true }, portler: { path: basename(configPath), config: config2, sha256: sha256(config2) }, images });
29378
29580
  const hostname3 = check2.hostname ?? "app.invalid";
29379
29581
  try {
29380
- const compiled = compileDockerConfig({ softwareId: placeholder, publicUrl: `https://${hostname3}`, ingress: { hostname: hostname3, proxyPort: 2e4, exposures: check2.exposures ?? [] }, manifest, config: config2, environment: check2.environment ?? {} }, { environmentUnknown: check2.environment === void 0 });
29582
+ const compiled = compileDockerConfig({ softwareId: placeholder, publicUrl: `https://${hostname3}`, ingress: { hostname: hostname3, proxyPort: 2e4, exposures: check2.exposures ?? [] }, manifest, config: config2, environment: withGeneratedPlaceholders(config2, check2.environment ?? {}) }, { environmentUnknown: check2.environment === void 0 });
29381
29583
  assertServiceNamesAllowed(compiled.services);
29382
29584
  } catch (error62) {
29383
29585
  throw new Error(`Cloudler would refuse this portler.yml: ${error62.message}`);
@@ -29396,6 +29598,8 @@ async function buildRelease(input2) {
29396
29598
  const getGrant = async () => {
29397
29599
  const parsed = imageGrantSchema.safeParse(await input2.grant());
29398
29600
  if (!parsed.success) throw new Error("Invalid image cache grant (values redacted)");
29601
+ if (new URL(parsed.data.pushUrl).protocol !== "https:" && !input2.insecure)
29602
+ throw new Error("The image cache upload URL uses plain HTTP; pass --allow-insecure to send the push login over it (local/private testing only)");
29399
29603
  return parsed.data;
29400
29604
  };
29401
29605
  let grant = await getGrant();
@@ -29440,9 +29644,9 @@ async function buildRelease(input2) {
29440
29644
  }
29441
29645
 
29442
29646
  // ../../packages/schema/src/docker-review.ts
29443
- var import_yaml2 = __toESM(require_dist(), 1);
29647
+ var import_yaml3 = __toESM(require_dist(), 1);
29444
29648
  function reviewDockerImages(config2, manifest) {
29445
- const root = (0, import_yaml2.parse)(config2, { maxAliasCount: 0 });
29649
+ const root = (0, import_yaml3.parse)(config2, { maxAliasCount: 0 });
29446
29650
  const services = root?.services;
29447
29651
  if (!services || typeof services !== "object" || Array.isArray(services))
29448
29652
  throw new Error("Portler configuration needs a services mapping.");
@@ -31675,6 +31879,48 @@ async function retainRequest(id3, metadata) {
31675
31879
  }
31676
31880
  }
31677
31881
 
31882
+ // package.json
31883
+ var package_default = {
31884
+ name: "cloudler",
31885
+ version: "0.0.3",
31886
+ description: "Command line for Cloudler: deploy and manage apps on your own machines",
31887
+ license: "MIT",
31888
+ keywords: [
31889
+ "cloudler",
31890
+ "deploy",
31891
+ "self-hosted",
31892
+ "cli"
31893
+ ],
31894
+ homepage: "https://github.com/YJJosh/Cloudler#readme",
31895
+ repository: {
31896
+ type: "git",
31897
+ url: "git+https://github.com/YJJosh/Cloudler.git",
31898
+ directory: "apps/cli"
31899
+ },
31900
+ bugs: "https://github.com/YJJosh/Cloudler/issues",
31901
+ type: "module",
31902
+ engines: {
31903
+ node: ">=24"
31904
+ },
31905
+ bin: {
31906
+ cloudler: "dist/cloudler.js"
31907
+ },
31908
+ files: [
31909
+ "dist"
31910
+ ],
31911
+ scripts: {
31912
+ build: "node scripts/build.ts",
31913
+ typecheck: "tsc --noEmit",
31914
+ prepack: "pnpm build"
31915
+ },
31916
+ devDependencies: {
31917
+ "@cloudler/schema": "workspace:*",
31918
+ "@types/node": "^24.19.0",
31919
+ esbuild: "0.28.2",
31920
+ "tough-cookie": "^6.0.1"
31921
+ }
31922
+ };
31923
+
31678
31924
  // src/client.ts
31679
31925
  function origin(value, insecure = false) {
31680
31926
  if (!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(value))
@@ -31701,11 +31947,27 @@ async function reason(response) {
31701
31947
  try {
31702
31948
  const body = await response.json();
31703
31949
  const text4 = typeof body?.error === "string" ? body.error : body?.message;
31704
- return typeof text4 === "string" && text4 ? ` (${text4.replace(/[\x00-\x1f\x7f-\x9f]/g, "?").slice(0, 300)})` : "";
31950
+ return {
31951
+ text: typeof text4 === "string" && text4 ? ` (${text4.replace(/[\x00-\x1f\x7f-\x9f]/g, "?").slice(0, 300)})` : "",
31952
+ unknownRoute: response.status === 404 && body?.code === "not-found" && body.error === void 0
31953
+ };
31705
31954
  } catch {
31706
- return "";
31955
+ return { text: "", unknownRoute: false };
31707
31956
  }
31708
31957
  }
31958
+ var OLDER_SERVER = `the server does not have this API. It may be older than this CLI (cloudler ${package_default.version}): update the server, or use the CLI release that matches it`;
31959
+ var ApiUnavailableError = class extends Error {
31960
+ constructor() {
31961
+ super("API unavailable or request timed out (outcome may be unknown)");
31962
+ }
31963
+ };
31964
+ var ApiHttpError = class extends Error {
31965
+ status;
31966
+ constructor(message, status2) {
31967
+ super(message);
31968
+ this.status = status2;
31969
+ }
31970
+ };
31709
31971
  var Client = class _Client {
31710
31972
  jar;
31711
31973
  server;
@@ -31779,21 +32041,20 @@ var Client = class _Client {
31779
32041
  if (key) headers["idempotency-key"] = key;
31780
32042
  if (this.org && this.token === void 0) headers[ORG_HEADER] = this.org;
31781
32043
  let response;
32044
+ const requestSignal = AbortSignal.any([
32045
+ AbortSignal.timeout(3e4),
32046
+ ...signal ? [signal] : []
32047
+ ]);
31782
32048
  try {
31783
32049
  response = await fetch(url2, {
31784
32050
  method,
31785
32051
  headers,
31786
32052
  body: body === void 0 ? void 0 : JSON.stringify(body),
31787
32053
  redirect: "manual",
31788
- signal: AbortSignal.any([
31789
- AbortSignal.timeout(3e4),
31790
- ...signal ? [signal] : []
31791
- ])
32054
+ signal: requestSignal
31792
32055
  });
31793
32056
  } catch {
31794
- throw new Error(
31795
- "API unavailable or request timed out (outcome may be unknown)"
31796
- );
32057
+ throw new ApiUnavailableError();
31797
32058
  }
31798
32059
  if (response.status >= 300 && response.status < 400)
31799
32060
  throw new Error(
@@ -31804,15 +32065,19 @@ var Client = class _Client {
31804
32065
  await this.jar.setCookie(cookie, url2);
31805
32066
  if (this.saved) await this.persist();
31806
32067
  }
31807
- const deployment = method === "POST" && /^\/api\/software\/(?:[^/]+\/(?:deploy|previews))?$/.test(path);
31808
- if (!response.ok)
31809
- throw new Error(
31810
- `API HTTP ${response.status}${await reason(response)}${response.status === 404 && this.org && /^\/api\/(?!orgs|invites)/.test(path) ? " (in the chosen organization; see cloudler orgs)" : ""}${response.status === 401 ? ": authenticate again; CI tokens never fall back to cookies" : response.status === 409 && deployment ? ": conflict; inspect status, do not blindly submit another deployment" : ""}`
32068
+ if (!response.ok) {
32069
+ const { text: text4, unknownRoute } = await reason(response);
32070
+ if (unknownRoute) throw new ApiHttpError(`API HTTP 404: ${OLDER_SERVER}`, 404);
32071
+ const reusedKey = response.status === 409 && key !== void 0 && text4.includes("Idempotency key");
32072
+ throw new ApiHttpError(
32073
+ `API HTTP ${response.status}${text4}${response.status === 404 && this.org && /^\/api\/(?!orgs|invites)/.test(path) ? " (in the chosen organization; see cloudler orgs)" : ""}${response.status === 401 ? ": authenticate again; CI tokens never fall back to cookies" : reusedKey ? ": inspect status, do not blindly submit another deployment" : ""}`,
32074
+ response.status
31811
32075
  );
32076
+ }
31812
32077
  try {
31813
32078
  return await response.json();
31814
32079
  } catch {
31815
- throw new Error("Invalid API response");
32080
+ throw requestSignal.aborted ? new ApiUnavailableError() : new Error("Invalid API response");
31816
32081
  }
31817
32082
  }
31818
32083
  async logout() {
@@ -31826,10 +32091,10 @@ var Client = class _Client {
31826
32091
 
31827
32092
  // src/prompt.ts
31828
32093
  import { createInterface } from "node:readline/promises";
31829
- async function prompt(label, hidden = false) {
32094
+ async function prompt(label, hidden = false, flag) {
31830
32095
  if (!process.stdin.isTTY || !process.stderr.isTTY)
31831
32096
  throw new Error(
31832
- "Interactive terminal required; use --yes for consent or explicit --password-stdin for account setup (not CI)"
32097
+ label.includes("[y/N]") ? "No terminal to confirm in; add --yes" : `No terminal to ask for "${label.replace(/[:\s]+$/, "")}" in; ${flag ? `use ${flag}` : "pass it with a flag (see --help)"}`
31833
32098
  );
31834
32099
  if (!hidden) {
31835
32100
  const rl = createInterface({
@@ -31902,8 +32167,8 @@ var ControlEndpoints = class {
31902
32167
  // bootstrap order (including explicit --servers) does not authenticate a URL.
31903
32168
  accepted;
31904
32169
  reachable;
31905
- constructor(urls, accepted, reachable = (url2) => url2) {
31906
- this.reachable = reachable;
32170
+ constructor(urls, accepted, reachable2 = (url2) => url2) {
32171
+ this.reachable = reachable2;
31907
32172
  this.urls = this.origins(urls);
31908
32173
  this.active = this.urls[0];
31909
32174
  this.accepted = accepted ? this.origins([accepted])[0] : void 0;
@@ -32029,6 +32294,24 @@ var restoreRequestSchema = external_exports.object({ snapshotId: external_export
32029
32294
  var copyRequestSchema = external_exports.object({ snapshotId: external_exports.uuid(), confirmed: external_exports.literal(true) });
32030
32295
  var backupRequestSchema = external_exports.object({ confirmed: external_exports.literal(true), note: external_exports.string().trim().max(200).optional() });
32031
32296
 
32297
+ // ../../packages/schema/src/scaling.ts
32298
+ var MAX_REPLICAS = 20;
32299
+ var DEFAULT_CPU_TARGET_MILLIS = 500;
32300
+ var replicas = external_exports.number().int().min(1).max(MAX_REPLICAS);
32301
+ var serviceScalingSchema = external_exports.discriminatedUnion("mode", [
32302
+ external_exports.object({ mode: external_exports.literal("fixed"), replicas }),
32303
+ external_exports.object({
32304
+ mode: external_exports.literal("auto"),
32305
+ min: replicas,
32306
+ max: replicas,
32307
+ cpuTargetMillis: external_exports.number().int().min(50).max(64e3).default(DEFAULT_CPU_TARGET_MILLIS)
32308
+ }).refine((s) => s.min <= s.max, { message: "Min containers must not be more than max containers", path: ["max"] })
32309
+ ]);
32310
+ var softwareScalingSchema = external_exports.record(external_exports.string().regex(/^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$/), serviceScalingSchema).refine(
32311
+ (s) => Object.keys(s).length <= 100,
32312
+ "Too many services"
32313
+ );
32314
+
32032
32315
  // ../../packages/schema/src/uplink.ts
32033
32316
  var ACCESS_TOKEN_PROTOCOL_PREFIX = "cloudler.access-token.";
32034
32317
  var epochSchema = external_exports.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine((v) => /^(0|[1-9][0-9]{0,18})$/.test(v) && BigInt(v) <= 9223372036854775806n, "Epoch exhausted");
@@ -32045,7 +32328,7 @@ var presenceSchema = external_exports.object({
32045
32328
  var id = external_exports.uuid();
32046
32329
  var time3 = external_exports.iso.datetime({ offset: true });
32047
32330
  var text2 = (max) => external_exports.string().max(max);
32048
- var jobActionSchema = external_exports.enum(["deploy", "redeploy", "rollback", "stop", "restart", "backup", "restore"]);
32331
+ var jobActionSchema = external_exports.enum(["deploy", "redeploy", "rollback", "stop", "restart", "backup", "restore", "scale"]);
32049
32332
  var jobStatusSchema = external_exports.enum(["queued", "running", "succeeded", "failed", "cancelled"]);
32050
32333
  var softwareStatusSchema = external_exports.enum(["pending", "running", "stopped", "failed"]);
32051
32334
  var uplinkJobSchema = external_exports.object({
@@ -32083,7 +32366,7 @@ var uplinkComputeSchema = external_exports.object({
32083
32366
  version: text2(100).nullable(),
32084
32367
  capabilities: external_exports.array(text2(100)).max(50),
32085
32368
  // Bounded: the server is not trusted, and Cloudler stores this as is.
32086
- systemInfo: external_exports.unknown().refine((v) => JSON.stringify(v ?? null).length <= 16384, "systemInfo is too large"),
32369
+ systemInfo: external_exports.unknown().refine((v) => jsonBytes(v) <= 16384, "systemInfo is too large"),
32087
32370
  edgeError: text2(4e3).nullable(),
32088
32371
  edgeBusyPorts: busyPortsSchema,
32089
32372
  // Optional: older control servers do not send it.
@@ -32171,12 +32454,17 @@ var softwareSnapshotSchema = external_exports.object({
32171
32454
  // Port mode. A server that drops it would run the app as a direct endpoint.
32172
32455
  publicPort: external_exports.number().int().nullable(),
32173
32456
  exposures: external_exports.array(exposureSchema),
32457
+ // Hosts of the app's other gateways. Older Cloudler versions do not send it.
32458
+ extraHosts: external_exports.array(external_exports.string().max(253)).max(100).default([]),
32459
+ extraExposures: external_exports.array(exposureSchema).max(400).default([]),
32174
32460
  parentSoftwareId: external_exports.string().nullable(),
32175
32461
  previewName: external_exports.string().nullable(),
32176
32462
  removeAfterStop: external_exports.boolean(),
32177
32463
  // So the server refuses its own release changes of an app that requires a snapshot. Optional:
32178
32464
  // older Cloudler versions do not send it.
32179
- dataMode: dataSnapshotModeSchema.optional()
32465
+ dataMode: dataSnapshotModeSchema.optional(),
32466
+ // Kubernetes replica settings; older Cloudler versions do not send them, which keeps the saved ones.
32467
+ scaling: softwareScalingSchema.optional()
32180
32468
  });
32181
32469
  var releaseSnapshotSchema = external_exports.object({
32182
32470
  id,
@@ -32203,6 +32491,9 @@ var uplinkRequestParams = {
32203
32491
  // The server's current state of these jobs; ones it does not have are left out.
32204
32492
  "jobs.state": external_exports.object({ jobIds: external_exports.array(id).max(500) }),
32205
32493
  "software.sync": external_exports.object({ software: softwareSnapshotSchema }),
32494
+ // The latest live Kubernetes state of an app its agent reported, from the server's memory. Answer: K8sStateReply.
32495
+ // Also marks the app as watched there, so the agent keeps reporting it. Only with UPLINK_FEATURES.k8sScaling.
32496
+ "k8s.state": external_exports.object({ softwareId: id }),
32206
32497
  "software.remove": external_exports.object({ softwareId: id }),
32207
32498
  "compute.remove": external_exports.object({ computeId: id }),
32208
32499
  "edge.set": external_exports.object({ computeId: id, hash: external_exports.string(), state: external_exports.unknown() }),
@@ -32248,6 +32539,29 @@ var uplinkDownSchema = external_exports.discriminatedUnion("type", [
32248
32539
  external_exports.object({ type: external_exports.literal("terminal.close"), sessionId: external_exports.string(), reason: external_exports.string() })
32249
32540
  ]);
32250
32541
 
32542
+ // src/suggest.ts
32543
+ function closest(input2, names) {
32544
+ let best, score = Infinity;
32545
+ for (const name4 of names) {
32546
+ const d = distance(input2, name4);
32547
+ if (d < score) [best, score] = [name4, d];
32548
+ }
32549
+ return best && score <= Math.max(2, Math.floor(best.length / 3)) ? best : void 0;
32550
+ }
32551
+ function distance(a, b) {
32552
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
32553
+ for (let i = 1; i <= a.length; i++) {
32554
+ let prev = row[0];
32555
+ row[0] = i;
32556
+ for (let j = 1; j <= b.length; j++) {
32557
+ const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
32558
+ prev = row[j];
32559
+ row[j] = next;
32560
+ }
32561
+ }
32562
+ return row[b.length];
32563
+ }
32564
+
32251
32565
  // src/format.ts
32252
32566
  function inert(value) {
32253
32567
  return String(value ?? "").replace(/[\x00-\x1f\x7f-\x9f]/g, "?");
@@ -32334,7 +32648,7 @@ function terminalSession(ws) {
32334
32648
  }
32335
32649
 
32336
32650
  // src/control.ts
32337
- var controlHelp = `cloudler control login https://control-server [https://backup ...] [--token TOKEN] (asks for the token if left out)
32651
+ var controlHelp = `cloudler control login https://control-server [https://backup ...] [--token-stdin] (asks for the token if left out)
32338
32652
  cloudler control logout
32339
32653
  cloudler control status
32340
32654
  cloudler control logs --software ID|name [--job UUID]
@@ -32348,6 +32662,14 @@ Works while Cloudler is down. Use --server URL to pick a saved control server.`;
32348
32662
  var FILE = "control.json";
32349
32663
  var TERMINAL = ["succeeded", "failed", "cancelled"];
32350
32664
  var ACTIONS = { stop: "stop", start: "redeploy", rollback: "rollback" };
32665
+ async function readToken() {
32666
+ let token = "";
32667
+ for await (const chunk of process.stdin) {
32668
+ token += chunk;
32669
+ if (token.length > 4096) throw new Error("Token input is too large");
32670
+ }
32671
+ return token.trim();
32672
+ }
32351
32673
  function inert2(text4) {
32352
32674
  return text4.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "?");
32353
32675
  }
@@ -32385,6 +32707,7 @@ var ControlClient = class _ControlClient {
32385
32707
  }
32386
32708
  async request(path, method = "GET", body) {
32387
32709
  const count = this.endpoints.urls.length;
32710
+ let unauthorized;
32388
32711
  for (let attempt = 0; attempt < count; attempt++) {
32389
32712
  const ticket = this.endpoints.ticket();
32390
32713
  let refusal = false;
@@ -32403,7 +32726,8 @@ var ControlClient = class _ControlClient {
32403
32726
  if (!response.ok || foreign) {
32404
32727
  if (refusal) this.endpoints.failed(ticket, foreign ? void 0 : data?.primaryUrl);
32405
32728
  if (foreign) throw Object.assign(new Error(`Control server ${ticket.url} belongs to another group`), { status: method === "GET" ? 421 : 503 });
32406
- throw Object.assign(new Error(`Control server HTTP ${response.status}${data?.error ? ` (${inert2(String(data.error)).slice(0, 300)})` : ""}`), { status: response.status });
32729
+ const primary = refusal && typeof data?.primaryUrl === "string" && !this.endpoints.urls.includes(data.primaryUrl) ? `. It names ${inert2(data.primaryUrl).slice(0, 200)} as the primary; add that address to cloudler control login` : "";
32730
+ throw Object.assign(new Error(`Control server HTTP ${response.status}${data?.error ? ` (${inert2(String(data.error)).slice(0, 300)})` : response.status === 404 && data?.code === "not-found" ? `: ${OLDER_SERVER}` : ""}${primary}`), { status: response.status });
32407
32731
  }
32408
32732
  if (this.endpoints.succeeded(ticket)) {
32409
32733
  if (data?.server?.groupId) {
@@ -32426,10 +32750,11 @@ var ControlClient = class _ControlClient {
32426
32750
  } catch (error62) {
32427
32751
  const code = error62.status;
32428
32752
  if (code && code < 500 && code !== 421 && !(code === 401 && method === "GET")) throw error62;
32753
+ if (code === 401) unauthorized ??= error62;
32429
32754
  this.endpoints.failed(ticket);
32430
32755
  if (attempt + 1 === count || method !== "GET" && !refusal) {
32431
32756
  if (method !== "GET" && !refusal) throw new Error(`Action response is uncertain; inspect cloudler control status/logs before retrying. ${error62.message}`);
32432
- throw error62;
32757
+ throw unauthorized ?? error62;
32433
32758
  }
32434
32759
  }
32435
32760
  }
@@ -32439,7 +32764,10 @@ var ControlClient = class _ControlClient {
32439
32764
  async software(ref) {
32440
32765
  const status2 = await this.request("/api/direct/status");
32441
32766
  const matches = status2.software.filter((p) => p.id === ref || p.name === ref);
32442
- if (matches.length !== 1) throw new Error(matches.length ? `Several apps are called ${ref}; use the id` : `No software ${ref} on this control server`);
32767
+ if (matches.length !== 1) {
32768
+ const close = closest(ref, status2.software.map((p) => p.name));
32769
+ throw new Error(matches.length ? `Several apps are called ${ref}; use the id` : `No software ${ref} on this control server${close ? `. Did you mean ${close}?` : ""}`);
32770
+ }
32443
32771
  return matches[0];
32444
32772
  }
32445
32773
  async compute(ref) {
@@ -32460,10 +32788,22 @@ function required2(value, flag) {
32460
32788
  }
32461
32789
  async function waitFor(client, softwareId, jobId, timeoutSeconds2) {
32462
32790
  const deadline = Date.now() + timeoutSeconds2 * 1e3;
32791
+ let status2 = "unknown";
32792
+ let unanswered;
32463
32793
  for (; ; ) {
32464
- const { job } = await client.request(`/api/direct/software/${softwareId}/jobs/${jobId}`);
32465
- if (TERMINAL.includes(job.status)) return job;
32466
- if (Date.now() > deadline) throw new Error(`Job ${jobId} still ${job.status} after ${timeoutSeconds2} s`);
32794
+ try {
32795
+ const { job } = await client.request(`/api/direct/software/${softwareId}/jobs/${jobId}`);
32796
+ if (TERMINAL.includes(job.status)) return job;
32797
+ status2 = job.status;
32798
+ unanswered = void 0;
32799
+ } catch (e) {
32800
+ const code = e.status;
32801
+ if (code !== void 0 && code < 500) throw e;
32802
+ if (!unanswered) console.error(`${e.message}; asking again until the --timeout.`);
32803
+ unanswered = e.message;
32804
+ }
32805
+ if (Date.now() > deadline)
32806
+ throw new Error(`Job ${jobId} still ${status2} after ${timeoutSeconds2} s${unanswered ? `; the last read failed: ${unanswered}` : ""}`);
32467
32807
  await new Promise((resolve2) => setTimeout(resolve2, 2e3));
32468
32808
  }
32469
32809
  }
@@ -32475,9 +32815,14 @@ async function control(args, o, print) {
32475
32815
  }
32476
32816
  if (sub === "login") {
32477
32817
  const server = origin(required2(args[2] ?? o.server, "control server URL"), !!o["allow-insecure"]);
32478
- if (!o.token && (!process.stdin.isTTY || !process.stderr.isTTY))
32479
- throw new Error("No terminal to ask for the token in; pass it with --token");
32480
- const token = o.token ?? await prompt("CLI access token: ", true);
32818
+ let token;
32819
+ if (o["token-stdin"]) token = await readToken();
32820
+ else if (o.token) {
32821
+ console.error("Warning: --token leaves the token in shell history and the process list; use --token-stdin.");
32822
+ token = o.token;
32823
+ } else if (!process.stdin.isTTY || !process.stderr.isTTY)
32824
+ throw new Error("No terminal to ask for the token in; pipe it with --token-stdin");
32825
+ else token = await prompt("CLI access token: ", true);
32481
32826
  if (server.startsWith("http:"))
32482
32827
  console.error("Warning: insecure HTTP; the token travels in plaintext. Local/private testing only.");
32483
32828
  const urls = args.slice(2).length ? args.slice(2).map((url2) => origin(url2, !!o["allow-insecure"])) : [server];
@@ -32682,48 +33027,6 @@ cloudler deploy --github OWNER/REPO --pr NUMBER --software APP
32682
33027
  the normal review/deploy flow. Requires an owner login, not CLOUDLER_TOKEN.
32683
33028
  Private images need a separate registry login. File upload still works.`;
32684
33029
 
32685
- // package.json
32686
- var package_default = {
32687
- name: "cloudler",
32688
- version: "0.0.2",
32689
- description: "Command line for Cloudler: deploy and manage apps on your own machines",
32690
- license: "MIT",
32691
- keywords: [
32692
- "cloudler",
32693
- "deploy",
32694
- "self-hosted",
32695
- "cli"
32696
- ],
32697
- homepage: "https://github.com/YJJosh/Cloudler#readme",
32698
- repository: {
32699
- type: "git",
32700
- url: "git+https://github.com/YJJosh/Cloudler.git",
32701
- directory: "apps/cli"
32702
- },
32703
- bugs: "https://github.com/YJJosh/Cloudler/issues",
32704
- type: "module",
32705
- engines: {
32706
- node: ">=24"
32707
- },
32708
- bin: {
32709
- cloudler: "dist/cloudler.js"
32710
- },
32711
- files: [
32712
- "dist"
32713
- ],
32714
- scripts: {
32715
- build: "node scripts/build.ts",
32716
- typecheck: "tsc --noEmit",
32717
- prepack: "pnpm build"
32718
- },
32719
- devDependencies: {
32720
- "@cloudler/schema": "workspace:*",
32721
- "@types/node": "^24.19.0",
32722
- esbuild: "0.28.2",
32723
- "tough-cookie": "^6.0.1"
32724
- }
32725
- };
32726
-
32727
33030
  // src/help.ts
32728
33031
  var VERSION = package_default.version;
32729
33032
  var orgsHelp = `cloudler orgs List your organizations (* = the one in use)
@@ -32765,6 +33068,16 @@ cloudler software address --software APP --hostname app.example.com | --port-mod
32765
33068
  Moves the app and its previews to another host name, or to its own gateway
32766
33069
  port (port mode). Running apps are redeployed with their current release.
32767
33070
  The port mode the app already has gives it another port.
33071
+ cloudler software gateways --software APP
33072
+ cloudler software gateways add --software APP --gateway GATEWAY \\
33073
+ --hostname app.example.com | --port-mode https|http [--expose service:tcp:25565]... [--yes] [--wait]
33074
+ cloudler software gateways on|off --software APP --gateway GATEWAY [--yes]
33075
+ cloudler software gateways primary --software APP --gateway GATEWAY [--yes] [--wait]
33076
+ cloudler software gateways remove --software APP --gateway GATEWAY [--yes]
33077
+ An app can be reachable through several gateways at once, for example a
33078
+ Tailscale port and a public host name. The primary gateway's URL is the
33079
+ app's URL. Off closes a gateway but keeps its address saved. Adding one or
33080
+ changing the primary redeploys a running app.
32768
33081
  cloudler software remove APP [--keep-data] [--yes]
32769
33082
  Removes a stopped app from Cloudler. Its data stays on the host. Its data
32770
33083
  snapshots in Volumler are removed 7 days later, unless --keep-data.`,
@@ -32799,7 +33112,10 @@ cloudler deploy ./deploy.json --software APP --stage dev
32799
33112
  Every command that takes --software also takes --stage.
32800
33113
  --port-mode: no host name; the app gets its own port of an Internal or Ports
32801
33114
  gateway (https://192.168.1.10:10000). https uses a self-signed certificate.
32802
- Inputs: --env-file environment.json (replaces the saved env; omit to reuse it)
33115
+ Inputs: --env KEY=VALUE (repeatable; changes single keys of the saved env)
33116
+ --env-file FILE (JSON or KEY=VALUE lines; replaces the saved env,
33117
+ --env on top; omit both to reuse it). Keys with generate: true in
33118
+ portler.yml get a value from Cloudler unless you supply one.
32803
33119
  --config portler.yml (local builds or legacy manifests)
32804
33120
  Retry: --request-id KEY (default random; retry with the SAME key and inputs)
32805
33121
  --wait returns 0 ONLY when the submitted job succeeded. Without --wait,
@@ -32879,6 +33195,16 @@ cloudler gateways app-ports --gateway GATEWAY 12000-12999
32879
33195
  cloudler gateways move --gateway GATEWAY [--yes]
32880
33196
  After the machine was registered in its tailnet again: moves a Tailscale
32881
33197
  gateway and its apps to the new tailnet address. Ports stay; apps restart.
33198
+ cloudler gateways share --gateway GATEWAY --compute COMPUTE[,COMPUTE] [--relay-address IP] [--relay-port 7100]
33199
+ [--relay-public-address IP|NAME] [--relay-public-port PORT] [--yes]
33200
+ Lets apps on other machines use this Internal, Tailscale or Ports gateway. Their agents
33201
+ connect out to a relay on the gateway's machine. It listens on --relay-address (an address
33202
+ of that machine, such as its LAN address; needed the first time). Behind NAT or a port
33203
+ forward, --relay-public-address/--relay-public-port is where the others connect instead
33204
+ ("" clears it). Flags you leave out keep their current value. That machine then holds
33205
+ their TLS keys and sees their traffic.
33206
+ cloudler gateways unshare --gateway GATEWAY --compute COMPUTE[,COMPUTE]
33207
+ Refused while apps on that machine still use the gateway.
32882
33208
  cloudler gateways remove GATEWAY [--yes]`,
32883
33209
  domains: `cloudler domains List domains
32884
33210
  cloudler domains add example.com --account-id CLOUDFLARE_ACCOUNT_ID [--token-stdin]
@@ -32948,25 +33274,7 @@ only deploy, manage previews and read jobs. Deploy authority can replace code
32948
33274
  and access app data; it is NOT a sandbox. Never send account passwords in CI.`;
32949
33275
  var commands = Object.keys(commandHelp);
32950
33276
  function suggest(input2, names = commands) {
32951
- let best, score = Infinity;
32952
- for (const name4 of names) {
32953
- const d = distance(input2, name4);
32954
- if (d < score) [best, score] = [name4, d];
32955
- }
32956
- return best && score <= Math.max(2, Math.floor(best.length / 3)) ? best : void 0;
32957
- }
32958
- function distance(a, b) {
32959
- const row = Array.from({ length: b.length + 1 }, (_, i) => i);
32960
- for (let i = 1; i <= a.length; i++) {
32961
- let prev = row[0];
32962
- row[0] = i;
32963
- for (let j = 1; j <= b.length; j++) {
32964
- const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
32965
- prev = row[j];
32966
- row[j] = next;
32967
- }
32968
- }
32969
- return row[b.length];
33277
+ return closest(input2, names);
32970
33278
  }
32971
33279
 
32972
33280
  // src/wait.ts
@@ -32989,8 +33297,9 @@ async function waitForJob(read, id3, timeout, signal, pause = 1e3, onStatus) {
32989
33297
  `Stopped watching job ${id3}; server job was NOT cancelled`
32990
33298
  );
32991
33299
  if (Date.now() >= deadline || bound.aborted)
32992
- throw new Error(`Timed out watching job ${id3}`);
33300
+ throw new Error(`Timed out watching job ${id3}${unanswered ? `; the last read failed: ${unanswered}` : ""}`);
32993
33301
  }
33302
+ let unanswered;
32994
33303
  let previous;
32995
33304
  while (true) {
32996
33305
  check2();
@@ -33005,11 +33314,17 @@ async function waitForJob(read, id3, timeout, signal, pause = 1e3, onStatus) {
33005
33314
  ({ job } = await Promise.race([read(bound), aborted2]));
33006
33315
  } catch (e) {
33007
33316
  check2();
33008
- throw e;
33317
+ if (!(e instanceof ApiUnavailableError || e instanceof ApiHttpError && [502, 503, 504].includes(e.status))) throw e;
33318
+ if (!unanswered) console.error(`${e.message}; asking again until the --timeout.`);
33319
+ unanswered = e.message;
33320
+ await pauseFor(pause);
33321
+ continue;
33009
33322
  } finally {
33010
33323
  bound.removeEventListener("abort", onAbort);
33011
33324
  }
33012
33325
  check2();
33326
+ if (!job) throw new Error("Invalid API response");
33327
+ unanswered = void 0;
33013
33328
  if (job.id !== id3)
33014
33329
  throw new Error(`API returned wrong job while watching ${id3}`);
33015
33330
  if (job.status !== previous) {
@@ -33018,10 +33333,13 @@ async function waitForJob(read, id3, timeout, signal, pause = 1e3, onStatus) {
33018
33333
  }
33019
33334
  if (job.status === "succeeded") return job;
33020
33335
  if (!["queued", "running"].includes(job.status)) throw new JobFailure(job);
33021
- await new Promise((resolve2) => {
33336
+ await pauseFor(pause);
33337
+ }
33338
+ function pauseFor(pause2) {
33339
+ return new Promise((resolve2) => {
33022
33340
  const timer = setTimeout(
33023
33341
  done,
33024
- Math.min(pause, Math.max(1, deadline - Date.now()))
33342
+ Math.min(pause2, Math.max(1, deadline - Date.now()))
33025
33343
  );
33026
33344
  function done() {
33027
33345
  clearTimeout(timer);
@@ -33131,13 +33449,13 @@ async function copyFrom(ctx, base, name4, from) {
33131
33449
  if (!source) throw new Error(`No other instance ${inert(from)}; pick one of: ${view.sources.map((s) => inert(s.label)).join(", ") || "none"}`);
33132
33450
  const snapshot = o.snapshot ? source.snapshots.find((s) => s.id === o.snapshot) : source.snapshots[0];
33133
33451
  if (!snapshot) throw new Error(o.snapshot ? `${inert(source.label)} has no finished snapshot ${inert(o.snapshot)}` : `${inert(source.label)} has no finished snapshot yet; make one: cloudler backup`);
33134
- if (snapshot.missing.length) throw new Error(`That snapshot has no data for ${snapshot.missing.join(", ")}, which ${inert(name4)} uses`);
33452
+ if (snapshot.missing.length) throw new Error(`That snapshot has no data for ${inert(snapshot.missing.join(", "))}, which ${inert(name4)} uses`);
33135
33453
  console.error(`${inert(name4)} keeps release ${inert(snapshot.targetVersion)} and starts on the data ${inert(source.label)} had ${ago(snapshot.createdAt)} (made by ${inert(snapshot.sourceVersion)}). Its own data stays on the machine.`);
33136
33454
  console.error("Logins and passwords stored in the data come with it: both instances must use the same database credentials.");
33137
33455
  if (!snapshot.clean) console.error("Warning: this snapshot was taken after a failed start; its data may be half migrated.");
33138
33456
  for (const change of snapshot.imageChanges)
33139
- console.error(`Warning: ${change.volume} is used by ${change.target.join(", ")} here, but was made by ${change.source.join(", ") || "an unknown image"}.`);
33140
- await confirm(o, `Copy ${source.label}'s data into ${name4}?`);
33457
+ console.error(`Warning: ${inert(change.volume)} is used by ${inert(change.target.join(", "))} here, but was made by ${inert(change.source.join(", ")) || "an unknown image"}.`);
33458
+ await confirm(o, `Copy ${inert(source.label)}'s data into ${inert(name4)}?`);
33141
33459
  const result = await client.request(`${base}/copy`, "POST", { snapshotId: snapshot.id, confirmed: true });
33142
33460
  return queued(ctx, result, () => `${inert(name4)} runs on a copy of ${inert(source.label)}'s data.`);
33143
33461
  }
@@ -33191,6 +33509,13 @@ function addressFlags(o, command2) {
33191
33509
  }
33192
33510
  return { hostname: required3(o.hostname, "--hostname app.example.com or --port-mode https|http", command2) };
33193
33511
  }
33512
+ function parseExposure(value) {
33513
+ const parts = value.split(":");
33514
+ const [service, protocol, port2] = parts.length === 2 ? [parts[0], "tcp", parts[1]] : parts;
33515
+ if (parts.length < 2 || parts.length > 3 || !service || !protocol || !/^\d+$/.test(port2 ?? ""))
33516
+ throw new Error("--expose must look like service:tcp:25565 or service:udp:19132");
33517
+ return { service, protocol, port: Number(port2) };
33518
+ }
33194
33519
  function appPorts(value) {
33195
33520
  const match = /^(\d{1,5})-(\d{1,5})$/.exec(value.trim());
33196
33521
  if (!match) throw new Error("--app-ports must look like 10000-10999");
@@ -33218,6 +33543,57 @@ async function softwareAddress(ctx) {
33218
33543
  const done = `${inert(result.software.name)} is now at ${inert(result.software.publicUrl)}${!o.wait && result.redeploys ? ` (${result.redeploys} redeploy${result.redeploys === 1 ? "" : "s"} queued)` : ""}.`;
33219
33544
  return print(o.json ? result : done);
33220
33545
  }
33546
+ var showAppGateways = (rows) => table(rows, [
33547
+ ["GATEWAY", (g) => g.gatewayName],
33548
+ ["TYPE", (g) => g.gatewayType],
33549
+ ["STATE", (g) => g.primary ? "primary" : g.active ? "on" : "off"],
33550
+ ["URL", (g) => g.publicUrl],
33551
+ ["PROBLEM", (g) => g.ingressMessage?.split("\n")[0]]
33552
+ ], "This app has no gateway.");
33553
+ async function softwareGateways(ctx) {
33554
+ const { args, o, client, print } = ctx;
33555
+ const sub = args[2] ?? "list";
33556
+ const subs = ["list", "add", "on", "off", "primary", "remove"];
33557
+ if (!subs.includes(sub)) throw unknown2("software gateways", sub, subs);
33558
+ ownerOnly(client, "change app gateways");
33559
+ if (o.wait) timeoutSeconds(o);
33560
+ const p = await find(client, "software", required3(o.software, "--software APP", "software"));
33561
+ const path = `/api/software/${p.id}/gateways`;
33562
+ const list2 = async () => (await client.request(path)).gateways;
33563
+ if (sub === "list") {
33564
+ const rows = await list2();
33565
+ return print(o.json ? { gateways: rows } : showAppGateways(rows));
33566
+ }
33567
+ const gateway = await find(client, "gateway", required3(o.gateway, "--gateway GATEWAY", "software"));
33568
+ const done = async (result2, message) => {
33569
+ const job = o.wait && result2.job ? await watch(client, p.id, result2.job.id, o) : result2.job;
33570
+ return print(o.json ? { ...result2, job } : `${message}${!o.wait && result2.job ? " A redeploy is queued." : ""}`);
33571
+ };
33572
+ if (sub === "add") {
33573
+ const address = addressFlags(o, "software");
33574
+ const exposures = (o.expose ?? []).map(parseExposure);
33575
+ console.error("The app stays at its current URL. Running apps are redeployed with their current release, so they briefly stop.");
33576
+ await confirm(o, `Add gateway ${gateway.name} to ${p.name}?`);
33577
+ const result2 = await client.request(path, "POST", { gatewayId: gateway.id, ...address, exposures, confirmed: true });
33578
+ return done(result2, `${inert(p.name)} is now also at ${inert(result2.attachment.publicUrl)}.`);
33579
+ }
33580
+ const site = (await list2()).find((g) => g.gatewayId === gateway.id);
33581
+ if (!site) throw new Error(`${inert(p.name)} does not use gateway ${inert(gateway.name)}; see cloudler software gateways --software ${arg(p.name)}`);
33582
+ if (sub === "on" || sub === "off") {
33583
+ if (sub === "off") await confirm(o, `Turn off ${site.publicUrl}? It stops answering${site.hostname ? " and its DNS record is removed" : ""}; its address stays saved.`);
33584
+ const result2 = await client.request(`${path}/${site.id}`, "PATCH", { active: sub === "on" });
33585
+ return print(o.json ? result2 : sub === "on" ? `${inert(p.name)} is reachable at ${inert(site.publicUrl)} again within a minute.` : `${inert(site.publicUrl)} is off. Its address stays saved for ${inert(p.name)}.`);
33586
+ }
33587
+ if (sub === "primary") {
33588
+ console.error("The app's URL changes: catalog apps get their URL settings again, and running apps are redeployed. Existing previews stay where they are.");
33589
+ await confirm(o, `Make ${site.publicUrl} the URL of ${p.name}?`);
33590
+ const result2 = await client.request(`${path}/${site.id}`, "PATCH", { primary: true, confirmed: true });
33591
+ return done(result2, `${inert(result2.software.name)} is now at ${inert(result2.software.publicUrl)}.`);
33592
+ }
33593
+ await confirm(o, `Remove ${site.publicUrl} from ${p.name}? Its host name or port is freed.`);
33594
+ const result = await client.request(`${path}/${site.id}`, "DELETE");
33595
+ return print(o.json ? result : `Removed gateway ${inert(gateway.name)} from ${inert(p.name)}.`);
33596
+ }
33221
33597
  function required3(value, flag, command2) {
33222
33598
  if (!value) throw new Error(`Required ${flag}; see cloudler ${command2 ?? ""} --help`.replace(" ", " "));
33223
33599
  return value;
@@ -33299,7 +33675,7 @@ async function watch(client, softwareId, jobId, o) {
33299
33675
  seconds * 1e3,
33300
33676
  stop.signal,
33301
33677
  1e3,
33302
- (job) => console.error(`Job ${job.id}: ${inert(job.status)}`)
33678
+ (job) => console.error(`Job ${inert(job.id)}: ${inert(job.status)}`)
33303
33679
  );
33304
33680
  } catch (e) {
33305
33681
  if (e instanceof JobFailure) {
@@ -33316,13 +33692,13 @@ async function queued(ctx, result, done) {
33316
33692
  const { o, client, print } = ctx;
33317
33693
  const ref = result.software.name ?? result.software.id;
33318
33694
  if (!o.wait)
33319
- return print(o.json ? result : `Queued ${result.job.action ?? "job"} ${result.job.id} for ${inert(ref)}.
33695
+ return print(o.json ? result : `Queued ${inert(result.job.action ?? "job")} ${inert(result.job.id)} for ${inert(ref)}.
33320
33696
  Watch it: cloudler jobs --software ${arg(ref)} (or add --wait)`);
33321
33697
  let job;
33322
33698
  try {
33323
33699
  job = await watch(client, result.software.id, result.job.id, o);
33324
33700
  } catch (e) {
33325
- throw new Error(`${e.message}. See cloudler logs --software ${arg(ref)} --job ${result.job.id}`);
33701
+ throw new Error(`${e.message}. See cloudler logs --software ${arg(ref)} --job ${arg(result.job.id)}`);
33326
33702
  }
33327
33703
  print(o.json ? { softwareId: result.software.id, publicUrl: result.software.publicUrl ?? null, job } : done(job));
33328
33704
  }
@@ -33350,7 +33726,7 @@ async function status(ctx, id3) {
33350
33726
  const p = detail.software;
33351
33727
  const owner = client.token === void 0;
33352
33728
  const [computes2, gateways2] = owner ? await Promise.all([client.request("/api/computes/"), client.request("/api/gateways/")]) : [{ computes: [] }, { gateways: [] }];
33353
- const name4 = (list3, ref) => ref ? list3.find((x) => x.id === ref)?.name ?? ref : null;
33729
+ const name4 = (list2, ref) => ref ? list2.find((x) => x.id === ref)?.name ?? ref : null;
33354
33730
  print([
33355
33731
  details([
33356
33732
  ["Name", p.parentSoftwareId ? `${p.name} (preview ${p.previewName})` : p.name],
@@ -33384,7 +33760,7 @@ function unknown2(command2, sub, subs) {
33384
33760
  }
33385
33761
  async function lifecycle(ctx) {
33386
33762
  const { command: command2, args, o, client, print } = ctx;
33387
- if (command2 === "software" && args[1] !== "remove") throw unknown2("software", args[1], ["list", "kind", "address", "remove"]);
33763
+ if (command2 === "software" && args[1] !== "remove") throw unknown2("software", args[1], ["list", "kind", "address", "gateways", "remove"]);
33388
33764
  const softwareRef = required3(o.software ?? (command2 === "software" ? args[2] : void 0), "--software APP", command2);
33389
33765
  ownerOnly(client, command2 === "cancel" ? "cancel jobs" : command2 === "software" ? "remove apps" : `${command2} apps`);
33390
33766
  const p = await find(client, "software", softwareRef);
@@ -33531,8 +33907,9 @@ async function gateways(ctx) {
33531
33907
  ["COMPUTE", (g) => computes2.find((c) => c.id === g.computeId)?.name ?? g.computeId],
33532
33908
  ["ID", (g) => g.id],
33533
33909
  // Edge errors can be whole Docker messages; --json has all of it.
33910
+ // The edge error belongs to the machine, so it shows on each of its gateways.
33534
33911
  ["NOTE", (g) => {
33535
- const note = String(g.edgeError ?? g.statusMessage ?? "").replace(/\s+/g, " ").trim();
33912
+ const note = [g.statusMessage, g.edgeError && `machine: ${g.edgeError}`].filter(Boolean).join("; ").replace(/\s+/g, " ").trim();
33536
33913
  return note.length > 100 ? `${note.slice(0, 99)}\u2026` : note;
33537
33914
  }]
33538
33915
  ], "No gateways yet. Add one: cloudler gateways add NAME --compute COMPUTE --type internal"));
@@ -33581,13 +33958,43 @@ async function gateways(ctx) {
33581
33958
  const moved = await client.request(`/api/gateways/${g.id}/tailnet-address`, "POST", { address: target });
33582
33959
  return print(o.json ? moved : `Moved ${inert(moved.gateway.name)} from ${inert(moved.from)} to ${inert(moved.gateway.settings.bindAddress)}: ${moved.apps} ${moved.apps === 1 ? "app" : "apps"}, ${moved.jobs.length} redeploying.`);
33583
33960
  }
33961
+ if (sub === "share" || sub === "unshare") {
33962
+ const g = await find(client, "gateway", required3(o.gateway ?? args[2], "--gateway GATEWAY", "gateways"));
33963
+ const names = String(required3(o.compute, "--compute COMPUTE[,COMPUTE]", "gateways")).split(",").map((v) => v.trim()).filter(Boolean);
33964
+ if (!names.length) throw new Error("--compute: name at least one machine");
33965
+ const machines = await Promise.all(names.map((n2) => find(client, "compute", n2)));
33966
+ const { gateways: gateways2 } = await client.request("/api/gateways/");
33967
+ const current = gateways2.find((x) => x.id === g.id)?.sharedWith ?? [];
33968
+ const ids = machines.map((m) => m.id);
33969
+ const computeIds = sub === "share" ? [.../* @__PURE__ */ new Set([...current, ...ids])] : current.filter((id3) => !ids.includes(id3));
33970
+ const flags = ["relay-address", "relay-port", "relay-public-address", "relay-public-port"].filter((f) => o[f] !== void 0);
33971
+ const was = gateways2.find((x) => x.id === g.id)?.relay ?? null;
33972
+ const given = (name4, parse6) => o[name4] === void 0 ? void 0 : o[name4] === "" ? null : parse6(String(o[name4]));
33973
+ if (flags.length && !was && o["relay-address"] === void 0) throw new Error(`${g.name} has no relay yet: add --relay-address`);
33974
+ const relay = flags.length ? relaySettingsSchema.safeParse({
33975
+ address: o["relay-address"] ?? was?.address,
33976
+ port: Number(o["relay-port"] ?? was?.port ?? DEFAULT_RELAY_PORT),
33977
+ publicAddress: given("relay-public-address", (v) => v),
33978
+ publicPort: given("relay-public-port", Number)
33979
+ }) : void 0;
33980
+ if (relay && !relay.success) {
33981
+ const flag = { address: "--relay-address", port: "--relay-port", publicAddress: "--relay-public-address", publicPort: "--relay-public-port" }[String(relay.error.issues[0]?.path[0])];
33982
+ throw new Error(`${flag ?? "--relay-address"}: ${relay.error.issues[0]?.message ?? "check it"}`);
33983
+ }
33984
+ if (sub === "share")
33985
+ await confirm(o, `Share ${g.name} with ${machines.map((m) => m.name).join(", ")}? Its machine then serves their apps on it: it holds their TLS keys and sees their traffic.`);
33986
+ const { gateway } = await client.request(`/api/gateways/${g.id}/sharing`, "PUT", { computeIds, previous: current, ...relay ? { relay: relay.data } : {} });
33987
+ const n = gateway.sharedWith.length;
33988
+ const list2 = n ? `shared with ${n} ${n === 1 ? "machine" : "machines"}` : "not shared";
33989
+ return print(o.json ? { gateway } : `${inert(gateway.name)} is ${list2}${gateway.relay ? `; relay ${inert(gateway.relay.address)}:${gateway.relay.port}${gateway.relay.publicAddress || gateway.relay.publicPort ? ` via ${inert(gateway.relay.publicAddress ?? gateway.relay.address)}:${gateway.relay.publicPort ?? gateway.relay.port}` : ""}` : ""}.`);
33990
+ }
33584
33991
  if (sub === "remove") {
33585
33992
  const g = await find(client, "gateway", required3(o.gateway ?? args[2], "--gateway GATEWAY", "gateways"));
33586
33993
  await confirm(o, `Remove gateway ${g.name}?`);
33587
33994
  await client.request(`/api/gateways/${g.id}`, "DELETE");
33588
33995
  return print(o.json ? { ok: true, id: g.id } : `Removed gateway ${inert(g.name)}.`);
33589
33996
  }
33590
- throw unknown2("gateways", sub, ["list", "add", "app-ports", "move", "remove"]);
33997
+ throw unknown2("gateways", sub, ["list", "add", "app-ports", "move", "share", "unshare", "remove"]);
33591
33998
  }
33592
33999
  async function domains(ctx) {
33593
34000
  const { args, o, client, print } = ctx;
@@ -33683,8 +34090,8 @@ async function catalog(ctx) {
33683
34090
  const updatePolicy = catalogPolicySchema.parse(o["update-policy"] ?? "manual");
33684
34091
  const values = await fillRequired(a.fields, await valuesFile(o.values));
33685
34092
  const where = address.hostname ? `https://${inert(address.hostname)}` : `its own port of ${inert(gateway.name)} (${address.portScheme})`;
33686
- console.error(`Install ${inert(a.name)} ${version3} as ${inert(name4)} on ${inert(compute.name)} at ${where} (${updatePolicy} updates)`);
33687
- console.error(`Notes for ${version3}:
34093
+ console.error(`Install ${inert(a.name)} ${inert(version3)} as ${inert(name4)} on ${inert(compute.name)} at ${where} (${updatePolicy} updates)`);
34094
+ console.error(`Notes for ${inert(version3)}:
33688
34095
  ${text3(indent(v.notes))}`);
33689
34096
  console.error("Back up app data yourself. Anyone who can change the catalog can run code on this machine with automatic updates.");
33690
34097
  await confirm(o, `Install ${a.name}?`);
@@ -33894,7 +34301,7 @@ Keep the same DATABASE_URL and CONTROL_SECRET; only the token changes.`);
33894
34301
  "",
33895
34302
  ` ${inert(result.token)}`,
33896
34303
  "",
33897
- result.urls.length ? `Use it: cloudler control login ${result.urls.map(inert).join(" ")}${result.urls.some((u) => u.startsWith("http:")) ? " --allow-insecure" : ""} (paste the token when asked)` : "The group has no server address yet."
34304
+ result.urls.length ? `Use it: cloudler control login ${result.urls.map(arg).join(" ")}${result.urls.some((u) => u.startsWith("http:")) ? " --allow-insecure" : ""} (paste the token when asked)` : "The group has no server address yet."
33898
34305
  ].join("\n"));
33899
34306
  }
33900
34307
  if (action === "revoke") {
@@ -33962,7 +34369,7 @@ async function github({ client, args, o, print }) {
33962
34369
  if (token.length > 4096) throw new Error("Token input is too large");
33963
34370
  }
33964
34371
  token = token.trim();
33965
- } else token = await prompt("GitHub token: ", true);
34372
+ } else token = await prompt("GitHub token: ", true, "--token-stdin");
33966
34373
  print(await client.request("/api/github/connections", "POST", { label, githubOwner, token }));
33967
34374
  return;
33968
34375
  }
@@ -34200,7 +34607,7 @@ async function instances(ctx) {
34200
34607
  ], "Nothing runs yet."));
34201
34608
  }
34202
34609
  var typeNames = { internal: "internal", tailscale: "tailscale", ports: "ports", tunnel: "cloudflare_tunnel", remote: "remote" };
34203
- var list2 = (value) => value.split(",").map((v) => v.trim()).filter(Boolean);
34610
+ var list = (value) => value.split(",").map((v) => v.trim()).filter(Boolean);
34204
34611
  async function previewRules(ctx) {
34205
34612
  const { o, client, print, softwareId } = ctx;
34206
34613
  ownerOnly(client, "change preview rules");
@@ -34209,15 +34616,15 @@ async function previewRules(ctx) {
34209
34616
  let shown = current;
34210
34617
  if (changes) {
34211
34618
  if (o.gateway !== void 0 && o["gateway-type"] !== void 0) throw new Error("Give --gateway or --gateway-type, not both");
34212
- const types = o["gateway-type"] !== void 0 ? list2(o["gateway-type"]).map((t) => {
34619
+ const types = o["gateway-type"] !== void 0 ? list(o["gateway-type"]).map((t) => {
34213
34620
  const type = typeNames[t];
34214
34621
  if (!type) throw new Error("--gateway-type takes internal, tailscale, ports, tunnel or remote");
34215
34622
  return type;
34216
34623
  }) : void 0;
34217
34624
  const next = {
34218
- runtimes: o.runtime !== void 0 ? list2(o.runtime) : current.rules.runtimes,
34219
- computeIds: o.compute !== void 0 ? await Promise.all(list2(o.compute).map(async (c) => (await find(client, "compute", c)).id)) : current.rules.computeIds,
34220
- gateways: o.gateway !== void 0 ? { ids: await Promise.all(list2(o.gateway).map(async (g) => (await find(client, "gateway", g)).id)) } : types ? { types } : current.rules.gateways,
34625
+ runtimes: o.runtime !== void 0 ? list(o.runtime) : current.rules.runtimes,
34626
+ computeIds: o.compute !== void 0 ? await Promise.all(list(o.compute).map(async (c) => (await find(client, "compute", c)).id)) : current.rules.computeIds,
34627
+ gateways: o.gateway !== void 0 ? { ids: await Promise.all(list(o.gateway).map(async (g) => (await find(client, "gateway", g)).id)) } : types ? { types } : current.rules.gateways,
34221
34628
  pick: o.pick ?? current.rules.pick
34222
34629
  };
34223
34630
  const parsed = previewRulesSchema.safeParse(next);
@@ -34243,13 +34650,6 @@ function required4(value, flag) {
34243
34650
  if (!value) throw new Error(`Required ${flag}; see --help`);
34244
34651
  return value;
34245
34652
  }
34246
- function parseExposure(value) {
34247
- const parts = value.split(":");
34248
- const [service, protocol, port2] = parts.length === 2 ? [parts[0], "tcp", parts[1]] : parts;
34249
- if (parts.length < 2 || parts.length > 3 || !service || !protocol || !/^\d+$/.test(port2 ?? ""))
34250
- throw new Error("--expose must look like service:tcp:25565 or service:udp:19132");
34251
- return { service, protocol, port: Number(port2) };
34252
- }
34253
34653
  function clean(s) {
34254
34654
  return s.replace(/[\x00-\x1f\x7f-\x9f]/g, "?");
34255
34655
  }
@@ -34263,6 +34663,13 @@ async function jsonFile(path) {
34263
34663
  throw new Error(`Cannot read JSON input file ${path}`);
34264
34664
  }
34265
34665
  }
34666
+ async function readEnvFile(path) {
34667
+ try {
34668
+ return await readFile4(path, "utf8");
34669
+ } catch {
34670
+ throw new Error(`Cannot read --env-file ${path}`);
34671
+ }
34672
+ }
34266
34673
  async function main() {
34267
34674
  const { values: o, positionals: args } = parseArgs({
34268
34675
  allowPositionals: true,
@@ -34302,6 +34709,10 @@ async function main() {
34302
34709
  "bind-address",
34303
34710
  "https-port",
34304
34711
  "control-port",
34712
+ "relay-address",
34713
+ "relay-port",
34714
+ "relay-public-address",
34715
+ "relay-public-port",
34305
34716
  "domain",
34306
34717
  "account-id",
34307
34718
  "values",
@@ -34348,7 +34759,8 @@ async function main() {
34348
34759
  "keep-tokens",
34349
34760
  "without-snapshot"
34350
34761
  ].map((k) => [k, { type: "boolean" }]),
34351
- ["expose", { type: "string", multiple: true }]
34762
+ ["expose", { type: "string", multiple: true }],
34763
+ ["env", { type: "string", multiple: true }]
34352
34764
  ])
34353
34765
  });
34354
34766
  if (args[0] === "help" && args.shift() && args[0]) o.help = true;
@@ -34408,7 +34820,7 @@ async function main() {
34408
34820
  console.error(
34409
34821
  "Warning: insecure HTTP; credentials travel in plaintext. Local/private testing only."
34410
34822
  );
34411
- const email3 = o.email ?? await prompt("Email: ");
34823
+ const email3 = o.email ?? await prompt("Email: ", false, "--email");
34412
34824
  let password;
34413
34825
  if (o["password-stdin"]) {
34414
34826
  console.error(
@@ -34417,7 +34829,7 @@ async function main() {
34417
34829
  const chunks = [];
34418
34830
  for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
34419
34831
  password = Buffer.concat(chunks).toString().replace(/\r?\n$/, "");
34420
- } else password = await prompt("Password: ", true);
34832
+ } else password = await prompt("Password: ", true, "--password-stdin");
34421
34833
  await client2.request("/api/auth/sign-in/email", "POST", {
34422
34834
  email: email3,
34423
34835
  password
@@ -34507,6 +34919,7 @@ async function main() {
34507
34919
  return;
34508
34920
  }
34509
34921
  if (command2 === "software" && args[1] === "address") return softwareAddress(ctx);
34922
+ if (command2 === "software" && args[1] === "gateways") return softwareGateways(ctx);
34510
34923
  if (command2 === "software" && (args[1] === void 0 || args[1] === "list")) {
34511
34924
  if (client.token !== void 0)
34512
34925
  throw new Error("Software tokens cannot list software. Use --software UUID from the owner console.");
@@ -34536,11 +34949,14 @@ async function main() {
34536
34949
  "CI software tokens require --software UUID, not a name (cannot list software)"
34537
34950
  );
34538
34951
  const result2 = await client.request("/api/software/");
34952
+ const names = result2.software.map((p) => p.name);
34539
34953
  const matches = result2.software.filter((p) => p.name === softwareInput);
34540
- if (matches.length !== 1)
34541
- throw new Error(
34542
- matches.length ? "Ambiguous software name; use UUID" : "Software not found; creation requires explicit --create, --compute, --gateway and --hostname or --port-mode"
34543
- );
34954
+ if (matches.length > 1) throw new Error("Ambiguous software name; use UUID");
34955
+ if (!matches.length) {
34956
+ const close = suggest(softwareInput, names);
34957
+ const create = command2 === "deploy" ? "; to create it, add --create, --compute, --gateway and --hostname or --port-mode" : "";
34958
+ throw new Error(`No software ${inert(softwareInput)}${close ? `. Did you mean ${inert(close)}?` : ""} (list them: cloudler software)${create}`);
34959
+ }
34544
34960
  return matches[0].id;
34545
34961
  }
34546
34962
  const previewName = (fallback) => {
@@ -34559,7 +34975,7 @@ async function main() {
34559
34975
  `/api/software/${await resolveSoftware()}/previews/${encodeURIComponent(name4)}`,
34560
34976
  "DELETE"
34561
34977
  );
34562
- print(o.json ? removed : removed.state === "removed" ? `Removed preview ${name4}.` : `Stopping preview ${name4}; it is removed when it has stopped.`);
34978
+ print(o.json ? removed : removed.state === "removed" ? `Removed preview ${name4}.` : removed.state === "absent" ? `No preview ${name4}; nothing to remove.` : `Stopping preview ${name4}; it is removed when it has stopped.`);
34563
34979
  return;
34564
34980
  }
34565
34981
  if (command2 === "preview" && args[1] === "list") {
@@ -34596,7 +35012,10 @@ async function main() {
34596
35012
  const seconds = Number(o.timeout ?? 600);
34597
35013
  if (!Number.isFinite(seconds) || seconds <= 0 || seconds > 86400)
34598
35014
  throw new Error("--timeout must be 1-86400 seconds");
34599
- const environment = o["env-file"] ? await jsonFile(o["env-file"]) : void 0;
35015
+ const envFlags = parseEnvFlags(o.env ?? []);
35016
+ const envFile = o["env-file"] ? parseEnvFile(await readEnvFile(o["env-file"]), o["env-file"]) : void 0;
35017
+ const environment = envFile !== void 0 || o.create ? { ...envFile, ...envFlags } : void 0;
35018
+ const environmentPatch = environment === void 0 && Object.keys(envFlags).length ? envFlags : void 0;
34600
35019
  const kind = softwareKindSchema.safeParse(o.kind ?? "own");
34601
35020
  if (o.create && !kind.success) throw new Error("--kind must be own or self-hosted");
34602
35021
  const createInput = o.create ? {
@@ -34616,17 +35035,18 @@ async function main() {
34616
35035
  );
34617
35036
  }
34618
35037
  if (environment !== void 0 && !createSoftwareRequestSchema.shape.environment.safeParse(environment).success)
34619
- throw new Error("Invalid --env-file: expected a JSON object of string values (values redacted)");
35038
+ throw new Error("Invalid --env-file or --env: expected string values with valid names (values redacted)");
34620
35039
  let reservedId;
34621
35040
  const built = o.build ? await buildRelease({
34622
35041
  configPath: o.config ?? "portler.yml",
34623
35042
  platform: o.platform,
34624
35043
  version: o["app-version"],
34625
35044
  preview,
35045
+ insecure: client.insecure,
34626
35046
  // A new app starts with the env file or nothing; an update without
34627
35047
  // --env-file reuses the saved one, which only the server knows.
34628
35048
  check: {
34629
- environment: environment ?? (o.create ? {} : void 0),
35049
+ environment,
34630
35050
  ...createCheck?.success ? { hostname: createCheck.data.hostname, exposures: createCheck.data.exposures } : {}
34631
35051
  },
34632
35052
  grant: async () => {
@@ -34657,13 +35077,16 @@ async function main() {
34657
35077
  if (manifest.portler.sha256 && createHash5("sha256").update(config2).digest("hex") !== manifest.portler.sha256)
34658
35078
  throw new Error("Configuration SHA-256 mismatch");
34659
35079
  if (!o.create && !softwareId) softwareId = await resolveSoftware();
35080
+ if (environmentPatch && !((await client.request("/api/instance")).features ?? []).includes("environmentPatch"))
35081
+ throw new Error("This Cloudler server is too old for --env without --env-file. Update it, or pass the whole environment with --env-file.");
34660
35082
  const body = {
34661
35083
  manifest,
34662
35084
  config: config2,
34663
35085
  confirmed: true,
34664
35086
  ...name4 ? { name: name4 } : {},
34665
35087
  ...placement,
34666
- ...environment !== void 0 ? { environment } : o.create ? { environment: {} } : {},
35088
+ ...environment !== void 0 ? { environment } : {},
35089
+ ...environmentPatch ? { environmentPatch } : {},
34667
35090
  ...o.create ? {
34668
35091
  name: softwareInput,
34669
35092
  ...built ? { id: built.rootId } : {},
@@ -34693,6 +35116,11 @@ async function main() {
34693
35116
  console.error(
34694
35117
  ` ${clean(image.service)}: ${clean(image.image)}${image.pinned ? " (digest pinned)" : " (MUTABLE TAG)"}`
34695
35118
  );
35119
+ const saved2 = environment !== void 0 ? /* @__PURE__ */ new Set() : softwareId && !preview ? await client.request(`/api/software/${softwareId}`).then((d) => new Set(d.environmentKeys ?? []), () => void 0) : void 0;
35120
+ const inputs = describeInputs(config2, { ...environment, ...environmentPatch }, saved2);
35121
+ if (inputs.lines.length) console.error(["Environment:", ...inputs.lines.map(clean)].join("\n"));
35122
+ if (inputs.missing.length)
35123
+ throw new Error(`Missing required environment: ${inputs.missing.join(", ")}. Add --env KEY=VALUE.`);
34696
35124
  console.error(
34697
35125
  "Only trust known images/configuration. Back up app data; deployment can replace code and access app secrets/data."
34698
35126
  );
@@ -34716,13 +35144,14 @@ async function main() {
34716
35144
  try {
34717
35145
  result2 = await client.request(path, "POST", parsed.data, requestId);
34718
35146
  } catch (e) {
35147
+ if (e instanceof ApiHttpError && e.status < 500 && e.status !== 408 && e.status !== 429) throw e;
34719
35148
  throw new Error(
34720
35149
  `${e.message}. Recovery request ID: ${requestId}; retry the SAME request/key only, never generate a replacement automatically.`
34721
35150
  );
34722
35151
  }
34723
- const recovery = `cloudler logs --software ${result2.software.id} --job ${result2.job.id}`;
35152
+ const recovery = `cloudler logs --software ${arg(result2.software.id)} --job ${arg(result2.job.id)}`;
34724
35153
  console.error(
34725
- `Accepted job ${result2.job.id} (${result2.job.status}); ${recovery}`
35154
+ `Accepted job ${inert(result2.job.id)} (${inert(result2.job.status)}); ${recovery}`
34726
35155
  );
34727
35156
  if (!o.wait) {
34728
35157
  const accepted = { ...result2, requestId, accepted: true, message: "Accepted, not necessarily deployed" };
@@ -34833,7 +35262,7 @@ ${result2.job.error}` : ""}`
34833
35262
  main().catch((error62) => {
34834
35263
  const message = error62 instanceof Error ? error62.message : "Command failed";
34835
35264
  console.error(`cloudler: ${terminalText(message)}`);
34836
- if (/^API unavailable|^API HTTP 50[234]/.test(message))
35265
+ if (/(^|: )(API unavailable|API HTTP 50[234])/.test(message))
34837
35266
  console.error("If Cloudler is down, reach your own control server directly: cloudler control status");
34838
35267
  process.exitCode = 1;
34839
35268
  });