koigrid 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -2
- package/dist/api.js +78 -6
- package/dist/args.js +19 -0
- package/dist/commands/analytics.js +1 -1
- package/dist/commands/apps.js +369 -27
- package/dist/commands/audit.js +1 -1
- package/dist/commands/billing.js +87 -0
- package/dist/commands/bots.js +1 -1
- package/dist/commands/changelog.js +19 -0
- package/dist/commands/checks.js +4 -3
- package/dist/commands/config.js +9 -6
- package/dist/commands/connect.js +2 -2
- package/dist/commands/db.js +761 -17
- package/dist/commands/dns.js +1 -1
- package/dist/commands/errors.js +1 -1
- package/dist/commands/events.js +15 -3
- package/dist/commands/experiments.js +105 -0
- package/dist/commands/flags.js +22 -3
- package/dist/commands/heartbeats.js +3 -3
- package/dist/commands/images.js +1 -1
- package/dist/commands/jobs.js +39 -4
- package/dist/commands/links.js +59 -0
- package/dist/commands/logs.js +1 -1
- package/dist/commands/members.js +26 -1
- package/dist/commands/network.js +28 -0
- package/dist/commands/notices.js +24 -0
- package/dist/commands/notifications.js +2 -2
- package/dist/commands/otel.js +1 -1
- package/dist/commands/pricing.js +37 -0
- package/dist/commands/projects.js +1 -1
- package/dist/commands/queues.js +4 -3
- package/dist/commands/redis.js +80 -2
- package/dist/commands/registry.js +58 -3
- package/dist/commands/rewards.js +92 -14
- package/dist/commands/sandboxes.js +507 -2
- package/dist/commands/speed.js +1 -1
- package/dist/commands/spend.js +1 -1
- package/dist/commands/status.js +1 -1
- package/dist/commands/storage.js +51 -3
- package/dist/commands/support.js +47 -0
- package/dist/commands/tokens.js +7 -3
- package/dist/commands/up.js +6 -2
- package/dist/commands/waf.js +1 -1
- package/dist/commands/webhooks.js +1 -1
- package/dist/commands/wordpress.js +4 -3
- package/dist/commands/workflows.js +4 -3
- package/dist/esperar.js +41 -0
- package/dist/help.js +14 -1
- package/dist/index.js +26 -6
- package/dist/manifest.js +29 -12
- package/dist/output.js +1 -0
- package/dist/proyecto.js +6 -0
- package/dist/registry-flags.js +17 -0
- package/dist/registry.js +8 -2
- package/package.json +1 -1
- package/dist/commands/ai.js +0 -56
package/dist/commands/apps.js
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
2
3
|
import { api } from '../api.js';
|
|
3
|
-
import { output, green } from '../output.js';
|
|
4
|
+
import { output, green, yellow, red, dim } from '../output.js';
|
|
5
|
+
import { esperarDesenlace, finalDelRegistro, debeEsperar } from '../esperar.js';
|
|
6
|
+
import { credencialRegistryDeFlags } from '../registry-flags.js';
|
|
7
|
+
import { proyectoDeFlags } from '../proyecto.js';
|
|
8
|
+
/**
|
|
9
|
+
* Espera al desenlace de un despliegue y lo cuenta (ficha f76082de): el progreso, y al final la URL o el error con el
|
|
10
|
+
* final del registro. Un fallo deja exit code 1; agotar la espera no es un fallo (el despliegue sigue) y lo dice.
|
|
11
|
+
*/
|
|
12
|
+
async function esperarYContar(appId, depId, plazoMin, json) {
|
|
13
|
+
const leer = async () => {
|
|
14
|
+
const l = ((await api(`/apps/${encodeURIComponent(appId)}/deployments`)).deployments ?? []);
|
|
15
|
+
return depId ? l.find((x) => x.id === depId) : l[0];
|
|
16
|
+
};
|
|
17
|
+
const r = await esperarDesenlace({
|
|
18
|
+
leer, dormir: (ms) => new Promise((ok) => setTimeout(ok, ms)), ahora: () => Date.now(), plazoMs: plazoMin * 60_000,
|
|
19
|
+
alCambiar: json ? undefined : (e) => console.log(dim(` · ${e}`)),
|
|
20
|
+
});
|
|
21
|
+
const url = r.final?.status === 'live' ? ((await api(`/apps/${encodeURIComponent(appId)}`)).app?.url ?? null) : null;
|
|
22
|
+
if (json) {
|
|
23
|
+
console.log(JSON.stringify({ deploymentId: r.final?.id ?? depId ?? null, appId, status: r.final?.status ?? 'unknown', url, error: r.final?.error ?? null, timedOut: r.agotado }, null, 2));
|
|
24
|
+
}
|
|
25
|
+
else if (r.agotado) {
|
|
26
|
+
console.log(yellow(`… still ${r.final?.status ?? 'starting'} after ${plazoMin} min — it keeps going. Follow it: koigrid apps deployments ${appId}`));
|
|
27
|
+
}
|
|
28
|
+
else if (r.final?.status === 'live') {
|
|
29
|
+
console.log(green(`✓ Live: ${url ?? '(no URL yet)'}`));
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
console.log(red(`✗ Deployment ${r.final?.status}${r.final?.error ? `: ${r.final.error}` : ''}`));
|
|
33
|
+
const fin = finalDelRegistro(r.final?.logs);
|
|
34
|
+
if (fin)
|
|
35
|
+
console.log(dim(`--- last lines of the build/deploy log ---\n${fin}`));
|
|
36
|
+
console.log(dim(`Full logs: koigrid apps logs ${appId} --type build`));
|
|
37
|
+
}
|
|
38
|
+
if (!r.agotado && r.final?.status !== 'live')
|
|
39
|
+
process.exitCode = 1;
|
|
40
|
+
}
|
|
4
41
|
export async function apps(a) {
|
|
5
42
|
const json = !!a.flags.json, sub = a.sub || 'ls';
|
|
6
43
|
const id = a.positionals[0];
|
|
@@ -18,15 +55,7 @@ export async function apps(a) {
|
|
|
18
55
|
const dir = a.flags.dir; // deploy desde un directorio LOCAL (código privado, sin git/Docker)
|
|
19
56
|
const repoToken = a.flags['repo-token']; // token/deploy-key para repos privados
|
|
20
57
|
// Registry PRIVADO (imagen inmutable de CI: build en CI → koigrid la corre): credenciales para el pull.
|
|
21
|
-
const
|
|
22
|
-
const registryUsername = a.flags['registry-user'];
|
|
23
|
-
const registryPassword = a.flags['registry-password'];
|
|
24
|
-
const registryAwsRegion = a.flags['registry-aws-region']; // ECR: token fresco por deploy
|
|
25
|
-
const registryAwsAccessKeyId = a.flags['registry-aws-key'];
|
|
26
|
-
const registryAwsSecretKey = a.flags['registry-aws-secret'];
|
|
27
|
-
const reg = registry && registryUsername && registryPassword ? { registry, registryUsername, registryPassword }
|
|
28
|
-
: registry && registryAwsRegion && registryAwsAccessKeyId && registryAwsSecretKey ? { registry, registryAwsRegion, registryAwsAccessKeyId, registryAwsSecretKey }
|
|
29
|
-
: {};
|
|
58
|
+
const reg = credencialRegistryDeFlags(a); // compartido con `jobs` (cli/src/registry-flags.ts)
|
|
30
59
|
const healthPath = a.flags['health-path']; // ruta de salud (/api/health) → koigrid detecta apps rotas
|
|
31
60
|
const hc = healthPath ? { healthCheckPath: healthPath } : {};
|
|
32
61
|
// Build settings (git/dir): overridean lo que detecta nixpacks. Un koigrid.json en el repo tiene prioridad.
|
|
@@ -41,13 +70,46 @@ export async function apps(a) {
|
|
|
41
70
|
bs.rootDirectory = a.flags['root-dir'];
|
|
42
71
|
if (a.flags['node-version'])
|
|
43
72
|
bs.nodeVersion = a.flags['node-version'];
|
|
73
|
+
if (a.flags.branch)
|
|
74
|
+
bs.branch = a.flags.branch; // rama a clonar (repo); sin ella, main
|
|
75
|
+
if (a.flags.dockerfile)
|
|
76
|
+
bs.dockerfilePath = a.flags.dockerfile; // otro Dockerfile que el de la raíz de build
|
|
77
|
+
if (a.flags['release-cmd'])
|
|
78
|
+
bs.releaseCommand = a.flags['release-cmd']; // fase de release (migraciones), antes de arrancar la versión nueva
|
|
79
|
+
// Tamaño AL CREAR (POST /apps ya lo admitía): sin esto había que crear y luego `apps resize`, o sea dos
|
|
80
|
+
// despliegues, y el primero arrancaba con la memoria por defecto (un Chromium no cabe en ella).
|
|
81
|
+
const tam = {};
|
|
82
|
+
if (a.flags.memory)
|
|
83
|
+
tam.memoryMb = Number(a.flags.memory);
|
|
84
|
+
if (a.flags.cpus)
|
|
85
|
+
tam.cpus = Number(a.flags.cpus);
|
|
86
|
+
// ENTRADA: por defecto la app la sirve el EDGE CENTRAL (su DNS apunta al VIP, no a la máquina). El opt-out
|
|
87
|
+
// es declarado y va al crear, porque cambiarla después es una transición ordenada, no una bandera.
|
|
88
|
+
const ing = a.flags.ingress === 'runner' ? { ingress: 'runner' } : {};
|
|
89
|
+
if (a.flags.ingress !== undefined && a.flags.ingress !== 'runner' && a.flags.ingress !== 'edge')
|
|
90
|
+
throw new Error("--ingress must be 'edge' (default) or 'runner'");
|
|
44
91
|
if (!name || (!image && !repo && !dir))
|
|
45
|
-
throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--repo-token <t>] [--port N] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V]');
|
|
92
|
+
throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--branch B] [--repo-token <t>] [--port N] [--ingress edge|runner] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--release-cmd C] [--memory <mb>] [--cpus <n>] [--project <id>] [--env KEY=VALUE ...] [--env-target all|production|preview]');
|
|
46
93
|
const port = a.flags.port ? Number(a.flags.port) : 3000;
|
|
94
|
+
// Esperar al desenlace (ficha f76082de): por defecto sí (personas y agentes), --json sólo con --wait, --no-wait nunca.
|
|
95
|
+
const esperar = debeEsperar(a.flags, json);
|
|
96
|
+
const plazoMin = a.flags.timeout ? Math.max(1, Number(a.flags.timeout)) : 20;
|
|
97
|
+
// --env KEY=VAL (repetible): el entorno viaja CON la creación, así que el primer despliegue ya sale con él
|
|
98
|
+
// (ficha d62bcde4). Antes había que crear, fijar variables y redesplegar: el primer despliegue fallaba siempre.
|
|
99
|
+
const envPares = [].concat(a.flags.env ?? []);
|
|
100
|
+
const env = {};
|
|
101
|
+
for (const par of envPares) {
|
|
102
|
+
const i = par.indexOf('=');
|
|
103
|
+
if (i <= 0)
|
|
104
|
+
throw new Error(`--env needs KEY=VALUE (got "${par}")`);
|
|
105
|
+
env[par.slice(0, i)] = par.slice(i + 1);
|
|
106
|
+
}
|
|
107
|
+
const en = envPares.length ? { env, ...(a.flags['env-target'] ? { envTarget: a.flags['env-target'] } : {}) } : {};
|
|
47
108
|
// deploy --dir: empaqueta el directorio (excluye lo pesado/irrelevante) → subida presignada a koigrid →
|
|
48
109
|
// el runner lo construye igual que un repo. No requiere git ni Docker local.
|
|
49
110
|
if (dir) {
|
|
50
|
-
|
|
111
|
+
// `sourceType: 'archive'` (ficha 828d84dd): la app nace esperando su código, y así lo dice desde el primer momento.
|
|
112
|
+
const app = await api('/apps', { method: 'POST', body: { name, sourceType: 'archive', port, ...hc, ...bs, ...tam, ...ing, ...en, ...proyectoDeFlags(a) } });
|
|
51
113
|
const aid = app.app?.id || app.id;
|
|
52
114
|
const up = await api(`/apps/${encodeURIComponent(aid)}/source-upload`, { method: 'POST', body: {} });
|
|
53
115
|
const { uploadUrl, archiveKey } = up.upload;
|
|
@@ -59,12 +121,36 @@ export async function apps(a) {
|
|
|
59
121
|
const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: { sourceType: 'archive', archiveKey } });
|
|
60
122
|
// Devuelve el ID del DEPLOYMENT (el que aparece en GET /apps/:id/deployments), NO el del app — evita la
|
|
61
123
|
// confusión "ids CLI≠API" del journey. appId aparte, etiquetado.
|
|
62
|
-
|
|
124
|
+
if (!json)
|
|
125
|
+
console.log(green(`✓ Deploying "${name}" from ${dir}… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
|
|
126
|
+
if (esperar)
|
|
127
|
+
return esperarYContar(aid, d.deployment?.id, plazoMin, json);
|
|
128
|
+
return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued', source: 'dir' }, null, 2)) : undefined;
|
|
63
129
|
}
|
|
64
|
-
const app = await api('/apps', { method: 'POST', body: repo ? { name, sourceType: 'git', repo, port, ...(repoToken ? { repoToken } : {}), ...hc, ...bs } : { name, sourceType: 'image', image, port, ...hc, ...reg } });
|
|
130
|
+
const app = await api('/apps', { method: 'POST', body: { ...proyectoDeFlags(a), ...(repo ? { name, sourceType: 'git', repo, port, ...(repoToken ? { repoToken } : {}), ...hc, ...bs, ...tam, ...ing, ...en } : { name, sourceType: 'image', image, port, ...hc, ...tam, ...reg, ...ing, ...en }) } });
|
|
65
131
|
const aid = app.app?.id || app.id;
|
|
132
|
+
// ⚠️ Una app de IMAGEN se despliega SOLA al crearse. Lanzar aquí otro despliegue daba DOS por cada `apps deploy
|
|
133
|
+
// --image`, que chocaban entre sí (ficha d62bcde4). Con imagen se informa del automático; con repo se lanza.
|
|
134
|
+
if (!repo) {
|
|
135
|
+
// El automático se lanza en segundo plano al crear: se espera hasta ~15 s a que aparezca para devolver su id,
|
|
136
|
+
// que es lo que devolvía este comando (un guion que lea `deploymentId` del --json no debe romperse).
|
|
137
|
+
let auto;
|
|
138
|
+
for (let i = 0; i < 15 && !auto; i++) {
|
|
139
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
140
|
+
auto = ((await api(`/apps/${encodeURIComponent(aid)}/deployments`)).deployments ?? [])[0];
|
|
141
|
+
}
|
|
142
|
+
if (!json)
|
|
143
|
+
console.log(green(`✓ Deploying "${name}"… (deployment ${String(auto?.id || '').slice(0, 8) || 'starting'}, automatic on create)`));
|
|
144
|
+
if (esperar)
|
|
145
|
+
return esperarYContar(aid, auto?.id, plazoMin, json);
|
|
146
|
+
return json ? console.log(JSON.stringify({ deploymentId: auto?.id ?? null, appId: aid, status: auto?.status || 'queued', automatic: true }, null, 2)) : undefined;
|
|
147
|
+
}
|
|
66
148
|
const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: {} });
|
|
67
|
-
|
|
149
|
+
if (!json)
|
|
150
|
+
console.log(green(`✓ Deploying "${name}"… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
|
|
151
|
+
if (esperar)
|
|
152
|
+
return esperarYContar(aid, d.deployment?.id, plazoMin, json);
|
|
153
|
+
return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued' }, null, 2)) : undefined;
|
|
68
154
|
}
|
|
69
155
|
case 'deployments':
|
|
70
156
|
need('');
|
|
@@ -73,9 +159,38 @@ export async function apps(a) {
|
|
|
73
159
|
const l = r.deployments || r || [];
|
|
74
160
|
return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), status: x.status, source: x.source || '—' })), columns: ['id', 'status', 'source'] });
|
|
75
161
|
}
|
|
76
|
-
case 'logs':
|
|
162
|
+
case 'logs': {
|
|
77
163
|
need('');
|
|
78
|
-
|
|
164
|
+
// Los mismos filtros que la API (ficha d53876c6): --since/--until (ISO UTC), --replica, --runner, --q y --type build.
|
|
165
|
+
const qs = new URLSearchParams({ tail: String(a.flags.tail || 200) });
|
|
166
|
+
for (const k of ['type', 'since', 'until', 'replica', 'runner', 'q'])
|
|
167
|
+
if (typeof a.flags[k] === 'string' && a.flags[k])
|
|
168
|
+
qs.set(k, String(a.flags[k]));
|
|
169
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/logs?${qs}`);
|
|
170
|
+
return console.log(json ? JSON.stringify(r, null, 2) : r.logs || '');
|
|
171
|
+
}
|
|
172
|
+
// Lo que vio el PROXY (ficha 7d10e8b8): peticiones, 5xx por código y las rutas que fallaron — también los 502/504
|
|
173
|
+
// que la app nunca registra. --hours (1-840, def. 24; más de 168 pide --bucket 1h|6h|1d) · --bucket 1m|5m|15m|1h|6h|1d (def. 5m).
|
|
174
|
+
case 'http': {
|
|
175
|
+
need(' [--hours 24] [--bucket 5m]');
|
|
176
|
+
const q = new URLSearchParams();
|
|
177
|
+
if (a.flags.hours)
|
|
178
|
+
q.set('hours', String(a.flags.hours));
|
|
179
|
+
if (a.flags.bucket)
|
|
180
|
+
q.set('bucket', String(a.flags.bucket));
|
|
181
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/http${q.size ? `?${q}` : ''}`);
|
|
182
|
+
if (json)
|
|
183
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
184
|
+
const t = r.totals || {};
|
|
185
|
+
const codigos = Object.entries(t.byStatus || {}).map(([c, n]) => `${c}×${n}`).join(' ');
|
|
186
|
+
console.log(`${r.hours} h · ${t.requests ?? 0} requests · ${t.errors5xx ?? 0} 5xx${codigos ? ` (${codigos})` : ''} · availability ${t.availabilityPct ?? '—'}%`);
|
|
187
|
+
output(r.series || [], false, { rows: (r.series || []).filter((p) => p.errors5xx > 0).map((p) => ({ at: String(p.at), requests: String(p.requests), '5xx': String(p.errors5xx), 'err%': String(p.errorPct ?? '—'), p99max: String(p.p99MaxMs ?? '—') })), columns: ['at', 'requests', '5xx', 'err%', 'p99max'] });
|
|
188
|
+
if ((r.errors || []).length) {
|
|
189
|
+
console.log(`\nlatest 5xx${r.errorsOmitted ? ` (+${r.errorsOmitted} not kept individually)` : ''}:`);
|
|
190
|
+
output(r.errors, false, { rows: r.errors.slice(0, 50).map((e) => ({ at: String(e.at), status: String(e.status), method: String(e.method || '—'), path: String(e.path || '—'), ms: String(e.durationMs ?? '—') })), columns: ['at', 'status', 'method', 'path', 'ms'] });
|
|
191
|
+
}
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
79
194
|
case 'rm':
|
|
80
195
|
case 'delete':
|
|
81
196
|
need('');
|
|
@@ -89,8 +204,19 @@ export async function apps(a) {
|
|
|
89
204
|
await api(`/apps/${encodeURIComponent(id)}/rollback`, { method: 'POST', body: { deploymentId: d } });
|
|
90
205
|
return console.log(green('✓ Rolling back…'));
|
|
91
206
|
}
|
|
92
|
-
|
|
93
|
-
|
|
207
|
+
// Pausar/reanudar: apaga el cómputo sin perder nada (config, env, dominios, historial, volúmenes).
|
|
208
|
+
case 'pause': {
|
|
209
|
+
need('');
|
|
210
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/pause`, { method: 'POST', body: {} });
|
|
211
|
+
return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(r.alreadyPaused ? `✓ ${id} ya estaba pausada` : `✓ Paused ${id} — se conserva todo; reanuda con: koigrid apps resume ${id}`));
|
|
212
|
+
}
|
|
213
|
+
case 'resume': {
|
|
214
|
+
need('');
|
|
215
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/resume`, { method: 'POST', body: {} });
|
|
216
|
+
return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(r.wasPaused ? (r.redeployed ? `✓ Resuming ${id}… (relanzando la última imagen)` : `✓ ${id} reanudada (nunca tuvo un deploy vivo: despliega con: koigrid apps deploy)`) : `✓ ${id} no estaba pausada`));
|
|
217
|
+
}
|
|
218
|
+
case 'loadtest': { // reporte de capacidad: rps + p50/p95/p99 + rodilla + señales del servidor (docs/platform/CAPACITY.md)
|
|
219
|
+
need(' [--duration <s≤600>] [--concurrency <n≤100>] [--path /] [--ramp] [--stages 3] [--warmup 3] [--paths \'[{"path":"/","weight":3}]\'] [--header "X-Origin-Verify: <secreto>"]…');
|
|
94
220
|
const body = {};
|
|
95
221
|
if (a.flags.duration !== undefined)
|
|
96
222
|
body.durationSec = Number(a.flags.duration);
|
|
@@ -98,11 +224,41 @@ export async function apps(a) {
|
|
|
98
224
|
body.concurrency = Number(a.flags.concurrency);
|
|
99
225
|
if (a.flags.path !== undefined)
|
|
100
226
|
body.path = String(a.flags.path);
|
|
227
|
+
if (a.flags.ramp)
|
|
228
|
+
body.mode = 'ramp';
|
|
229
|
+
if (a.flags.stages !== undefined)
|
|
230
|
+
body.stages = Number(a.flags.stages);
|
|
231
|
+
if (a.flags.warmup !== undefined)
|
|
232
|
+
body.warmupSec = Number(a.flags.warmup);
|
|
233
|
+
if (a.flags.paths !== undefined)
|
|
234
|
+
body.paths = JSON.parse(String(a.flags.paths));
|
|
235
|
+
// --header "Nombre: valor", repetible: p. ej. el secreto de origen que exige tu CDN (si no, sólo se mide un 403).
|
|
236
|
+
if (a.flags.header !== undefined) {
|
|
237
|
+
const headers = {};
|
|
238
|
+
for (const h of [].concat(a.flags.header)) {
|
|
239
|
+
const linea = String(h);
|
|
240
|
+
const i = linea.indexOf(':');
|
|
241
|
+
if (i <= 0)
|
|
242
|
+
throw new Error(`--header necesita "Nombre: valor" (recibido sin «:»)`);
|
|
243
|
+
headers[linea.slice(0, i).trim()] = linea.slice(i + 1).trim();
|
|
244
|
+
}
|
|
245
|
+
body.headers = headers;
|
|
246
|
+
}
|
|
101
247
|
const r = await api(`/apps/${encodeURIComponent(id)}/loadtest`, { method: 'POST', body });
|
|
102
248
|
if (a.flags.json)
|
|
103
249
|
return console.log(JSON.stringify(r, null, 2));
|
|
104
250
|
console.log(green(`✓ load-test ${r.app} (${r.target})`));
|
|
251
|
+
if (r.headersSent?.length)
|
|
252
|
+
console.log(` cabeceras enviadas: ${r.headersSent.join(', ')}`);
|
|
105
253
|
console.log(` ${r.requests} reqs · ~${Math.round(r.rps)} req/s · p50 ${Math.round(r.p50)}ms · p95 ${Math.round(r.p95)}ms · p99 ${Math.round(r.p99)}ms · errores ${(r.errorRate * 100).toFixed(1)}%`);
|
|
254
|
+
if (r.coldStartP95 != null)
|
|
255
|
+
console.log(` arranque en frío (excluido del p95): ${r.coldStartP95}ms`);
|
|
256
|
+
if (r.stages) {
|
|
257
|
+
console.log(' escalones:');
|
|
258
|
+
for (const s of r.stages)
|
|
259
|
+
console.log(` ${String(s.concurrency).padStart(3)} simultáneos → ${Math.round(s.rps)} req/s · p95 ${Math.round(s.p95)}ms · errores ${(s.errorRate * 100).toFixed(1)}%`);
|
|
260
|
+
console.log(` rodilla: ${r.knee?.concurrency ?? '—'}${r.knee?.concurrency ? ' simultáneos' : ''}`);
|
|
261
|
+
}
|
|
106
262
|
return console.log(` ${r.saturated ? '⚠ ' : '✓ '}${r.note}`);
|
|
107
263
|
}
|
|
108
264
|
case 'restore': {
|
|
@@ -150,8 +306,34 @@ export async function apps(a) {
|
|
|
150
306
|
const r = await api(`/apps/${encodeURIComponent(id)}/autoscale`, { method: 'PUT', body });
|
|
151
307
|
return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Autoscale updated'));
|
|
152
308
|
}
|
|
309
|
+
case 'scale-out': {
|
|
310
|
+
// Sirve la app por el edge central en vez de por el Caddy de su runner. Es lo que hace que se APLIQUEN
|
|
311
|
+
// las reglas (redirect/rewrite/header) de una app en un runner heredado.
|
|
312
|
+
need(' --enabled true|false');
|
|
313
|
+
if (a.flags.enabled === undefined) {
|
|
314
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/scale-out`);
|
|
315
|
+
return console.log(json ? JSON.stringify(r, null, 2) : JSON.stringify(r.scaleOut));
|
|
316
|
+
}
|
|
317
|
+
const body = { enabled: a.flags.enabled === 'true' || a.flags.enabled === true };
|
|
318
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/scale-out`, { method: 'PUT', body });
|
|
319
|
+
if (json)
|
|
320
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
321
|
+
// Apagar NO es inmediato ni es un flag: es una transición en segundo plano (ficha 0d3557e1). Decir
|
|
322
|
+
// «✓ disabled» aquí sería exactamente el tipo de mensaje que este repo persigue —algo declarado hecho sin
|
|
323
|
+
// estarlo—, así que se dice lo que de verdad ha pasado y cómo mirar en qué acaba.
|
|
324
|
+
if (r.transition?.state === 'in_progress') {
|
|
325
|
+
return console.log(`→ Scale-out is being turned off (deployment ${r.transition.deploymentId}).
|
|
326
|
+
` +
|
|
327
|
+
` The app keeps being served while it happens; replicas are removed only after its runner is verified.
|
|
328
|
+
` +
|
|
329
|
+
` Follow it: koigrid apps scale-out ${id} (enabled:false = done)
|
|
330
|
+
` +
|
|
331
|
+
` koigrid events --limit 5 (why, if it kept the replicas)`);
|
|
332
|
+
}
|
|
333
|
+
return console.log(green(`✓ Scale-out ${body.enabled ? 'enabled' : 'disabled'} — ${r.note ?? ''}`));
|
|
334
|
+
}
|
|
153
335
|
case 'env': {
|
|
154
|
-
need(' set KEY=VAL [--target production|preview|all] | rm KEY | ls');
|
|
336
|
+
need(' set KEY=VAL [--target production|preview|all] | replace KEY=VAL ... | rm KEY | ls | verify [KEY] [--value <v>]');
|
|
155
337
|
const act = a.positionals[1];
|
|
156
338
|
if (!act || act === 'ls') {
|
|
157
339
|
const r = await api(`/apps/${encodeURIComponent(id)}/env`);
|
|
@@ -176,13 +358,59 @@ export async function apps(a) {
|
|
|
176
358
|
await api(`/apps/${encodeURIComponent(id)}/env`, { method: 'POST', body: { env: { [k]: v.join('=') }, target } });
|
|
177
359
|
return console.log(green(`✓ Set ${k} [${target}] (redeploying)`));
|
|
178
360
|
}
|
|
179
|
-
|
|
361
|
+
// replace: la lista dada pasa a ser el entorno ENTERO de la app (las guardadas que no estén se borran, en la misma
|
|
362
|
+
// transacción) y se despliega. Es la forma de quitar una referencia ${{…}} a un recurso que ya no existe sin
|
|
363
|
+
// ir variable a variable: así se despublicó vencecolombia.co el 2026-10-10.
|
|
364
|
+
if (act === 'replace') {
|
|
365
|
+
const pares = a.positionals.slice(2);
|
|
366
|
+
if (!pares.length)
|
|
367
|
+
throw new Error('need KEY=VALUE ... (the full environment)');
|
|
368
|
+
const env = {};
|
|
369
|
+
for (const par of pares) {
|
|
370
|
+
const i = par.indexOf('=');
|
|
371
|
+
if (i <= 0)
|
|
372
|
+
throw new Error(`need KEY=VALUE (got "${par}")`);
|
|
373
|
+
env[par.slice(0, i)] = par.slice(i + 1);
|
|
374
|
+
}
|
|
375
|
+
const target = a.flags.target || 'all';
|
|
376
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/deployments`, { method: 'POST', body: { env, envTarget: target, envMode: 'replace' } });
|
|
377
|
+
return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(`✓ Environment replaced (${Object.keys(env).length} vars, [${target}]) — deploying ${String(r.deployment?.id || '').slice(0, 8)}`));
|
|
378
|
+
}
|
|
379
|
+
// ⭐ verify: ¿lo que ve el contenedor es lo que crees? Nunca devuelve valores — compara huellas.
|
|
380
|
+
// Con `--value` el sha256 se calcula AQUÍ, en tu máquina: el secreto no sale de ella.
|
|
381
|
+
if (act === 'verify') {
|
|
382
|
+
const k = a.positionals[2];
|
|
383
|
+
const val = a.flags.value;
|
|
384
|
+
const sha = val !== undefined ? createHash('sha256').update(val, 'utf8').digest('hex') : a.flags.sha256;
|
|
385
|
+
if (sha && !k)
|
|
386
|
+
throw new Error('--value/--sha256 necesitan la KEY: koigrid apps env <id> verify KEY --value <valor>');
|
|
387
|
+
const qs = new URLSearchParams();
|
|
388
|
+
if (k)
|
|
389
|
+
qs.set('key', k);
|
|
390
|
+
if (sha)
|
|
391
|
+
qs.set('expected', sha);
|
|
392
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/env/verify${qs.toString() ? `?${qs}` : ''}`);
|
|
393
|
+
if (json)
|
|
394
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
395
|
+
if (!r.reachable)
|
|
396
|
+
console.log('⚠️ no se pudo preguntar al contenedor (¿la app está desplegada y en marcha?)');
|
|
397
|
+
for (const v of r.vars || []) {
|
|
398
|
+
const estado = !v.present ? '✗ no llega al contenedor' : v.matchesConfigured === false ? '⚠ distinta de la guardada (falta desplegar)' : v.matchesConfigured ? '✓ al día' : '· presente';
|
|
399
|
+
console.log(`${v.key}\t[${v.target}]\t${estado}\t${v.fingerprint ?? '-'}`);
|
|
400
|
+
}
|
|
401
|
+
if (r.verdict)
|
|
402
|
+
console.log(`\n${r.verdict.code === 'matches_expected' || r.verdict.code === 'in_sync' ? green('✓') : '→'} ${r.verdict.detail}`);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
throw new Error('usage: koigrid apps env <id> set KEY=VAL [--target production|preview|all] | replace KEY=VAL ... | rm KEY | ls | verify [KEY] [--value <v> | --sha256 <h>]');
|
|
180
406
|
}
|
|
181
407
|
case 'domains': {
|
|
182
|
-
need(' add <domain> | rm <domain> | ls | verify');
|
|
408
|
+
need(' add <domain> | move <domain> | rm <domain> | ls | verify');
|
|
183
409
|
const act = a.positionals[1];
|
|
184
|
-
|
|
185
|
-
const
|
|
410
|
+
// `acme`: la delegación opcional del reto del certificado, para migrar sin corte (cert listo ANTES de apuntar el DNS).
|
|
411
|
+
const cols = ['domain', 'status', 'record', 'acme'];
|
|
412
|
+
const acmeDe = (x) => !x.acme ? '' : !x.acme.supported ? 'n/a (runner ingress)' : `${x.acme.record ? `CNAME ${x.acme.record.name} → ${x.acme.record.value}` : ''}${x.acme.delegated ? ` [delegated${x.acme.certReady ? ', cert ready' : ', issuing'}]` : ''}`;
|
|
413
|
+
const rowsOf = (l) => l.map((x) => (typeof x === 'string' ? { domain: x, status: '', record: '', acme: '' } : { domain: x.domain, status: x.status ?? '', record: x.record ? `${x.record.type} ${x.record.name} → ${x.record.value}` : '', acme: acmeDe(x) }));
|
|
186
414
|
if (!act || act === 'ls') {
|
|
187
415
|
const r = await api(`/apps/${encodeURIComponent(id)}/domains`);
|
|
188
416
|
const l = r.domains || r || [];
|
|
@@ -198,7 +426,7 @@ export async function apps(a) {
|
|
|
198
426
|
if (!d)
|
|
199
427
|
throw new Error('need <domain>');
|
|
200
428
|
const r = await api(`/apps/${encodeURIComponent(id)}/domains`, { method: 'POST', body: { domain: d } });
|
|
201
|
-
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Added ${d} — create DNS: ${r.instructions}`));
|
|
429
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Added ${d} — create DNS: ${r.instructions}`) + (r.acme?.record ? `\n zero-downtime migration (optional): CNAME ${r.acme.record.name} → ${r.acme.record.value} (cert is issued before your DNS points here)` : ''));
|
|
202
430
|
}
|
|
203
431
|
if (act === 'rm') {
|
|
204
432
|
const d = a.positionals[2];
|
|
@@ -207,7 +435,15 @@ export async function apps(a) {
|
|
|
207
435
|
await api(`/apps/${encodeURIComponent(id)}/domains?domain=${encodeURIComponent(d)}`, { method: 'DELETE' });
|
|
208
436
|
return console.log(green(`✓ Removed ${d}`));
|
|
209
437
|
}
|
|
210
|
-
|
|
438
|
+
// Mover un dominio desde otra app de la organización conservando su certificado y su delegación ACME.
|
|
439
|
+
if (act === 'move') {
|
|
440
|
+
const d = a.positionals[2];
|
|
441
|
+
if (!d)
|
|
442
|
+
throw new Error('need <domain>');
|
|
443
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/domains`, { method: 'POST', body: { domain: d, move: true } });
|
|
444
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Moved ${d}${r.movedFrom ? ` from ${r.movedFrom}` : ''} (certificate and ACME delegation kept)`));
|
|
445
|
+
}
|
|
446
|
+
throw new Error('usage: koigrid apps domains <id> add <domain> | move <domain> | rm <domain> | ls | verify');
|
|
211
447
|
}
|
|
212
448
|
case 'volumes': {
|
|
213
449
|
need(' add <name> --size N --mount /path | rm <volId> | ls');
|
|
@@ -264,11 +500,28 @@ export async function apps(a) {
|
|
|
264
500
|
const act = a.positionals[1];
|
|
265
501
|
if (!act) {
|
|
266
502
|
const r = await api(`/apps/${encodeURIComponent(id)}/cdn`);
|
|
267
|
-
return console.log(json ? JSON.stringify(r, null, 2) : `cdn: ${r.cdn?.enabled ? 'on' : 'off'}`);
|
|
503
|
+
return console.log(json ? JSON.stringify(r, null, 2) : `cdn: ${r.cdn?.enabled ? 'on' : 'off'}${r.cdn?.reason ? ` (${r.cdn.reason}: ${r.cdn.detail ?? ''})` : ''}`);
|
|
268
504
|
}
|
|
269
505
|
const r = await api(`/apps/${encodeURIComponent(id)}/cdn`, { method: 'PUT', body: { enabled: act === 'on' } });
|
|
270
506
|
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ CDN ${act}`));
|
|
271
507
|
}
|
|
508
|
+
case 'cache': {
|
|
509
|
+
// Caché compartida del edge (guarda sólo lo que la app marca como cacheable: s-maxage / public). Distinta de `cdn`.
|
|
510
|
+
need(' [on|off|purge]');
|
|
511
|
+
const act = a.positionals[1];
|
|
512
|
+
if (!act) {
|
|
513
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/cache`);
|
|
514
|
+
return console.log(json ? JSON.stringify(r, null, 2) : `edge cache: ${r.cache?.enabled ? 'on' : 'off'}`);
|
|
515
|
+
}
|
|
516
|
+
if (act === 'purge') {
|
|
517
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/cache/purge`, { method: 'POST' });
|
|
518
|
+
return console.log(json ? JSON.stringify(r, null, 2) : r.purged ? green('✓ Edge cache purged') : `purge incomplete: ${(r.nodes || []).filter((n) => !n.ok).map((n) => n.node).join(', ')}`);
|
|
519
|
+
}
|
|
520
|
+
if (act !== 'on' && act !== 'off')
|
|
521
|
+
throw new Error('usage: koigrid apps cache <id> [on|off|purge]');
|
|
522
|
+
const r = await api(`/apps/${encodeURIComponent(id)}/cache`, { method: 'PUT', body: { enabled: act === 'on' } });
|
|
523
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Edge cache ${act}`));
|
|
524
|
+
}
|
|
272
525
|
case 'retention': {
|
|
273
526
|
need(' [<keepLast> | off]');
|
|
274
527
|
const arg = a.positionals[1];
|
|
@@ -426,6 +679,95 @@ export async function apps(a) {
|
|
|
426
679
|
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { name } });
|
|
427
680
|
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ App renamed to "${name}"`));
|
|
428
681
|
}
|
|
682
|
+
case 'health-path': {
|
|
683
|
+
// Ruta de «lista» (readiness) de la app: la puerta del despliegue y el sondeo activo del edge. `off` la quita.
|
|
684
|
+
const ruta = a.positionals[1];
|
|
685
|
+
if (!id || !ruta)
|
|
686
|
+
throw new Error('usage: koigrid apps health-path <appId> </path|off>');
|
|
687
|
+
const healthCheckPath = ruta === 'off' ? null : ruta;
|
|
688
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { healthCheckPath } });
|
|
689
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(healthCheckPath ? `✓ Health path set to ${healthCheckPath}` : '✓ Health path removed'));
|
|
690
|
+
}
|
|
691
|
+
case 'port': {
|
|
692
|
+
// Puerto del contenedor (PORT=<n>, ficha 4d8b02da): se aplica en el siguiente despliegue.
|
|
693
|
+
const n = Number(a.positionals[1]);
|
|
694
|
+
if (!id || !Number.isInteger(n) || n < 1 || n > 65535)
|
|
695
|
+
throw new Error('usage: koigrid apps port <appId> <1-65535>');
|
|
696
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { port: n } });
|
|
697
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Port set to ${n} (applies on the next deploy)`));
|
|
698
|
+
}
|
|
699
|
+
case 'release': {
|
|
700
|
+
// FASE DE RELEASE (como Heroku release / Fly release_command): corre una vez por despliegue, con la imagen y el
|
|
701
|
+
// entorno de la app, ANTES de arrancar la versión nueva. Se aplica en el siguiente despliegue. `off` la quita.
|
|
702
|
+
const orden = a.positionals.slice(1).join(' ');
|
|
703
|
+
if (!id || !orden)
|
|
704
|
+
throw new Error('usage: koigrid apps release <appId> <command|off> (e.g. "npx prisma migrate deploy")');
|
|
705
|
+
const releaseCommand = orden === 'off' ? null : orden;
|
|
706
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { releaseCommand } });
|
|
707
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(releaseCommand ? `✓ Release command set; it runs on the next deploy, before the new version starts` : '✓ Release command removed'));
|
|
708
|
+
}
|
|
709
|
+
case 'build-settings': {
|
|
710
|
+
// Ajustes de build de una app EXISTENTE (antes sólo al crearla). Se aplican en el siguiente despliegue; `off` quita uno.
|
|
711
|
+
const mapa = { 'build-cmd': 'buildCommand', 'install-cmd': 'installCommand', 'start-cmd': 'startCommand', 'root-dir': 'rootDirectory', 'node-version': 'nodeVersion', dockerfile: 'dockerfilePath', 'release-cmd': 'releaseCommand' };
|
|
712
|
+
const body = {};
|
|
713
|
+
for (const [flag, campo] of Object.entries(mapa))
|
|
714
|
+
if (typeof a.flags[flag] === 'string')
|
|
715
|
+
body[campo] = a.flags[flag] === 'off' ? null : a.flags[flag];
|
|
716
|
+
if (!id || !Object.keys(body).length)
|
|
717
|
+
throw new Error('usage: koigrid apps build-settings <appId> [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--release-cmd C] (value "off" removes it; applies on the next deploy)');
|
|
718
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body });
|
|
719
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Build settings saved (${Object.keys(body).join(', ')}); they apply on the next deploy`));
|
|
720
|
+
}
|
|
721
|
+
case 'traffic-ramp': {
|
|
722
|
+
// Traspaso gradual al desplegar: N segundos para pasar los clientes de la versión anterior a la nueva. `off` = de golpe.
|
|
723
|
+
const v = a.positionals[1];
|
|
724
|
+
if (!id || !v)
|
|
725
|
+
throw new Error('usage: koigrid apps traffic-ramp <appId> <seconds 30-600|off>');
|
|
726
|
+
const trafficRampSeconds = v === 'off' ? 0 : Number(v);
|
|
727
|
+
if (!Number.isInteger(trafficRampSeconds))
|
|
728
|
+
throw new Error('seconds must be an integer between 30 and 600, or off');
|
|
729
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { trafficRampSeconds } });
|
|
730
|
+
return console.log(json ? JSON.stringify(r, null, 2) : green(trafficRampSeconds ? `✓ Deploys will shift traffic gradually over ${trafficRampSeconds} s` : '✓ Deploys will switch traffic at once'));
|
|
731
|
+
}
|
|
732
|
+
case 'max-surge': {
|
|
733
|
+
// Despliegue por tandas: como mucho N réplicas nuevas a la vez junto a las viejas (maxSurge de Kubernetes). `off` = sin límite.
|
|
734
|
+
const v = a.positionals[1];
|
|
735
|
+
if (!id || !v)
|
|
736
|
+
throw new Error('usage: koigrid apps max-surge <appId> <replicas 1-100|off>');
|
|
737
|
+
const maxSurge = v === 'off' ? 0 : Number(v);
|
|
738
|
+
if (!Number.isInteger(maxSurge) || maxSurge < 0 || maxSurge > 100)
|
|
739
|
+
throw new Error('replicas must be an integer between 1 and 100, or off');
|
|
740
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { maxSurge } });
|
|
741
|
+
if (json)
|
|
742
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
743
|
+
// Lo que dice el SERVIDOR que hará (deployBatches), no lo que se pidió: se sube para no pasar del tope de tandas
|
|
744
|
+
// y fuera del reparto del edge no hay tandas.
|
|
745
|
+
const b = r.app?.deployBatches;
|
|
746
|
+
console.log(green(maxSurge ? `✓ maxSurge ${maxSurge} saved` : '✓ Deploys will start all new replicas at once when they fit'));
|
|
747
|
+
if (b && maxSurge && b.applies && b.effectiveMaxSurge)
|
|
748
|
+
console.log(` Redeploys: ${b.batches} batch(es) of up to ${b.effectiveMaxSurge} replica(s)`);
|
|
749
|
+
if (b?.note)
|
|
750
|
+
console.log(yellow(` ⚠ ${b.note}`));
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
case 'deploy-analysis': {
|
|
754
|
+
// Análisis entre tandas: tras cada tanda se observan N s y se deshace si las réplicas nuevas dan claramente más 5xx
|
|
755
|
+
// que las viejas a la vez (Kayenta/Flagger). `off` = apagado.
|
|
756
|
+
const v = a.positionals[1];
|
|
757
|
+
if (!id || !v)
|
|
758
|
+
throw new Error('usage: koigrid apps deploy-analysis <appId> <seconds 30-600|off>');
|
|
759
|
+
const deployAnalysisSeconds = v === 'off' ? 0 : Number(v);
|
|
760
|
+
if (!Number.isInteger(deployAnalysisSeconds))
|
|
761
|
+
throw new Error('seconds must be an integer between 30 and 600, or off');
|
|
762
|
+
const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { deployAnalysisSeconds } });
|
|
763
|
+
if (json)
|
|
764
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
765
|
+
const b = r.app?.deployBatches;
|
|
766
|
+
console.log(green(deployAnalysisSeconds ? `✓ Batched deploys will watch ${deployAnalysisSeconds} s of traffic after each batch` : '✓ Deploy analysis off'));
|
|
767
|
+
if (b?.analysisNote)
|
|
768
|
+
console.log(` ${b.analysisNote}`);
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
429
771
|
default: throw new Error(`unknown: apps ${sub}`);
|
|
430
772
|
}
|
|
431
773
|
}
|
package/dist/commands/audit.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { api } from '../api.js';
|
|
2
2
|
import { output } from '../output.js';
|
|
3
3
|
// koigrid audit — Audit Log (quién hizo qué, con IP y fecha). Sustituto de AWS CloudTrail. owner/admin only.
|
|
4
|
-
// Ver docs/AUDIT-LOG.md.
|
|
4
|
+
// Ver docs/products/AUDIT-LOG.md.
|
|
5
5
|
// koigrid audit ls [--category members,security] [--type token.created] [--actor-type agent] [--since 30] [--limit 100]
|
|
6
6
|
// koigrid audit export [mismos filtros] > audit.csv
|
|
7
7
|
export async function audit(a) {
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { api } from '../api.js';
|
|
2
|
+
import { green, dim } from '../output.js';
|
|
3
|
+
// koigrid billing — cómo paga la organización y el TRASPASO al pago. Ver docs/products/BILLING.md.
|
|
4
|
+
//
|
|
5
|
+
// Desde los precios por recurso (ficha 91d809ff) ya no hay planes que comprar: se paga lo reservado por horas a la
|
|
6
|
+
// tarjeta guardada. `card` no cobra: pide al proveedor el enlace para GUARDAR una tarjeta y lo imprime, porque un
|
|
7
|
+
// agente puede conducir toda una migración por API y se paraba justo aquí — el único paso que no puede dar él.
|
|
8
|
+
export async function billing(a) {
|
|
9
|
+
const json = !!a.flags.json;
|
|
10
|
+
const sub = a.sub || 'show';
|
|
11
|
+
if (sub === 'show' || sub === 'status') {
|
|
12
|
+
const r = await api('/billing');
|
|
13
|
+
if (json)
|
|
14
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
15
|
+
const modo = { free: 'gratis (sin tarjeta)', card: 'tarjeta guardada', granted: 'concedido por koigrid (no paga)', legacy_plan: `plan antiguo '${r.plan}'` };
|
|
16
|
+
console.log(`pago: ${modo[r.paymentMode] ?? r.paymentMode}${r.cardSetupAvailable || r.cardOnFile ? '' : dim(' (cobro con tarjeta no configurado)')}`);
|
|
17
|
+
console.log(`reservado este mes (desde ${r.monthToDate?.since}): $${Number(r.monthToDate?.reservedUsd ?? 0).toFixed(2)}${r.cardOnFile ? '' : dim(' (no se cobra sin tarjeta)')}`);
|
|
18
|
+
console.log(`modo de cobro: ${r.billingMode === 'monthly' ? 'factura mensual a la tarjeta' : 'prepago (cada hora sale del saldo)'}${dim(' (koigrid billing mode prepaid|monthly)')}`);
|
|
19
|
+
const p = r.pricing?.prices ?? {};
|
|
20
|
+
console.log(dim(`tarifa: $${p.ramGbMonth}/GB RAM${p.vcpuMonth ? ` · $${p.vcpuMonth}/vCPU` : ' (vCPU compartida incluida)'} · $${p.diskGbMonth}/GB disco · $${p.objectStorageGbMonth}/GB objetos, al mes, por horas · tráfico incluido`));
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (sub === 'card' || sub === 'add-card') {
|
|
24
|
+
const r = await api('/billing/checkout-session', { method: 'POST', body: {} });
|
|
25
|
+
if (json)
|
|
26
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
27
|
+
console.log(green('✓ enlace para guardar una tarjeta (no se cobra nada al guardarla):'));
|
|
28
|
+
console.log(` ${r.url}`);
|
|
29
|
+
return console.log(dim(' Ábrelo tú (o pásaselo a quien paga): koigrid no recoge tarjetas por API.'));
|
|
30
|
+
}
|
|
31
|
+
// MONEDERO prepagado (docs/design/MONEDERO.md): `wallet` · `topup <usd>` · `auto-topup <usd>|off` · `entries`.
|
|
32
|
+
if (sub === 'wallet' || sub === 'balance') {
|
|
33
|
+
const r = (await api('/billing/wallet')).wallet;
|
|
34
|
+
if (json)
|
|
35
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
36
|
+
console.log(`saldo: $${Number(r.balanceUsd).toFixed(2)}${r.creditUsd ? ` · crédito de koigrid: $${Number(r.creditUsd).toFixed(2)} (se gasta antes)` : ''}`);
|
|
37
|
+
const at = r.autoTopUp;
|
|
38
|
+
console.log(at.enabled ? `recarga automática: $${at.amountUsd} cuando el saldo baje de $${at.thresholdUsd}` : at.disabledAfterFailures ? `recarga automática: APAGADA tras ${at.consecutiveFailures} rechazos (revisa la tarjeta y vuelve a encenderla)` : dim('recarga automática: apagada'));
|
|
39
|
+
if (r.graceUntil)
|
|
40
|
+
console.log(`⚠ saldo agotado: todo sigue hasta ${r.graceUntil}; después se pausan apps y VMs (las bases y los datos nunca)`);
|
|
41
|
+
if (!r.hourlyChargingActive)
|
|
42
|
+
console.log(dim('el cargo por horas al saldo aún no está activo'));
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (sub === 'topup' || sub === 'add-funds') {
|
|
46
|
+
const usd = Number(a.positionals[0] ?? a.flags.amount);
|
|
47
|
+
if (!Number.isFinite(usd) || usd <= 0)
|
|
48
|
+
throw new Error('uso: koigrid billing topup <dólares> (de 10 a 10000)');
|
|
49
|
+
const r = await api('/billing/wallet/topup', { method: 'POST', body: { amountCents: Math.round(usd * 100) } });
|
|
50
|
+
if (json)
|
|
51
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
52
|
+
console.log(green(`✓ recarga de $${Number(r.amountUsd).toFixed(2)}: ábrela para pagar (emite la factura y guarda la tarjeta para las recargas automáticas)`));
|
|
53
|
+
console.log(` ${r.url}`);
|
|
54
|
+
return console.log(dim(' koigrid no recoge tarjetas por API: la página es del proveedor de pagos.'));
|
|
55
|
+
}
|
|
56
|
+
if (sub === 'auto-topup') {
|
|
57
|
+
const v = String(a.positionals[0] ?? '');
|
|
58
|
+
const amountCents = v === 'off' ? null : Math.round(Number(v) * 100);
|
|
59
|
+
if (amountCents !== null && !(amountCents > 0))
|
|
60
|
+
throw new Error('uso: koigrid billing auto-topup <dólares>|off');
|
|
61
|
+
const r = (await api('/billing/wallet/auto-topup', { method: 'PUT', body: { amountCents } })).wallet;
|
|
62
|
+
if (json)
|
|
63
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
64
|
+
return console.log(green(amountCents === null ? '✓ recarga automática apagada' : `✓ recarga automática: $${r.autoTopUp.amountUsd} cuando el saldo baje de $${r.autoTopUp.thresholdUsd}`));
|
|
65
|
+
}
|
|
66
|
+
if (sub === 'entries' || sub === 'movements') {
|
|
67
|
+
const r = await api(`/billing/wallet/entries?limit=${Number(a.flags.limit ?? 30)}`);
|
|
68
|
+
if (json)
|
|
69
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
70
|
+
for (const e of r.entries)
|
|
71
|
+
console.log(`${e.createdAt.slice(0, 16).replace('T', ' ')} ${e.kind.padEnd(10)} ${(e.amountUsd >= 0 ? '+' : '') + Number(e.amountUsd).toFixed(4)} ${dim(e.description ?? '')}`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
// Cómo se paga lo reservado: `mode` enseña el actual; `mode prepaid|monthly` lo cambia (owner/admin).
|
|
75
|
+
if (sub === 'mode') {
|
|
76
|
+
const nuevo = a.positionals[0];
|
|
77
|
+
const r = nuevo ? await api('/billing/mode', { method: 'PUT', body: { mode: nuevo } }) : await api('/billing/mode');
|
|
78
|
+
if (json)
|
|
79
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
80
|
+
const texto = r.billingMode === 'monthly' ? 'factura mensual a la tarjeta guardada' : 'prepago: cada hora sale del saldo del monedero';
|
|
81
|
+
return console.log(nuevo ? (r.changed ? green(`✓ modo de cobro: ${texto}`) : `ya estaba en: ${texto}`) : `modo de cobro: ${texto}${dim(' (cámbialo con: koigrid billing mode prepaid|monthly)')}`);
|
|
82
|
+
}
|
|
83
|
+
if (sub === 'upgrade' || sub === 'checkout' || sub === 'change' || sub === 'set') {
|
|
84
|
+
throw new Error('koigrid ya no vende planes: pagas lo reservado por horas. Guarda una tarjeta con `koigrid billing card` y mira precios con `koigrid pricing`.');
|
|
85
|
+
}
|
|
86
|
+
throw new Error(`unknown: billing ${sub}`);
|
|
87
|
+
}
|
package/dist/commands/bots.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { api } from '../api.js';
|
|
2
2
|
import { green } from '../output.js';
|
|
3
|
-
// koigrid bots — Bot Management (clasifica + decide allow/challenge/block + reto PoW). Ver docs/BOT-MANAGEMENT.md.
|
|
3
|
+
// koigrid bots — Bot Management (clasifica + decide allow/challenge/block + reto PoW). Ver docs/products/BOT-MANAGEMENT.md.
|
|
4
4
|
export async function bots(a) {
|
|
5
5
|
const json = !!a.flags.json;
|
|
6
6
|
const sub = a.sub || 'policy';
|