@redcumbrecl/cli 0.1.0 → 0.3.1

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 (40) hide show
  1. package/README.md +129 -16
  2. package/dist/cli.js +2531 -488
  3. package/dist/plantillas/dotnet/_comun.cs +101 -0
  4. package/dist/plantillas/dotnet/capa/AGENTS.md +31 -0
  5. package/dist/plantillas/dotnet/capa/Directory.Build.props +9 -0
  6. package/dist/plantillas/dotnet/recetas/boleta-honorarios/redcumbre/BoletaHonorarios.cs +30 -0
  7. package/dist/plantillas/dotnet/recetas/boleta-terceros/redcumbre/BoletaTerceros.cs +28 -0
  8. package/dist/plantillas/dotnet/recetas/consultar-rut/redcumbre/ConsultarRut.cs +23 -0
  9. package/dist/plantillas/dotnet/recetas/factura/redcumbre/Factura.cs +33 -0
  10. package/dist/plantillas/php/_comun.php +135 -0
  11. package/dist/plantillas/php/capa/AGENTS.md +31 -0
  12. package/dist/plantillas/php/recetas/boleta-honorarios/redcumbre/boleta-honorarios.php +24 -0
  13. package/dist/plantillas/php/recetas/boleta-terceros/redcumbre/boleta-terceros.php +22 -0
  14. package/dist/plantillas/php/recetas/consultar-rut/redcumbre/consultar-rut.php +25 -0
  15. package/dist/plantillas/php/recetas/factura/redcumbre/factura.php +34 -0
  16. package/dist/plantillas/python/_comun.py +105 -0
  17. package/dist/plantillas/python/capa/AGENTS.md +31 -0
  18. package/dist/plantillas/python/recetas/boleta-honorarios/redcumbre_boleta_honorarios.py +27 -0
  19. package/dist/plantillas/python/recetas/boleta-terceros/redcumbre_boleta_terceros.py +25 -0
  20. package/dist/plantillas/python/recetas/consultar-rut/redcumbre_consultar_rut.py +21 -0
  21. package/dist/plantillas/python/recetas/factura/redcumbre_factura.py +30 -0
  22. package/dist/plantillas/typescript/_comun.ts +98 -0
  23. package/dist/plantillas/typescript/capa/AGENTS.md +31 -0
  24. package/dist/plantillas/typescript/recetas/boleta-honorarios/redcumbre/boleta-honorarios.ts +23 -0
  25. package/dist/plantillas/typescript/recetas/boleta-terceros/redcumbre/boleta-terceros.ts +21 -0
  26. package/dist/plantillas/typescript/recetas/consultar-rut/redcumbre/consultar-rut.ts +17 -0
  27. package/dist/plantillas/typescript/recetas/factura/redcumbre/factura.ts +24 -0
  28. package/package.json +1 -1
  29. package/dist/plantillas/dotnet/AGENTS.md +0 -24
  30. package/dist/plantillas/dotnet/Program.cs +0 -106
  31. package/dist/plantillas/dotnet/Redcumbre/LlaveRedcumbre.cs +0 -48
  32. package/dist/plantillas/php/AGENTS.md +0 -24
  33. package/dist/plantillas/php/redcumbre/ejemplo.php +0 -117
  34. package/dist/plantillas/php/redcumbre/llave.php +0 -48
  35. package/dist/plantillas/python/AGENTS.md +0 -24
  36. package/dist/plantillas/python/redcumbre_ejemplo.py +0 -97
  37. package/dist/plantillas/python/redcumbre_llave.py +0 -38
  38. package/dist/plantillas/typescript/AGENTS.md +0 -24
  39. package/dist/plantillas/typescript/redcumbre/ejemplo.ts +0 -82
  40. package/dist/plantillas/typescript/redcumbre/llave.ts +0 -44
package/dist/cli.js CHANGED
@@ -3,138 +3,116 @@
3
3
  // src/cli.ts
4
4
  import { Command, Option } from "commander";
5
5
 
6
- // src/comandos/conectar-mcp.ts
7
- import fs from "node:fs";
8
- import path from "node:path";
6
+ // src/comandos/api.ts
7
+ import fs3 from "node:fs";
8
+ import path3 from "node:path";
9
9
 
10
10
  // src/nucleo/salida.ts
11
+ var CODIGOS_DE_SALIDA = {
12
+ listo: 0,
13
+ error: 1,
14
+ uso: 2,
15
+ confirmacion: 3,
16
+ sesion: 4,
17
+ llave: 5,
18
+ api4xx: 6,
19
+ api5xx: 7,
20
+ modo: 8
21
+ };
22
+ var CODIGO_DE_ERROR_POR_SALIDA = {
23
+ 1: "ERROR_DEL_CLI",
24
+ 2: "USO_INCORRECTO",
25
+ 3: "FALTA_CONFIRMACION",
26
+ 4: "SIN_SESION",
27
+ 5: "SIN_LLAVE",
28
+ 6: "API_RECHAZO",
29
+ 7: "API_NO_DISPONIBLE",
30
+ 8: "PROHIBIDO_POR_EL_MODO"
31
+ };
11
32
  var ErrorCli = class extends Error {
12
- constructor(mensaje, codigoSalida = 1) {
33
+ constructor(mensaje, codigoSalida = 1, detalle = {}) {
13
34
  super(mensaje);
14
35
  this.codigoSalida = codigoSalida;
15
36
  this.name = "ErrorCli";
37
+ this.codigo = detalle.codigo ?? (codigoSalida === 0 ? "ERROR_DEL_CLI" : CODIGO_DE_ERROR_POR_SALIDA[codigoSalida]);
38
+ this.comando = detalle.comando;
39
+ this.datos = detalle.datos;
16
40
  }
41
+ codigo;
42
+ comando;
43
+ datos;
17
44
  };
18
- function crearSalida(json, flujos = { out: process.stdout, err: process.stderr }) {
45
+ var errorDeUso = (mensaje) => new ErrorCli(mensaje, CODIGOS_DE_SALIDA.uso);
46
+ var faltaConfirmacion = (mensaje, comando2, codigo) => new ErrorCli(mensaje, CODIGOS_DE_SALIDA.confirmacion, { comando: comando2, codigo });
47
+ function esModoAgente(json2, tty = { stdin: Boolean(process.stdin.isTTY), stdout: Boolean(process.stdout.isTTY) }) {
48
+ return json2 || !tty.stdin || !tty.stdout;
49
+ }
50
+ var esObjeto = (valor) => typeof valor === "object" && valor !== null && !Array.isArray(valor);
51
+ function crearSalida(json2, flujos = { out: process.stdout, err: process.stderr }) {
19
52
  const avisos = [];
20
- const humano = json ? flujos.err : flujos.out;
53
+ const humano = json2 ? flujos.err : flujos.out;
21
54
  return {
22
- json,
55
+ json: json2,
56
+ humano,
23
57
  avisos,
24
- linea(texto = "") {
25
- humano.write(`${texto}
58
+ linea(texto2 = "") {
59
+ humano.write(`${texto2}
26
60
  `);
27
61
  },
28
- aviso(texto) {
29
- avisos.push(texto);
30
- humano.write(`\u26A0 ${texto}
62
+ aviso(texto2) {
63
+ avisos.push(texto2);
64
+ humano.write(`\u26A0 ${texto2}
31
65
  `);
32
66
  },
33
- resultado(objeto) {
34
- if (json) flujos.out.write(`${JSON.stringify({ ...objeto, avisos }, null, 2)}
67
+ resultado(valor) {
68
+ if (!json2) return;
69
+ const final = esObjeto(valor) && avisos.length > 0 ? { ...valor, avisos } : valor;
70
+ flujos.out.write(`${JSON.stringify(final, null, 2)}
35
71
  `);
72
+ },
73
+ evento(valor) {
74
+ if (json2) flujos.out.write(`${JSON.stringify(valor)}
75
+ `);
76
+ },
77
+ error(error) {
78
+ const cli = error instanceof ErrorCli ? error : null;
79
+ const mensaje = error instanceof Error ? error.message : String(error);
80
+ const codigoSalida = cli ? cli.codigoSalida : CODIGOS_DE_SALIDA.error;
81
+ flujos.err.write(`\u2717 ${mensaje}
82
+ `);
83
+ if (cli?.comando) flujos.err.write(` Para hacerlo: ${cli.comando}
84
+ `);
85
+ if (json2) {
86
+ const cuerpo = {
87
+ ...cli?.datos ?? {},
88
+ error: { codigo: cli ? cli.codigo : CODIGO_DE_ERROR_POR_SALIDA[1], mensaje, ...cli?.comando ? { comando: cli.comando } : {} },
89
+ ...avisos.length ? { avisos } : {}
90
+ };
91
+ flujos.out.write(`${JSON.stringify(cuerpo, null, 2)}
92
+ `);
93
+ }
94
+ return codigoSalida;
36
95
  }
37
96
  };
38
97
  }
39
98
 
40
- // src/comandos/conectar-mcp.ts
41
- var URL_MCP_REDCUMBRE = "https://mcp.redcumbre.cl";
42
- var NOMBRE_SERVIDOR_MCP = "rcapi";
43
- var ARCHIVOS_MCP = [".mcp.json", path.join(".cursor", "mcp.json")];
44
- var ENTRADA = { type: "http", url: URL_MCP_REDCUMBRE };
45
- function esObjeto(v) {
46
- return typeof v === "object" && v !== null && !Array.isArray(v);
47
- }
48
- function mismaEntrada(v) {
49
- return esObjeto(v) && Object.keys(v).length === 2 && v.type === ENTRADA.type && v.url === ENTRADA.url;
50
- }
51
- function planificar(proyecto, relativa) {
52
- const absoluta = path.join(proyecto, relativa);
53
- const ruta = relativa.split(path.sep).join("/");
54
- if (!fs.existsSync(absoluta)) {
55
- return { ruta, absoluta, accion: "creado", contenido: `${JSON.stringify({ mcpServers: { [NOMBRE_SERVIDOR_MCP]: ENTRADA } }, null, 2)}
56
- ` };
57
- }
58
- let actual;
59
- try {
60
- actual = JSON.parse(fs.readFileSync(absoluta, "utf8"));
61
- } catch (error) {
62
- throw new ErrorCli(`${ruta} no tiene JSON v\xE1lido (${error.message}): no se modific\xF3. Corr\xEDgelo y vuelve a correr redcumbre conectar-mcp.`);
63
- }
64
- if (!esObjeto(actual) || actual.mcpServers !== void 0 && !esObjeto(actual.mcpServers)) {
65
- throw new ErrorCli(`${ruta} no tiene la forma { "mcpServers": { \u2026 } }: no se modific\xF3.`);
66
- }
67
- const servidores2 = actual.mcpServers ?? {};
68
- if (mismaEntrada(servidores2[NOMBRE_SERVIDOR_MCP])) return { ruta, absoluta, accion: "sin_cambios" };
69
- const fusionado = { ...actual, mcpServers: { ...servidores2, [NOMBRE_SERVIDOR_MCP]: ENTRADA } };
70
- return { ruta, absoluta, accion: "actualizado", contenido: `${JSON.stringify(fusionado, null, 2)}
71
- ` };
72
- }
73
- function conectarMcp(proyecto) {
74
- const planes = ARCHIVOS_MCP.map((relativa) => planificar(proyecto, relativa));
75
- for (const p of planes) {
76
- if (p.contenido === void 0) continue;
77
- fs.mkdirSync(path.dirname(p.absoluta), { recursive: true });
78
- fs.writeFileSync(p.absoluta, p.contenido);
79
- }
80
- return planes.map(({ ruta, accion }) => ({ ruta, accion }));
81
- }
82
- var TEXTO_ACCION = {
83
- creado: "creado",
84
- actualizado: "actualizado (se agreg\xF3 rcapi; los otros servidores quedaron igual)",
85
- sin_cambios: "ya estaba configurado"
86
- };
87
- function informarMcp(salida, archivos) {
88
- salida.linea(`Servidor MCP de rCAPI (${URL_MCP_REDCUMBRE}):`);
89
- for (const a of archivos) salida.linea(` ${a.ruta}: ${TEXTO_ACCION[a.accion]}`);
90
- if (archivos.some((a) => a.accion !== "sin_cambios")) {
91
- salida.linea("Al abrir el proyecto en Claude Code o Cursor, el asistente te pedir\xE1 autorizar rCAPI con tu cuenta.");
92
- }
93
- }
94
- async function ejecutarConectarMcp(opciones, deps) {
95
- const proyecto = path.resolve(deps.cwd, opciones.carpeta ?? ".");
96
- if (!fs.existsSync(proyecto) || !fs.statSync(proyecto).isDirectory()) throw new ErrorCli(`La carpeta ${proyecto} no existe.`);
97
- const archivos = conectarMcp(proyecto);
98
- informarMcp(deps.salida, archivos);
99
- deps.salida.resultado({ ok: true, archivos });
100
- }
101
-
102
- // src/comandos/init.ts
103
- import path4 from "node:path";
104
-
105
- // ../../packages/config/src/cli/llaves.ts
106
- var ENTORNOS_LLAVE = ["sandbox", "produccion"];
107
- var ENTORNO_LLAVE_REGISTRY = {
108
- sandbox: { label: "Sandbox", isSandbox: true },
109
- produccion: { label: "Producci\xF3n", isSandbox: false }
110
- };
111
- function esEntornoLlave(valor) {
112
- return typeof valor === "string" && ENTORNOS_LLAVE.includes(valor);
113
- }
114
-
115
99
  // src/nucleo/api.ts
116
- var ErrorSesionRechazada = class extends Error {
100
+ var ErrorSesionRechazada = class extends ErrorCli {
117
101
  constructor() {
118
- super("La plataforma rechaz\xF3 tu sesi\xF3n.");
102
+ super("La plataforma rechaz\xF3 tu sesi\xF3n. Inicia sesi\xF3n de nuevo con \xABredcumbre login\xBB.", CODIGOS_DE_SALIDA.sesion, { comando: "redcumbre login" });
119
103
  this.name = "ErrorSesionRechazada";
120
104
  }
121
105
  };
122
- var ErrorVerificacionNoDisponible = class extends ErrorCli {
123
- constructor() {
124
- super("La plataforma no pudo verificar tu sesi\xF3n en este momento. No se cre\xF3 ninguna llave; vuelve a intentarlo en unos minutos.");
125
- this.name = "ErrorVerificacionNoDisponible";
126
- }
127
- };
128
- var ErrorSinRolAdministrador = class extends Error {
129
- constructor() {
130
- super("Crear llaves exige ser administrador de la empresa.");
131
- this.name = "ErrorSinRolAdministrador";
106
+ var ErrorSinRol = class extends ErrorCli {
107
+ constructor(mensaje) {
108
+ super(mensaje, CODIGOS_DE_SALIDA.api4xx, { codigo: "SIN_ROL" });
109
+ this.name = "ErrorSinRol";
132
110
  }
133
111
  };
134
112
  var ErrorDeRed = class extends ErrorCli {
135
113
  constructor(url, causa) {
136
- const detalle = causa instanceof Error && causa.cause instanceof Error ? causa.cause.message : String(causa);
137
- super(`No pude conectar con ${url} (${detalle}). Revisa tu conexi\xF3n y vuelve a correr el comando; no se cre\xF3 ninguna llave.`);
114
+ const detalle = causa instanceof Error && causa.cause instanceof Error ? causa.cause.message : causa instanceof Error ? causa.message : String(causa);
115
+ super(`No pude conectar con ${new URL(url).origin} (${detalle}). Revisa tu conexi\xF3n y vuelve a correr el comando.`, CODIGOS_DE_SALIDA.api5xx, { codigo: "SIN_CONEXION" });
138
116
  this.name = "ErrorDeRed";
139
117
  }
140
118
  };
@@ -144,97 +122,522 @@ var ClienteApi = class {
144
122
  this.api = api;
145
123
  this.hacerFetch = hacerFetch;
146
124
  }
147
- async pedir(ruta, init) {
148
- const url = `${this.api}${ruta}`;
125
+ url(ruta, query) {
126
+ const url = new URL(`${this.api}${ruta}`);
127
+ for (const [clave, valor] of Object.entries(query ?? {})) if (valor !== void 0) url.searchParams.append(clave, valor);
128
+ return url.toString();
129
+ }
130
+ /** La petición cruda: sin red, `ErrorDeRed` (7). */
131
+ async crudo(metodo, ruta, peticion = {}, senal) {
132
+ const url = this.url(ruta, peticion.query);
133
+ const headers = { Accept: "application/json, */*;q=0.5", ...peticion.headers ?? {} };
134
+ if (peticion.credencial) headers.Authorization = `Bearer ${peticion.credencial.token}`;
135
+ if (peticion.cuerpo !== void 0) headers["Content-Type"] = "application/json";
149
136
  try {
150
- return await this.hacerFetch(url, init);
137
+ return await this.hacerFetch(url, {
138
+ method: metodo,
139
+ headers,
140
+ body: peticion.cuerpo === void 0 ? void 0 : JSON.stringify(peticion.cuerpo),
141
+ signal: senal
142
+ });
151
143
  } catch (error) {
144
+ if (senal?.aborted) throw error;
152
145
  throw new ErrorDeRed(url, error);
153
146
  }
154
147
  }
155
- /**
156
- * Traduce las respuestas que valen para toda petición con la sesión del CLI y devuelve el cuerpo ya
157
- * leído (un `Response` se lee una sola vez).
158
- */
159
- async leerConSesion(res) {
160
- if (res.status === 401) throw new ErrorSesionRechazada();
161
- const cuerpo = await leerJson(res);
162
- if (res.status === 503 && cuerpo?.code === "REAUTH_CHECK_UNAVAILABLE") throw new ErrorVerificacionNoDisponible();
163
- if (res.status === 403 && cuerpo?.code === "CLI_USER_NOT_FOUND") throw new ErrorCli(MENSAJE_SIN_FILA_LOCAL);
164
- return cuerpo;
165
- }
166
- async empresas(token) {
167
- const res = await this.pedir("/cli/empresas", { headers: { Authorization: `Bearer ${token}` } });
168
- const cuerpo = await this.leerConSesion(res);
169
- if (!res.ok) throw new ErrorCli(`No pude obtener tus empresas: ${describir(res, cuerpo)}.`);
170
- return cuerpo.empresas;
171
- }
172
- async crearLlave(token, tenantSlug, nombre, entorno) {
173
- const res = await this.pedir(`/${encodeURIComponent(tenantSlug)}/cli/llaves`, {
174
- method: "POST",
175
- headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
176
- body: JSON.stringify({ nombre, entorno })
177
- });
178
- const cuerpo = await this.leerConSesion(res);
179
- if (res.status === 403) throw new ErrorSinRolAdministrador();
180
- if (res.status !== 201) throw new ErrorCli(`No pude crear la llave en ${tenantSlug}: ${describir(res, cuerpo)}. No se cre\xF3 ninguna llave.`);
181
- return cuerpo;
148
+ /** La petición leída, sin traducir el status: la usa `redcumbre api`, que decide con él. */
149
+ async pedir(metodo, ruta, peticion = {}) {
150
+ const res = await this.crudo(metodo, ruta, peticion);
151
+ const tipo = res.headers.get("content-type") ?? "";
152
+ if (res.status === 204) return { status: res.status, headers: res.headers, json: null, bytes: null };
153
+ if (tipo.includes("json") || tipo === "") {
154
+ const texto2 = await res.text();
155
+ return { status: res.status, headers: res.headers, json: texto2 ? parsear(texto2) : null, bytes: null };
156
+ }
157
+ return { status: res.status, headers: res.headers, json: null, bytes: Buffer.from(await res.arrayBuffer()) };
158
+ }
159
+ /** La petición leída que tiene que responder 2xx; cualquier otro status sale con su código. */
160
+ async exigir(metodo, ruta, peticion, que) {
161
+ const r = await this.pedir(metodo, ruta, peticion);
162
+ if (r.status >= 200 && r.status < 300) return r.json;
163
+ throw errorDeRespuesta(r, peticion.credencial?.tipo ?? "llave", que);
164
+ }
165
+ // ─── Con la sesión de la persona ────────────────────────────────────────────────────────────────
166
+ async perfil(token) {
167
+ return this.exigir("GET", "/cli/empresas", { credencial: { tipo: "sesion", token } }, "obtener tus empresas");
168
+ }
169
+ /** Sin `alcance`, la llave del proyecto; con él, una llave de ValidaFirma (`D-402`). La clave viaja sólo si viene. */
170
+ async crearLlave(token, tenantSlug, nombre, entorno, alcance) {
171
+ const cuerpo = alcance === void 0 ? { nombre, entorno } : { nombre, entorno, alcance };
172
+ return this.exigir("POST", `/${encodeURIComponent(tenantSlug)}/cli/llaves`, { credencial: { tipo: "sesion", token }, cuerpo }, `crear la llave en ${tenantSlug}`);
173
+ }
174
+ async listarLlaves(token, tenantSlug) {
175
+ const r = await this.exigir("GET", `/${encodeURIComponent(tenantSlug)}/cli/llaves`, { credencial: { tipo: "sesion", token } }, `listar las llaves de ${tenantSlug}`);
176
+ return r.llaves;
177
+ }
178
+ async revocarLlave(token, tenantSlug, id) {
179
+ return this.exigir("DELETE", `/${encodeURIComponent(tenantSlug)}/cli/llaves/${encodeURIComponent(id)}`, { credencial: { tipo: "sesion", token } }, `revocar la llave ${id}`);
180
+ }
181
+ async llamadas(token, tenantSlug, id, query) {
182
+ return this.exigir("GET", `/${encodeURIComponent(tenantSlug)}/cli/llaves/${encodeURIComponent(id)}/llamadas`, { credencial: { tipo: "sesion", token }, query }, `leer las llamadas de la llave ${id}`);
183
+ }
184
+ async restaurar(token, tenantSlug) {
185
+ return this.exigir("POST", `/${encodeURIComponent(tenantSlug)}/cli/modo-prueba/restaurar`, { credencial: { tipo: "sesion", token }, cuerpo: { confirmar: tenantSlug } }, `restaurar el modo de prueba de ${tenantSlug}`);
186
+ }
187
+ async revisionPasoAReal(token, tenantSlug, llaveId, servicios) {
188
+ return this.exigir(
189
+ "GET",
190
+ `/${encodeURIComponent(tenantSlug)}/cli/paso-a-real/revision`,
191
+ { credencial: { tipo: "sesion", token }, query: { llaveId, servicios: servicios?.length ? servicios.join(",") : void 0 } },
192
+ `revisar el paso a real de ${tenantSlug}`
193
+ );
194
+ }
195
+ async acusarEntrega(token, tenantSlug, sesionId, acuse) {
196
+ await this.exigir("POST", `/${encodeURIComponent(tenantSlug)}/cli/relay/${encodeURIComponent(sesionId)}/acuse`, { credencial: { tipo: "sesion", token }, cuerpo: acuse }, "acusar la entrega");
182
197
  }
183
- /** `whoami` con la llave del proyecto: 200 = válida, 401 = rechazada, sin red = error (`D-112`). */
198
+ // ─── Con la llave del proyecto ──────────────────────────────────────────────────────────────────
199
+ /** `whoami` con la llave: 200 = válida, 401 = rechazada, sin red = error (nunca «no funciona»). */
184
200
  async whoami(tokenLlave, tenantSlug) {
185
- const res = await this.pedir(`/${encodeURIComponent(tenantSlug)}/whoami`, {
186
- headers: { Authorization: `Bearer ${tokenLlave}` }
187
- });
188
- if (res.status === 401) return { estado: "rechazada" };
189
- if (!res.ok) throw new ErrorCli(`No pude comprobar la llave: whoami respondi\xF3 ${res.status}. No se cre\xF3 ninguna llave.`);
190
- const cuerpo = await res.json();
191
- return { estado: "valida", tenant: cuerpo.data.tenant, sandbox: cuerpo.data.credencial.sandbox };
201
+ const r = await this.pedir("GET", `/${encodeURIComponent(tenantSlug)}/whoami`, { credencial: { tipo: "llave", token: tokenLlave } });
202
+ if (r.status === 401) return { estado: "rechazada" };
203
+ if (r.status < 200 || r.status >= 300) throw errorDeRespuesta(r, "llave", "comprobar la llave");
204
+ const cuerpo = r.json;
205
+ const { credencial } = cuerpo.data;
206
+ return { estado: "valida", tenant: cuerpo.data.tenant, sandbox: credencial.sandbox, nombre: credencial.nombre ?? null, roles: credencial.roles };
207
+ }
208
+ async conLlave(metodo, tokenLlave, ruta, que, peticion = {}) {
209
+ return this.exigir(metodo, ruta, { ...peticion, credencial: { tipo: "llave", token: tokenLlave } }, que);
192
210
  }
193
211
  };
194
- async function leerJson(res) {
195
- const texto = await res.text();
212
+ function parsear(texto2) {
196
213
  try {
197
- return JSON.parse(texto);
214
+ return JSON.parse(texto2);
198
215
  } catch {
216
+ return texto2;
217
+ }
218
+ }
219
+ function mensajeDelCuerpo(cuerpo) {
220
+ if (typeof cuerpo !== "object" || cuerpo === null) return typeof cuerpo === "string" && cuerpo.length < 300 ? cuerpo : null;
221
+ const c = cuerpo;
222
+ if (Array.isArray(c.message)) return c.message.join("; ");
223
+ if (typeof c.message === "string") return c.message;
224
+ if (typeof c.error === "object" && c.error !== null && typeof c.error.message === "string") return c.error.message;
225
+ return null;
226
+ }
227
+ function errorDeRespuesta(r, credencial, que) {
228
+ const cuerpo = typeof r.json === "object" && r.json !== null ? r.json : {};
229
+ const mensaje = mensajeDelCuerpo(r.json);
230
+ const detalle = `el API respondi\xF3 ${r.status}${mensaje ? ` (${mensaje})` : ""}`;
231
+ if (r.status === 401) {
232
+ if (credencial === "sesion") return new ErrorSesionRechazada();
233
+ return new ErrorCli(`La plataforma rechaz\xF3 la llave del proyecto al ${que}: puede estar revocada. Corre \xABredcumbre init\xBB para instalar una nueva.`, CODIGOS_DE_SALIDA.llave, {
234
+ codigo: "LLAVE_RECHAZADA",
235
+ comando: "redcumbre init"
236
+ });
237
+ }
238
+ if (r.status === 503 && cuerpo.code === "REAUTH_CHECK_UNAVAILABLE") {
239
+ return new ErrorCli("La plataforma no pudo verificar tu sesi\xF3n en este momento. No se hizo nada; vuelve a intentarlo en unos minutos.", CODIGOS_DE_SALIDA.api5xx, { codigo: "REAUTH_CHECK_UNAVAILABLE" });
240
+ }
241
+ if (r.status === 403 && cuerpo.code === "CLI_USER_NOT_FOUND") return new ErrorCli(MENSAJE_SIN_FILA_LOCAL, CODIGOS_DE_SALIDA.api4xx, { codigo: "CLI_USER_NOT_FOUND" });
242
+ if (r.status === 403 && credencial === "sesion") return new ErrorSinRol(`No pude ${que}: tu cuenta no tiene el rol que pide esa operaci\xF3n en la empresa (${detalle}).`);
243
+ if (r.status >= 400 && r.status < 500) return new ErrorCli(`No pude ${que}: ${detalle}.`, CODIGOS_DE_SALIDA.api4xx, { codigo: typeof cuerpo.code === "string" ? cuerpo.code : `HTTP_${r.status}` });
244
+ return new ErrorCli(`No pude ${que}: ${detalle}. Vuelve a intentarlo en unos minutos.`, CODIGOS_DE_SALIDA.api5xx, { codigo: typeof cuerpo.code === "string" ? cuerpo.code : `HTTP_${r.status}` });
245
+ }
246
+
247
+ // src/nucleo/confirmacion.ts
248
+ import { randomUUID } from "node:crypto";
249
+ var EFECTO_SIN_CONFIRMAR = "consulta";
250
+ function debeConfirmarPorEfecto(operacion, modo) {
251
+ if (modo !== "real") return false;
252
+ return operacion.efecto !== EFECTO_SIN_CONFIRMAR;
253
+ }
254
+ function metricasQueCruzanUmbral(operacion, metricas) {
255
+ if (!operacion.cobro?.seCobra) return [];
256
+ const codigos = new Set(operacion.cobro.metricas.map((m) => m.codigo));
257
+ return metricas.filter((m) => codigos.has(m.codigo) && m.precioSiguiente?.cruzaUmbral === true);
258
+ }
259
+ var pesos = (monto, moneda) => moneda === "CLP" ? `$${Math.round(monto).toLocaleString("es-CL")}` : `${monto} ${moneda}`;
260
+ function avisoDeUmbral(metrica) {
261
+ const precio = metrica.precioSiguiente ? ` (${pesos(metrica.precioSiguiente.monto, metrica.precioSiguiente.moneda)} cada una)` : "";
262
+ return `Con esta operaci\xF3n, \xAB${metrica.nombre}\xBB cruza el umbral de su tramo: todas las del per\xEDodo pasan al precio del tramo alcanzado${precio}.`;
263
+ }
264
+ async function confirmarSiCorresponde(pedido) {
265
+ const { operacion, modo, empresa: empresa2, cruces, salida } = pedido;
266
+ const porEfecto = debeConfirmarPorEfecto(operacion, modo);
267
+ const porUmbral = modo === "real" && cruces.length > 0;
268
+ if (!porEfecto && !porUmbral) return;
269
+ for (const metrica of porUmbral ? cruces : []) salida.aviso(avisoDeUmbral(metrica));
270
+ const comandoCompleto = `${pedido.comando} --confirmar ${empresa2.slug}`;
271
+ const codigo = porUmbral ? "CRUZA_UMBRAL" : "REQUIERE_CONFIRMACION";
272
+ if (pedido.confirmar !== void 0) {
273
+ if (pedido.confirmar === empresa2.slug) return;
274
+ throw new ErrorCli(
275
+ `--confirmar dice \xAB${pedido.confirmar}\xBB, pero la llave es de ${empresa2.nombre} (${empresa2.slug}). No se hizo nada.`,
276
+ CODIGOS_DE_SALIDA.confirmacion,
277
+ { codigo: "CONFIRMACION_DE_OTRA_EMPRESA", comando: comandoCompleto }
278
+ );
279
+ }
280
+ const que = operacion.resumen ? `\xAB${operacion.resumen}\xBB (${operacion.operationId})` : operacion.operationId;
281
+ if (salida.json || !pedido.terminal) {
282
+ const motivo = porUmbral ? "cruza el umbral de su tramo" : `tiene efecto \xAB${operacion.efecto ?? "sin declarar"}\xBB en real`;
283
+ throw faltaConfirmacion(`${que} ${motivo} en ${empresa2.nombre} y necesita confirmaci\xF3n. No se hizo nada.`, comandoCompleto, codigo);
284
+ }
285
+ const si = await pedido.terminal.confirmar(`\xBFEjecutar ${que} en real, en ${empresa2.nombre} (${empresa2.slug})?`);
286
+ if (!si) throw new ErrorCli("No confirmaste. No se hizo nada.", CODIGOS_DE_SALIDA.confirmacion, { codigo, comando: comandoCompleto });
287
+ }
288
+ function asegurarClaveDeIdempotencia(operacion, cuerpo, clave) {
289
+ const idem = operacion.idempotencia;
290
+ if (!idem || idem.forma !== "clave" || idem.ubicacion !== "cuerpo") {
291
+ if (clave !== void 0) throw errorDeUso("Esta operaci\xF3n no usa clave de idempotencia: quita --clave.");
199
292
  return null;
200
293
  }
294
+ if (cuerpo !== void 0 && (typeof cuerpo !== "object" || cuerpo === null || Array.isArray(cuerpo))) {
295
+ throw errorDeUso("El cuerpo de esta operaci\xF3n tiene que ser un objeto JSON.");
296
+ }
297
+ const base = { ...cuerpo ?? {} };
298
+ const enCuerpo = typeof base[idem.campo] === "string" && base[idem.campo] ? base[idem.campo] : null;
299
+ if (enCuerpo && clave !== void 0 && clave !== enCuerpo) {
300
+ throw errorDeUso(`El cuerpo ya trae ${idem.campo} \xAB${enCuerpo}\xBB y --clave dice \xAB${clave}\xBB. Deja s\xF3lo una.`);
301
+ }
302
+ if (clave !== void 0 && !clave.trim()) throw errorDeUso("--clave no puede ir vac\xEDa.");
303
+ const final = enCuerpo ?? clave ?? randomUUID();
304
+ base[idem.campo] = final;
305
+ return { cuerpo: base, clave: final, generada: !enCuerpo && clave === void 0 };
306
+ }
307
+
308
+ // src/nucleo/consumo.ts
309
+ async function leerConsumo(cliente, llave) {
310
+ const r = await cliente.conLlave("GET", llave.token, `/${encodeURIComponent(llave.tenantSlug)}/mi-suscripcion/consumo`, "leer el consumo");
311
+ return r.data ?? r;
312
+ }
313
+ var lineaDeTope = (t) => `${t.nombre}: ${t.consumidas} de ${t.tope} hoy (quedan ${t.remanente})`;
314
+ function incluidasEnTexto(m) {
315
+ switch (m.incluidas?.tipo) {
316
+ case "cantidad":
317
+ return `${m.incluidas.cantidad} incluidas en tu plan${m.restantes !== null ? `, quedan ${m.restantes}` : ""}`;
318
+ case "sin-limite":
319
+ return "sin l\xEDmite en tu plan";
320
+ case "sin-cargo-en-el-plan":
321
+ return "tu plan no tiene cargo para esta m\xE9trica";
322
+ case "por-dimension":
323
+ return "la tarifa depende de cada documento";
324
+ default:
325
+ return m.restantes !== null ? `quedan ${m.restantes} incluidas` : null;
326
+ }
327
+ }
328
+ function lineaDeMetrica(m) {
329
+ const partes = [`${m.usadas} usadas`];
330
+ const incluidas = incluidasEnTexto(m);
331
+ if (incluidas) partes.push(incluidas);
332
+ if (m.precioSiguiente) {
333
+ partes.push(`la siguiente cuesta ${pesos(m.precioSiguiente.monto, m.precioSiguiente.moneda)}${m.precioSiguiente.cruzaUmbral ? " y cruza el umbral del tramo" : ""}`);
334
+ } else if (m.motivoSinPrecio) {
335
+ partes.push(`sin precio de la siguiente (${m.motivoSinPrecio})`);
336
+ }
337
+ return `${m.nombre}: ${partes.join(" \xB7 ")}`;
338
+ }
339
+ function mostrarConsumo(salida, consumo2) {
340
+ if (consumo2.modo === "prueba") {
341
+ salida.linea(consumo2.mensaje ?? "En modo de prueba no se cobra.");
342
+ salida.linea("Tope del d\xEDa por servicio:");
343
+ for (const t of consumo2.topes) salida.linea(` ${lineaDeTope(t)}`);
344
+ return;
345
+ }
346
+ if (consumo2.periodo) salida.linea(`Per\xEDodo ${consumo2.periodo.desde} a ${consumo2.periodo.hasta}:`);
347
+ if (consumo2.metricas.length === 0) salida.linea("Tu plan no tiene m\xE9tricas de consumo.");
348
+ for (const m of consumo2.metricas) salida.linea(` ${lineaDeMetrica(m)}`);
201
349
  }
202
- function describir(res, cuerpo) {
203
- const mensaje = Array.isArray(cuerpo?.message) ? cuerpo.message.join("; ") : cuerpo?.message;
204
- return `el API respondi\xF3 ${res.status}${mensaje ? ` (${mensaje})` : ""}`;
350
+ function bloqueCobroDe(respuesta) {
351
+ if (typeof respuesta !== "object" || respuesta === null) return null;
352
+ const cobro = respuesta.cobro;
353
+ return typeof cobro === "object" && cobro !== null && "modo" in cobro ? cobro : null;
354
+ }
355
+ function mostrarCobro(salida, cobro) {
356
+ if (cobro.modo === "prueba") {
357
+ salida.linea(cobro.mensaje ?? "En modo de prueba no se cobra.");
358
+ return;
359
+ }
360
+ if (cobro.estado === "no-disponible") {
361
+ salida.aviso(`La operaci\xF3n se hizo, pero no pude calcular lo que se cobr\xF3 (${cobro.motivo ?? "sin motivo"}). Rev\xEDsalo con \xABredcumbre consumo --real\xBB.`);
362
+ return;
363
+ }
364
+ for (const m of cobro.metricas ?? []) salida.linea(`Cobro \xB7 ${lineaDeMetrica(m)}`);
205
365
  }
206
366
 
207
- // src/nucleo/config.ts
208
- var PRODUCCION = {
209
- api: "https://api.redcumbre.cl",
210
- web: "https://app.redcumbre.cl"
211
- };
212
- var CLIENTE_OIDC = {
213
- issuer: "https://id.redcumbre.cl",
214
- clientId: "391851369151135746",
215
- projectId: "346407127679500290"
216
- };
217
- var SCOPE = `openid profile email offline_access urn:zitadel:iam:org:project:id:${CLIENTE_OIDC.projectId}:aud`;
218
- var URL_ENTORNOS = "https://docs.redcumbre.cl/primeros-pasos/entornos/";
219
- var SERVICIO_LLAVERO = "redcumbrecl-cli";
220
- function origen(variable, valor) {
221
- let url;
367
+ // src/nucleo/documento.ts
368
+ import fs from "node:fs";
369
+ import path from "node:path";
370
+ var METODOS = ["get", "post", "put", "patch", "delete"];
371
+ var rutaCopiaDocumento = (carpeta) => path.join(carpeta, "api-docs.json");
372
+ var rutaEtagDocumento = (carpeta) => path.join(carpeta, "api-docs.etag");
373
+ function leerEtiqueta(carpeta) {
374
+ const ruta = rutaEtagDocumento(carpeta);
375
+ if (!fs.existsSync(ruta) || !fs.existsSync(rutaCopiaDocumento(carpeta))) return null;
222
376
  try {
223
- url = new URL(valor);
377
+ const datos = JSON.parse(fs.readFileSync(ruta, "utf8"));
378
+ return typeof datos.api === "string" ? { api: datos.api, etag: typeof datos.etag === "string" ? datos.etag : null } : null;
224
379
  } catch {
225
- throw new Error(`${variable} no es una URL v\xE1lida: \xAB${valor}\xBB`);
380
+ return null;
226
381
  }
227
- if (url.protocol !== "https:" && url.hostname !== "127.0.0.1" && url.hostname !== "localhost") {
228
- throw new Error(`${variable} debe usar https (recib\xED \xAB${valor}\xBB)`);
382
+ }
383
+ function leerCopia(carpeta) {
384
+ try {
385
+ return JSON.parse(fs.readFileSync(rutaCopiaDocumento(carpeta), "utf8"));
386
+ } catch {
387
+ return null;
229
388
  }
230
- return url.origin;
231
389
  }
232
- function servidores(env = process.env) {
390
+ function guardarCopia(carpeta, api, texto2, etag) {
391
+ fs.mkdirSync(carpeta, { recursive: true, mode: 448 });
392
+ fs.writeFileSync(rutaCopiaDocumento(carpeta), texto2);
393
+ fs.writeFileSync(rutaEtagDocumento(carpeta), `${JSON.stringify({ api, etag })}
394
+ `);
395
+ }
396
+ var fechaLegible = (fecha) => fecha.toLocaleString("es-CL", { dateStyle: "medium", timeStyle: "short" });
397
+ async function cargarDocumento(cliente, carpeta, salida) {
398
+ const etiqueta = leerEtiqueta(carpeta);
399
+ const copiaDelMismoApi = etiqueta?.api === cliente.api ? etiqueta : null;
400
+ const usarCopiaSinRevalidar = (motivo) => {
401
+ const crudo2 = copiaDelMismoApi ? leerCopia(carpeta) : null;
402
+ if (!crudo2) throw new ErrorCli(`${motivo} No tengo una copia del documento del API para seguir sin \xE9l.`, CODIGOS_DE_SALIDA.api5xx, { codigo: "DOCUMENTO_NO_DISPONIBLE" });
403
+ const fecha = fs.statSync(rutaCopiaDocumento(carpeta)).mtime;
404
+ salida.aviso(`${motivo} Uso la copia del documento del API del ${fechaLegible(fecha)}: puede no traer las operaciones m\xE1s nuevas.`);
405
+ return { ...indexar(crudo2), copiaSinRevalidar: fecha };
406
+ };
407
+ let respuesta;
408
+ try {
409
+ respuesta = await cliente.crudo("GET", "/api-docs-json", { headers: copiaDelMismoApi?.etag ? { "If-None-Match": copiaDelMismoApi.etag } : {} });
410
+ } catch (error) {
411
+ if (!(error instanceof ErrorDeRed)) throw error;
412
+ return usarCopiaSinRevalidar(`No pude conectar con ${cliente.api}.`);
413
+ }
414
+ if (respuesta.status === 304) {
415
+ const crudo2 = copiaDelMismoApi ? leerCopia(carpeta) : null;
416
+ if (crudo2) return { ...indexar(crudo2), copiaSinRevalidar: null };
417
+ return cargarDocumentoSinCopia(cliente, carpeta);
418
+ }
419
+ if (respuesta.status !== 200) return usarCopiaSinRevalidar(`El API respondi\xF3 ${respuesta.status} al pedir su documento.`);
420
+ const texto2 = await respuesta.text();
421
+ const crudo = JSON.parse(texto2);
422
+ guardarCopia(carpeta, cliente.api, texto2, respuesta.headers.get("etag"));
423
+ return { ...indexar(crudo), copiaSinRevalidar: null };
424
+ }
425
+ async function cargarDocumentoSinCopia(cliente, carpeta) {
426
+ const respuesta = await cliente.crudo("GET", "/api-docs-json");
427
+ if (respuesta.status !== 200) {
428
+ throw new ErrorCli(`El API respondi\xF3 ${respuesta.status} al pedir su documento. Vuelve a intentarlo en unos minutos.`, CODIGOS_DE_SALIDA.api5xx, { codigo: "DOCUMENTO_NO_DISPONIBLE" });
429
+ }
430
+ const texto2 = await respuesta.text();
431
+ guardarCopia(carpeta, cliente.api, texto2, respuesta.headers.get("etag"));
432
+ return { ...indexar(JSON.parse(texto2)), copiaSinRevalidar: null };
433
+ }
434
+ var esObjeto2 = (valor) => typeof valor === "object" && valor !== null && !Array.isArray(valor);
435
+ var texto = (valor) => typeof valor === "string" && valor.trim() ? valor : null;
436
+ function parametro(crudo) {
437
+ if (!esObjeto2(crudo) || typeof crudo.name !== "string" || typeof crudo.in !== "string") return null;
438
+ const esquema = esObjeto2(crudo.schema) ? crudo.schema : {};
233
439
  return {
234
- api: env.REDCUMBRE_API_URL ? origen("REDCUMBRE_API_URL", env.REDCUMBRE_API_URL) : PRODUCCION.api,
235
- web: env.REDCUMBRE_WEB_URL ? origen("REDCUMBRE_WEB_URL", env.REDCUMBRE_WEB_URL) : PRODUCCION.web
440
+ nombre: crudo.name,
441
+ en: crudo.in,
442
+ requerido: crudo.required === true || crudo.in === "path",
443
+ tipo: texto(esquema.type),
444
+ valores: Array.isArray(esquema.enum) ? esquema.enum : null,
445
+ descripcion: texto(crudo.description)
236
446
  };
237
447
  }
448
+ function indexar(documento) {
449
+ if (!esObjeto2(documento) || !esObjeto2(documento.paths)) {
450
+ throw new ErrorCli("El documento del API no tiene el formato esperado (falta `paths`).", CODIGOS_DE_SALIDA.api5xx, { codigo: "DOCUMENTO_INVALIDO" });
451
+ }
452
+ const operaciones = [];
453
+ for (const [ruta, item] of Object.entries(documento.paths)) {
454
+ if (!esObjeto2(item)) continue;
455
+ const comunes = Array.isArray(item.parameters) ? item.parameters : [];
456
+ for (const metodo of METODOS) {
457
+ const op = item[metodo];
458
+ if (!esObjeto2(op) || typeof op.operationId !== "string") continue;
459
+ const cuerpo = esObjeto2(op.requestBody) ? op.requestBody : null;
460
+ const contenido = cuerpo && esObjeto2(cuerpo.content) ? cuerpo.content : {};
461
+ const cobro = esObjeto2(op["x-rcapi-cobro"]) ? op["x-rcapi-cobro"] : null;
462
+ const prueba = esObjeto2(op["x-rcapi-prueba"]) ? op["x-rcapi-prueba"] : null;
463
+ const idem = esObjeto2(op["x-rcapi-idempotencia"]) ? op["x-rcapi-idempotencia"] : null;
464
+ operaciones.push({
465
+ operationId: op.operationId,
466
+ metodo: metodo.toUpperCase(),
467
+ ruta,
468
+ resumen: texto(op.summary),
469
+ descripcion: texto(op.description),
470
+ etiquetas: Array.isArray(op.tags) ? op.tags.filter((t) => typeof t === "string") : [],
471
+ parametros: [...comunes, ...Array.isArray(op.parameters) ? op.parameters : []].map(parametro).filter((p) => p !== null),
472
+ cuerpo: cuerpo ? { requerido: cuerpo.required === true, tipos: Object.keys(contenido), esquema: esObjeto2(contenido["application/json"]) ? contenido["application/json"].schema ?? null : null } : null,
473
+ efecto: texto(op["x-rcapi-efecto"]),
474
+ cobro: cobro ? {
475
+ seCobra: cobro.seCobra === true,
476
+ metricas: Array.isArray(cobro.metricas) ? cobro.metricas.filter(esObjeto2).map((m) => ({ codigo: String(m.codigo), nombre: String(m.nombre), ...typeof m.momento === "string" ? { momento: m.momento } : {} })) : []
477
+ } : null,
478
+ prueba: prueba && typeof prueba.comportamiento === "string" ? { comportamiento: prueba.comportamiento, porque: String(prueba.porque ?? "") } : null,
479
+ roles: Array.isArray(op["x-rcapi-roles"]) ? op["x-rcapi-roles"].filter((r) => typeof r === "string") : [],
480
+ idempotencia: idem && typeof idem.forma === "string" && typeof idem.campo === "string" ? { forma: idem.forma, ubicacion: String(idem.ubicacion ?? "cuerpo"), campo: idem.campo } : null
481
+ });
482
+ }
483
+ }
484
+ operaciones.sort((a, b) => a.operationId.localeCompare(b.operationId));
485
+ return { operaciones, componentes: esObjeto2(documento.components) ? documento.components : {} };
486
+ }
487
+ function buscarOperacion(documento, operationId) {
488
+ const op = documento.operaciones.find((o) => o.operationId === operationId);
489
+ if (op) return op;
490
+ const minuscula = operationId.toLowerCase();
491
+ const parecidas = documento.operaciones.filter((o) => o.operationId.toLowerCase().includes(minuscula) || minuscula.includes(o.operationId.toLowerCase())).slice(0, 5);
492
+ const sugerencia = parecidas.length ? ` \xBFQuisiste decir ${parecidas.map((o) => o.operationId).join(", ")}?` : " Corre \xABredcumbre api buscar <texto>\xBB para encontrarla.";
493
+ throw new ErrorCli(`El API no tiene la operaci\xF3n \xAB${operationId}\xBB.${sugerencia}`, CODIGOS_DE_SALIDA.uso, { codigo: "OPERACION_DESCONOCIDA" });
494
+ }
495
+ function buscarOperaciones(documento, consulta) {
496
+ const normalizar = (s) => s.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
497
+ const palabras = normalizar(consulta).split(/\s+/).filter(Boolean);
498
+ return documento.operaciones.filter((op) => {
499
+ const pajar = normalizar([op.operationId, op.resumen ?? "", op.descripcion ?? "", ...op.etiquetas].join(" "));
500
+ return palabras.every((p) => pajar.includes(p));
501
+ });
502
+ }
503
+
504
+ // ../../packages/config/src/cli/llaves.ts
505
+ var ENTORNOS_LLAVE = ["prueba", "real"];
506
+ var ENTORNO_LLAVE_REGISTRY = {
507
+ prueba: { label: "Llave de prueba", isSandbox: true },
508
+ real: { label: "Llave real", isSandbox: false }
509
+ };
510
+ function esEntornoLlave(valor) {
511
+ return typeof valor === "string" && ENTORNOS_LLAVE.includes(valor);
512
+ }
513
+ function mensajeEntornoLlaveInvalido(valor) {
514
+ return `El entorno \xAB${String(valor)}\xBB no existe. Usa ${ENTORNOS_LLAVE.map((e) => `\xAB${e}\xBB`).join(" o ")}.`;
515
+ }
516
+ var ALCANCES_LLAVE_VALIDAFIRMA = ["carpetas", "cuenta"];
517
+ var ALCANCE_LLAVE_VALIDAFIRMA_REGISTRY = {
518
+ carpetas: { label: "Carpetas y documentos" },
519
+ cuenta: { label: "Cuenta corporativa" }
520
+ };
521
+ function esAlcanceLlaveValidaFirma(valor) {
522
+ return typeof valor === "string" && ALCANCES_LLAVE_VALIDAFIRMA.includes(valor);
523
+ }
524
+ function mensajeAlcanceLlaveInvalido(valor) {
525
+ return `El alcance \xAB${String(valor)}\xBB no existe para una llave de ValidaFirma. Usa ${ALCANCES_LLAVE_VALIDAFIRMA.map((a) => `\xAB${a}\xBB`).join(" o ")}.`;
526
+ }
527
+
528
+ // ../../packages/config/src/cli/solicitud-de-cuenta.ts
529
+ var SOLICITUD_CUENTA_DOMINIOS = [
530
+ "dte",
531
+ "bhe",
532
+ "bhet",
533
+ "lookup_rut",
534
+ "webhooks",
535
+ "procesos_batch",
536
+ "sms",
537
+ "pin_rut"
538
+ ];
539
+ var SOLICITUD_CUENTA_DOMINIO_LABELS = {
540
+ dte: "Facturas electr\xF3nicas (DTE)",
541
+ bhe: "Boletas de honorarios (BHE)",
542
+ bhet: "Boletas de terceros (BHET)",
543
+ lookup_rut: "Consulta de RUT en el SII",
544
+ webhooks: "Webhooks",
545
+ procesos_batch: "Procesos batch por Excel",
546
+ sms: "Env\xEDo de SMS",
547
+ pin_rut: "Verificaci\xF3n PINRUT"
548
+ };
549
+ var SOLICITUD_CUENTA_CAMPOS = [
550
+ { campo: "nombre", label: "Tu nombre", largoMaximo: 150 },
551
+ { campo: "email", label: "Tu correo", largoMaximo: 254 },
552
+ { campo: "empresa", label: "Empresa", largoMaximo: 150 },
553
+ { campo: "rut_empresa", label: "RUT de la empresa", largoMaximo: 20 },
554
+ { campo: "stack", label: "\xBFCon qu\xE9 stack?", largoMaximo: 200 }
555
+ ];
556
+ var SOLICITUD_CUENTA_FINALIDAD = "solo para crear tu cuenta y contactarte";
557
+ var SOLICITUD_CUENTA_URL_PRIVACIDAD = "https://redcumbre.cl/privacidad";
558
+ var SOLICITUD_CUENTA_AVISO = `REDCUMBRE usa estos datos ${SOLICITUD_CUENTA_FINALIDAD}. Pol\xEDtica de Privacidad: ${SOLICITUD_CUENTA_URL_PRIVACIDAD}`;
559
+
560
+ // ../../packages/config/src/cli/paso-a-real.ts
561
+ var SERVICIOS_DTE = ["DTE_33", "DTE_34", "DTE_39", "DTE_41", "DTE_43", "DTE_46", "DTE_52", "DTE_56", "DTE_61"];
562
+ var SERVICIOS_DE_PASO_A_REAL = [
563
+ {
564
+ codigo: "dte",
565
+ nombre: "Documentos tributarios",
566
+ operaciones: ["emitirDte", "emitirBorradorDte", "reintentarEmisionDte", "enviarArchivoDtePorEmail"],
567
+ habilitadoPor: SERVICIOS_DTE,
568
+ emisor: "dte"
569
+ },
570
+ {
571
+ codigo: "bhe",
572
+ nombre: "Boletas de honorarios propias",
573
+ operaciones: [
574
+ "emitirBoletaHonorarios",
575
+ "anularBoletaHonorarios",
576
+ "anularBoletaHonorariosExterna",
577
+ "reintentarAnulacionBoletaHonorarios"
578
+ ],
579
+ habilitadoPor: ["SII_BHE"],
580
+ emisor: "bhe"
581
+ },
582
+ {
583
+ codigo: "bhet",
584
+ nombre: "Boletas de terceros",
585
+ operaciones: [
586
+ "emitirBoletaTerceros",
587
+ "anularBoletaTerceros",
588
+ "anularBoletaTercerosExterna",
589
+ "reintentarAnulacionBoletaTerceros"
590
+ ],
591
+ habilitadoPor: ["SII_BHET"],
592
+ emisor: "bhet"
593
+ },
594
+ {
595
+ codigo: "procesos-batch",
596
+ nombre: "Procesos batch de boletas",
597
+ operaciones: ["ejecutarProcesoBatch", "iniciarProcesoBatch"],
598
+ habilitadoPor: null,
599
+ emisor: "bhe-o-bhet"
600
+ },
601
+ {
602
+ codigo: "validacion-rut",
603
+ nombre: "Consulta y validaci\xF3n de RUT",
604
+ operaciones: ["consultarRutEnSii", "iniciarProcesoValidacionRut"],
605
+ habilitadoPor: null,
606
+ emisor: null
607
+ },
608
+ {
609
+ codigo: "tokenizacion",
610
+ nombre: "Tokenizaci\xF3n",
611
+ operaciones: ["iniciarTokenizacionSii", "invitarTokenizacionSii"],
612
+ habilitadoPor: null,
613
+ emisor: null
614
+ },
615
+ {
616
+ codigo: "sms",
617
+ nombre: "SMS",
618
+ operaciones: ["enviarSms"],
619
+ habilitadoPor: ["SMS"],
620
+ emisor: null
621
+ },
622
+ {
623
+ codigo: "whatsapp",
624
+ nombre: "WhatsApp",
625
+ operaciones: ["enviarMensajeWhatsapp"],
626
+ habilitadoPor: ["WHATSAPP_MENSAJERIA"],
627
+ emisor: null
628
+ },
629
+ {
630
+ codigo: "pin-rut",
631
+ nombre: "Verificaci\xF3n PINRUT",
632
+ operaciones: ["crearTransaccionPinrut"],
633
+ habilitadoPor: ["PIN_RUT"],
634
+ emisor: null
635
+ }
636
+ ];
637
+ var CODIGOS_SERVICIO_DE_PASO_A_REAL = SERVICIOS_DE_PASO_A_REAL.map((s) => s.codigo);
638
+ function esCodigoServicioDePasoAReal(valor) {
639
+ return typeof valor === "string" && CODIGOS_SERVICIO_DE_PASO_A_REAL.includes(valor);
640
+ }
238
641
 
239
642
  // src/nucleo/instalacion.ts
240
643
  import { spawnSync } from "node:child_process";
@@ -246,15 +649,17 @@ function fechaLocal(fecha) {
246
649
  const dos = (n) => String(n).padStart(2, "0");
247
650
  return `${fecha.getFullYear()}-${dos(fecha.getMonth() + 1)}-${dos(fecha.getDate())}`;
248
651
  }
249
- function nombreDeLlave(carpeta, entorno, fecha) {
250
- const cola = `${SEPARADOR}${entorno}${SEPARADOR}${fechaLocal(fecha)}`;
652
+ function nombreDeLlave(carpeta, etiqueta, fecha) {
653
+ const cola = `${SEPARADOR}${etiqueta}${SEPARADOR}${fechaLocal(fecha)}`;
251
654
  const proyecto = Array.from(path2.basename(path2.resolve(carpeta)).trim());
252
655
  const disponible = LARGO_MAXIMO_NOMBRE - cola.length;
253
656
  return `${proyecto.slice(0, disponible).join("").trimEnd()}${cola}`;
254
657
  }
658
+ var etiquetaLlaveValidaFirma = (alcance, modo) => `validafirma-${alcance}${SEPARADOR}${modo}`;
255
659
  var variableDeEntorno = (entorno) => `REDCUMBRE_LLAVE_${entorno.toUpperCase()}`;
256
660
  var rutaRelativaLlave = (entorno) => `keys/redcumbre-${entorno}.json`;
257
661
  var rutaLlave = (proyecto, entorno) => path2.join(proyecto, "keys", `redcumbre-${entorno}.json`);
662
+ var rutaRelativaLlaveValidaFirma = (empresa2, alcance, modo) => `keys/validafirma-${empresa2}-${alcance}-${modo}.json`;
258
663
  function estaVersionado(proyecto, archivo) {
259
664
  const r = spawnSync("git", ["ls-files", "--error-unmatch", "--", archivo], { cwd: proyecto, stdio: "ignore" });
260
665
  return r.status === 0;
@@ -267,20 +672,24 @@ function asegurarExclusiones(proyecto, envVersionado) {
267
672
  const faltan = deseadas.filter((linea) => !presentes.has(linea) && !presentes.has(`/${linea}`));
268
673
  if (faltan.length === 0) return [];
269
674
  const prefijo = actual.length > 0 && !actual.endsWith("\n") ? "\n" : "";
270
- fs2.writeFileSync(ruta, `${actual}${prefijo}# Llaves de rCAPI (npx @redcumbrecl/cli init)
675
+ fs2.writeFileSync(ruta, `${actual}${prefijo}# Llaves de REDCUMBRE (npx @redcumbrecl/cli init)
271
676
  ${faltan.join("\n")}
272
677
  `);
273
678
  return faltan;
274
679
  }
275
680
  function escribirLlave(proyecto, entorno, llave) {
276
- const ruta = rutaLlave(proyecto, entorno);
681
+ escribirArchivoLlave(rutaLlave(proyecto, entorno), llave);
682
+ }
683
+ function escribirArchivoLlave(ruta, llave) {
277
684
  fs2.mkdirSync(path2.dirname(ruta), { recursive: true });
278
685
  fs2.writeFileSync(ruta, `${JSON.stringify(llave, null, 2)}
279
686
  `, { mode: 384 });
280
687
  fs2.chmodSync(ruta, 384);
281
688
  }
282
689
  function leerLlave(proyecto, entorno) {
283
- const ruta = rutaLlave(proyecto, entorno);
690
+ return leerArchivoLlave(rutaLlave(proyecto, entorno));
691
+ }
692
+ function leerArchivoLlave(ruta) {
284
693
  if (!fs2.existsSync(ruta)) return null;
285
694
  let datos;
286
695
  try {
@@ -289,7 +698,7 @@ function leerLlave(proyecto, entorno) {
289
698
  throw new Error(`${ruta} no es un JSON v\xE1lido. D\xE9jalo tal como lo descargaste de la web, o b\xF3rralo y vuelve a correr el comando.`);
290
699
  }
291
700
  if (typeof datos.token !== "string" || typeof datos.tenantSlug !== "string") {
292
- throw new Error(`${ruta} no tiene el formato de una llave de rCAPI (faltan tenantSlug o token).`);
701
+ throw new Error(`${ruta} no tiene el formato de una llave de REDCUMBRE (faltan tenantSlug o token).`);
293
702
  }
294
703
  return datos;
295
704
  }
@@ -298,8 +707,8 @@ function borrarLlave(proyecto, entorno) {
298
707
  }
299
708
  function lineasEnv(proyecto) {
300
709
  const ruta = path2.join(proyecto, ".env");
301
- const texto = fs2.existsSync(ruta) ? fs2.readFileSync(ruta, "utf8") : "";
302
- return { ruta, lineas: texto === "" ? [] : texto.replace(/\n$/, "").split("\n"), finalConSalto: texto.endsWith("\n") || texto === "" };
710
+ const texto2 = fs2.existsSync(ruta) ? fs2.readFileSync(ruta, "utf8") : "";
711
+ return { ruta, lineas: texto2 === "" ? [] : texto2.replace(/\n$/, "").split("\n"), finalConSalto: texto2.endsWith("\n") || texto2 === "" };
303
712
  }
304
713
  var esLineaDe = (variable) => (linea) => new RegExp(`^\\s*(export\\s+)?${variable}\\s*=`).test(linea);
305
714
  function escribirPuntero(proyecto, entorno) {
@@ -323,29 +732,85 @@ function quitarPuntero(proyecto, entorno) {
323
732
  fs2.writeFileSync(ruta, quedan.length ? `${quedan.join("\n")}${finalConSalto ? "\n" : ""}` : "");
324
733
  }
325
734
  var rutaEstado = (proyecto) => path2.join(proyecto, ".redcumbre", "estado.json");
735
+ function ambienteValido(entorno, valor) {
736
+ if (typeof valor !== "object" || valor === null) return null;
737
+ const a = valor;
738
+ if (typeof a.keyEnvVar !== "string" || a.modo !== entorno) return null;
739
+ return { keyEnvVar: a.keyEnvVar, ...typeof a.llaveId === "string" && a.llaveId ? { llaveId: a.llaveId } : {}, modo: entorno };
740
+ }
326
741
  function leerEstado(proyecto) {
327
742
  const ruta = rutaEstado(proyecto);
328
743
  if (!fs2.existsSync(ruta)) return null;
329
- return JSON.parse(fs2.readFileSync(ruta, "utf8"));
744
+ let crudo;
745
+ try {
746
+ crudo = JSON.parse(fs2.readFileSync(ruta, "utf8"));
747
+ } catch {
748
+ throw new Error(`${ruta} no es un JSON v\xE1lido. Corr\xEDgelo o b\xF3rralo y vuelve a correr \xABredcumbre init\xBB.`);
749
+ }
750
+ if (typeof crudo.tenantSlug !== "string") return null;
751
+ const origen2 = typeof crudo.ambientes === "object" && crudo.ambientes !== null ? crudo.ambientes : {};
752
+ const ambientes = {};
753
+ for (const entorno of ENTORNOS_LLAVE) {
754
+ const ambiente = ambienteValido(entorno, origen2[entorno]);
755
+ if (ambiente) ambientes[entorno] = ambiente;
756
+ }
757
+ const { actualizado: _viejo, ...resto } = crudo;
758
+ void _viejo;
759
+ return { ...resto, tenantSlug: crudo.tenantSlug, ambientes };
330
760
  }
331
- function registrarEnEstado(proyecto, tenantSlug, entorno, sandbox) {
332
- const anterior = leerEstado(proyecto) ?? {};
333
- const ambientes = anterior.tenantSlug === tenantSlug ? { ...anterior.ambientes ?? {} } : {};
334
- ambientes[entorno] = { keyEnvVar: variableDeEntorno(entorno), sandbox };
335
- const estado = { ...anterior, tenantSlug, ambientes, actualizado: (/* @__PURE__ */ new Date()).toISOString() };
761
+ function escribirEstado(proyecto, estado2) {
336
762
  fs2.mkdirSync(path2.dirname(rutaEstado(proyecto)), { recursive: true });
337
- fs2.writeFileSync(rutaEstado(proyecto), `${JSON.stringify(estado, null, 2)}
763
+ fs2.writeFileSync(rutaEstado(proyecto), `${JSON.stringify(estado2, null, 2)}
338
764
  `);
339
765
  }
766
+ function registrarEnEstado(proyecto, tenantSlug, entorno, datos) {
767
+ const anterior = leerEstado(proyecto);
768
+ const ambientes = anterior?.tenantSlug === tenantSlug ? { ...anterior.ambientes } : {};
769
+ ambientes[entorno] = { keyEnvVar: variableDeEntorno(entorno), ...datos.llaveId ? { llaveId: datos.llaveId } : {}, modo: datos.modo };
770
+ escribirEstado(proyecto, { ...anterior ?? {}, tenantSlug, ambientes });
771
+ }
772
+ function guardarLlaveId(proyecto, entorno, llaveId) {
773
+ const estado2 = leerEstado(proyecto);
774
+ const ambiente = estado2?.ambientes[entorno];
775
+ if (!estado2 || !ambiente) return;
776
+ estado2.ambientes[entorno] = { keyEnvVar: ambiente.keyEnvVar, llaveId, modo: ambiente.modo };
777
+ escribirEstado(proyecto, estado2);
778
+ }
779
+ function valorEnEnv(proyecto, variable) {
780
+ const { lineas } = lineasEnv(proyecto);
781
+ const linea = lineas.find(esLineaDe(variable));
782
+ if (!linea) return null;
783
+ return linea.slice(linea.indexOf("=") + 1).trim().replace(/^(['"])(.*)\1$/, "$2");
784
+ }
785
+ function rutaDeLaLlave(proyecto, entorno, env = process.env) {
786
+ const variable = variableDeEntorno(entorno);
787
+ const valor = env[variable] || valorEnEnv(proyecto, variable);
788
+ return valor ? path2.resolve(proyecto, valor) : rutaLlave(proyecto, entorno);
789
+ }
790
+ function llaveDelEntorno(proyecto, entorno, env = process.env) {
791
+ return leerArchivoLlave(rutaDeLaLlave(proyecto, entorno, env));
792
+ }
793
+ function tieneInstalacionDelCli(carpeta) {
794
+ return [rutaEstado(carpeta), ...ENTORNOS_LLAVE.map((e) => rutaLlave(carpeta, e))].some((m) => fs2.existsSync(m));
795
+ }
796
+ function raizDelProyecto(desde) {
797
+ let actual = path2.resolve(desde);
798
+ for (; ; ) {
799
+ if (tieneInstalacionDelCli(actual)) return actual;
800
+ const padre = path2.dirname(actual);
801
+ if (padre === actual) return path2.resolve(desde);
802
+ actual = padre;
803
+ }
804
+ }
340
805
  function llavesDelProyecto(proyecto) {
341
- const llaves = {};
806
+ const llaves2 = {};
342
807
  for (const entorno of ENTORNOS_LLAVE) {
343
808
  const llave = leerLlave(proyecto, entorno);
344
- if (llave) llaves[entorno] = llave;
809
+ if (llave) llaves2[entorno] = llave;
345
810
  }
346
- return llaves;
811
+ return llaves2;
347
812
  }
348
- var llavesAjenas = (proyecto, empresa) => Object.entries(llavesDelProyecto(proyecto)).filter(([, llave]) => llave.tenantSlug !== empresa);
813
+ var llavesAjenas = (proyecto, empresa2) => Object.entries(llavesDelProyecto(proyecto)).filter(([, llave]) => llave.tenantSlug !== empresa2);
349
814
  function empresaAnterior(proyecto, nuevaEmpresa) {
350
815
  const ajenas = llavesAjenas(proyecto, nuevaEmpresa);
351
816
  return ajenas.length ? { empresa: ajenas[0][1].tenantSlug, entornos: ajenas.map(([entorno]) => entorno) } : null;
@@ -357,10 +822,471 @@ function soltarEmpresaAnterior(proyecto, nuevaEmpresa) {
357
822
  }
358
823
  }
359
824
 
825
+ // src/nucleo/llaves-del-proyecto.ts
826
+ var COMANDO_INIT = "npx @redcumbrecl/cli init";
827
+ var COMANDO_PASAR_A_REAL = "redcumbre pasar-a-real";
828
+ function exigirLlave(ctx, entorno) {
829
+ const archivo = llaveDelEntorno(ctx.proyecto, entorno, ctx.env);
830
+ const ruta = rutaDeLaLlave(ctx.proyecto, entorno, ctx.env);
831
+ if (archivo) return { entorno, archivo, ruta };
832
+ if (entorno === "real") {
833
+ throw new ErrorCli(`Este proyecto no tiene llave real (${ruta}). Para crearla, revisa primero que todo est\xE9 en orden con \xAB${COMANDO_PASAR_A_REAL}\xBB.`, CODIGOS_DE_SALIDA.llave, {
834
+ codigo: "SIN_LLAVE_REAL",
835
+ comando: COMANDO_PASAR_A_REAL
836
+ });
837
+ }
838
+ throw new ErrorCli(`Este proyecto no tiene llave de prueba (${ruta}). Para instalarla: ${COMANDO_INIT}`, CODIGOS_DE_SALIDA.llave, {
839
+ codigo: "SIN_LLAVE_DE_PRUEBA",
840
+ comando: COMANDO_INIT
841
+ });
842
+ }
843
+ var mismoInstante = (a, b) => {
844
+ const ta = Date.parse(a);
845
+ const tb = Date.parse(b);
846
+ return Number.isFinite(ta) && ta === tb;
847
+ };
848
+ function coincidencias(archivo, llaves2) {
849
+ return llaves2.filter((l) => l.nombre === archivo.name && mismoInstante(l.creadaEn, archivo.createdAt));
850
+ }
851
+ async function resolverLlaveId(ctx, llave) {
852
+ const estado2 = leerEstado(ctx.proyecto);
853
+ const guardado = estado2?.tenantSlug === llave.archivo.tenantSlug ? estado2.ambientes[llave.entorno]?.llaveId : void 0;
854
+ if (guardado) return guardado;
855
+ const sesion = await ctx.sesion();
856
+ const llaves2 = await sesion.usar((token) => ctx.cliente.listarLlaves(token, llave.archivo.tenantSlug));
857
+ const encontradas = coincidencias(llave.archivo, llaves2);
858
+ if (encontradas.length !== 1) return null;
859
+ guardarLlaveId(ctx.proyecto, llave.entorno, encontradas[0].id);
860
+ return encontradas[0].id;
861
+ }
862
+
863
+ // src/comandos/comun.ts
864
+ function desenvolver(cuerpo) {
865
+ if (typeof cuerpo === "object" && cuerpo !== null && !Array.isArray(cuerpo)) {
866
+ const c = cuerpo;
867
+ if (typeof c.success === "boolean" && "data" in c) return c.data;
868
+ }
869
+ return cuerpo;
870
+ }
871
+ var rutaDeEmpresa = (slug, resto) => `/${encodeURIComponent(slug)}${resto}`;
872
+ function empresaDelProyecto(ctx, empresa2) {
873
+ if (empresa2) return empresa2;
874
+ const estado2 = leerEstado(ctx.proyecto);
875
+ if (estado2) return estado2.tenantSlug;
876
+ const llaves2 = llavesDelProyecto(ctx.proyecto);
877
+ const slug = llaves2.prueba?.tenantSlug ?? llaves2.real?.tenantSlug;
878
+ if (slug) return slug;
879
+ throw new ErrorCli(`Esta carpeta no est\xE1 conectada con ninguna empresa de REDCUMBRE. Con\xE9ctala con \xAB${COMANDO_INIT}\xBB o indica la empresa con --empresa.`, CODIGOS_DE_SALIDA.error, {
880
+ codigo: "SIN_EMPRESA",
881
+ comando: COMANDO_INIT
882
+ });
883
+ }
884
+ var llaveDelComando = (ctx, real) => exigirLlave(ctx, real ? "real" : "prueba");
885
+ var nombreDelModo = (entorno) => entorno === "prueba" ? "modo de prueba" : "modo real";
886
+ var etiquetaLlave = (entorno) => ENTORNO_LLAVE_REGISTRY[entorno].label.toLowerCase();
887
+ var nombreEmpresa = (empresa2) => `${empresa2.nombre} (${empresa2.slug})`;
888
+ function lista(valor, opcion) {
889
+ const partes = [...new Set(valor.split(",").map((p) => p.trim()).filter(Boolean))];
890
+ if (partes.length === 0) throw errorDeUso(`${opcion} no puede ir vac\xEDo.`);
891
+ return partes;
892
+ }
893
+ function parClaveValor(texto2) {
894
+ const i = texto2.indexOf("=");
895
+ if (i <= 0) throw errorDeUso(`\xAB${texto2}\xBB no tiene la forma clave=valor.`);
896
+ return [texto2.slice(0, i), texto2.slice(i + 1)];
897
+ }
898
+
899
+ // src/comandos/api.ts
900
+ var MAXIMO_TODAS = 1e4;
901
+ var RUTA_INSEGURA = /[\u0000-\u001f\u007f/\\]|\.\./;
902
+ var resumenDe = (op) => ({
903
+ operationId: op.operationId,
904
+ metodo: op.metodo,
905
+ ruta: op.ruta,
906
+ resumen: op.resumen,
907
+ efecto: op.efecto,
908
+ seCobra: op.cobro?.seCobra ?? false,
909
+ etiquetas: op.etiquetas
910
+ });
911
+ function mostrarLista(ctx, operaciones) {
912
+ for (const op of operaciones) ctx.salida.linea(`${op.operationId.padEnd(44)} ${op.metodo.padEnd(6)} ${op.resumen ?? ""}`);
913
+ ctx.salida.linea(`${operaciones.length} operaciones. Detalle de una: \xABredcumbre api describir <operaci\xF3n>\xBB.`);
914
+ }
915
+ async function apiListar(ctx) {
916
+ const doc = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, ctx.salida);
917
+ mostrarLista(ctx, doc.operaciones);
918
+ ctx.salida.resultado({ operaciones: doc.operaciones.map(resumenDe) });
919
+ }
920
+ async function apiBuscar(ctx, texto2) {
921
+ const doc = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, ctx.salida);
922
+ const encontradas = buscarOperaciones(doc, texto2);
923
+ if (encontradas.length === 0) ctx.salida.linea(`Ninguna operaci\xF3n menciona \xAB${texto2}\xBB.`);
924
+ else mostrarLista(ctx, encontradas);
925
+ ctx.salida.resultado({ operaciones: encontradas.map(resumenDe) });
926
+ }
927
+ async function apiDescribir(ctx, operationId) {
928
+ const doc = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, ctx.salida);
929
+ const op = buscarOperacion(doc, operationId);
930
+ const esquema = op.cuerpo ? resolverRefs(op.cuerpo.esquema, doc.componentes) : null;
931
+ ctx.salida.linea(`${op.operationId} \xB7 ${op.metodo} ${op.ruta}`);
932
+ if (op.resumen) ctx.salida.linea(op.resumen);
933
+ if (op.descripcion) ctx.salida.linea(op.descripcion);
934
+ ctx.salida.linea(`Efecto: ${op.efecto ?? "sin declarar (confirma en real)"}`);
935
+ ctx.salida.linea(`Cobro: ${op.cobro?.seCobra ? op.cobro.metricas.map((m) => m.nombre).join(", ") : "no se cobra"}`);
936
+ if (op.prueba) ctx.salida.linea(`En prueba: ${op.prueba.comportamiento}${op.prueba.porque ? ` (${op.prueba.porque})` : ""}`);
937
+ if (op.roles.length) ctx.salida.linea(`Roles: ${op.roles.join(", ")}`);
938
+ for (const p of op.parametros.filter((x) => x.nombre !== "tenantSlug")) {
939
+ ctx.salida.linea(` --param ${p.nombre}=<${p.tipo ?? "valor"}>${p.requerido ? " (obligatorio)" : ""}${p.descripcion ? ` ${p.descripcion}` : ""}`);
940
+ }
941
+ if (op.cuerpo) ctx.salida.linea(` --cuerpo @archivo.json${op.cuerpo.requerido ? " (obligatorio)" : ""}`);
942
+ if (op.idempotencia) ctx.salida.linea(`Idempotencia: ${op.idempotencia.campo} en el ${op.idempotencia.ubicacion} (--clave)`);
943
+ ctx.salida.resultado({ ...op, cuerpo: op.cuerpo ? { ...op.cuerpo, esquema } : null });
944
+ }
945
+ function resolverRefs(esquema, componentes, profundidad = 0, vistos = []) {
946
+ if (Array.isArray(esquema)) return esquema.map((e) => resolverRefs(e, componentes, profundidad, vistos));
947
+ if (typeof esquema !== "object" || esquema === null) return esquema;
948
+ const objeto = esquema;
949
+ const ref = typeof objeto.$ref === "string" ? objeto.$ref : null;
950
+ if (ref?.startsWith("#/components/")) {
951
+ if (vistos.includes(ref) || profundidad > 8) return { $ref: ref };
952
+ const destino = ref.slice("#/components/".length).split("/").reduce((n, k) => n && typeof n === "object" ? n[k] : void 0, componentes);
953
+ return destino === void 0 ? objeto : resolverRefs(destino, componentes, profundidad + 1, [...vistos, ref]);
954
+ }
955
+ return Object.fromEntries(Object.entries(objeto).map(([k, v]) => [k, resolverRefs(v, componentes, profundidad, vistos)]));
956
+ }
957
+ async function apiEjecutar(ctx, operationId, opciones) {
958
+ const llave = llaveDelComando(ctx, opciones.real);
959
+ const slug = llave.archivo.tenantSlug;
960
+ const doc = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, ctx.salida);
961
+ const op = buscarOperacion(doc, operationId);
962
+ const { ruta, query } = armarRuta(op, slug, opciones.param ?? []);
963
+ let cuerpo = opciones.cuerpo !== void 0 ? leerCuerpo(opciones.cuerpo) : void 0;
964
+ if (op.cuerpo?.requerido && cuerpo === void 0) throw errorDeUso(`${op.operationId} necesita un cuerpo: --cuerpo @archivo.json, --cuerpo - (entrada est\xE1ndar) o el JSON directo.`);
965
+ const campos = opciones.campos !== void 0 ? lista(opciones.campos, "--campos") : void 0;
966
+ const idem = asegurarClaveDeIdempotencia(op, cuerpo, opciones.clave);
967
+ if (idem) cuerpo = idem.cuerpo;
968
+ if (opciones.ensayo) {
969
+ ctx.salida.linea(`Ensayo: no llam\xE9 al API. Con la llave \xAB${llave.archivo.name}\xBB (${nombreDelModo(llave.entorno)}) de ${slug} har\xEDa:`);
970
+ ctx.salida.linea(` ${op.metodo} ${ctx.cliente.url(ruta, query)}`);
971
+ if (cuerpo !== void 0) ctx.salida.linea(` ${JSON.stringify(cuerpo)}`);
972
+ ctx.salida.resultado({
973
+ solicitud: { metodo: op.metodo, ruta, query, cuerpo: cuerpo ?? null },
974
+ empresa: slug,
975
+ llave: llave.archivo.name,
976
+ modo: llave.entorno,
977
+ requiereConfirmacion: debeConfirmarPorEfecto(op, llave.entorno)
978
+ });
979
+ return;
980
+ }
981
+ const cruces = llave.entorno === "real" && op.cobro?.seCobra ? await crucesDeUmbral(ctx, llave, op) : [];
982
+ if (debeConfirmarPorEfecto(op, llave.entorno) || cruces.length) {
983
+ const empresa2 = await empresaDeLaLlave(ctx, llave);
984
+ await confirmarSiCorresponde({
985
+ operacion: op,
986
+ modo: llave.entorno,
987
+ empresa: empresa2,
988
+ cruces,
989
+ confirmar: opciones.confirmar,
990
+ comando: comandoDe(op, opciones, idem?.clave),
991
+ salida: ctx.salida,
992
+ terminal: ctx.salida.json ? null : ctx.terminal
993
+ });
994
+ }
995
+ if (idem?.generada) ctx.salida.linea(`Clave de idempotencia: ${idem.clave}. Para reintentar sin duplicar, repite el comando con --clave ${idem.clave}.`);
996
+ const resultado = opciones.todas ? await todas(ctx, llave, op, ruta, query) : await una(ctx, llave, op, ruta, query, cuerpo, opciones.salida);
997
+ if (resultado === void 0) return;
998
+ const cobro = bloqueCobroDe(resultado);
999
+ if (cobro) mostrarCobro(ctx.salida, cobro);
1000
+ const recortado = campos ? recortar(resultado, campos) : resultado;
1001
+ if (!ctx.salida.json) ctx.salida.linea(JSON.stringify(recortado, null, 2));
1002
+ ctx.salida.resultado(recortado);
1003
+ }
1004
+ function armarRuta(op, slug, params) {
1005
+ const valores = /* @__PURE__ */ new Map();
1006
+ for (const p of params) {
1007
+ const [clave, valor] = parClaveValor(p);
1008
+ if (valores.has(clave)) throw errorDeUso(`--param ${clave} viene dos veces.`);
1009
+ valores.set(clave, valor);
1010
+ }
1011
+ const declarados = new Map(op.parametros.map((p) => [p.nombre, p]));
1012
+ for (const clave of valores.keys()) {
1013
+ if (clave === "tenantSlug") throw errorDeUso("La empresa sale de la llave del proyecto: quita --param tenantSlug.");
1014
+ const p = declarados.get(clave);
1015
+ if (!p || p.en !== "path" && p.en !== "query") {
1016
+ const validos = op.parametros.filter((x) => x.nombre !== "tenantSlug" && (x.en === "path" || x.en === "query")).map((x) => x.nombre);
1017
+ throw errorDeUso(`${op.operationId} no tiene el par\xE1metro \xAB${clave}\xBB. ${validos.length ? `Tiene: ${validos.join(", ")}.` : "No recibe par\xE1metros."}`);
1018
+ }
1019
+ }
1020
+ const ruta = op.ruta.replace(/\{([^}]+)\}/g, (_, nombre) => {
1021
+ if (nombre === "tenantSlug") return encodeURIComponent(slug);
1022
+ const valor = valores.get(nombre);
1023
+ if (valor === void 0) throw errorDeUso(`Falta --param ${nombre}=<valor>.`);
1024
+ if (!valor || RUTA_INSEGURA.test(valor)) {
1025
+ throw new ErrorCli(`El valor de ${nombre} tiene caracteres que no van en una ruta (control, \xAB/\xBB o \xAB..\xBB). No llam\xE9 al API.`, CODIGOS_DE_SALIDA.error, { codigo: "PARAMETRO_INVALIDO" });
1026
+ }
1027
+ return encodeURIComponent(valor);
1028
+ });
1029
+ const query = {};
1030
+ for (const p of op.parametros.filter((x) => x.en === "query")) {
1031
+ const valor = valores.get(p.nombre);
1032
+ if (valor !== void 0) query[p.nombre] = valor;
1033
+ else if (p.requerido) throw errorDeUso(`Falta --param ${p.nombre}=<valor>.`);
1034
+ }
1035
+ return { ruta, query };
1036
+ }
1037
+ function leerCuerpo(valor) {
1038
+ let texto2;
1039
+ if (valor === "-") texto2 = fs3.readFileSync(0, "utf8");
1040
+ else if (valor.startsWith("@")) {
1041
+ const archivo = valor.slice(1);
1042
+ if (!fs3.existsSync(archivo)) throw errorDeUso(`No encuentro el archivo del cuerpo: ${archivo}`);
1043
+ texto2 = fs3.readFileSync(archivo, "utf8");
1044
+ } else texto2 = valor;
1045
+ try {
1046
+ return JSON.parse(texto2);
1047
+ } catch (error) {
1048
+ throw errorDeUso(`El cuerpo no es JSON v\xE1lido (${error.message}).`);
1049
+ }
1050
+ }
1051
+ async function crucesDeUmbral(ctx, llave, op) {
1052
+ const consumo2 = await leerConsumo(ctx.cliente, llave.archivo);
1053
+ return consumo2.modo === "real" ? metricasQueCruzanUmbral(op, consumo2.metricas) : [];
1054
+ }
1055
+ async function empresaDeLaLlave(ctx, llave) {
1056
+ const w = await ctx.cliente.whoami(llave.archivo.token, llave.archivo.tenantSlug);
1057
+ if (w.estado !== "valida") throw errorDeRespuesta({ status: 401, headers: new Headers(), json: null, bytes: null }, "llave", "comprobar la llave");
1058
+ return w.tenant;
1059
+ }
1060
+ function comandoDe(op, opciones, clave) {
1061
+ const partes = ["redcumbre api", op.operationId];
1062
+ for (const p of opciones.param ?? []) partes.push(`--param ${p}`);
1063
+ if (opciones.cuerpo !== void 0) partes.push(`--cuerpo ${opciones.cuerpo}`);
1064
+ if (clave) partes.push(`--clave ${clave}`);
1065
+ if (opciones.real) partes.push("--real");
1066
+ return partes.join(" ");
1067
+ }
1068
+ async function pedir(ctx, llave, op, ruta, query, cuerpo) {
1069
+ const r = await ctx.cliente.pedir(op.metodo, ruta, { credencial: { tipo: "llave", token: llave.archivo.token }, query, cuerpo });
1070
+ if (r.status >= 200 && r.status < 300) return r;
1071
+ const error = errorDeRespuesta(r, "llave", `ejecutar ${op.operationId}`);
1072
+ throw new ErrorCli(error.message, error.codigoSalida, { codigo: error.codigo, comando: error.comando, datos: { status: r.status, ...r.json !== null && typeof r.json === "object" ? { respuesta: r.json } : {} } });
1073
+ }
1074
+ async function una(ctx, llave, op, ruta, query, cuerpo, salidaArchivo) {
1075
+ const r = await pedir(ctx, llave, op, ruta, query, cuerpo);
1076
+ if (r.bytes === null) return r.json;
1077
+ const tipo = r.headers.get("content-type") ?? "application/octet-stream";
1078
+ const extension = tipo.includes("pdf") ? "pdf" : tipo.includes("xml") ? "xml" : tipo.includes("zip") ? "zip" : "bin";
1079
+ const archivo = path3.resolve(ctx.cwd, salidaArchivo ?? `${op.operationId}.${extension}`);
1080
+ fs3.writeFileSync(archivo, r.bytes);
1081
+ ctx.salida.linea(`\u2713 Guard\xE9 ${r.bytes.length} bytes en ${archivo}`);
1082
+ ctx.salida.resultado({ archivo, bytes: r.bytes.length, tipo });
1083
+ return void 0;
1084
+ }
1085
+ function itemsDe(cuerpo) {
1086
+ const datos = desenvolver(cuerpo);
1087
+ if (Array.isArray(datos)) return { items: datos, total: null };
1088
+ if (typeof datos !== "object" || datos === null) return null;
1089
+ const objeto = datos;
1090
+ const clave = ["data", "items", "resultados", "registros"].find((k) => Array.isArray(objeto[k]));
1091
+ if (!clave) return null;
1092
+ const total = typeof objeto.total === "number" ? objeto.total : typeof objeto.meta?.total === "number" ? objeto.meta.total : null;
1093
+ return { items: objeto[clave], total };
1094
+ }
1095
+ async function todas(ctx, llave, op, ruta, query) {
1096
+ const nombres = new Set(op.parametros.filter((p) => p.en === "query").map((p) => p.nombre));
1097
+ const porOffset = nombres.has("offset");
1098
+ const porPagina = !porOffset && nombres.has("page");
1099
+ if (!porOffset && !porPagina) throw errorDeUso(`${op.operationId} no es un listado paginado: quita --todas.`);
1100
+ const juntados = [];
1101
+ let pagina = porPagina ? Number(query.page ?? 1) : 0;
1102
+ let offset = porOffset ? Number(query.offset ?? 0) : 0;
1103
+ for (; ; ) {
1104
+ const q = { ...query, ...porOffset ? { offset: String(offset) } : { page: String(pagina) } };
1105
+ const r = await pedir(ctx, llave, op, ruta, q);
1106
+ const pagina_ = itemsDe(r.json);
1107
+ if (!pagina_) throw new ErrorCli(`La respuesta de ${op.operationId} no trae una lista que recorrer. \xDAsala sin --todas.`, CODIGOS_DE_SALIDA.error, { codigo: "SIN_LISTA" });
1108
+ juntados.push(...pagina_.items);
1109
+ const completo = pagina_.items.length === 0 || pagina_.total !== null && offset + pagina_.items.length >= pagina_.total;
1110
+ if (juntados.length >= MAXIMO_TODAS) {
1111
+ if (!completo) ctx.salida.aviso(`Junt\xE9 el m\xE1ximo de ${MAXIMO_TODAS} \xEDtems; hay m\xE1s. Acota la b\xFAsqueda con --param.`);
1112
+ return juntados.slice(0, MAXIMO_TODAS);
1113
+ }
1114
+ if (completo || pagina_.total === null && porPagina && pagina_.items.length === 0) return juntados;
1115
+ offset += pagina_.items.length;
1116
+ pagina += 1;
1117
+ }
1118
+ }
1119
+ function recortar(valor, campos) {
1120
+ const elegir = (o) => typeof o === "object" && o !== null && !Array.isArray(o) ? Object.fromEntries(campos.filter((c) => c in o).map((c) => [c, o[c]])) : o;
1121
+ return Array.isArray(valor) ? valor.map(elegir) : elegir(valor);
1122
+ }
1123
+
1124
+ // src/comandos/doctor.ts
1125
+ import fs5 from "node:fs";
1126
+ import path5 from "node:path";
1127
+
1128
+ // src/nucleo/aviso-version.ts
1129
+ import fs4 from "node:fs";
1130
+ import path4 from "node:path";
1131
+ var PAQUETE_CLI = "@redcumbrecl/cli";
1132
+ var REGISTRO_NPM = "https://registry.npmjs.org/";
1133
+ var urlUltimaVersion = (registro = REGISTRO_NPM) => `${registro.replace(/\/+$/, "")}/${PAQUETE_CLI}/latest`;
1134
+ var TIEMPO_MAXIMO_MS = 1500;
1135
+ var UN_DIA_MS = 24 * 60 * 60 * 1e3;
1136
+ var rutaMarcaVersion = (carpeta) => path4.join(carpeta, "aviso-version.json");
1137
+ function leerMarca(carpeta) {
1138
+ try {
1139
+ const marca = JSON.parse(fs4.readFileSync(rutaMarcaVersion(carpeta), "utf8"));
1140
+ return typeof marca.revisadoEn === "string" ? { revisadoEn: marca.revisadoEn, ultima: typeof marca.ultima === "string" ? marca.ultima : null } : null;
1141
+ } catch {
1142
+ return null;
1143
+ }
1144
+ }
1145
+ function escribirMarca(carpeta, marca) {
1146
+ try {
1147
+ fs4.mkdirSync(carpeta, { recursive: true, mode: 448 });
1148
+ fs4.writeFileSync(rutaMarcaVersion(carpeta), `${JSON.stringify(marca)}
1149
+ `);
1150
+ } catch {
1151
+ }
1152
+ }
1153
+ function compararVersiones(a, b) {
1154
+ const partes = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10));
1155
+ const pa = partes(a);
1156
+ const pb = partes(b);
1157
+ if ([...pa, ...pb].some((n) => !Number.isFinite(n))) return 0;
1158
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1159
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
1160
+ if (d !== 0) return d > 0 ? 1 : -1;
1161
+ }
1162
+ return 0;
1163
+ }
1164
+ async function consultarRegistro(url, senal) {
1165
+ const r = await fetch(url, { signal: senal, headers: { accept: "application/json" } });
1166
+ if (!r.ok) return null;
1167
+ const cuerpo = await r.json();
1168
+ return typeof cuerpo.version === "string" ? cuerpo.version : null;
1169
+ }
1170
+ async function avisarSiHayVersionNueva(opciones) {
1171
+ const marca = leerMarca(opciones.carpeta);
1172
+ if (marca && opciones.ahora.getTime() - Date.parse(marca.revisadoEn) < UN_DIA_MS) return;
1173
+ let ultima = null;
1174
+ try {
1175
+ const senal = AbortSignal.timeout(TIEMPO_MAXIMO_MS);
1176
+ ultima = opciones.consultar ? await opciones.consultar(senal) : await consultarRegistro(urlUltimaVersion(opciones.registro || void 0), senal);
1177
+ } catch {
1178
+ ultima = null;
1179
+ }
1180
+ escribirMarca(opciones.carpeta, { revisadoEn: opciones.ahora.toISOString(), ultima });
1181
+ if (ultima && compararVersiones(ultima, opciones.version) > 0) {
1182
+ opciones.humano.write(`\u2139 Hay una versi\xF3n m\xE1s nueva del CLI: ${ultima} (tienes ${opciones.version}). Actual\xEDzala con \xABnpm install -g ${PAQUETE_CLI}@latest\xBB o usa \xABnpx ${PAQUETE_CLI}@latest\xBB.
1183
+ `);
1184
+ }
1185
+ }
1186
+
1187
+ // src/comandos/doctor.ts
1188
+ async function doctor(ctx) {
1189
+ const { salida, proyecto } = ctx;
1190
+ const revisiones = [];
1191
+ const anotar = (r) => {
1192
+ revisiones.push(r);
1193
+ salida.linea(`${r.ok ? "\u2713" : r.opcional ? "\xB7" : "\u2717"} ${r.detalle}${!r.ok && r.comando ? ` \u2192 ${r.comando}` : ""}`);
1194
+ };
1195
+ const haySesion = await ctx.haySesion();
1196
+ anotar(
1197
+ haySesion ? { revision: "sesion", ok: true, detalle: "Hay una sesi\xF3n iniciada en este computador." } : { revision: "sesion", ok: false, detalle: "No hay una sesi\xF3n iniciada en este computador.", comando: "redcumbre login" }
1198
+ );
1199
+ const estado2 = leerEstado(proyecto);
1200
+ let slug = null;
1201
+ if (estado2) {
1202
+ slug = estado2.tenantSlug;
1203
+ anotar({ revision: "empresa", ok: true, detalle: `El proyecto ${proyecto} apunta a la empresa ${slug}.` });
1204
+ } else {
1205
+ anotar({ revision: "empresa", ok: false, detalle: `La carpeta ${proyecto} no est\xE1 conectada con REDCUMBRE (falta .redcumbre/estado.json).`, comando: COMANDO_INIT });
1206
+ }
1207
+ for (const entorno of ENTORNOS_LLAVE) {
1208
+ anotar(await revisarLlave(ctx, entorno, slug));
1209
+ }
1210
+ const gitignore = path5.join(proyecto, ".gitignore");
1211
+ const lineas = new Set((fs5.existsSync(gitignore) ? fs5.readFileSync(gitignore, "utf8") : "").split(/\r?\n/).map((l) => l.trim()));
1212
+ const faltanExclusiones = ["keys/", ".redcumbre/"].filter((l) => !lineas.has(l) && !lineas.has(`/${l}`));
1213
+ const versionadas = ENTORNOS_LLAVE.map((e) => path5.relative(proyecto, rutaDeLaLlave(proyecto, e, ctx.env))).filter(
1214
+ (relativa) => fs5.existsSync(path5.join(proyecto, relativa)) && estaVersionado(proyecto, relativa)
1215
+ );
1216
+ if (versionadas.length > 0) {
1217
+ anotar({
1218
+ revision: "exclusiones",
1219
+ ok: false,
1220
+ detalle: `La llave est\xE1 en el control de versiones (${versionadas.join(", ")}): s\xE1cala con \xABgit rm --cached ${versionadas.join(" ")}\xBB y rev\xF3cala en la web, porque qued\xF3 en el historial.`
1221
+ });
1222
+ } else if (faltanExclusiones.length > 0) {
1223
+ anotar({ revision: "exclusiones", ok: false, detalle: `Al .gitignore le falta ${faltanExclusiones.join(" y ")}.`, comando: COMANDO_INIT });
1224
+ } else {
1225
+ anotar({ revision: "exclusiones", ok: true, detalle: "keys/ y .redcumbre/ est\xE1n fuera del control de versiones." });
1226
+ }
1227
+ try {
1228
+ const documento = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, salida);
1229
+ anotar({
1230
+ revision: "documento",
1231
+ ok: true,
1232
+ detalle: documento.copiaSinRevalidar ? `Uso la copia del documento del API sin revalidar (${documento.operaciones.length} operaciones).` : `El documento del API est\xE1 al d\xEDa (${documento.operaciones.length} operaciones).`
1233
+ });
1234
+ } catch (error) {
1235
+ anotar({ revision: "documento", ok: false, detalle: `No pude leer el documento del API: ${error instanceof Error ? error.message : String(error)}` });
1236
+ }
1237
+ if (!salida.json && ctx.terminal) {
1238
+ await avisarSiHayVersionNueva({ carpeta: ctx.carpetaConfiguracion, version: ctx.version, ahora: ctx.ahora(), humano: process.stderr, registro: ctx.env.REDCUMBRE_NPM_REGISTRY });
1239
+ }
1240
+ const faltantes = revisiones.filter((r) => !r.ok && !r.opcional).map((r) => ({ revision: r.revision, detalle: r.detalle, ...r.comando ? { comando: r.comando } : {} }));
1241
+ if (faltantes.length > 0) {
1242
+ throw new ErrorCli(`Hay ${faltantes.length === 1 ? "una cosa que arreglar" : `${faltantes.length} cosas que arreglar`} en el proyecto.`, CODIGOS_DE_SALIDA.error, {
1243
+ codigo: "DOCTOR_CON_FALTANTES",
1244
+ datos: { revisiones, faltantes }
1245
+ });
1246
+ }
1247
+ salida.linea("Todo en orden.");
1248
+ salida.resultado({ ok: true, proyecto, revisiones, faltantes: [] });
1249
+ }
1250
+ async function revisarLlave(ctx, entorno, slug) {
1251
+ const revision = `llave-${entorno}`;
1252
+ const nombre = etiquetaLlave(entorno);
1253
+ const ruta = path5.relative(ctx.proyecto, rutaDeLaLlave(ctx.proyecto, entorno, ctx.env)) || rutaDeLaLlave(ctx.proyecto, entorno, ctx.env);
1254
+ const archivo = llaveDelEntorno(ctx.proyecto, entorno, ctx.env);
1255
+ if (!archivo) {
1256
+ return entorno === "prueba" ? { revision, ok: false, detalle: `Falta la ${nombre} (${ruta}).`, comando: COMANDO_INIT } : { revision, ok: false, opcional: true, detalle: `El proyecto todav\xEDa no tiene ${nombre}.`, comando: COMANDO_PASAR_A_REAL };
1257
+ }
1258
+ if (slug && archivo.tenantSlug !== slug) {
1259
+ return { revision, ok: false, detalle: `La ${nombre} es de ${archivo.tenantSlug}, pero el proyecto apunta a ${slug}.`, comando: COMANDO_INIT };
1260
+ }
1261
+ try {
1262
+ const r = await ctx.cliente.whoami(archivo.token, archivo.tenantSlug);
1263
+ if (r.estado === "rechazada") return { revision, ok: false, detalle: `La API rechaza la ${nombre} (${ruta}): fue revocada o venci\xF3.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_REAL };
1264
+ if (r.sandbox !== (entorno === "prueba")) {
1265
+ return { revision, ok: false, detalle: `El archivo ${ruta} no trae una ${nombre}: seg\xFAn la API es de otro modo.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_REAL };
1266
+ }
1267
+ return { revision, ok: true, detalle: `La ${nombre} funciona (${r.tenant.nombre}).` };
1268
+ } catch (error) {
1269
+ return { revision, ok: false, detalle: `No pude comprobar la ${nombre}: ${error instanceof Error ? error.message : String(error)}` };
1270
+ }
1271
+ }
1272
+ async function panel(ctx, opciones) {
1273
+ const slug = empresaDelProyecto(ctx, opciones.empresa);
1274
+ const url = `${ctx.servidores.web}${rutaDeEmpresa(slug, "/dashboard")}`;
1275
+ const abierto = opciones.sinNavegador ? false : await ctx.abrir(url);
1276
+ ctx.salida.linea(abierto ? `Abr\xED el panel de ${slug} en el navegador: ${url}` : `El panel de ${slug}: ${url}`);
1277
+ ctx.salida.resultado({ ok: true, empresa: slug, url, abierto });
1278
+ }
1279
+
1280
+ // src/comandos/init.ts
1281
+ import { randomUUID as randomUUID2 } from "node:crypto";
1282
+ import fs9 from "node:fs";
1283
+ import os2 from "node:os";
1284
+ import path9 from "node:path";
1285
+
360
1286
  // src/nucleo/proyecto.ts
361
1287
  import { spawnSync as spawnSync2 } from "node:child_process";
362
- import fs3 from "node:fs";
363
- import path3 from "node:path";
1288
+ import fs6 from "node:fs";
1289
+ import path6 from "node:path";
364
1290
  import { fileURLToPath } from "node:url";
365
1291
  var LENGUAJES = ["typescript", "python", "dotnet", "php"];
366
1292
  var LENGUAJE_REGISTRY = {
@@ -368,49 +1294,52 @@ var LENGUAJE_REGISTRY = {
368
1294
  label: "TypeScript con Node",
369
1295
  binario: "npm",
370
1296
  generador: ["npm", "create", "--yes"],
371
- correrEjemplo: "npm run redcumbre:ejemplo",
372
- ajustar(proyecto) {
373
- const ruta = path3.join(proyecto, "package.json");
374
- const paquete = JSON.parse(fs3.readFileSync(ruta, "utf8"));
375
- paquete.scripts = { ...paquete.scripts, "redcumbre:ejemplo": "npx --yes tsx redcumbre/ejemplo.ts" };
376
- fs3.writeFileSync(ruta, `${JSON.stringify(paquete, null, 2)}
377
- `);
378
- }
1297
+ ejecutar: (archivo) => ["npx", "--yes", "tsx", archivo],
1298
+ archivoDeReceta: (receta2) => `redcumbre/${receta2}.ts`,
1299
+ marcas: [/^package\.json$/, /^tsconfig\.json$/]
379
1300
  },
380
1301
  python: {
381
1302
  label: "Python",
382
1303
  binario: "uv",
383
1304
  // `--vcs none`: el CLI no inicia ni cambia repositorios de git (`D-16`).
384
1305
  generador: ["uv", "init", "--app", "--vcs", "none", "--no-workspace", "."],
385
- correrEjemplo: "uv run redcumbre_ejemplo.py"
1306
+ // Las recetas usan sólo la biblioteca estándar: corren con `python3` con o sin `uv`.
1307
+ ejecutar: (archivo) => ["python3", archivo],
1308
+ archivoDeReceta: (receta2) => `redcumbre_${receta2.replaceAll("-", "_")}.py`,
1309
+ marcas: [/^pyproject\.toml$/, /^requirements\.txt$/, /^setup\.py$/]
386
1310
  },
387
1311
  dotnet: {
388
1312
  label: ".NET (C#)",
389
1313
  binario: "dotnet",
390
1314
  generador: ["dotnet", "new", "console", "--output", "."],
391
- correrEjemplo: "dotnet run"
1315
+ // Apps de un solo archivo (.NET 10): `Directory.Build.props` de la capa las saca de la compilación del proyecto.
1316
+ ejecutar: (archivo) => ["dotnet", "run", "--file", archivo],
1317
+ archivoDeReceta: (receta2) => `redcumbre/${receta2.split("-").map((p) => p[0].toUpperCase() + p.slice(1)).join("")}.cs`,
1318
+ marcas: [/\.csproj$/, /\.sln$/, /\.slnx$/]
392
1319
  },
393
1320
  php: {
394
1321
  label: "PHP",
395
1322
  binario: "composer",
396
1323
  generador: ["composer", "create-project", "--no-interaction", "slim/slim-skeleton", "."],
397
- correrEjemplo: "php redcumbre/ejemplo.php"
1324
+ ejecutar: (archivo) => ["php", archivo],
1325
+ archivoDeReceta: (receta2) => `redcumbre/${receta2}.php`,
1326
+ marcas: [/^composer\.json$/]
398
1327
  }
399
1328
  };
400
1329
  function esLenguaje(valor) {
401
1330
  return typeof valor === "string" && LENGUAJES.includes(valor);
402
1331
  }
403
1332
  function carpetaVacia(carpeta) {
404
- return !fs3.existsSync(carpeta) || fs3.readdirSync(carpeta).length === 0;
1333
+ return !fs6.existsSync(carpeta) || fs6.readdirSync(carpeta).length === 0;
405
1334
  }
406
1335
  function encontrarEnPath(binario, env = process.env) {
407
- const directorios = (env.PATH ?? env.Path ?? "").split(path3.delimiter).filter(Boolean);
1336
+ const directorios = (env.PATH ?? env.Path ?? "").split(path6.delimiter).filter(Boolean);
408
1337
  const extensiones = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
409
1338
  for (const directorio of directorios) {
410
1339
  for (const extension of extensiones) {
411
- const candidato = path3.join(directorio, `${binario}${extension}`);
1340
+ const candidato = path6.join(directorio, `${binario}${extension}`);
412
1341
  try {
413
- if (fs3.statSync(candidato).isFile()) return candidato;
1342
+ if (fs6.statSync(candidato).isFile()) return candidato;
414
1343
  } catch {
415
1344
  }
416
1345
  }
@@ -424,311 +1353,1190 @@ function exigirGenerador(lenguaje, env = process.env) {
424
1353
  }
425
1354
  }
426
1355
  function correrGenerador(lenguaje, carpeta, salidaHumana) {
427
- const [comando, ...argumentos] = LENGUAJE_REGISTRY[lenguaje].generador;
428
- fs3.mkdirSync(carpeta, { recursive: true });
429
- const r = spawnSync2(comando, argumentos, {
1356
+ const [comando2, ...argumentos] = LENGUAJE_REGISTRY[lenguaje].generador;
1357
+ fs6.mkdirSync(carpeta, { recursive: true });
1358
+ const r = spawnSync2(comando2, argumentos, {
430
1359
  cwd: carpeta,
431
1360
  // Con `--json` la salida estándar es del objeto final: la del generador va a stderr.
432
1361
  stdio: ["ignore", salidaHumana === "inherit" ? "inherit" : process.stderr, "inherit"],
433
1362
  shell: process.platform === "win32"
434
1363
  });
435
- if (r.error) throw new ErrorCli(`No pude correr \`${comando}\`: ${r.error.message}`);
436
- if (r.status !== 0) throw new ErrorCli(`\`${[comando, ...argumentos].join(" ")}\` termin\xF3 con error (${r.status}). Revisa su salida arriba.`);
1364
+ if (r.error) throw new ErrorCli(`No pude correr \`${comando2}\`: ${r.error.message}`);
1365
+ if (r.status !== 0) throw new ErrorCli(`\`${[comando2, ...argumentos].join(" ")}\` termin\xF3 con error (${r.status}). Revisa su salida arriba.`);
437
1366
  }
438
1367
  var carpetaPlantillas = () => {
439
- const aqui = path3.dirname(fileURLToPath(import.meta.url));
440
- for (const candidata of [path3.join(aqui, "plantillas"), path3.join(aqui, "..", "..", "plantillas")]) {
441
- if (fs3.existsSync(candidata)) return candidata;
1368
+ const aqui = path6.dirname(fileURLToPath(import.meta.url));
1369
+ for (const candidata of [path6.join(aqui, "plantillas"), path6.join(aqui, "..", "..", "plantillas")]) {
1370
+ if (fs6.existsSync(candidata)) return candidata;
442
1371
  }
443
1372
  throw new ErrorCli("El paquete no trae las plantillas por lenguaje: la instalaci\xF3n del CLI est\xE1 incompleta. Reinst\xE1lalo.");
444
1373
  };
1374
+ function detectarLenguaje(proyecto) {
1375
+ if (!fs6.existsSync(proyecto)) return null;
1376
+ const entradas = fs6.readdirSync(proyecto);
1377
+ const encontrados = LENGUAJES.filter((l) => entradas.some((e) => LENGUAJE_REGISTRY[l].marcas.some((m) => m.test(e))));
1378
+ return encontrados.length === 1 ? encontrados[0] : null;
1379
+ }
445
1380
  function agregarCapa(lenguaje, proyecto) {
446
- const origen2 = path3.join(carpetaPlantillas(), lenguaje);
1381
+ const origen2 = path6.join(carpetaPlantillas(), lenguaje, "capa");
447
1382
  const escritos = [];
448
1383
  const copiar = (desde, hacia) => {
449
- for (const entrada of fs3.readdirSync(desde, { withFileTypes: true })) {
450
- const a = path3.join(desde, entrada.name);
451
- const b = path3.join(hacia, entrada.name);
1384
+ for (const entrada of fs6.readdirSync(desde, { withFileTypes: true })) {
1385
+ const a = path6.join(desde, entrada.name);
1386
+ const b = path6.join(hacia, entrada.name);
452
1387
  if (entrada.isDirectory()) {
453
- fs3.mkdirSync(b, { recursive: true });
1388
+ fs6.mkdirSync(b, { recursive: true });
454
1389
  copiar(a, b);
455
- } else {
456
- fs3.copyFileSync(a, b);
457
- escritos.push(path3.relative(proyecto, b));
1390
+ } else if (!fs6.existsSync(b)) {
1391
+ fs6.copyFileSync(a, b);
1392
+ escritos.push(path6.relative(proyecto, b));
458
1393
  }
459
1394
  }
460
1395
  };
461
1396
  copiar(origen2, proyecto);
462
- LENGUAJE_REGISTRY[lenguaje].ajustar?.(proyecto);
463
1397
  return escritos.sort();
464
1398
  }
465
1399
 
1400
+ // src/nucleo/recetas.ts
1401
+ import fs7 from "node:fs";
1402
+ import path7 from "node:path";
1403
+ var RECETAS = ["consultar-rut", "factura", "boleta-honorarios", "boleta-terceros"];
1404
+ var RECETA_REGISTRY = {
1405
+ "consultar-rut": { label: "Consulta un RUT del registro de prueba", emite: false },
1406
+ factura: { label: "Emite una factura electr\xF3nica con el emisor de prueba", emite: true },
1407
+ "boleta-honorarios": { label: "Emite una boleta de honorarios con el emisor de prueba", emite: true },
1408
+ "boleta-terceros": { label: "Emite una boleta de prestaci\xF3n de servicios de terceros con el emisor de prueba", emite: true }
1409
+ };
1410
+ function esReceta(valor) {
1411
+ return typeof valor === "string" && RECETAS.includes(valor);
1412
+ }
1413
+ var MARCA_COMUN = "@redcumbre-comun";
1414
+ var EXTENSION_COMUN = { typescript: "ts", python: "py", dotnet: "cs", php: "php" };
1415
+ function archivosDeReceta(lenguaje, receta2) {
1416
+ const raiz = path7.join(carpetaPlantillas(), lenguaje);
1417
+ const comun = fs7.readFileSync(path7.join(raiz, `_comun.${EXTENSION_COMUN[lenguaje]}`), "utf8").trimEnd();
1418
+ const origen2 = path7.join(raiz, "recetas", receta2);
1419
+ const archivos = [];
1420
+ const recorrer = (dir) => {
1421
+ for (const entrada of fs7.readdirSync(dir, { withFileTypes: true })) {
1422
+ const ruta = path7.join(dir, entrada.name);
1423
+ if (entrada.isDirectory()) {
1424
+ recorrer(ruta);
1425
+ continue;
1426
+ }
1427
+ const lineas = fs7.readFileSync(ruta, "utf8").split("\n");
1428
+ const contenido = lineas.map((linea) => linea.includes(MARCA_COMUN) ? comun : linea).join("\n");
1429
+ archivos.push({ relativa: path7.relative(origen2, ruta).split(path7.sep).join("/"), contenido });
1430
+ }
1431
+ };
1432
+ recorrer(origen2);
1433
+ return archivos.sort((a, b) => a.relativa.localeCompare(b.relativa));
1434
+ }
1435
+ function comandoDeReceta(lenguaje, receta2) {
1436
+ const { ejecutar, archivoDeReceta } = LENGUAJE_REGISTRY[lenguaje];
1437
+ return ejecutar(archivoDeReceta(receta2));
1438
+ }
1439
+ function agregarReceta(lenguaje, receta2, proyecto) {
1440
+ const archivos = archivosDeReceta(lenguaje, receta2);
1441
+ const existentes = archivos.filter((a) => fs7.existsSync(path7.join(proyecto, a.relativa))).map((a) => a.relativa);
1442
+ if (existentes.length > 0) {
1443
+ throw new ErrorCli(
1444
+ `La receta \xAB${receta2}\xBB no se agreg\xF3: ${existentes.length === 1 ? "el archivo" : "los archivos"} ${existentes.join(", ")} ya ${existentes.length === 1 ? "existe" : "existen"} en el proyecto. Una receta s\xF3lo agrega archivos; no escrib\xED nada.`,
1445
+ CODIGOS_DE_SALIDA.error,
1446
+ { codigo: "RECETA_YA_EXISTE", datos: { existentes } }
1447
+ );
1448
+ }
1449
+ for (const a of archivos) {
1450
+ const destino = path7.join(proyecto, a.relativa);
1451
+ fs7.mkdirSync(path7.dirname(destino), { recursive: true });
1452
+ fs7.writeFileSync(destino, a.contenido, { flag: "wx" });
1453
+ }
1454
+ return archivos.map((a) => a.relativa);
1455
+ }
1456
+
1457
+ // src/comandos/instalar-llave.ts
1458
+ function negativaSinRol(ctx, proyecto, empresa2, entorno) {
1459
+ const pantalla = `${ctx.servidores.web}/${empresa2.slug}/admin/api-keys`;
1460
+ return new ErrorCli(
1461
+ `Crear la ${ENTORNO_LLAVE_REGISTRY[entorno].label.toLowerCase()} exige ser administrador de ${empresa2.nombre}: p\xEDdele a un administrador de ${empresa2.nombre} que cree la llave en la pantalla web de llaves (${pantalla}), y deja el archivo descargado en ${rutaLlave(proyecto, entorno)}`,
1462
+ CODIGOS_DE_SALIDA.api4xx,
1463
+ { codigo: "SIN_ROL", datos: { pantalla, archivo: rutaLlave(proyecto, entorno) } }
1464
+ );
1465
+ }
1466
+ async function instalarLlave(ctx, proyecto, empresa2, entorno) {
1467
+ const { salida, cliente } = ctx;
1468
+ const envVersionado = estaVersionado(proyecto, ".env");
1469
+ const modoEsperado = ENTORNO_LLAVE_REGISTRY[entorno].isSandbox;
1470
+ let resultado = "creada";
1471
+ const guardada = leerLlave(proyecto, entorno);
1472
+ const existente = guardada?.tenantSlug === empresa2.slug ? guardada : null;
1473
+ if (existente) {
1474
+ const estado2 = await cliente.whoami(existente.token, existente.tenantSlug);
1475
+ if (estado2.estado === "valida" && estado2.tenant.slug === empresa2.slug && estado2.sandbox === modoEsperado) {
1476
+ asegurarExclusiones(proyecto, envVersionado);
1477
+ escribirPuntero(proyecto, entorno);
1478
+ const llaveId = llaveIdGuardado(proyecto, empresa2.slug, entorno);
1479
+ registrarEnEstado(proyecto, empresa2.slug, entorno, { llaveId, modo: entorno });
1480
+ avisarEnvVersionado(salida, envVersionado);
1481
+ mostrarWhoami(salida, estado2.tenant, entorno, "Se reutiliz\xF3 la llave que ya ten\xEDa el proyecto");
1482
+ return instalada(entorno, "reutilizada", llaveId, estado2.nombre ?? existente.name);
1483
+ }
1484
+ salida.linea(
1485
+ estado2.estado === "rechazada" ? `La llave de ${rutaRelativaLlave(entorno)} ya no funciona (puede estar revocada): creo una nueva en su lugar.` : `La llave de ${rutaRelativaLlave(entorno)} no es de ${nombreEmpresa(empresa2)} en ${nombreDelModo(entorno)}: creo una nueva en su lugar.`
1486
+ );
1487
+ resultado = "reemplazada";
1488
+ }
1489
+ asegurarExclusiones(proyecto, envVersionado);
1490
+ const sesion = await ctx.sesion();
1491
+ let creada;
1492
+ try {
1493
+ creada = await sesion.usar((token) => cliente.crearLlave(token, empresa2.slug, nombreDeLlave(proyecto, entorno, ctx.ahora()), entorno));
1494
+ } catch (error) {
1495
+ if (!(error instanceof ErrorSinRol)) throw error;
1496
+ escribirPuntero(proyecto, entorno);
1497
+ avisarEnvVersionado(salida, envVersionado);
1498
+ throw negativaSinRol(ctx, proyecto, empresa2, entorno);
1499
+ }
1500
+ escribirLlave(proyecto, entorno, {
1501
+ tenantSlug: creada.tenantSlug,
1502
+ name: creada.nombre,
1503
+ role: "FULL-API",
1504
+ isSandbox: ENTORNO_LLAVE_REGISTRY[creada.entorno].isSandbox,
1505
+ token: creada.token,
1506
+ expiresAt: creada.expiresAt,
1507
+ createdAt: creada.createdAt
1508
+ });
1509
+ escribirPuntero(proyecto, entorno);
1510
+ avisarEnvVersionado(salida, envVersionado);
1511
+ const comprobada = await cliente.whoami(creada.token, creada.tenantSlug);
1512
+ if (comprobada.estado !== "valida") {
1513
+ throw new ErrorCli(`La llave reci\xE9n creada no pas\xF3 la comprobaci\xF3n de la plataforma. Qued\xF3 en ${rutaRelativaLlave(entorno)}; rev\xEDsala en la pantalla web de llaves.`, CODIGOS_DE_SALIDA.llave, {
1514
+ codigo: "LLAVE_RECHAZADA"
1515
+ });
1516
+ }
1517
+ const modo = comprobada.sandbox ? "prueba" : "real";
1518
+ registrarEnEstado(proyecto, comprobada.tenant.slug, entorno, { llaveId: creada.id, modo });
1519
+ mostrarWhoami(salida, comprobada.tenant, modo, `Llave \xAB${creada.nombre}\xBB instalada en ${rutaRelativaLlave(entorno)}`);
1520
+ return instalada(entorno, resultado, creada.id, creada.nombre, modo);
1521
+ }
1522
+ var llaveIdGuardado = (proyecto, slug, entorno) => {
1523
+ const estado2 = leerEstado(proyecto);
1524
+ return estado2?.tenantSlug === slug ? estado2.ambientes[entorno]?.llaveId ?? null : null;
1525
+ };
1526
+ var instalada = (entorno, resultado, id, nombre, modo = entorno) => ({
1527
+ entorno,
1528
+ resultado,
1529
+ id,
1530
+ nombre,
1531
+ archivo: rutaRelativaLlave(entorno),
1532
+ variable: variableDeEntorno(entorno),
1533
+ modo
1534
+ });
1535
+ function avisarEnvVersionado(salida, versionado) {
1536
+ if (versionado) {
1537
+ salida.aviso("Tu .env est\xE1 en el control de versiones: s\xF3lo le agregu\xE9 la ruta a la llave (el secreto qued\xF3 en keys/, excluido). No lo saqu\xE9 de git; decide t\xFA si corresponde.");
1538
+ }
1539
+ }
1540
+ function mostrarWhoami(salida, tenant, modo, encabezado) {
1541
+ salida.linea(`\u2713 ${encabezado}.`);
1542
+ salida.linea(` Empresa ${nombreEmpresa(tenant)}`);
1543
+ salida.linea(
1544
+ ` Modo ${modo === "prueba" ? "prueba: no llega al SII, no consume folios y no se cobra" : "real: los documentos que emitas son reales ante el SII y se cobran seg\xFAn tu plan"}`
1545
+ );
1546
+ }
1547
+
1548
+ // src/comandos/mcp.ts
1549
+ import fs8 from "node:fs";
1550
+ import os from "node:os";
1551
+ import path8 from "node:path";
1552
+ var URL_MCP_REDCUMBRE = "https://mcp.redcumbre.cl";
1553
+ var NOMBRE_SERVIDOR_MCP = "redcumbre";
1554
+ var COMANDO_MCP_AGREGAR = "redcumbre mcp agregar";
1555
+ var ASISTENTES_MCP = ["claude-code", "cursor"];
1556
+ var ASISTENTE_REGISTRY = {
1557
+ "claude-code": {
1558
+ label: "Claude Code",
1559
+ archivo: [".claude.json"],
1560
+ autorizar: "abre Claude Code, corre /mcp, elige \xABredcumbre\xBB y autoriza con tu cuenta de REDCUMBRE en el navegador"
1561
+ },
1562
+ cursor: {
1563
+ label: "Cursor",
1564
+ archivo: [".cursor", "mcp.json"],
1565
+ autorizar: "abre Cursor, ve a Settings \u2192 MCP, activa \xABredcumbre\xBB y autoriza con tu cuenta de REDCUMBRE en el navegador"
1566
+ }
1567
+ };
1568
+ var ENTRADA = { type: "http", url: URL_MCP_REDCUMBRE };
1569
+ var esObjeto3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1570
+ var mismaEntrada = (v) => esObjeto3(v) && Object.keys(v).length === 2 && v.type === ENTRADA.type && v.url === ENTRADA.url;
1571
+ var rutaConfigMcp = (asistente, home = os.homedir()) => path8.join(home, ...ASISTENTE_REGISTRY[asistente].archivo);
1572
+ function leerConfig(ruta) {
1573
+ if (!fs8.existsSync(ruta)) return null;
1574
+ let actual;
1575
+ try {
1576
+ actual = JSON.parse(fs8.readFileSync(ruta, "utf8"));
1577
+ } catch (error) {
1578
+ throw new ErrorCli(`${ruta} no tiene JSON v\xE1lido (${error.message}): no lo modifiqu\xE9. Corr\xEDgelo y vuelve a correr el comando.`, CODIGOS_DE_SALIDA.error, {
1579
+ codigo: "CONFIG_MCP_INVALIDA"
1580
+ });
1581
+ }
1582
+ if (!esObjeto3(actual) || actual.mcpServers !== void 0 && !esObjeto3(actual.mcpServers)) {
1583
+ throw new ErrorCli(`${ruta} no tiene la forma { "mcpServers": { \u2026 } }: no lo modifiqu\xE9.`, CODIGOS_DE_SALIDA.error, { codigo: "CONFIG_MCP_INVALIDA" });
1584
+ }
1585
+ return actual;
1586
+ }
1587
+ function planAgregar(asistente, home) {
1588
+ const ruta = rutaConfigMcp(asistente, home);
1589
+ const actual = leerConfig(ruta);
1590
+ if (!actual) return { asistente, ruta, accion: "creado", contenido: `${JSON.stringify({ mcpServers: { [NOMBRE_SERVIDOR_MCP]: ENTRADA } }, null, 2)}
1591
+ ` };
1592
+ const servidores2 = actual.mcpServers ?? {};
1593
+ if (mismaEntrada(servidores2[NOMBRE_SERVIDOR_MCP])) return { asistente, ruta, accion: "sin_cambios" };
1594
+ return { asistente, ruta, accion: "actualizado", contenido: `${JSON.stringify({ ...actual, mcpServers: { ...servidores2, [NOMBRE_SERVIDOR_MCP]: ENTRADA } }, null, 2)}
1595
+ ` };
1596
+ }
1597
+ function planQuitar(asistente, home) {
1598
+ const ruta = rutaConfigMcp(asistente, home);
1599
+ const actual = leerConfig(ruta);
1600
+ const servidores2 = actual?.mcpServers ?? {};
1601
+ if (!actual || !(NOMBRE_SERVIDOR_MCP in servidores2)) return { asistente, ruta, accion: "sin_cambios" };
1602
+ const { [NOMBRE_SERVIDOR_MCP]: _quitada, ...otros } = servidores2;
1603
+ void _quitada;
1604
+ return { asistente, ruta, accion: "actualizado", contenido: `${JSON.stringify({ ...actual, mcpServers: otros }, null, 2)}
1605
+ ` };
1606
+ }
1607
+ function escribir(planes) {
1608
+ for (const p of planes) {
1609
+ if (p.contenido === void 0) continue;
1610
+ fs8.mkdirSync(path8.dirname(p.ruta), { recursive: true });
1611
+ fs8.writeFileSync(p.ruta, p.contenido);
1612
+ }
1613
+ }
1614
+ function asistentesPedidos(asistente) {
1615
+ if (asistente === void 0) return [...ASISTENTES_MCP];
1616
+ if (!ASISTENTES_MCP.includes(asistente)) throw errorDeUso(`El asistente \xAB${asistente}\xBB no existe. Usa ${ASISTENTES_MCP.join(" o ")}.`);
1617
+ return [asistente];
1618
+ }
1619
+ async function mcpAgregar(ctx, opciones) {
1620
+ const asistentes = asistentesPedidos(opciones.asistente);
1621
+ const planes = asistentes.map((a) => planAgregar(a));
1622
+ const nombres = asistentes.map((a) => ASISTENTE_REGISTRY[a].label).join(" y ");
1623
+ const comando2 = `${COMANDO_MCP_AGREGAR}${opciones.asistente ? ` --asistente ${opciones.asistente}` : ""}`;
1624
+ const aviso = `Con el servidor MCP de REDCUMBRE, ${nombres} opera sobre los datos reales de tus empresas con tu cuenta; para emitir, te pide confirmaci\xF3n antes.`;
1625
+ const terminal = ctx.salida.json ? null : ctx.terminal;
1626
+ if (!terminal) throw faltaConfirmacion(`${aviso} Configurarlo lo confirma una persona en una terminal: no escrib\xED nada.`, comando2, "MCP_REQUIERE_PERSONA");
1627
+ ctx.salida.linea(aviso);
1628
+ for (const p of planes) ctx.salida.linea(` ${ASISTENTE_REGISTRY[p.asistente].label}: ${p.ruta}`);
1629
+ if (!await terminal.confirmar(`\xBFAgrego REDCUMBRE a ${nombres}?`)) throw faltaConfirmacion("No confirmaste: no escrib\xED nada.", comando2);
1630
+ escribir(planes);
1631
+ ctx.salida.linea(`\u2713 Servidor MCP de REDCUMBRE (${URL_MCP_REDCUMBRE}) configurado.`);
1632
+ ctx.salida.linea("Para autorizar la conexi\xF3n:");
1633
+ for (const p of planes) ctx.salida.linea(` \xB7 ${ASISTENTE_REGISTRY[p.asistente].label}: ${ASISTENTE_REGISTRY[p.asistente].autorizar}.`);
1634
+ ctx.salida.resultado({ ok: true, archivos: planes.map(({ asistente, ruta, accion }) => ({ asistente, ruta, accion })) });
1635
+ }
1636
+ async function mcpQuitar(ctx, opciones) {
1637
+ const planes = asistentesPedidos(opciones.asistente).map((a) => planQuitar(a));
1638
+ escribir(planes);
1639
+ for (const p of planes) {
1640
+ ctx.salida.linea(`${ASISTENTE_REGISTRY[p.asistente].label}: ${p.accion === "sin_cambios" ? "no ten\xEDa REDCUMBRE" : "quit\xE9 REDCUMBRE; los otros servidores quedaron igual"} (${p.ruta})`);
1641
+ }
1642
+ ctx.salida.resultado({ ok: true, archivos: planes.map(({ asistente, ruta, accion }) => ({ asistente, ruta, accion })) });
1643
+ }
1644
+
1645
+ // src/comandos/pasar-a-real.ts
1646
+ async function pasarAReal(ctx, opciones) {
1647
+ const { salida, cliente } = ctx;
1648
+ const terminal = salida.json ? null : ctx.terminal;
1649
+ const proyecto = opciones.proyecto ?? ctx.proyecto;
1650
+ let pedidos;
1651
+ if (opciones.servicios !== void 0) {
1652
+ const codigos = lista(opciones.servicios, "--servicios");
1653
+ const desconocidos = codigos.filter((c) => !esCodigoServicioDePasoAReal(c));
1654
+ if (desconocidos.length) {
1655
+ throw errorDeUso(`${desconocidos.length === 1 ? "El servicio" : "Los servicios"} \xAB${desconocidos.join("\xBB, \xAB")}\xBB no existe${desconocidos.length === 1 ? "" : "n"}. Usa: ${CODIGOS_SERVICIO_DE_PASO_A_REAL.join(", ")}.`);
1656
+ }
1657
+ pedidos = codigos;
1658
+ }
1659
+ const slug = empresaDelProyecto({ proyecto }, opciones.empresa);
1660
+ const sesion = await ctx.sesion();
1661
+ const perfil = await sesion.usar((token) => cliente.perfil(token));
1662
+ const empresa2 = perfil.empresas.find((e) => e.slug === slug);
1663
+ if (!empresa2) throw errorDeUso(`No perteneces a la empresa \xAB${slug}\xBB. Tus empresas: ${perfil.empresas.map((e) => e.slug).join(", ") || "ninguna"}.`);
1664
+ const comando2 = (servicios) => `redcumbre pasar-a-real --empresa ${slug} --servicios ${servicios.length ? servicios.join(",") : "<c\xF3digo,c\xF3digo>"}`;
1665
+ try {
1666
+ const prueba = leerLlave(proyecto, "prueba");
1667
+ const llaveId = prueba?.tenantSlug === slug ? await resolverLlaveId({ proyecto, sesion: ctx.sesion, cliente }, { entorno: "prueba", archivo: prueba, ruta: rutaLlave(proyecto, "prueba") }) ?? void 0 : void 0;
1668
+ const revisar = (servicios2) => sesion.usar((token) => cliente.revisionPasoAReal(token, slug, llaveId, servicios2));
1669
+ let revision = await revisar(pedidos);
1670
+ if (revision.servicios.length === 0) {
1671
+ if (!terminal) {
1672
+ throw faltaConfirmacion(
1673
+ `La llave de prueba no tiene llamadas de las que deducir qu\xE9 servicios usa el proyecto. Dime cu\xE1les con --servicios (${CODIGOS_SERVICIO_DE_PASO_A_REAL.join(", ")}).`,
1674
+ comando2([]),
1675
+ "PASO_A_REAL_REQUIERE_SERVICIOS"
1676
+ );
1677
+ }
1678
+ revision = await revisar(await elegirServicios(terminal, "La llave de prueba no tiene llamadas. \xBFQu\xE9 servicios usa este proyecto?"));
1679
+ } else if (!pedidos && terminal && revision.servicios.some((s) => s.deducido)) {
1680
+ salida.linea("Por las llamadas de la llave de prueba, el proyecto usa:");
1681
+ for (const s of revision.servicios) salida.linea(` \xB7 ${s.nombre} (${s.codigo})`);
1682
+ if (!await terminal.confirmar("\xBFSon esos los servicios del proyecto?")) revision = await revisar(await elegirServicios(terminal, "\xBFQu\xE9 servicios usa este proyecto?"));
1683
+ }
1684
+ const servicios = revision.servicios.map((s) => s.codigo);
1685
+ mostrarRevision(ctx, revision);
1686
+ if (!revision.listo) {
1687
+ throw new ErrorCli(`A ${nombreEmpresa(empresa2)} le falta configurar lo de arriba para pasar a real. No cre\xE9 la llave real.`, CODIGOS_DE_SALIDA.error, {
1688
+ codigo: "PASO_A_REAL_INCOMPLETO",
1689
+ datos: { servicios: revision.servicios }
1690
+ });
1691
+ }
1692
+ if (!terminal) {
1693
+ throw new ErrorCli(
1694
+ `${nombreEmpresa(empresa2)} est\xE1 lista para pasar a real. La llave real la crea una persona que confirma en una terminal. No cre\xE9 nada.`,
1695
+ CODIGOS_DE_SALIDA.confirmacion,
1696
+ { codigo: "PASO_A_REAL_REQUIERE_PERSONA", comando: comando2(servicios), datos: { servicios: revision.servicios } }
1697
+ );
1698
+ }
1699
+ const confirmada = await terminal.confirmar(
1700
+ `\xBFConfirmas crear la llave real de ${nombreEmpresa(empresa2)}? Lo que emitas con ella es real ante el SII y se cobra seg\xFAn tu plan.`
1701
+ );
1702
+ if (!confirmada) throw faltaConfirmacion("No confirmaste: no cre\xE9 la llave real.", comando2(servicios));
1703
+ const llave = await instalarLlave(ctx, proyecto, empresa2, "real");
1704
+ salida.linea("La llave de prueba sigue igual: \xABredcumbre api\xBB la usa por omisi\xF3n y la real s\xF3lo con --real.");
1705
+ let consulta = null;
1706
+ if (await terminal.confirmar("\xBFQuieres consultar un RUT en el SII con la llave real? (se cobra como una consulta)")) {
1707
+ try {
1708
+ consulta = await consultarRut(ctx, proyecto, empresa2, terminal);
1709
+ } catch (error) {
1710
+ if (!(error instanceof ErrorCli)) throw error;
1711
+ salida.aviso(`La llave real qued\xF3 instalada, pero la consulta del RUT no se pudo hacer: ${error.message}`);
1712
+ consulta = { error: { codigo: error.codigo, mensaje: error.message } };
1713
+ }
1714
+ }
1715
+ salida.resultado({ ok: true, empresa: { slug: empresa2.slug, nombre: empresa2.nombre }, entorno: "real", llave, servicios: revision.servicios, consulta });
1716
+ } catch (error) {
1717
+ if (!(error instanceof ErrorSinRol)) throw error;
1718
+ asegurarExclusiones(proyecto, estaVersionado(proyecto, ".env"));
1719
+ escribirPuntero(proyecto, "real");
1720
+ throw negativaSinRol(ctx, proyecto, empresa2, "real");
1721
+ }
1722
+ }
1723
+ async function elegirServicios(terminal, pregunta) {
1724
+ return terminal.elegirVarias(
1725
+ pregunta,
1726
+ SERVICIOS_DE_PASO_A_REAL.map((s) => ({ valor: s.codigo, etiqueta: `${s.nombre} (${s.codigo})` }))
1727
+ );
1728
+ }
1729
+ function mostrarRevision(ctx, revision) {
1730
+ for (const s of revision.servicios) {
1731
+ ctx.salida.linea(`${s.faltantes.length ? "\u2717" : "\u2713"} ${s.nombre}`);
1732
+ for (const f of s.faltantes) ctx.salida.linea(` Falta: ${f.que}. Config\xFAralo en ${ctx.servidores.web}${f.donde}`);
1733
+ for (const aviso of s.avisos) ctx.salida.aviso(`${s.nombre}: ${aviso}`);
1734
+ }
1735
+ }
1736
+ async function consultarRut(ctx, proyecto, empresa2, terminal) {
1737
+ const real = leerLlave(proyecto, "real");
1738
+ if (!real) throw new ErrorCli("No encuentro la llave real reci\xE9n instalada.", CODIGOS_DE_SALIDA.llave, { codigo: "SIN_LLAVE_REAL" });
1739
+ const rut = await terminal.preguntar("RUT a consultar (por ejemplo 76086428-5): ");
1740
+ if (!rut) {
1741
+ ctx.salida.linea("No consult\xE9 ning\xFAn RUT.");
1742
+ return { rut: null };
1743
+ }
1744
+ const respuesta = await ctx.cliente.conLlave("POST", real.token, rutaDeEmpresa(empresa2.slug, "/herramientas/lookup-rut"), `consultar el RUT ${rut} en el SII`, { cuerpo: { rut } });
1745
+ const datos = desenvolver(respuesta);
1746
+ const persona = respuesta.persona ?? null;
1747
+ const nombre = datos?.razonSocial ?? persona?.nombre ?? null;
1748
+ for (const linea of lineasDeLaConsultaDeRut(rut, datos, persona)) ctx.salida.linea(linea);
1749
+ return { rut, razonSocial: nombre };
1750
+ }
1751
+ function lineasDeLaConsultaDeRut(rut, datos, persona) {
1752
+ if (!datos?.razonSocial && !persona?.nombre) return [`El SII no devolvi\xF3 datos para ${rut}.`];
1753
+ const lineas = [`\u2713 El SII responde para ${rut}:`];
1754
+ if (datos?.razonSocial) lineas.push(` Raz\xF3n social: ${datos.razonSocial}`);
1755
+ if (persona?.nombre) lineas.push(` Nombre: ${persona.nombre}`);
1756
+ if (persona?.fallecido) lineas.push(" El SII lo registra como fallecido.");
1757
+ if (datos?.giroGlosa) lineas.push(` Giro: ${datos.giroGlosa}`);
1758
+ for (const a of datos?.actividadesEconomicas ?? []) lineas.push(` Actividad econ\xF3mica: ${a.codigo} ${a.descripcion}`);
1759
+ for (const d of datos?.direcciones ?? []) lineas.push(` Direcci\xF3n: ${d.direccion}, ${d.comuna}`);
1760
+ return lineas;
1761
+ }
1762
+
1763
+ // src/comandos/solicitar-cuenta.ts
1764
+ var COMANDO_SOLICITAR_CUENTA = "npx @redcumbrecl/cli solicitar-cuenta";
1765
+ var MAXIMO_INTENTOS = 3;
1766
+ var CORREO = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1767
+ async function solicitarCuenta(ctx, prellenado = {}) {
1768
+ const terminal = ctx.salida.json ? null : ctx.terminal;
1769
+ if (!terminal) {
1770
+ throw new ErrorCli(
1771
+ `La solicitud de cuenta la env\xEDa una persona desde una terminal: ${SOLICITUD_CUENTA_AVISO}. No se envi\xF3 nada.`,
1772
+ CODIGOS_DE_SALIDA.confirmacion,
1773
+ { codigo: "SOLICITUD_REQUIERE_PERSONA", comando: COMANDO_SOLICITAR_CUENTA }
1774
+ );
1775
+ }
1776
+ const datos = {};
1777
+ const [nombre, email, empresa2, rut, stack] = SOLICITUD_CUENTA_CAMPOS;
1778
+ for (const campo of [nombre, email, empresa2, rut]) datos[campo.campo] = await pedirCampo(ctx, terminal, campo, prellenado[campo.campo]);
1779
+ const dominios = await terminal.elegirVarias(
1780
+ "\xBFQu\xE9 servicios quieres integrar?",
1781
+ SOLICITUD_CUENTA_DOMINIOS.map((d) => ({ valor: d, etiqueta: SOLICITUD_CUENTA_DOMINIO_LABELS[d] }))
1782
+ );
1783
+ datos.stack = await pedirCampo(ctx, terminal, stack);
1784
+ ctx.salida.linea();
1785
+ ctx.salida.linea(SOLICITUD_CUENTA_AVISO);
1786
+ ctx.salida.linea();
1787
+ for (const campo of SOLICITUD_CUENTA_CAMPOS) {
1788
+ ctx.salida.linea(` ${campo.label.padEnd(20)} ${datos[campo.campo]}`);
1789
+ if (campo.campo === "rut_empresa") ctx.salida.linea(` ${"Servicios".padEnd(20)} ${dominios.map((d) => SOLICITUD_CUENTA_DOMINIO_LABELS[d]).join(", ")}`);
1790
+ }
1791
+ if (!await terminal.confirmar("\xBFEnviar la solicitud?")) {
1792
+ ctx.salida.linea("No envi\xE9 la solicitud.");
1793
+ return false;
1794
+ }
1795
+ const r = await ctx.cliente.pedir("POST", "/public/forms", {
1796
+ cuerpo: { form_type: "solicitud_cuenta", page: `cli/${ctx.version}`, ...datos, dominios }
1797
+ });
1798
+ if (r.status < 200 || r.status >= 300) {
1799
+ const detalle = mensajeDelCuerpo(r.json);
1800
+ throw new ErrorCli(
1801
+ `No pude enviar la solicitud: el API respondi\xF3 ${r.status}${detalle ? ` (${detalle})` : ""}.`,
1802
+ r.status >= 500 ? CODIGOS_DE_SALIDA.api5xx : CODIGOS_DE_SALIDA.api4xx,
1803
+ { codigo: `HTTP_${r.status}` }
1804
+ );
1805
+ }
1806
+ ctx.salida.linea(`\u2713 Solicitud enviada. Te escribiremos a ${datos.email}.`);
1807
+ return true;
1808
+ }
1809
+ async function pedirCampo(ctx, terminal, campo, previo) {
1810
+ for (let intento = 0; intento < MAXIMO_INTENTOS; intento++) {
1811
+ const respuesta = await terminal.preguntar(`${campo.label}${previo ? ` [${previo}]` : ""}: `) || previo || "";
1812
+ const problema = !respuesta ? "no puede ir vac\xEDo" : respuesta.length > campo.largoMaximo ? `admite hasta ${campo.largoMaximo} caracteres` : campo.campo === "email" && !CORREO.test(respuesta) ? "no parece un correo" : null;
1813
+ if (!problema) return respuesta;
1814
+ ctx.salida.linea(`\xAB${campo.label}\xBB ${problema}.`);
1815
+ }
1816
+ throw new ErrorCli(`\xAB${campo.label}\xBB qued\xF3 sin un valor v\xE1lido despu\xE9s de ${MAXIMO_INTENTOS} intentos. No se envi\xF3 nada.`, CODIGOS_DE_SALIDA.error, { codigo: "SOLICITUD_INCOMPLETA" });
1817
+ }
1818
+
466
1819
  // src/comandos/init.ts
467
- async function ejecutarInit(opciones, deps) {
468
- const { salida, interactivo, preguntas } = deps;
469
- if (opciones.entorno !== void 0 && !esEntornoLlave(opciones.entorno)) {
470
- throw new ErrorCli(`--entorno debe ser ${ENTORNOS_LLAVE.join(" o ")} (recib\xED \xAB${opciones.entorno}\xBB).`);
471
- }
472
- if (!interactivo && opciones.entorno === void 0) {
473
- throw new ErrorCli(`Sin una terminal interactiva, --entorno es obligatorio (${ENTORNOS_LLAVE.join(" o ")}). No elijo el entorno por ti.`);
474
- }
475
- if (opciones.lenguaje !== void 0 && !esLenguaje(opciones.lenguaje)) {
476
- throw new ErrorCli(`--lenguaje debe ser uno de: ${LENGUAJES.join(", ")} (recib\xED \xAB${opciones.lenguaje}\xBB).`);
477
- }
478
- let proyecto = path4.resolve(deps.cwd, opciones.carpeta ?? ".");
479
- let lenguaje = null;
480
- if (carpetaVacia(proyecto)) {
481
- if (opciones.lenguaje) lenguaje = opciones.lenguaje;
482
- else if (interactivo) lenguaje = await preguntas.lenguaje();
483
- else salida.linea(`La carpeta ${proyecto} est\xE1 vac\xEDa y no pasaste --lenguaje: instalo s\xF3lo la llave, sin armar un proyecto.`);
484
- if (lenguaje) exigirGenerador(lenguaje);
485
- } else {
486
- if (opciones.lenguaje) throw new ErrorCli(`La carpeta ${proyecto} no est\xE1 vac\xEDa: --lenguaje s\xF3lo sirve para armar un proyecto desde cero. En un proyecto existente instalo s\xF3lo la llave.`);
487
- if (interactivo && opciones.carpeta === void 0) proyecto = path4.resolve(deps.cwd, await preguntas.dondeInstalar("."));
1820
+ var MAXIMO_INTENTOS2 = 3;
1821
+ async function init(ctx, opciones) {
1822
+ const { salida } = ctx;
1823
+ const terminal = salida.json ? null : ctx.terminal;
1824
+ if (opciones.entorno !== void 0 && !esEntornoLlave(opciones.entorno)) throw errorDeUso(mensajeEntornoLlaveInvalido(opciones.entorno));
1825
+ if (opciones.lenguaje !== void 0 && !esLenguaje(opciones.lenguaje)) throw errorDeUso(`El lenguaje \xAB${opciones.lenguaje}\xBB no existe. Usa ${LENGUAJES.join(", ")}.`);
1826
+ let proyecto = path9.resolve(ctx.cwd, opciones.carpeta ?? ".");
1827
+ if (opciones.entorno === "real") {
1828
+ if (opciones.lenguaje) throw errorDeUso("--lenguaje arma un proyecto desde cero y va s\xF3lo con la llave de prueba; --entorno real se agrega a un proyecto ya conectado.");
1829
+ return pasarAReal(ctx, { empresa: opciones.empresa, servicios: opciones.servicios, proyecto });
488
1830
  }
489
- const sesion = await deps.sesion();
490
- const empresas = await sesion.usar((token) => deps.api.empresas(token));
491
- if (empresas.length === 0) throw new ErrorCli("Tu cuenta no pertenece a ninguna empresa en rCAPI.");
492
- let slug;
493
- if (opciones.empresa) {
494
- if (!empresas.some((e) => e.slug === opciones.empresa)) {
495
- throw new ErrorCli(`No perteneces a la empresa \xAB${opciones.empresa}\xBB. Tus empresas: ${empresas.map((e) => e.slug).join(", ")}.`);
1831
+ if (opciones.servicios !== void 0) throw errorDeUso("--servicios va s\xF3lo con --entorno real.");
1832
+ const vacia = carpetaVacia(proyecto);
1833
+ if (!vacia && opciones.lenguaje) {
1834
+ throw errorDeUso(`La carpeta ${proyecto} no est\xE1 vac\xEDa: --lenguaje s\xF3lo sirve para armar un proyecto desde cero. En un proyecto existente instalo s\xF3lo la llave.`);
1835
+ }
1836
+ if (opciones.lenguaje) exigirGenerador(opciones.lenguaje, ctx.env);
1837
+ const sesion = await ctx.sesion();
1838
+ const perfil = await sesion.usar((token) => ctx.cliente.perfil(token));
1839
+ if (perfil.empresas.length === 0) {
1840
+ if (!terminal) {
1841
+ throw new ErrorCli("Tu cuenta todav\xEDa no pertenece a ninguna empresa en REDCUMBRE. Para pedir una cuenta, corre el comando en una terminal.", CODIGOS_DE_SALIDA.error, {
1842
+ codigo: "SIN_EMPRESAS",
1843
+ comando: COMANDO_SOLICITAR_CUENTA
1844
+ });
496
1845
  }
497
- slug = opciones.empresa;
498
- } else if (interactivo) {
499
- slug = await preguntas.empresa(empresas);
500
- } else {
501
- throw new ErrorCli(`Sin una terminal interactiva, --empresa es obligatorio. Tus empresas: ${empresas.map((e) => e.slug).join(", ")}.`);
1846
+ salida.linea("Tu cuenta todav\xEDa no pertenece a ninguna empresa en REDCUMBRE.");
1847
+ if (await terminal.confirmar("\xBFQuieres enviar una solicitud de cuenta?")) {
1848
+ const enviada = await solicitarCuenta(ctx, { nombre: perfil.persona.nombre, email: perfil.persona.correo });
1849
+ salida.resultado({ ok: true, solicitud: enviada ? "enviada" : "no-enviada" });
1850
+ } else {
1851
+ salida.linea(`Cuando quieras pedirla: ${COMANDO_SOLICITAR_CUENTA}`);
1852
+ salida.resultado({ ok: true, solicitud: "no-enviada" });
1853
+ }
1854
+ return;
502
1855
  }
503
- const empresa = empresas.find((e) => e.slug === slug);
504
- const entorno = opciones.entorno ?? await preguntas.entorno();
1856
+ const empresa2 = await elegirEmpresa(ctx, perfil.empresas, opciones.empresa);
1857
+ let lenguaje = opciones.lenguaje ?? null;
1858
+ if (vacia && !lenguaje && terminal) {
1859
+ lenguaje = await preguntarLenguaje(ctx);
1860
+ if (lenguaje) exigirGenerador(lenguaje, ctx.env);
1861
+ } else if (!vacia && terminal && opciones.carpeta === void 0 && !tieneInstalacionDelCli(proyecto)) {
1862
+ const respuesta = await terminal.preguntar("\xBFD\xF3nde instalo la llave? [.]: ");
1863
+ proyecto = path9.resolve(ctx.cwd, respuesta || ".");
1864
+ }
1865
+ let capa = [];
505
1866
  if (lenguaje) {
506
- salida.linea(`Armando el proyecto ${LENGUAJE_REGISTRY[lenguaje].label} con \`${LENGUAJE_REGISTRY[lenguaje].generador.join(" ")}\`\u2026`);
1867
+ const { label, generador } = LENGUAJE_REGISTRY[lenguaje];
1868
+ salida.linea(`Armando el proyecto ${label} con \xAB${generador.join(" ")}\xBB\u2026`);
507
1869
  correrGenerador(lenguaje, proyecto, salida.json ? "pipe" : "inherit");
508
- const capa = agregarCapa(lenguaje, proyecto);
509
- salida.linea(`Capa de rCAPI agregada: ${capa.join(", ")}.`);
1870
+ capa = [...agregarCapa(lenguaje, proyecto), ...agregarReceta(lenguaje, "factura", proyecto)];
1871
+ salida.linea(`Capa de REDCUMBRE agregada: ${capa.join(", ")}.`);
1872
+ salida.linea(`La receta factura se corre con \xAB${comandoDeReceta(lenguaje, "factura").join(" ")}\xBB.`);
510
1873
  }
511
- const anterior = empresaAnterior(proyecto, slug);
512
- const instaladas = [];
513
- instaladas.push(await instalarEntorno(proyecto, empresa, entorno, sesion, deps));
1874
+ const anterior = empresaAnterior(proyecto, empresa2.slug);
1875
+ const llave = await instalarLlave(ctx, proyecto, empresa2, "prueba");
514
1876
  if (anterior) {
515
- soltarEmpresaAnterior(proyecto, slug);
516
- salida.aviso(`El proyecto apuntaba a ${anterior.empresa} (${anterior.entornos.join(" y ")}). Dej\xF3 de apuntar a esas llaves; siguen activas en la web y puedes revocarlas ah\xED.`);
517
- }
518
- for (const faltante of anterior?.entornos.filter((e) => e !== entorno) ?? []) {
519
- salida.aviso(`El proyecto qued\xF3 sin llave de ${ENTORNO_LLAVE_REGISTRY[faltante].label} para ${empresa.nombre}.`);
520
- if (interactivo && await preguntas.otroEntorno(faltante, empresa.nombre)) {
521
- instaladas.push(await instalarEntorno(proyecto, empresa, faltante, sesion, deps));
522
- } else {
523
- salida.linea(`Para crearla: npx @redcumbrecl/cli init --empresa ${slug} --entorno ${faltante}`);
524
- }
1877
+ soltarEmpresaAnterior(proyecto, empresa2.slug);
1878
+ salida.aviso(`El proyecto apuntaba a ${anterior.empresa}. Dej\xF3 de apuntar a esas llaves; siguen activas en la web y puedes revocarlas ah\xED.`);
1879
+ if (anterior.entornos.includes("real")) salida.aviso(`El proyecto qued\xF3 sin llave real para ${nombreEmpresa(empresa2)}. Se obtiene con \xAB${COMANDO_PASAR_A_REAL}\xBB.`);
525
1880
  }
526
- if (lenguaje) salida.linea(`Para probar la integraci\xF3n: ${LENGUAJE_REGISTRY[lenguaje].correrEjemplo}`);
527
- let mcp = null;
528
- if (!opciones.sinMcp) {
529
- try {
530
- mcp = conectarMcp(proyecto);
531
- informarMcp(salida, mcp);
532
- } catch (error) {
533
- if (!(error instanceof ErrorCli)) throw error;
534
- salida.aviso(`${error.message} La llave qued\xF3 instalada; el servidor MCP no se configur\xF3.`);
535
- }
1881
+ const comandoPrimeraPrueba = `${COMANDO_INIT} --empresa ${empresa2.slug}`;
1882
+ let primeraPrueba;
1883
+ if (terminal) {
1884
+ primeraPrueba = await hacerPrimeraPrueba(ctx, proyecto, empresa2);
1885
+ } else {
1886
+ primeraPrueba = {
1887
+ comando: comandoPrimeraPrueba,
1888
+ descripcion: "C\xF3rrelo en una terminal: reutiliza la llave de prueba, emite una factura con el emisor de prueba y abre su PDF."
1889
+ };
536
1890
  }
1891
+ salida.linea();
1892
+ salida.linea(`Para que tu asistente (Claude Code o Cursor) trabaje con REDCUMBRE: ${COMANDO_MCP_AGREGAR}`);
537
1893
  salida.resultado({
538
1894
  ok: true,
539
1895
  proyecto,
540
- empresa: { slug: empresa.slug, nombre: empresa.nombre },
1896
+ empresa: { slug: empresa2.slug, nombre: empresa2.nombre },
1897
+ entorno: "prueba",
541
1898
  lenguaje,
542
- llaves: instaladas.map((i) => ({
543
- entorno: i.entorno,
544
- resultado: i.resultado,
545
- archivo: rutaRelativaLlave(i.entorno),
546
- variable: variableDeEntorno(i.entorno),
547
- sandbox: i.sandbox
548
- })),
549
- mcp
1899
+ archivos: capa,
1900
+ llave,
1901
+ primeraPrueba,
1902
+ mcp: { comando: COMANDO_MCP_AGREGAR }
550
1903
  });
551
1904
  }
552
- async function instalarEntorno(proyecto, empresa, entorno, sesion, deps) {
553
- const { salida, api } = deps;
554
- const envVersionado = estaVersionado(proyecto, ".env");
1905
+ async function elegirEmpresa(ctx, empresas, pedida) {
1906
+ if (pedida) {
1907
+ const encontrada = empresas.find((e) => e.slug === pedida);
1908
+ if (!encontrada) throw errorDeUso(`No perteneces a la empresa \xAB${pedida}\xBB. Tus empresas: ${empresas.map((e) => e.slug).join(", ")}.`);
1909
+ return encontrada;
1910
+ }
1911
+ if (empresas.length === 1) return empresas[0];
1912
+ const terminal = ctx.salida.json ? null : ctx.terminal;
1913
+ if (!terminal) throw errorDeUso(`Perteneces a m\xE1s de una empresa: indica cu\xE1l con --empresa (${empresas.map((e) => e.slug).join(", ")}).`);
1914
+ return terminal.elegir(
1915
+ "\xBFCon qu\xE9 empresa conecto este proyecto?",
1916
+ empresas.map((e) => ({ valor: e, etiqueta: nombreEmpresa(e) }))
1917
+ );
1918
+ }
1919
+ async function preguntarLenguaje(ctx) {
1920
+ const terminal = ctx.terminal;
1921
+ const opciones = LENGUAJES.map((l) => `${l} (${LENGUAJE_REGISTRY[l].label})`).join(", ");
1922
+ for (let intento = 0; intento < MAXIMO_INTENTOS2; intento++) {
1923
+ const respuesta = (await terminal.preguntar(`\xBFArmo un proyecto nuevo desde cero? Escribe el lenguaje \u2014${opciones}\u2014 o d\xE9jalo vac\xEDo para instalar s\xF3lo la llave: `)).toLowerCase();
1924
+ if (!respuesta) return null;
1925
+ if (esLenguaje(respuesta)) return respuesta;
1926
+ ctx.salida.linea(`\xAB${respuesta}\xBB no es uno de los lenguajes. Usa ${LENGUAJES.join(", ")}.`);
1927
+ }
1928
+ throw errorDeUso(`No reconoc\xED el lenguaje despu\xE9s de ${MAXIMO_INTENTOS2} intentos. Usa ${LENGUAJES.join(", ")}.`);
1929
+ }
1930
+ async function hacerPrimeraPrueba(ctx, proyecto, empresa2) {
1931
+ const { salida, cliente } = ctx;
1932
+ const llave = leerLlave(proyecto, "prueba");
1933
+ if (!llave) throw new ErrorCli(`No encuentro la llave de prueba reci\xE9n instalada en ${proyecto}.`, CODIGOS_DE_SALIDA.llave, { codigo: "SIN_LLAVE_DE_PRUEBA" });
1934
+ const { token } = llave;
1935
+ try {
1936
+ salida.linea();
1937
+ salida.linea("Primera prueba: emito una factura con el emisor de prueba de tu empresa.");
1938
+ const escenarios2 = desenvolver(
1939
+ await cliente.conLlave("GET", token, rutaDeEmpresa(empresa2.slug, "/modo-prueba/escenarios"), "leer los escenarios de prueba")
1940
+ );
1941
+ const receptor = escenarios2.ruts.find((r) => r.rol === "cliente");
1942
+ if (!escenarios2.emisorDte || !receptor) {
1943
+ throw new ErrorCli(`El modo de prueba de ${nombreEmpresa(empresa2)} no trae el emisor de prueba o un RUT cliente de prueba.`, CODIGOS_DE_SALIDA.error, { codigo: "SIN_ESCENARIO" });
1944
+ }
1945
+ const hoy = new Intl.DateTimeFormat("en-CA", { timeZone: "America/Santiago" }).format(ctx.ahora());
1946
+ const emitido = desenvolver(
1947
+ await cliente.conLlave("POST", token, rutaDeEmpresa(empresa2.slug, "/dte"), "emitir la factura de prueba", {
1948
+ cuerpo: {
1949
+ emisorDteId: escenarios2.emisorDte.id,
1950
+ tipoDte: "FACTURA_AFECTA",
1951
+ receptor: {
1952
+ rut: receptor.rut,
1953
+ razonSocial: "CLIENTE DE PRUEBA",
1954
+ giro: "SERVICIOS",
1955
+ direccion: "AV PRUEBA 123",
1956
+ comuna: "PROVIDENCIA",
1957
+ ciudad: "SANTIAGO"
1958
+ },
1959
+ lineas: [{ nombre: "Primera prueba con REDCUMBRE", cantidad: 1, precioUnitario: 1e3, subtotal: 1e3 }],
1960
+ formaPago: "CONTADO",
1961
+ fechaEmision: hoy,
1962
+ idempotencyKey: randomUUID2()
1963
+ }
1964
+ })
1965
+ );
1966
+ const id = emitido.dte?.id;
1967
+ if (id === void 0) throw new ErrorCli("El API emiti\xF3 la factura de prueba pero no devolvi\xF3 su id.", CODIGOS_DE_SALIDA.error, { codigo: "SIN_ID" });
1968
+ salida.linea(`\u2713 Factura de prueba emitida (id ${id}${emitido.dte?.folio ? `, folio ${emitido.dte.folio}` : ""}). No llega al SII ni consume folios.`);
1969
+ const pdf = await cliente.pedir("GET", rutaDeEmpresa(empresa2.slug, `/dte/${encodeURIComponent(String(id))}/pdf`), { credencial: { tipo: "llave", token } });
1970
+ if (pdf.status < 200 || pdf.status >= 300 || !pdf.bytes) {
1971
+ throw new ErrorCli(`No pude descargar el PDF de la factura de prueba: el API respondi\xF3 ${pdf.status}.`, pdf.status >= 500 ? CODIGOS_DE_SALIDA.api5xx : CODIGOS_DE_SALIDA.api4xx, {
1972
+ codigo: `HTTP_${pdf.status}`
1973
+ });
1974
+ }
1975
+ const ruta = path9.join(os2.tmpdir(), `redcumbre-factura-de-prueba-${id}.pdf`);
1976
+ fs9.writeFileSync(ruta, pdf.bytes);
1977
+ if (await ctx.abrir(ruta)) salida.linea(`\u2713 Abr\xED el PDF: ${ruta}`);
1978
+ else salida.linea(`El PDF qued\xF3 en ${ruta}; \xE1brelo desde ah\xED.`);
1979
+ return { dteId: String(id), pdf: ruta };
1980
+ } catch (error) {
1981
+ if (!(error instanceof ErrorCli)) throw error;
1982
+ throw new ErrorCli(`La llave de prueba qued\xF3 instalada, pero la primera prueba fall\xF3: ${error.message}`, error.codigoSalida, {
1983
+ codigo: error.codigo,
1984
+ comando: `${COMANDO_INIT} --empresa ${empresa2.slug}`,
1985
+ datos: error.datos
1986
+ });
1987
+ }
1988
+ }
1989
+
1990
+ // src/comandos/llaves.ts
1991
+ async function llaves(ctx, opciones) {
1992
+ const slug = empresaDelProyecto(ctx, opciones.empresa);
1993
+ const sesion = await ctx.sesion();
1994
+ const listadas = await sesion.usar((token) => ctx.cliente.listarLlaves(token, slug));
1995
+ const delProyecto = /* @__PURE__ */ new Set();
1996
+ for (const entorno of ["prueba", "real"]) {
1997
+ const archivo = leerLlave(ctx.proyecto, entorno);
1998
+ if (archivo?.tenantSlug !== slug) continue;
1999
+ const estado2 = leerEstado(ctx.proyecto);
2000
+ const guardado = estado2?.tenantSlug === slug ? estado2.ambientes[entorno]?.llaveId : void 0;
2001
+ if (guardado) {
2002
+ delProyecto.add(guardado);
2003
+ continue;
2004
+ }
2005
+ const encontradas = coincidencias(archivo, listadas);
2006
+ if (encontradas.length !== 1) continue;
2007
+ guardarLlaveId(ctx.proyecto, entorno, encontradas[0].id);
2008
+ delProyecto.add(encontradas[0].id);
2009
+ }
2010
+ const marcadas = listadas.map((l) => ({ ...l, delProyecto: delProyecto.has(l.id) }));
2011
+ if (marcadas.length === 0) ctx.salida.linea(`${slug} no tiene llaves.`);
2012
+ for (const l of marcadas) {
2013
+ const uso = l.ultimoUso ? `\xFAltimo uso ${l.ultimoUso}` : "sin uso";
2014
+ ctx.salida.linea(`${l.delProyecto ? "\u25CF" : " "} ${l.id.padEnd(8)} ${l.nombre} (${etiquetaLlave(l.entorno)}, ${l.activa ? "activa" : "revocada"}, ${uso})`);
2015
+ }
2016
+ if (delProyecto.size) ctx.salida.linea("\u25CF = instalada en este proyecto");
2017
+ ctx.salida.resultado({ empresa: slug, llaves: marcadas });
2018
+ }
2019
+ async function revocarLlave(ctx, id, opciones) {
2020
+ const slug = empresaDelProyecto(ctx, opciones.empresa);
2021
+ const comando2 = `redcumbre llaves revocar ${id} --confirmar ${slug}`;
2022
+ if (opciones.confirmar !== void 0) {
2023
+ if (opciones.confirmar !== slug) throw errorDeUso(`--confirmar tiene que ser el identificador de la empresa (${slug}), no \xAB${opciones.confirmar}\xBB. No revoqu\xE9 nada.`);
2024
+ } else {
2025
+ const terminal = ctx.salida.json ? null : ctx.terminal;
2026
+ if (!terminal) throw faltaConfirmacion(`Revocar la llave ${id} de ${slug} corta de inmediato todo lo que la use. Conf\xEDrmalo con --confirmar ${slug}. No revoqu\xE9 nada.`, comando2);
2027
+ ctx.salida.linea(`Revocar la llave ${id} corta de inmediato todo lo que la use; no se puede deshacer.`);
2028
+ const escrito = await terminal.preguntar(`Escribe \xAB${slug}\xBB para confirmar: `);
2029
+ if (escrito.trim() !== slug) throw faltaConfirmacion("No confirmaste: no revoqu\xE9 nada.", comando2);
2030
+ }
2031
+ const sesion = await ctx.sesion();
2032
+ const r = await sesion.usar((token) => ctx.cliente.revocarLlave(token, slug, id));
2033
+ const propia = Object.values(llavesDelProyecto(ctx.proyecto)).some((a) => a !== void 0) ? await esDelProyecto(ctx, id) : false;
2034
+ ctx.salida.linea(`\u2713 Llave ${id} revocada.${propia ? " Era la de este proyecto: instala otra con \xABredcumbre init\xBB." : ""}`);
2035
+ ctx.salida.resultado({ ...r, empresa: slug, delProyecto: propia });
2036
+ }
2037
+ async function esDelProyecto(ctx, id) {
2038
+ for (const entorno of ["prueba", "real"]) {
2039
+ const archivo = leerLlave(ctx.proyecto, entorno);
2040
+ if (!archivo) continue;
2041
+ const propio = await resolverLlaveId(ctx, { entorno, archivo, ruta: "" }).catch(() => null);
2042
+ if (propio === id) return true;
2043
+ }
2044
+ return false;
2045
+ }
2046
+ async function llamadas(ctx, opciones) {
2047
+ let slug;
2048
+ let id;
2049
+ if (opciones.llave) {
2050
+ slug = empresaDelProyecto(ctx);
2051
+ id = opciones.llave;
2052
+ } else {
2053
+ const llave = llaveDelComando(ctx, opciones.real);
2054
+ slug = llave.archivo.tenantSlug;
2055
+ const resuelto = await resolverLlaveId(ctx, llave);
2056
+ if (!resuelto) {
2057
+ throw new ErrorCli(
2058
+ `No pude saber cu\xE1l de las llaves de ${slug} es la de ${llave.ruta}. Mira los ids con \xABredcumbre llaves\xBB y p\xE1salo con --llave <id>.`,
2059
+ CODIGOS_DE_SALIDA.uso,
2060
+ { codigo: "LLAVE_SIN_ID", comando: "redcumbre llaves" }
2061
+ );
2062
+ }
2063
+ id = resuelto;
2064
+ }
2065
+ const sesion = await ctx.sesion();
2066
+ const respuesta = await sesion.usar(
2067
+ (token) => ctx.cliente.llamadas(token, slug, id, { desde: opciones.desde, hasta: opciones.hasta, limit: opciones.limite })
2068
+ );
2069
+ const filas = (respuesta.data ?? []).map((l) => ({ ...l, status: l.codigoRespuesta }));
2070
+ if (filas.length === 0) ctx.salida.linea(`La llave ${id} no tiene llamadas registradas en el per\xEDodo.`);
2071
+ for (const l of filas) {
2072
+ const error = l.error?.codigo;
2073
+ ctx.salida.linea(`${String(l.ocurridaEn)} ${String(l.status)} ${String(l.metodo).padEnd(6)} ${String(l.ruta)} ${String(l.duracionMs)} ms${error ? ` ${error}` : ""}`);
2074
+ }
2075
+ ctx.salida.resultado({ empresa: slug, llave: id, modo: respuesta.modo, total: respuesta.total ?? filas.length, llamadas: filas });
2076
+ }
2077
+
2078
+ // src/comandos/llave-validafirma.ts
2079
+ import path10 from "node:path";
2080
+ function declararOpcionesLlaveValidaFirma(comando2) {
2081
+ return comando2.requiredOption("--empresa <slug>", "la empresa (tenantSlug) donde se crea la llave").requiredOption("--alcance <alcance>", "carpetas (carpetas y documentos) o cuenta (cuenta corporativa)").option("--modo <modo>", "prueba (por omisi\xF3n) o real");
2082
+ }
2083
+ async function llaveValidaFirma(ctx, opciones) {
2084
+ const empresa2 = opciones.empresa.trim();
2085
+ if (empresa2 === "") throw errorDeUso("--empresa no puede ir vac\xEDa: pasa el identificador de la empresa (tenantSlug).");
2086
+ if ((opciones.alcance ?? "").trim() === "") throw errorDeUso(`Falta --alcance: ${ALCANCES_LLAVE_VALIDAFIRMA.map((a) => `\xAB${a}\xBB`).join(" o ")}.`);
2087
+ if (!esAlcanceLlaveValidaFirma(opciones.alcance)) {
2088
+ throw new ErrorCli(mensajeAlcanceLlaveInvalido(opciones.alcance), CODIGOS_DE_SALIDA.uso, { codigo: "ALCANCE_NO_EMITIDO" });
2089
+ }
2090
+ const alcance = opciones.alcance;
2091
+ const modoPedido = opciones.modo ?? "prueba";
2092
+ if (!esEntornoLlave(modoPedido)) throw errorDeUso(mensajeEntornoLlaveInvalido(modoPedido));
2093
+ const modo = modoPedido;
2094
+ const relativa = rutaRelativaLlaveValidaFirma(empresa2, alcance, modo);
2095
+ const archivo = path10.resolve(ctx.proyecto, relativa);
2096
+ if (path10.join(ctx.proyecto, "keys", path10.basename(relativa)) !== archivo || path10.basename(relativa) !== relativa.slice("keys/".length)) throw errorDeUso(`\xAB${empresa2}\xBB no es el identificador de una empresa (tenantSlug).`);
2097
+ const comando2 = `redcumbre llaves validafirma --empresa ${empresa2} --alcance ${alcance} --modo ${modo}`;
2098
+ const modoEsperado = ENTORNO_LLAVE_REGISTRY[modo].isSandbox;
555
2099
  let resultado = "creada";
556
- const guardada = leerLlave(proyecto, entorno);
557
- const existente = guardada?.tenantSlug === empresa.slug ? guardada : null;
2100
+ const existente = leerExistente(archivo, relativa);
558
2101
  if (existente) {
559
- const estado = await api.whoami(existente.token, existente.tenantSlug);
560
- if (estado.estado === "valida" && estado.tenant.slug === empresa.slug && estado.sandbox === ENTORNO_LLAVE_REGISTRY[entorno].isSandbox) {
561
- asegurarExclusiones(proyecto, envVersionado);
562
- escribirPuntero(proyecto, entorno);
563
- registrarEnEstado(proyecto, empresa.slug, entorno, estado.sandbox);
564
- avisarEnvVersionado(salida, envVersionado);
565
- mostrarWhoami(salida, estado.tenant, estado.sandbox, "Se reutiliz\xF3 la llave que ya ten\xEDa el proyecto");
566
- return { entorno, resultado: "reutilizada", sandbox: estado.sandbox };
2102
+ const estado2 = await conTraduccion(empresa2, () => ctx.cliente.whoami(existente.token, existente.tenantSlug));
2103
+ if (estado2.estado === "valida" && estado2.tenant.slug === empresa2 && estado2.sandbox === modoEsperado && estado2.roles.includes(existente.role)) {
2104
+ ctx.salida.linea(`\u2713 La llave de ${relativa} sigue funcionando en ${nombreEmpresa(estado2.tenant)}: la reutilizo, no cre\xE9 otra.`);
2105
+ advertir(ctx, relativa, estado2.tenant);
2106
+ ctx.salida.resultado(salidaJson(archivo, estado2.tenant, alcance, modo, existente.role, null, "reutilizada"));
2107
+ return;
567
2108
  }
568
- salida.linea(
569
- estado.estado === "rechazada" ? `La llave de ${rutaRelativaLlave(entorno)} ya no funciona (\xBFla revocaron?): creo una nueva en su lugar.` : `La llave de ${rutaRelativaLlave(entorno)} no es de ${empresa.nombre} en ${ENTORNO_LLAVE_REGISTRY[entorno].label}: creo una nueva en su lugar.`
2109
+ ctx.salida.linea(
2110
+ estado2.estado === "rechazada" ? `La llave de ${relativa} ya no funciona (puede estar revocada): creo una nueva en su lugar.` : `La llave de ${relativa} no es la de ${empresa2} con alcance ${alcance} en ${nombreDelModo(modo)}: creo una nueva en su lugar.`
570
2111
  );
571
2112
  resultado = "reemplazada";
572
2113
  }
573
- asegurarExclusiones(proyecto, envVersionado);
574
- const nombre = nombreDeLlave(proyecto, entorno, deps.ahora());
575
- let creada;
576
- try {
577
- creada = await sesion.usar((token) => api.crearLlave(token, empresa.slug, nombre, entorno));
578
- } catch (error) {
579
- if (!(error instanceof ErrorSinRolAdministrador)) throw error;
580
- escribirPuntero(proyecto, entorno);
581
- avisarEnvVersionado(salida, envVersionado);
582
- throw new ErrorCli(
583
- `Crear llaves exige ser administrador de ${empresa.nombre}: p\xEDdele a un administrador de ${empresa.nombre} que cree la llave en la pantalla web de llaves, y deja el archivo descargado en ${rutaLlave(proyecto, entorno)}`
2114
+ const terminal = ctx.salida.json ? null : ctx.terminal;
2115
+ if (modo === "real" && !terminal) {
2116
+ throw faltaConfirmacion(
2117
+ `La llave real de ValidaFirma en ${empresa2} la crea una persona en una terminal: corre el comando sin --json y escribe el identificador de la empresa cuando te lo pida. No cre\xE9 nada.`,
2118
+ comando2
584
2119
  );
585
2120
  }
586
- escribirLlave(proyecto, entorno, {
2121
+ const sesion = await ctx.sesion();
2122
+ if (modo === "real" && terminal) {
2123
+ ctx.salida.linea(`Vas a crear una llave REAL de ValidaFirma (${ALCANCE_LLAVE_VALIDAFIRMA_REGISTRY[alcance].label.toLowerCase()}) en ${empresa2}.`);
2124
+ const escrito = await terminal.preguntar(`Escribe \xAB${empresa2}\xBB para confirmar: `);
2125
+ if (escrito.trim() !== empresa2) throw faltaConfirmacion("No confirmaste: no cre\xE9 nada.", comando2);
2126
+ }
2127
+ const nombre = nombreDeLlave(ctx.proyecto, etiquetaLlaveValidaFirma(alcance, modo), ctx.ahora());
2128
+ const creada = await conTraduccion(empresa2, () => sesion.usar((token) => ctx.cliente.crearLlave(token, empresa2, nombre, modo, alcance)));
2129
+ asegurarExclusiones(ctx.proyecto, estaVersionado(ctx.proyecto, ".env"));
2130
+ escribirArchivoLlave(archivo, {
587
2131
  tenantSlug: creada.tenantSlug,
588
2132
  name: creada.nombre,
589
- role: "FULL-API",
2133
+ role: creada.rol,
590
2134
  isSandbox: ENTORNO_LLAVE_REGISTRY[creada.entorno].isSandbox,
591
2135
  token: creada.token,
592
2136
  expiresAt: creada.expiresAt,
593
2137
  createdAt: creada.createdAt
594
2138
  });
595
- escribirPuntero(proyecto, entorno);
596
- avisarEnvVersionado(salida, envVersionado);
597
- const comprobada = await api.whoami(creada.token, creada.tenantSlug);
598
- if (comprobada.estado !== "valida") {
599
- throw new ErrorCli(`La llave reci\xE9n creada no pas\xF3 whoami. Qued\xF3 en ${rutaRelativaLlave(entorno)}; rev\xEDsala en la pantalla web de llaves.`);
2139
+ const comprobada = await conTraduccion(empresa2, () => ctx.cliente.whoami(creada.token, creada.tenantSlug));
2140
+ if (comprobada.estado !== "valida" || !comprobada.roles.includes(creada.rol)) {
2141
+ throw new ErrorCli(`La llave reci\xE9n creada no pas\xF3 la comprobaci\xF3n de la plataforma. Qued\xF3 en ${relativa}; rev\xEDsala en la pantalla web de llaves.`, CODIGOS_DE_SALIDA.llave, {
2142
+ codigo: "LLAVE_RECHAZADA",
2143
+ comando: comando2,
2144
+ datos: { archivo }
2145
+ });
600
2146
  }
601
- registrarEnEstado(proyecto, comprobada.tenant.slug, entorno, comprobada.sandbox);
602
- mostrarWhoami(salida, comprobada.tenant, comprobada.sandbox, `Llave \xAB${creada.nombre}\xBB instalada en ${rutaRelativaLlave(entorno)}`);
603
- return { entorno, resultado, sandbox: comprobada.sandbox };
2147
+ ctx.salida.linea(`\u2713 Llave de ValidaFirma ${resultado === "reemplazada" ? "reemplazada" : "creada"} en ${relativa}: ${nombreEmpresa(comprobada.tenant)}, alcance ${alcance}, ${nombreDelModo(modo)} (${creada.rol}).`);
2148
+ advertir(ctx, relativa, comprobada.tenant);
2149
+ ctx.salida.resultado(salidaJson(archivo, comprobada.tenant, alcance, modo, creada.rol, creada.id, resultado));
604
2150
  }
605
- function avisarEnvVersionado(salida, versionado) {
606
- if (versionado) {
607
- salida.aviso("Tu .env est\xE1 en el control de versiones: s\xF3lo le agregu\xE9 la ruta a la llave (el secreto qued\xF3 en keys/, excluido). No lo saqu\xE9 de git; decide t\xFA si corresponde.");
2151
+ function leerExistente(archivo, relativa) {
2152
+ try {
2153
+ return leerArchivoLlave(archivo);
2154
+ } catch (error) {
2155
+ throw new ErrorCli(`No pude leer la llave que ya est\xE1: ${error.message} No toqu\xE9 el archivo.`, CODIGOS_DE_SALIDA.error, { codigo: "ERROR_DEL_CLI", datos: { archivo } });
608
2156
  }
609
2157
  }
610
- function mostrarWhoami(salida, tenant, sandbox, encabezado) {
611
- salida.linea(`\u2713 ${encabezado}.`);
612
- salida.linea(` Empresa ${tenant.nombre} (${tenant.slug})`);
613
- salida.linea(` Entorno ${sandbox ? "sandbox \u2014 no llega al SII ni consume folios" : "producci\xF3n \u2014 los documentos que emitas son reales ante el SII"}`);
614
- if (sandbox) salida.aviso(`En sandbox no todo funciona. La lista de lo que s\xED: ${URL_ENTORNOS}`);
2158
+ async function conTraduccion(empresa2, accion) {
2159
+ try {
2160
+ return await accion();
2161
+ } catch (error) {
2162
+ if (error instanceof ErrorSinRol) {
2163
+ throw new ErrorCli(`Crear llaves en ${empresa2} pide el rol de administrador, y tu cuenta no lo tiene en esa empresa. No cre\xE9 nada.`, CODIGOS_DE_SALIDA.api4xx, { codigo: "SIN_ROL" });
2164
+ }
2165
+ if (error instanceof ErrorCli && error.codigoSalida === CODIGOS_DE_SALIDA.api5xx && !(error instanceof ErrorDeRed)) {
2166
+ throw new ErrorCli(error.message, CODIGOS_DE_SALIDA.api5xx, { codigo: "API_NO_DISPONIBLE" });
2167
+ }
2168
+ throw error;
2169
+ }
615
2170
  }
616
-
617
- // src/comandos/login.ts
618
- async function ejecutarLogin(deps) {
619
- const sesion = await deps.sesion();
620
- const empresas = await sesion.usar((token) => deps.api.empresas(token));
621
- deps.salida.linea(`Tienes sesi\xF3n. Tus empresas: ${empresas.map((e) => `${e.nombre} (${e.slug})`).join(", ") || "ninguna"}.`);
622
- deps.salida.resultado({ ok: true, empresas });
2171
+ function advertir(ctx, relativa, empresa2) {
2172
+ ctx.salida.linea(`Ese archivo da acceso a ValidaFirma en ${empresa2.nombre}: no lo compartas ni lo subas al repositorio.`);
623
2173
  }
624
-
625
- // src/comandos/logout.ts
626
- async function ejecutarLogout(deps) {
627
- const cerrada = await (await deps.sesion()).cerrar();
628
- deps.salida.linea(cerrada ? "Sesi\xF3n cerrada: la revoqu\xE9 en el servidor de identidad y la borr\xE9 de este computador." : "No hab\xEDa una sesi\xF3n iniciada.");
629
- deps.salida.resultado({ ok: true, sesionCerrada: cerrada });
2174
+ function salidaJson(archivo, empresa2, alcance, modo, rol, llaveId, resultado) {
2175
+ return { archivo, empresa: { slug: empresa2.slug, nombre: empresa2.nombre }, alcance, modo, rol, llaveId, resultado };
630
2176
  }
631
2177
 
632
- // src/nucleo/preguntas.ts
633
- import { confirm, input, select } from "@inquirer/prompts";
634
- var DETALLE_ENTORNO = {
635
- sandbox: "pruebas: no env\xEDa nada al SII ni consume folios",
636
- produccion: "los documentos que emitas son reales ante el SII"
637
- };
638
- function preguntaEntorno() {
639
- const opciones = ENTORNOS_LLAVE.map((entorno, i) => ` ${i + 1}) ${ENTORNO_LLAVE_REGISTRY[entorno].label} \u2014 ${DETALLE_ENTORNO[entorno]}`);
640
- return {
641
- message: ["\xBFPara qu\xE9 entorno es la llave?", ...opciones, `Escribe ${ENTORNOS_LLAVE.map((_, i) => i + 1).join(" o ")}:`].join("\n"),
642
- validate: (respuesta) => interpretarEntorno(respuesta) ? true : `Escribe ${ENTORNOS_LLAVE.map((_, i) => i + 1).join(" o ")} (sin valor por omisi\xF3n).`
643
- };
2178
+ // src/comandos/modo-prueba.ts
2179
+ async function estado(ctx, opciones) {
2180
+ const llave = llaveDelComando(ctx, opciones.real);
2181
+ const slug = llave.archivo.tenantSlug;
2182
+ const [crudo, consumo2] = await Promise.all([
2183
+ ctx.cliente.conLlave("GET", llave.archivo.token, rutaDeEmpresa(slug, "/modo-prueba/estado"), "leer el estado del modo de prueba"),
2184
+ leerConsumo(ctx.cliente, llave.archivo)
2185
+ ]);
2186
+ const datos = desenvolver(crudo);
2187
+ const topes = consumo2.modo === "prueba" ? consumo2.topes : [];
2188
+ const quien = await quienEres(ctx, slug);
2189
+ ctx.salida.linea(`Empresa ${datos.empresa.nombre} (${datos.empresa.slug})`);
2190
+ ctx.salida.linea(`Modo ${nombreDelModo(datos.modo)} (llave ${llave.ruta})`);
2191
+ for (const t of topes) ctx.salida.linea(` ${lineaDeTope(t)}`);
2192
+ ctx.salida.linea(`Webhooks ${datos.webhooks.destino ?? "sin destino configurado"} \xB7 ${datos.webhooks.relaysAbiertos} relay${datos.webhooks.relaysAbiertos === 1 ? "" : "s"} abierto${datos.webhooks.relaysAbiertos === 1 ? "" : "s"}`);
2193
+ ctx.salida.linea(
2194
+ quien.sesion ? `Sesi\xF3n ${quien.sesion.nombre} (${quien.sesion.correo}) \xB7 ${quien.sesion.roles.length ? `roles ${quien.sesion.roles.join(", ")}` : "sin roles en esta empresa"}` : `Sesi\xF3n ${quien.motivo}`
2195
+ );
2196
+ ctx.salida.resultado({ ...datos, topes, ...consumo2.modo === "real" ? { metricas: consumo2.metricas } : {}, sesion: quien.sesion, ...quien.sesion ? {} : { sinSesion: quien.motivo } });
644
2197
  }
645
- function interpretarEntorno(respuesta) {
646
- const limpia = respuesta.trim().toLowerCase();
647
- const porNumero = ENTORNOS_LLAVE[Number(limpia) - 1];
648
- if (/^\d+$/.test(limpia) && porNumero) return porNumero;
649
- return ENTORNOS_LLAVE.includes(limpia) ? limpia : null;
2198
+ async function quienEres(ctx, slug) {
2199
+ if (!await ctx.haySesion()) return { sesion: null, motivo: "sin sesi\xF3n: inicia una con \xABredcumbre login\xBB para ver tu rol" };
2200
+ try {
2201
+ const sesion = await ctx.sesion();
2202
+ const perfil = await sesion.usar((token) => ctx.cliente.perfil(token));
2203
+ const empresa2 = perfil.empresas.find((e) => e.slug === slug);
2204
+ return { sesion: { nombre: perfil.persona.nombre, correo: perfil.persona.correo, roles: empresa2?.roles ?? [] } };
2205
+ } catch (error) {
2206
+ if (error instanceof ErrorCli && error.codigoSalida === CODIGOS_DE_SALIDA.sesion) {
2207
+ return { sesion: null, motivo: "la sesi\xF3n guardada ya no sirve: inicia una con \xABredcumbre login\xBB" };
2208
+ }
2209
+ throw error;
2210
+ }
650
2211
  }
651
- async function preguntarEntorno() {
652
- const respuesta = await input(preguntaEntorno());
653
- return interpretarEntorno(respuesta);
2212
+ async function consumo(ctx, opciones) {
2213
+ const llave = llaveDelComando(ctx, opciones.real);
2214
+ const datos = await leerConsumo(ctx.cliente, llave.archivo);
2215
+ mostrarConsumo(ctx.salida, datos);
2216
+ ctx.salida.resultado({ empresa: llave.archivo.tenantSlug, ...datos });
654
2217
  }
655
- async function preguntarEmpresa(empresas) {
656
- return select({
657
- message: "\xBFPara qu\xE9 empresa es la llave?",
658
- choices: empresas.map((e) => ({ name: `${e.nombre} (${e.slug})`, value: e.slug }))
659
- });
2218
+ async function conLlaveDePrueba(ctx, metodo, resto, que, peticion = {}) {
2219
+ const llave = llaveDelComando(ctx, false);
2220
+ const respuesta = await ctx.cliente.conLlave(metodo, llave.archivo.token, rutaDeEmpresa(llave.archivo.tenantSlug, resto), que, peticion);
2221
+ return desenvolver(respuesta);
660
2222
  }
661
- async function preguntarLenguaje() {
662
- return select({
663
- message: "La carpeta est\xE1 vac\xEDa. \xBFEn qu\xE9 lenguaje armo el proyecto?",
664
- choices: LENGUAJES.map((l) => ({ name: LENGUAJE_REGISTRY[l].label, value: l }))
665
- });
2223
+ async function escenarios(ctx) {
2224
+ const datos = await conLlaveDePrueba(ctx, "GET", "/modo-prueba/escenarios", "leer los escenarios de prueba");
2225
+ const e = datos;
2226
+ if (e.emisorDte) ctx.salida.linea(`Emisor de documentos: ${e.emisorDte.rut} (${e.emisorDte.tipos.join(", ")})`);
2227
+ for (const t of e.emisoresTributarios ?? []) ctx.salida.linea(`Emisor ${t.servicio}: ${t.rut}`);
2228
+ if (e.ruts?.length) ctx.salida.linea("RUT de prueba:");
2229
+ for (const r of e.ruts ?? []) ctx.salida.linea(` ${r.rut.padEnd(12)} ${r.rol.padEnd(22)} ${r.descripcion}`);
2230
+ ctx.salida.resultado(datos);
666
2231
  }
667
- async function preguntarDondeInstalar(actual) {
668
- return input({ message: "\xBFEn qu\xE9 carpeta del proyecto instalo la llave? (Enter = la carpeta actual)", default: actual });
669
- }
670
- async function preguntarOtroEntorno(entorno, empresa) {
671
- return confirm({ message: `\xBFCreo tambi\xE9n la llave de ${ENTORNO_LLAVE_REGISTRY[entorno].label} para ${empresa}?`, default: false });
672
- }
673
- async function leerLineaDeTerminal(pregunta, salida, entrada = process.stdin) {
674
- const { createInterface } = await import("node:readline");
675
- const rl = createInterface({ input: entrada, output: salida, terminal: false });
676
- salida.write(pregunta);
677
- return new Promise((resolver, rechazar) => {
678
- let leida = null;
679
- rl.once("line", (linea) => {
680
- leida = linea;
681
- rl.close();
682
- });
683
- rl.once("close", () => {
684
- entrada.pause();
685
- entrada.unref?.();
686
- if (leida === null) rechazar(new ErrorCli("La entrada se cerr\xF3 antes de recibir el c\xF3digo. Vuelve a correr el comando."));
687
- else resolver(leida);
688
- });
2232
+ async function bandeja(ctx, opciones) {
2233
+ const datos = await conLlaveDePrueba(ctx, "GET", "/modo-prueba/bandeja", "leer la bandeja del modo de prueba", {
2234
+ query: { canal: opciones.canal, destinatario: opciones.destinatario, limit: opciones.limite }
689
2235
  });
2236
+ const mensajes = datos.data ?? [];
2237
+ if (mensajes.length === 0) ctx.salida.linea("La bandeja del modo de prueba est\xE1 vac\xEDa.");
2238
+ for (const m of mensajes) ctx.salida.linea(`${m.creadoEn} ${m.canal} ${m.destinatario} ${m.asunto ?? ""}`);
2239
+ ctx.salida.resultado(datos);
2240
+ }
2241
+ async function eventos(ctx) {
2242
+ const datos = await conLlaveDePrueba(ctx, "GET", "/modo-prueba/eventos-de-webhook", "leer el cat\xE1logo de eventos de webhook");
2243
+ for (const e of datos.eventos ?? []) {
2244
+ ctx.salida.linea(`${e.disparable ? "\u25B6" : " "} ${e.key.padEnd(36)} ${e.label}${e.disparable ? "" : ` \u2014 no se dispara: ${e.porque ?? "sin motivo"}`}`);
2245
+ }
2246
+ ctx.salida.linea("\u25B6 = se puede disparar con \xABredcumbre eventos disparar <evento>\xBB");
2247
+ ctx.salida.resultado(datos);
2248
+ }
2249
+ async function dispararEvento(ctx, evento) {
2250
+ const datos = await conLlaveDePrueba(ctx, "POST", `/modo-prueba/eventos-de-webhook/${encodeURIComponent(evento)}/disparar`, `disparar el evento ${evento}`);
2251
+ ctx.salida.linea(`\u2713 Dispar\xE9 ${evento} en el modo de prueba (referencia ${String(datos.referencia)}). Llega a tu destino de prueba y a los relays abiertos.`);
2252
+ ctx.salida.resultado(datos);
2253
+ }
2254
+ async function restaurar(ctx, opciones) {
2255
+ const slug = empresaDelProyecto(ctx, opciones.empresa);
2256
+ const comando2 = `redcumbre restaurar --confirmar ${slug}`;
2257
+ const que = `Restaurar borra los documentos, boletas, mensajes de la bandeja y entregas de webhooks del modo de prueba de ${slug}, y vuelve a dejar los datos de ejemplo. No toca el modo real, el destino de webhooks de prueba ni el tope del d\xEDa.`;
2258
+ if (opciones.confirmar !== void 0) {
2259
+ if (opciones.confirmar !== slug) {
2260
+ throw new ErrorCli(`--confirmar dice \xAB${opciones.confirmar}\xBB, pero el proyecto es de ${slug}. No borr\xE9 nada.`, CODIGOS_DE_SALIDA.confirmacion, {
2261
+ codigo: "CONFIRMACION_DE_OTRA_EMPRESA",
2262
+ comando: comando2
2263
+ });
2264
+ }
2265
+ } else {
2266
+ const terminal = ctx.salida.json ? null : ctx.terminal;
2267
+ if (!terminal) throw faltaConfirmacion(`${que} Conf\xEDrmalo con --confirmar ${slug}. No borr\xE9 nada.`, comando2);
2268
+ ctx.salida.linea(que);
2269
+ const escrito = (await terminal.preguntar(`Para confirmar, escribe el identificador de la empresa (${slug}): `)).trim();
2270
+ if (escrito !== slug) throw faltaConfirmacion(`Escribiste \xAB${escrito}\xBB, no \xAB${slug}\xBB: no borr\xE9 nada.`, comando2);
2271
+ }
2272
+ const sesion = await ctx.sesion();
2273
+ const datos = desenvolver(await sesion.usar((token) => ctx.cliente.restaurar(token, slug)));
2274
+ ctx.salida.linea(`\u2713 El modo de prueba de ${slug} qued\xF3 como reci\xE9n creado.`);
2275
+ ctx.salida.resultado({ ok: true, empresa: slug, ...datos });
2276
+ }
2277
+ var HEADERS_PROHIBIDOS = /* @__PURE__ */ new Set(["host", "content-length", "connection", "transfer-encoding", "keep-alive", "expect", "upgrade"]);
2278
+ var ESPERA_DEL_REENVIO_MS = 15e3;
2279
+ var ESPERA_MAXIMA_RECONEXION_MS = 3e4;
2280
+ async function webhooksEscuchar(ctx, opciones) {
2281
+ let destino;
2282
+ try {
2283
+ destino = new URL(opciones.reenviarA);
2284
+ } catch {
2285
+ throw errorDeUso(`--reenviar-a \xAB${opciones.reenviarA}\xBB no es una URL. Por ejemplo: http://localhost:3000/webhooks`);
2286
+ }
2287
+ if (destino.protocol !== "http:" && destino.protocol !== "https:") throw errorDeUso("--reenviar-a tiene que ser una URL http o https.");
2288
+ const filtro = opciones.eventos !== void 0 ? lista(opciones.eventos, "--eventos") : void 0;
2289
+ const slug = empresaDelProyecto(ctx, opciones.empresa);
2290
+ const sesion = await ctx.sesion();
2291
+ const corte = new AbortController();
2292
+ const terminar = () => corte.abort();
2293
+ process.once("SIGINT", terminar);
2294
+ process.once("SIGTERM", terminar);
2295
+ let espera = 1e3;
2296
+ const relay = { sesionId: null };
2297
+ try {
2298
+ while (!corte.signal.aborted) {
2299
+ try {
2300
+ const res = await sesion.usar(async (token) => {
2301
+ const r = await ctx.cliente.crudo(
2302
+ "GET",
2303
+ rutaDeEmpresa(slug, "/cli/relay/eventos"),
2304
+ { credencial: { tipo: "sesion", token }, query: { eventos: filtro?.join(",") }, headers: { Accept: "text/event-stream, application/json;q=0.5" } },
2305
+ corte.signal
2306
+ );
2307
+ if (!r.ok) throw errorDeRespuesta({ status: r.status, headers: r.headers, json: parsear2(await r.text()), bytes: null }, "sesion", "abrir el relay de webhooks");
2308
+ return r;
2309
+ });
2310
+ for await (const mensaje of leerSse(res, corte.signal)) {
2311
+ espera = 1e3;
2312
+ await atender(ctx, slug, destino, mensaje, relay, (op) => sesion.usar(op));
2313
+ }
2314
+ if (corte.signal.aborted) break;
2315
+ ctx.salida.aviso("El relay se cort\xF3: me reconecto.");
2316
+ } catch (error) {
2317
+ if (corte.signal.aborted) break;
2318
+ const reintentable = error instanceof ErrorDeRed || error instanceof ErrorCli && error.codigoSalida === CODIGOS_DE_SALIDA.api5xx;
2319
+ if (!reintentable) throw error;
2320
+ ctx.salida.aviso(`${error.message} Me reconecto en ${Math.round(espera / 1e3)} s.`);
2321
+ }
2322
+ ctx.salida.evento({ tipo: "relay.reconectando", enMs: espera });
2323
+ await dormir(espera, corte.signal);
2324
+ espera = Math.min(espera * 2, ESPERA_MAXIMA_RECONEXION_MS);
2325
+ }
2326
+ } finally {
2327
+ process.off("SIGINT", terminar);
2328
+ process.off("SIGTERM", terminar);
2329
+ }
2330
+ ctx.salida.linea("Relay cerrado.");
2331
+ ctx.salida.evento({ tipo: "relay.cerrado" });
2332
+ }
2333
+ async function atender(ctx, slug, destino, mensaje, relay, conSesion) {
2334
+ if (mensaje.evento === "latido") return;
2335
+ if (mensaje.evento === "relay.abierto") {
2336
+ const abierto = JSON.parse(mensaje.datos);
2337
+ relay.sesionId = abierto.sesionId;
2338
+ ctx.salida.linea(`\u2713 Relay abierto en el modo de prueba de ${slug}: reenv\xEDo a ${destino.toString()} ${abierto.eventos ? `los eventos ${abierto.eventos.join(", ")}` : "todos los eventos"}.`);
2339
+ ctx.salida.linea(` Verifica X-Webhook-Signature con el secreto de prueba: ${abierto.secreto}`);
2340
+ ctx.salida.linea(" Ctrl+C para cerrar.");
2341
+ ctx.salida.evento({ tipo: "relay.abierto", ...abierto });
2342
+ return;
2343
+ }
2344
+ if (mensaje.evento !== "entrega" || !relay.sesionId) return;
2345
+ const sesionId = relay.sesionId;
2346
+ const entrega = JSON.parse(mensaje.datos);
2347
+ const inicio = Date.now();
2348
+ let codigo = null;
2349
+ let error;
2350
+ try {
2351
+ const headers = Object.fromEntries(Object.entries(entrega.headers).filter(([k]) => !HEADERS_PROHIBIDOS.has(k.toLowerCase())));
2352
+ const r = await fetch(destino, { method: "POST", headers, body: entrega.body, signal: AbortSignal.timeout(ESPERA_DEL_REENVIO_MS) });
2353
+ codigo = r.status;
2354
+ await r.arrayBuffer().catch(() => void 0);
2355
+ } catch (e) {
2356
+ error = `tu servidor local no respondi\xF3 (${e.message})`;
2357
+ }
2358
+ const duracionMs = Date.now() - inicio;
2359
+ ctx.salida.linea(`\u2192 ${entrega.evento.padEnd(32)} ${codigo ?? "sin respuesta"} ${duracionMs} ms`);
2360
+ ctx.salida.evento({ tipo: "entrega", entregaId: entrega.entregaId, evento: entrega.evento, codigo, duracionMs, ...error ? { error } : {} });
2361
+ try {
2362
+ await conSesion((token) => ctx.cliente.acusarEntrega(token, slug, sesionId, { entregaId: entrega.entregaId, codigo, duracionMs, error }));
2363
+ } catch (e) {
2364
+ ctx.salida.aviso(`No pude avisarle a la plataforma el resultado de ${entrega.evento}: ${e.message}`);
2365
+ }
2366
+ }
2367
+ async function* leerSse(res, senal) {
2368
+ if (!res.body) return;
2369
+ const lector = res.body.getReader();
2370
+ const decodificador = new TextDecoder();
2371
+ let pendiente = "";
2372
+ try {
2373
+ while (!senal.aborted) {
2374
+ const { value, done } = await lector.read();
2375
+ if (done) return;
2376
+ pendiente += decodificador.decode(value, { stream: true }).replace(/\r\n/g, "\n");
2377
+ let corte;
2378
+ while ((corte = pendiente.indexOf("\n\n")) >= 0) {
2379
+ const bloque = pendiente.slice(0, corte);
2380
+ pendiente = pendiente.slice(corte + 2);
2381
+ let evento = "message";
2382
+ const datos = [];
2383
+ for (const linea of bloque.split("\n")) {
2384
+ if (linea.startsWith("event:")) evento = linea.slice(6).trim();
2385
+ else if (linea.startsWith("data:")) datos.push(linea.slice(5).replace(/^ /, ""));
2386
+ }
2387
+ if (datos.length) yield { evento, datos: datos.join("\n") };
2388
+ }
2389
+ }
2390
+ } catch (error) {
2391
+ if (senal.aborted) return;
2392
+ throw new ErrorDeRed(res.url, error);
2393
+ } finally {
2394
+ lector.releaseLock();
2395
+ }
2396
+ }
2397
+ function parsear2(texto2) {
2398
+ try {
2399
+ return JSON.parse(texto2);
2400
+ } catch {
2401
+ return texto2;
2402
+ }
2403
+ }
2404
+ var dormir = (ms, senal) => new Promise((listo) => {
2405
+ const t = setTimeout(listo, ms);
2406
+ senal.addEventListener("abort", () => {
2407
+ clearTimeout(t);
2408
+ listo();
2409
+ }, { once: true });
2410
+ });
2411
+
2412
+ // src/comandos/receta.ts
2413
+ import fs10 from "node:fs";
2414
+ import path11 from "node:path";
2415
+ async function receta(ctx, nombre, opciones) {
2416
+ const { salida, proyecto } = ctx;
2417
+ if (!esReceta(nombre)) throw errorDeUso(`La receta \xAB${nombre}\xBB no existe. Las recetas son ${RECETAS.join(", ")}.`);
2418
+ if (opciones.lenguaje !== void 0 && !esLenguaje(opciones.lenguaje)) throw errorDeUso(`El lenguaje \xAB${opciones.lenguaje}\xBB no existe. Usa ${LENGUAJES.join(", ")}.`);
2419
+ const lenguaje = await elegirLenguaje(ctx, opciones.lenguaje);
2420
+ const prueba = llaveDelEntorno(proyecto, "prueba", ctx.env);
2421
+ const real = llaveDelEntorno(proyecto, "real", ctx.env);
2422
+ if (!prueba && real) {
2423
+ const r = await ctx.cliente.whoami(real.token, real.tenantSlug);
2424
+ if (r.estado === "rechazada") {
2425
+ throw new ErrorCli("La API rechaza la llave real del proyecto: fue revocada o venci\xF3.", CODIGOS_DE_SALIDA.llave, { codigo: "LLAVE_RECHAZADA", comando: COMANDO_INIT });
2426
+ }
2427
+ throw new ErrorCli(
2428
+ `La llave del proyecto es la llave real de ${nombreEmpresa(r.tenant)}. La receta \xAB${nombre}\xBB funciona s\xF3lo en el modo de prueba, as\xED que no la agregu\xE9 ni emit\xED nada. Agrega la llave de prueba con \xAB${COMANDO_INIT}\xBB.`,
2429
+ CODIGOS_DE_SALIDA.modo,
2430
+ { codigo: "RECETA_SOLO_EN_PRUEBA", comando: COMANDO_INIT, datos: { empresa: { slug: r.tenant.slug, nombre: r.tenant.nombre } } }
2431
+ );
2432
+ }
2433
+ const archivos = agregarReceta(lenguaje, nombre, proyecto);
2434
+ const ejecutar = comandoDeReceta(lenguaje, nombre);
2435
+ salida.linea(`\u2713 Receta \xAB${nombre}\xBB (${LENGUAJE_REGISTRY[lenguaje].label}) agregada: ${archivos.join(", ")}.`);
2436
+ salida.linea(` ${RECETA_REGISTRY[nombre].label}, en el modo de prueba. C\xF3rrela con: ${ejecutar.join(" ")}`);
2437
+ if (!prueba) salida.aviso(`El proyecto todav\xEDa no tiene llave de prueba: la receta la necesita. Inst\xE1lala con \xAB${COMANDO_INIT}\xBB.`);
2438
+ const avisoDotnet = lenguaje === "dotnet" ? avisoCompilacionDotnet(proyecto) : null;
2439
+ if (avisoDotnet) salida.aviso(avisoDotnet);
2440
+ salida.resultado({ ok: true, receta: nombre, lenguaje, archivos, ejecutar });
2441
+ }
2442
+ async function elegirLenguaje(ctx, pedido) {
2443
+ if (pedido) return pedido;
2444
+ const detectado = detectarLenguaje(ctx.proyecto);
2445
+ if (detectado) return detectado;
2446
+ const terminal = ctx.salida.json ? null : ctx.terminal;
2447
+ if (!terminal) throw errorDeUso(`No reconozco el lenguaje del proyecto. Ind\xEDcalo con --lenguaje (${LENGUAJES.join(", ")}).`);
2448
+ return terminal.elegir(
2449
+ "\xBFEn qu\xE9 lenguaje quieres la receta?",
2450
+ LENGUAJES.map((l) => ({ valor: l, etiqueta: LENGUAJE_REGISTRY[l].label }))
2451
+ );
2452
+ }
2453
+ function avisoCompilacionDotnet(proyecto) {
2454
+ const tieneProyecto = fs10.readdirSync(proyecto).some((e) => e.endsWith(".csproj"));
2455
+ if (!tieneProyecto) return null;
2456
+ const props = path11.join(proyecto, "Directory.Build.props");
2457
+ if (fs10.existsSync(props) && fs10.readFileSync(props, "utf8").includes("redcumbre/**")) return null;
2458
+ return "Tu proyecto .NET compila todos los .cs de su carpeta y chocar\xEDa con la receta. Agrega a tu .csproj, dentro de un <PropertyGroup>: <DefaultItemExcludes>$(DefaultItemExcludes);redcumbre/**</DefaultItemExcludes>";
690
2459
  }
691
2460
 
692
2461
  // src/nucleo/sesion.ts
693
2462
  import { spawn } from "node:child_process";
694
- import fs4 from "node:fs";
2463
+ import fs11 from "node:fs";
695
2464
  import http from "node:http";
696
- import os from "node:os";
697
- import path5 from "node:path";
2465
+ import os3 from "node:os";
2466
+ import path12 from "node:path";
698
2467
  import * as oidc from "openid-client";
2468
+
2469
+ // src/nucleo/config.ts
2470
+ var PRODUCCION = {
2471
+ api: "https://api.redcumbre.cl",
2472
+ web: "https://app.redcumbre.cl"
2473
+ };
2474
+ var CLIENTE_OIDC = {
2475
+ issuer: "https://id.redcumbre.cl",
2476
+ clientId: "391851369151135746",
2477
+ projectId: "346407127679500290"
2478
+ };
2479
+ var SCOPE = `openid profile email offline_access urn:zitadel:iam:org:project:id:${CLIENTE_OIDC.projectId}:aud`;
2480
+ var SERVICIO_LLAVERO = "redcumbrecl-cli";
2481
+ function origen(variable, valor) {
2482
+ let url;
2483
+ try {
2484
+ url = new URL(valor);
2485
+ } catch {
2486
+ throw new Error(`${variable} no es una URL v\xE1lida: \xAB${valor}\xBB`);
2487
+ }
2488
+ if (url.protocol !== "https:" && url.hostname !== "127.0.0.1" && url.hostname !== "localhost") {
2489
+ throw new Error(`${variable} debe usar https (recib\xED \xAB${valor}\xBB)`);
2490
+ }
2491
+ return url.origin;
2492
+ }
2493
+ function servidores(env = process.env) {
2494
+ return {
2495
+ api: env.REDCUMBRE_API_URL ? origen("REDCUMBRE_API_URL", env.REDCUMBRE_API_URL) : PRODUCCION.api,
2496
+ web: env.REDCUMBRE_WEB_URL ? origen("REDCUMBRE_WEB_URL", env.REDCUMBRE_WEB_URL) : PRODUCCION.web
2497
+ };
2498
+ }
2499
+
2500
+ // src/nucleo/sesion.ts
699
2501
  function carpetaDeConfiguracion(env = process.env, plataforma = process.platform) {
700
2502
  if (plataforma === "win32") {
701
2503
  if (!env.APPDATA) throw new ErrorCli("No encuentro %APPDATA%: no tengo d\xF3nde guardar la sesi\xF3n.");
702
- return path5.join(env.APPDATA, "redcumbre");
2504
+ return path12.join(env.APPDATA, "redcumbre");
703
2505
  }
704
- const base = env.XDG_CONFIG_HOME || path5.join(os.homedir(), ".config");
705
- return path5.join(base, "redcumbre");
2506
+ const base = env.XDG_CONFIG_HOME || path12.join(os3.homedir(), ".config");
2507
+ return path12.join(base, "redcumbre");
2508
+ }
2509
+ function estaDentro(base, ruta) {
2510
+ const relativa = path12.relative(path12.resolve(base), path12.resolve(ruta));
2511
+ return !relativa.startsWith("..") && !path12.isAbsolute(relativa);
2512
+ }
2513
+ function exigirFueraDelProyecto(carpeta, proyecto, personal = os3.homedir()) {
2514
+ if (!estaDentro(proyecto, carpeta)) return;
2515
+ if (estaDentro(proyecto, personal) && !tieneInstalacionDelCli(proyecto)) return;
2516
+ throw new ErrorCli(
2517
+ `La carpeta de configuraci\xF3n (${carpeta}) est\xE1 dentro del proyecto: ah\xED no guardo tu sesi\xF3n. Corre el comando con XDG_CONFIG_HOME fuera del proyecto.`
2518
+ );
706
2519
  }
707
2520
  var AlmacenArchivo = class {
708
2521
  ruta;
709
2522
  descripcion;
710
2523
  /** `proyecto`: la carpeta donde corre el CLI; la sesión nunca puede quedar debajo de ella. */
711
2524
  constructor(carpeta, proyecto) {
712
- this.ruta = path5.join(carpeta, "sesion.json");
713
- const relativa = path5.relative(path5.resolve(proyecto), path5.resolve(this.ruta));
714
- if (!relativa.startsWith("..") && !path5.isAbsolute(relativa)) {
715
- throw new ErrorCli(
716
- `La carpeta de configuraci\xF3n (${carpeta}) est\xE1 dentro del proyecto: ah\xED no guardo tu sesi\xF3n. Corre el comando con XDG_CONFIG_HOME fuera del proyecto.`
717
- );
718
- }
2525
+ this.ruta = path12.join(carpeta, "sesion.json");
2526
+ exigirFueraDelProyecto(carpeta, proyecto);
719
2527
  this.descripcion = `el archivo ${this.ruta} (permisos 0600)`;
720
2528
  }
721
2529
  leer() {
722
- if (!fs4.existsSync(this.ruta)) return null;
723
- return JSON.parse(fs4.readFileSync(this.ruta, "utf8"));
2530
+ if (!fs11.existsSync(this.ruta)) return null;
2531
+ return JSON.parse(fs11.readFileSync(this.ruta, "utf8"));
724
2532
  }
725
2533
  guardar(par) {
726
- fs4.mkdirSync(path5.dirname(this.ruta), { recursive: true, mode: 448 });
727
- fs4.writeFileSync(this.ruta, JSON.stringify(par), { mode: 384 });
728
- fs4.chmodSync(this.ruta, 384);
2534
+ fs11.mkdirSync(path12.dirname(this.ruta), { recursive: true, mode: 448 });
2535
+ fs11.writeFileSync(this.ruta, JSON.stringify(par), { mode: 384 });
2536
+ fs11.chmodSync(this.ruta, 384);
729
2537
  }
730
2538
  borrar() {
731
- fs4.rmSync(this.ruta, { force: true });
2539
+ fs11.rmSync(this.ruta, { force: true });
732
2540
  }
733
2541
  };
734
2542
  var AlmacenLlavero = class {
@@ -845,9 +2653,9 @@ function hayQueIrSinNavegador(pedido, env = process.env, plataforma = process.pl
845
2653
  return plataforma === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
846
2654
  }
847
2655
  async function abrirNavegadorDelSistema(url) {
848
- const [comando, argumentos] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
2656
+ const [comando2, argumentos] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
849
2657
  return new Promise((resolver) => {
850
- const hijo = spawn(comando, argumentos, { stdio: "ignore", detached: true });
2658
+ const hijo = spawn(comando2, argumentos, { stdio: "ignore", detached: true });
851
2659
  hijo.once("error", () => resolver(false));
852
2660
  hijo.once("spawn", () => {
853
2661
  hijo.unref();
@@ -913,12 +2721,56 @@ async function loginPegandoCodigo(identidad, salida, opciones) {
913
2721
  async function iniciarSesion(identidad, salida, opciones) {
914
2722
  return opciones.sinNavegador ? loginPegandoCodigo(identidad, salida, opciones) : loginConLoopback(identidad, salida, opciones);
915
2723
  }
2724
+ var VIDA_DEL_INICIO_PENDIENTE_MS = 10 * 6e4;
2725
+ var rutaInicioPendiente = (carpeta) => path12.join(carpeta, "sesion-pendiente.json");
2726
+ var volverAEmpezar = (motivo) => new ErrorCli(`${motivo} Vuelve a empezar con \xABredcumbre login --json\xBB.`, CODIGOS_DE_SALIDA.sesion, { comando: "redcumbre login --json" });
2727
+ async function iniciarLoginDelegado(identidad, carpeta, proyecto, web, ahora = /* @__PURE__ */ new Date()) {
2728
+ exigirFueraDelProyecto(carpeta, proyecto);
2729
+ const pkce = await crearPkce();
2730
+ const redirectUri = `${web}/cli/codigo`;
2731
+ const url = await identidad.urlDeAutorizacion(redirectUri, pkce);
2732
+ const expira = new Date(ahora.getTime() + VIDA_DEL_INICIO_PENDIENTE_MS).toISOString();
2733
+ const pendiente = { verificador: pkce.verificador, estado: pkce.estado, redirectUri, expira };
2734
+ const ruta = rutaInicioPendiente(carpeta);
2735
+ fs11.mkdirSync(carpeta, { recursive: true, mode: 448 });
2736
+ fs11.writeFileSync(ruta, JSON.stringify(pendiente), { mode: 384 });
2737
+ fs11.chmodSync(ruta, 384);
2738
+ return { url, expiraEn: expira };
2739
+ }
2740
+ function leerInicioPendiente(ruta) {
2741
+ if (!fs11.existsSync(ruta)) return null;
2742
+ try {
2743
+ const datos = JSON.parse(fs11.readFileSync(ruta, "utf8"));
2744
+ const completo = ["verificador", "estado", "redirectUri", "expira"].every((k) => typeof datos[k] === "string");
2745
+ return completo ? datos : null;
2746
+ } catch {
2747
+ return null;
2748
+ }
2749
+ }
2750
+ async function completarLoginDelegado(identidad, carpeta, codigo, ahora = /* @__PURE__ */ new Date()) {
2751
+ const ruta = rutaInicioPendiente(carpeta);
2752
+ const pendiente = leerInicioPendiente(ruta);
2753
+ fs11.rmSync(ruta, { force: true });
2754
+ if (!pendiente) throw volverAEmpezar("No hay un inicio de sesi\xF3n pendiente.");
2755
+ if (new Date(pendiente.expira).getTime() <= ahora.getTime()) throw volverAEmpezar("El inicio de sesi\xF3n pendiente venci\xF3 (dura 10 minutos).");
2756
+ const limpio = codigo.trim();
2757
+ if (!limpio) throw volverAEmpezar("El c\xF3digo est\xE1 vac\xEDo.");
2758
+ const retorno = new URL(pendiente.redirectUri);
2759
+ retorno.searchParams.set("code", limpio);
2760
+ retorno.searchParams.set("state", pendiente.estado);
2761
+ if (await identidad.exigeIss()) retorno.searchParams.set("iss", CLIENTE_OIDC.issuer);
2762
+ try {
2763
+ return await identidad.canjear(retorno, { verificador: pendiente.verificador, desafio: "", estado: pendiente.estado });
2764
+ } catch (error) {
2765
+ throw volverAEmpezar(`El servidor de identidad no acept\xF3 el c\xF3digo (${error instanceof Error ? error.message : String(error)}).`);
2766
+ }
2767
+ }
916
2768
  var Sesion = class {
917
- constructor(almacen, identidad, salida, login) {
2769
+ constructor(almacen, identidad, salida, login2) {
918
2770
  this.almacen = almacen;
919
2771
  this.identidad = identidad;
920
2772
  this.salida = salida;
921
- this.login = login;
2773
+ this.login = login2;
922
2774
  }
923
2775
  actual = null;
924
2776
  async entrar() {
@@ -977,73 +2829,264 @@ var Sesion = class {
977
2829
  }
978
2830
  };
979
2831
 
980
- // src/cli.ts
981
- var TITULOS_AYUDA = { "Usage:": "Uso:", "Options:": "Opciones:", "Commands:": "Comandos:", "Arguments:": "Argumentos:" };
982
- function contexto(opciones, proyecto) {
983
- const salida = crearSalida(Boolean(opciones.json));
984
- const { api, web } = servidores();
985
- const clienteApi = new ClienteApi(api);
986
- const interactivo = Boolean(process.stdin.isTTY && process.stdout.isTTY);
987
- const sesion = async () => {
988
- const identidad = identidadOidc();
989
- const almacen = await elegirAlmacen(proyecto);
990
- return new Sesion(
991
- almacen,
992
- identidad,
993
- salida,
994
- () => iniciarSesion(identidad, salida, {
995
- web,
996
- sinNavegador: hayQueIrSinNavegador(Boolean(opciones.sinNavegador)),
997
- leerLinea: (pregunta) => leerLineaDeTerminal(pregunta, salida.json ? process.stderr : process.stdout)
998
- })
999
- );
2832
+ // src/comandos/sesion.ts
2833
+ async function login(ctx, opciones) {
2834
+ const { salida } = ctx;
2835
+ if (opciones.codigo !== void 0) {
2836
+ const par = await completarLoginDelegado(ctx.identidad, ctx.carpetaConfiguracion, opciones.codigo, ctx.ahora());
2837
+ await (await ctx.almacen()).guardar(par);
2838
+ return mostrarEmpresas(ctx);
2839
+ }
2840
+ if (salida.json || !ctx.terminal) {
2841
+ const { url, expiraEn } = await iniciarLoginDelegado(ctx.identidad, ctx.carpetaConfiguracion, ctx.proyecto, ctx.servidores.web, ctx.ahora());
2842
+ salida.linea(`P\xEDdele a la persona que abra esta direcci\xF3n, autorice con su cuenta y te pase el c\xF3digo que muestra: ${url}`);
2843
+ salida.linea("Despu\xE9s corre \xABredcumbre login --codigo <c\xF3digo>\xBB. La direcci\xF3n vence en 10 minutos.");
2844
+ salida.resultado({ url, expiraEn, siguiente: "redcumbre login --codigo <c\xF3digo>" });
2845
+ return;
2846
+ }
2847
+ return mostrarEmpresas(ctx);
2848
+ }
2849
+ async function mostrarEmpresas(ctx) {
2850
+ const sesion = await ctx.sesion();
2851
+ const perfil = await sesion.usar((token) => ctx.cliente.perfil(token));
2852
+ ctx.salida.linea(`\u2713 Tienes sesi\xF3n como ${perfil.persona.nombre} (${perfil.persona.correo}).`);
2853
+ ctx.salida.linea(`Tus empresas: ${perfil.empresas.map(nombreEmpresa).join(", ") || "ninguna"}.`);
2854
+ ctx.salida.resultado({ ok: true, persona: perfil.persona, empresas: perfil.empresas });
2855
+ }
2856
+ async function logout(ctx) {
2857
+ const cerrada = await ctx.haySesion() ? await (await ctx.sesion()).cerrar() : false;
2858
+ ctx.salida.linea(cerrada ? "Sesi\xF3n cerrada: la revoqu\xE9 en el servidor de identidad y la borr\xE9 de este computador." : "No hab\xEDa una sesi\xF3n iniciada.");
2859
+ ctx.salida.resultado({ ok: true, sesionCerrada: cerrada });
2860
+ }
2861
+
2862
+ // src/nucleo/contexto.ts
2863
+ var sinSesionEnModoAgente = () => new ErrorCli(
2864
+ "No hay una sesi\xF3n iniciada y en modo agente no puedo esperar a que la persona inicie sesi\xF3n. Corre \xABredcumbre login --json\xBB, abre la URL que responde y termina con \xABredcumbre login --codigo <c\xF3digo>\xBB.",
2865
+ CODIGOS_DE_SALIDA.sesion,
2866
+ { codigo: "SIN_SESION", comando: "redcumbre login --json" }
2867
+ );
2868
+ function crearContexto(opciones) {
2869
+ const { salida, terminal, env } = opciones;
2870
+ const destinos = servidores(env);
2871
+ const proyecto = raizDelProyecto(opciones.cwd);
2872
+ const carpeta = carpetaDeConfiguracion(env);
2873
+ const identidad = identidadOidc();
2874
+ let almacen = null;
2875
+ let sesion = null;
2876
+ const elAlmacen = () => almacen ??= elegirAlmacen(proyecto, env);
2877
+ const abrir = async (destino) => {
2878
+ const propio = env.REDCUMBRE_ABRIR;
2879
+ if (propio) return abrirCon(propio, destino);
2880
+ return abrirNavegadorDelSistema(destino);
2881
+ };
2882
+ return {
2883
+ salida,
2884
+ terminal,
2885
+ cliente: new ClienteApi(destinos.api),
2886
+ servidores: destinos,
2887
+ carpetaConfiguracion: carpeta,
2888
+ cwd: opciones.cwd,
2889
+ proyecto,
2890
+ env,
2891
+ version: opciones.version,
2892
+ identidad,
2893
+ ahora: () => /* @__PURE__ */ new Date(),
2894
+ abrir,
2895
+ almacen: elAlmacen,
2896
+ async haySesion() {
2897
+ return (await elAlmacen()).leer() !== null;
2898
+ },
2899
+ sesion() {
2900
+ sesion ??= elAlmacen().then(
2901
+ (a) => new Sesion(a, identidad, salida, async () => {
2902
+ if (!terminal) throw sinSesionEnModoAgente();
2903
+ return iniciarSesion(identidad, salida, {
2904
+ web: destinos.web,
2905
+ sinNavegador: hayQueIrSinNavegador(opciones.sinNavegador, env),
2906
+ leerLinea: (pregunta) => terminal.preguntar(pregunta),
2907
+ abrirNavegador: abrir
2908
+ });
2909
+ })
2910
+ );
2911
+ return sesion;
2912
+ }
1000
2913
  };
1001
- return { salida, api: clienteApi, interactivo, sesion };
1002
2914
  }
1003
- async function correr(salida, accion) {
1004
- try {
1005
- await accion();
1006
- } catch (error) {
1007
- const s = salida();
1008
- const mensaje = error instanceof Error ? error.message : String(error);
1009
- if (s.json) process.stdout.write(`${JSON.stringify({ ok: false, error: mensaje, avisos: s.avisos }, null, 2)}
2915
+ async function abrirCon(programa2, destino) {
2916
+ const { spawn: spawn2 } = await import("node:child_process");
2917
+ return new Promise((resolver) => {
2918
+ const hijo = spawn2(programa2, [destino], { stdio: "ignore" });
2919
+ hijo.once("error", () => resolver(false));
2920
+ hijo.once("exit", (codigo) => resolver(codigo === 0));
2921
+ });
2922
+ }
2923
+
2924
+ // src/nucleo/terminal.ts
2925
+ import readline from "node:readline";
2926
+ var MAXIMO_INTENTOS3 = 3;
2927
+ function crearTerminal(entrada, humano) {
2928
+ let rl = null;
2929
+ const lineas = [];
2930
+ const esperando = [];
2931
+ let cerrada = false;
2932
+ const abrir = () => {
2933
+ if (rl) return;
2934
+ rl = readline.createInterface({ input: entrada, terminal: false, crlfDelay: Infinity });
2935
+ rl.on("line", (linea) => {
2936
+ const siguiente = esperando.shift();
2937
+ if (siguiente) siguiente(linea);
2938
+ else lineas.push(linea);
2939
+ });
2940
+ rl.on("close", () => {
2941
+ cerrada = true;
2942
+ for (const resolver of esperando.splice(0)) resolver(null);
2943
+ });
2944
+ };
2945
+ const leer = (pregunta) => {
2946
+ abrir();
2947
+ humano.write(pregunta);
2948
+ const enCola = lineas.shift();
2949
+ if (enCola !== void 0) return Promise.resolve(enCola);
2950
+ if (cerrada) return Promise.reject(sinRespuesta());
2951
+ return new Promise((resolver, rechazar) => esperando.push((linea) => linea === null ? rechazar(sinRespuesta()) : resolver(linea)));
2952
+ };
2953
+ const lista2 = (opciones) => {
2954
+ opciones.forEach((opcion, i) => humano.write(` ${i + 1}) ${opcion.etiqueta}
2955
+ `));
2956
+ };
2957
+ const numero = (texto2, total) => {
2958
+ const limpio = texto2.trim();
2959
+ if (!/^\d+$/.test(limpio)) return null;
2960
+ const n = Number(limpio);
2961
+ return n >= 1 && n <= total ? n - 1 : null;
2962
+ };
2963
+ return {
2964
+ preguntar: async (pregunta) => (await leer(pregunta)).trim(),
2965
+ async confirmar(pregunta) {
2966
+ const respuesta = (await leer(`${pregunta} [s/N] `)).trim().toLowerCase();
2967
+ return respuesta === "s" || respuesta === "si" || respuesta === "s\xED";
2968
+ },
2969
+ async elegir(pregunta, opciones) {
2970
+ humano.write(`${pregunta}
1010
2971
  `);
1011
- process.stderr.write(`\u2717 ${mensaje}
2972
+ lista2(opciones);
2973
+ for (let intento = 0; intento < MAXIMO_INTENTOS3; intento++) {
2974
+ const respuesta = await leer(`Escribe un n\xFAmero del 1 al ${opciones.length}: `);
2975
+ if (!respuesta.trim()) throw sinEleccion();
2976
+ const i = numero(respuesta, opciones.length);
2977
+ if (i !== null) return opciones[i].valor;
2978
+ }
2979
+ throw new ErrorCli("No elegiste ninguna opci\xF3n v\xE1lida.", CODIGOS_DE_SALIDA.uso);
2980
+ },
2981
+ async elegirVarias(pregunta, opciones) {
2982
+ humano.write(`${pregunta}
1012
2983
  `);
1013
- process.exitCode = error instanceof ErrorCli ? error.codigoSalida : 1;
1014
- }
1015
- }
1016
- var programa = new Command().name("redcumbre").description("Conecta tu proyecto con rCAPI de REDCUMBRE: inicia sesi\xF3n con tu cuenta e instala la llave de la API en el proyecto.").version("0.1.0", "-v, --version", "muestra la versi\xF3n").helpOption("-h, --help", "muestra esta ayuda").helpCommand(false).usage("[opciones] [comando]").configureHelp({ styleTitle: (titulo) => TITULOS_AYUDA[titulo] ?? titulo, subcommandTerm: (comando) => `${comando.name()} [opciones]` }).showHelpAfterError("(corre redcumbre --help para ver los comandos)");
1017
- var opcionSinNavegador = new Option("--sin-navegador", "no abre el navegador: imprime la URL y espera el c\xF3digo que muestra la p\xE1gina");
1018
- var opcionJson = new Option("--json", "salida en JSON para agentes de c\xF3digo (nunca incluye el secreto de la llave)");
1019
- programa.command("init").usage("[opciones]").description("inicia sesi\xF3n si hace falta e instala la llave de la API en el proyecto (en una carpeta vac\xEDa, arma antes el proyecto)").option("--empresa <slug>", "la empresa (tenantSlug) de la llave").option("--entorno <entorno>", `entorno de la llave: ${ENTORNOS_LLAVE.join(" o ")}; obligatorio sin terminal interactiva`).option("--lenguaje <lenguaje>", `lenguaje del proyecto desde cero, s\xF3lo en una carpeta vac\xEDa: ${LENGUAJES.join(", ")}`).option("--carpeta <ruta>", "carpeta del proyecto (por defecto, la actual)").option("--sin-mcp", "no configura el servidor MCP de rCAPI en .mcp.json ni .cursor/mcp.json").addOption(opcionJson).addOption(opcionSinNavegador).action(async (opciones) => {
1020
- const ctx = contexto(opciones, opciones.carpeta ?? process.cwd());
1021
- await correr(
1022
- () => ctx.salida,
1023
- () => ejecutarInit(opciones, {
1024
- ...ctx,
1025
- cwd: process.cwd(),
1026
- ahora: () => /* @__PURE__ */ new Date(),
1027
- preguntas: {
1028
- entorno: preguntarEntorno,
1029
- empresa: preguntarEmpresa,
1030
- lenguaje: preguntarLenguaje,
1031
- dondeInstalar: preguntarDondeInstalar,
1032
- otroEntorno: preguntarOtroEntorno
2984
+ lista2(opciones);
2985
+ for (let intento = 0; intento < MAXIMO_INTENTOS3; intento++) {
2986
+ const respuesta = await leer(`Escribe uno o m\xE1s n\xFAmeros del 1 al ${opciones.length}, separados por coma: `);
2987
+ if (!respuesta.trim()) throw sinEleccion();
2988
+ const partes = respuesta.split(",").filter((p) => p.trim());
2989
+ const indices = partes.map((p) => numero(p, opciones.length));
2990
+ if (indices.length > 0 && indices.every((i) => i !== null)) return [...new Set(indices)].map((i) => opciones[i].valor);
1033
2991
  }
1034
- })
1035
- );
1036
- });
1037
- programa.command("conectar-mcp").usage("[opciones]").description("configura el servidor MCP de rCAPI para Claude Code (.mcp.json) y Cursor (.cursor/mcp.json) sin tocar otros servidores; no crea llaves").option("--carpeta <ruta>", "carpeta del proyecto (por defecto, la actual)").addOption(opcionJson).action(async (opciones) => {
1038
- const salida = crearSalida(Boolean(opciones.json));
1039
- await correr(() => salida, () => ejecutarConectarMcp(opciones, { salida, cwd: process.cwd() }));
1040
- });
1041
- programa.command("login").usage("[opciones]").description("inicia sesi\xF3n con tu cuenta de REDCUMBRE en el navegador (no crea llaves)").addOption(opcionJson).addOption(opcionSinNavegador).action(async (opciones) => {
1042
- const ctx = contexto(opciones, process.cwd());
1043
- await correr(() => ctx.salida, () => ejecutarLogin(ctx));
1044
- });
1045
- programa.command("logout").usage("[opciones]").description("cierra la sesi\xF3n: la revoca en el servidor de identidad y la borra de este computador").addOption(opcionJson).action(async (opciones) => {
1046
- const ctx = contexto(opciones, process.cwd());
1047
- await correr(() => ctx.salida, () => ejecutarLogout(ctx));
2992
+ throw new ErrorCli("No elegiste ninguna opci\xF3n v\xE1lida.", CODIGOS_DE_SALIDA.uso);
2993
+ },
2994
+ cerrar() {
2995
+ rl?.close();
2996
+ rl = null;
2997
+ }
2998
+ };
2999
+ }
3000
+ function sinEleccion() {
3001
+ return new ErrorCli("No elegiste ninguna opci\xF3n. No se hizo nada.", CODIGOS_DE_SALIDA.confirmacion);
3002
+ }
3003
+ function sinRespuesta() {
3004
+ return new ErrorCli("La entrada se cerr\xF3 antes de que respondieras. No se hizo nada.", CODIGOS_DE_SALIDA.confirmacion);
3005
+ }
3006
+
3007
+ // src/cli.ts
3008
+ var ERRORES_DE_USO = [
3009
+ [/unknown command '(.+)'/, (c) => `El comando \xAB${c}\xBB no existe.`],
3010
+ [/unknown option '(.+)'/, (o) => `La opci\xF3n \xAB${o}\xBB no existe.`],
3011
+ [/missing required argument '(.+)'/, (a) => `Falta el argumento \xAB${a}\xBB.`],
3012
+ [/option '(.+)' argument missing/, (o) => `La opci\xF3n \xAB${o}\xBB necesita un valor.`],
3013
+ [/required option '(.+)' not specified/, (o) => `Falta la opci\xF3n obligatoria \xAB${o}\xBB.`],
3014
+ [/too many arguments(?: for '(.+)')?/, (c) => c ? `Sobran argumentos para \xAB${c}\xBB.` : "Sobran argumentos."]
3015
+ ];
3016
+ function errorDeUsoEnEspanol(mensaje) {
3017
+ const limpio = mensaje.replace(/^error: /, "").trim();
3018
+ for (const [patron, traducir] of ERRORES_DE_USO) {
3019
+ const m = patron.exec(limpio);
3020
+ if (m) return traducir(...m.slice(1));
3021
+ }
3022
+ return limpio;
3023
+ }
3024
+ var TITULOS_AYUDA = { "Usage:": "Uso:", "Options:": "Opciones:", "Commands:": "Comandos:", "Arguments:": "Argumentos:" };
3025
+ async function correr(globales, accion) {
3026
+ const json2 = Boolean(globales.json);
3027
+ const agente = esModoAgente(json2);
3028
+ const salida = crearSalida(agente);
3029
+ const terminal = agente ? null : crearTerminal(process.stdin, process.stdout);
3030
+ const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.3.1" });
3031
+ try {
3032
+ if (!agente) {
3033
+ await avisarSiHayVersionNueva({ carpeta: ctx.carpetaConfiguracion, version: ctx.version, ahora: ctx.ahora(), humano: process.stderr, registro: process.env.REDCUMBRE_NPM_REGISTRY });
3034
+ }
3035
+ await accion(ctx);
3036
+ } catch (error) {
3037
+ process.exitCode = salida.error(error);
3038
+ } finally {
3039
+ terminal?.cerrar();
3040
+ }
3041
+ }
3042
+ var sumar = (valor, anteriores) => [...anteriores, valor];
3043
+ var programa = new Command().name("redcumbre").description("El CLI de REDCUMBRE: conecta tu proyecto en el modo de prueba, opera la API y pasa a real cuando est\xE9s listo.").version("0.3.1", "-v, --version", "muestra la versi\xF3n").helpOption("-h, --help", "muestra esta ayuda").helpCommand(false).usage("[opciones] [comando]").enablePositionalOptions().configureHelp({ styleTitle: (titulo) => TITULOS_AYUDA[titulo] ?? titulo, subcommandTerm: (comando2) => `${comando2.name()} ${comando2.usage()}`.trim() }).showHelpAfterError("(corre redcumbre --help para ver los comandos)").configureOutput({ outputError: (texto2, escribir2) => escribir2(`\u2717 ${errorDeUsoEnEspanol(texto2)}
3044
+ `) }).exitOverride((error) => {
3045
+ if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.code === "commander.help") process.exit(0);
3046
+ if (process.argv.includes("--json")) {
3047
+ process.stdout.write(`${JSON.stringify({ error: { codigo: "USO_INCORRECTO", mensaje: errorDeUsoEnEspanol(error.message) } }, null, 2)}
3048
+ `);
3049
+ }
3050
+ process.exit(CODIGOS_DE_SALIDA.uso);
1048
3051
  });
3052
+ var json = () => new Option("--json", "modo agente: no pregunta y deja un solo JSON en stdout (nunca el secreto de la llave)");
3053
+ var sinNavegador = () => new Option("--sin-navegador", "no abre el navegador: imprime la URL");
3054
+ var empresa = () => new Option("--empresa <slug>", "la empresa (tenantSlug); por omisi\xF3n, la del proyecto");
3055
+ var comando = (padre, nombre, descripcion) => padre.command(nombre).description(descripcion).addOption(json());
3056
+ comando(programa, "init", "conecta el proyecto con una llave de prueba y hace una primera prueba (en una carpeta vac\xEDa, arma antes el proyecto)").addOption(empresa()).option("--entorno <modo>", "prueba (por omisi\xF3n) o real; real sigue el flujo de pasar-a-real").option("--lenguaje <lenguaje>", `lenguaje del proyecto desde cero, s\xF3lo en una carpeta vac\xEDa: ${LENGUAJES.join(", ")}`).option("--carpeta <ruta>", "carpeta del proyecto (por omisi\xF3n, la actual)").option("--servicios <lista>", "con --entorno real: los servicios que activas en real, separados por coma").addOption(sinNavegador()).action((o) => correr(o, (ctx) => init(ctx, o)));
3057
+ comando(programa, "pasar-a-real", "revisa que todo est\xE9 en orden y agrega la llave real al proyecto (lo hace una persona)").addOption(empresa()).option("--servicios <lista>", "los servicios que activas en real, separados por coma").addOption(sinNavegador()).action((o) => correr(o, (ctx) => pasarAReal(ctx, o)));
3058
+ comando(programa, "login", "inicia sesi\xF3n con tu cuenta de REDCUMBRE (con --json, entrega la URL para que la persona la abra)").option("--codigo <c\xF3digo>", "termina un login delegado con el c\xF3digo que mostr\xF3 la p\xE1gina").addOption(sinNavegador()).action((o) => correr(o, (ctx) => login(ctx, o)));
3059
+ comando(programa, "logout", "cierra la sesi\xF3n: la revoca en el servidor de identidad y la borra de este computador").action((o) => correr(o, logout));
3060
+ var comandoLlaves = comando(programa, "llaves", "lista las llaves de la empresa y marca las de este proyecto").addOption(empresa()).action((o) => correr(o, (ctx) => llaves(ctx, o)));
3061
+ comando(comandoLlaves, "revocar", "revoca una llave (pide confirmar con el slug de la empresa)").argument("<id>", "el id de la llave").addOption(empresa()).option("--confirmar <slug>", "confirma la revocaci\xF3n sin preguntar").action((id, o) => correr(o, (ctx) => revocarLlave(ctx, id, o)));
3062
+ declararOpcionesLlaveValidaFirma(comando(comandoLlaves, "validafirma", "crea la llave con la que el CLI de ValidaFirma trabaja en una empresa (la real pide confirmar con el slug)")).action((o) => correr(o, (ctx) => llaveValidaFirma(ctx, o)));
3063
+ comando(programa, "llamadas", "las \xFAltimas llamadas a la API hechas con la llave del proyecto").option("--llave <id>", "otra llave de la empresa, por su id").option("--real", "las de la llave real").option("--desde <fecha>", "desde esta fecha (AAAA-MM-DD)").option("--hasta <fecha>", "hasta esta fecha (AAAA-MM-DD)").option("--limite <n>", "cu\xE1ntas, como m\xE1ximo").action((o) => correr(o, (ctx) => llamadas(ctx, o)));
3064
+ var comandoWebhooks = programa.command("webhooks").description("los webhooks de la empresa en tu computador");
3065
+ comando(comandoWebhooks, "escuchar", "recibe los eventos de la empresa y los reenv\xEDa a una URL local, firmados").requiredOption("--reenviar-a <url>", "la URL local que recibe los eventos (http://localhost:\u2026)").option("--eventos <lista>", "s\xF3lo estos eventos, separados por coma").addOption(empresa()).action((o) => correr(o, (ctx) => webhooksEscuchar(ctx, o)));
3066
+ var comandoEventos = comando(programa, "eventos", "los eventos de webhook que puedes disparar en el modo de prueba").action((o) => correr(o, eventos));
3067
+ comando(comandoEventos, "disparar", "dispara un evento de prueba hacia tus webhooks y los relays abiertos").argument("<evento>", "el evento, como dte.emitido").action((evento, o) => correr(o, (ctx) => dispararEvento(ctx, evento)));
3068
+ comando(programa, "escenarios", "los emisores, RUT y simulaciones del modo de prueba de la empresa").action((o) => correr(o, escenarios));
3069
+ comando(programa, "bandeja", "los correos y mensajes que el modo de prueba retuvo en vez de enviarlos").option("--canal <canal>", "s\xF3lo un canal (correo, sms, whatsapp)").option("--destinatario <destino>", "s\xF3lo los de este destinatario").option("--limite <n>", "cu\xE1ntos, como m\xE1ximo").action((o) => correr(o, (ctx) => bandeja(ctx, o)));
3070
+ comando(programa, "estado", "en qu\xE9 modo est\xE1 cada llave del proyecto y cu\xE1nto queda del tope diario de prueba").option("--real", "el de la llave real").action((o) => correr(o, (ctx) => estado(ctx, o)));
3071
+ comando(programa, "restaurar", "borra lo emitido en el modo de prueba y vuelve a sembrar los escenarios (pide confirmar)").addOption(empresa()).option("--confirmar <slug>", "confirma sin preguntar, con el slug de la empresa").action((o) => correr(o, (ctx) => restaurar(ctx, o)));
3072
+ var comandoApi = comando(programa, "api", "lista las operaciones de la API o ejecuta una con la llave del proyecto").argument("[operaci\xF3n]", "el operationId; sin \xE9l, lista las operaciones").option("--param <clave=valor>", "un par\xE1metro de ruta o de consulta; se repite", sumar, []).option("--cuerpo <json|@archivo|->", "el cuerpo: JSON, @archivo o - para leerlo de stdin").option("--real", "con la llave real (pide confirmar lo que escribe)").option("--confirmar <slug>", "confirma una escritura real o un cobro, con el slug de la empresa").option("--ensayo", "muestra la petici\xF3n sin hacerla").option("--clave <clave>", "la clave de idempotencia de una escritura").option("--todas", "recorre todas las p\xE1ginas de un listado").option("--campos <lista>", "s\xF3lo estos campos de cada elemento, separados por coma").option("--salida <archivo>", "guarda una respuesta binaria (un PDF) en este archivo").action((operacion, o) => correr(o, (ctx) => operacion ? apiEjecutar(ctx, operacion, o) : apiListar(ctx)));
3073
+ comando(comandoApi, "describir", "explica una operaci\xF3n: par\xE1metros, cuerpo, efecto y cobro").argument("<operaci\xF3n>", "el operationId").action((operacion, o) => correr(o, (ctx) => apiDescribir(ctx, operacion)));
3074
+ comando(comandoApi, "buscar", "busca operaciones por texto").argument("<texto>", "lo que buscas").action((texto2, o) => correr(o, (ctx) => apiBuscar(ctx, texto2)));
3075
+ comando(programa, "consumo", "lo consumido del plan y los topes del d\xEDa").option("--real", "el de la llave real").action((o) => correr(o, (ctx) => consumo(ctx, o)));
3076
+ comando(programa, "receta", "agrega al proyecto una receta que funciona en el modo de prueba (s\xF3lo agrega archivos)").argument("<receta>", RECETAS.join(", ")).option("--lenguaje <lenguaje>", `${LENGUAJES.join(", ")}; por omisi\xF3n, el del proyecto`).action((nombre, o) => correr(o, (ctx) => receta(ctx, nombre, o)));
3077
+ var comandoMcp = programa.command("mcp").description("el servidor MCP de REDCUMBRE en tu asistente de c\xF3digo");
3078
+ comando(comandoMcp, "agregar", "agrega el servidor MCP a la configuraci\xF3n de tu asistente (pide confirmar)").option("--asistente <asistente>", ASISTENTES_MCP.join(" o ")).action((o) => correr(o, (ctx) => mcpAgregar(ctx, o)));
3079
+ comando(comandoMcp, "quitar", "quita el servidor MCP de la configuraci\xF3n de tu asistente").option("--asistente <asistente>", ASISTENTES_MCP.join(" o ")).action((o) => correr(o, (ctx) => mcpQuitar(ctx, o)));
3080
+ comando(programa, "solicitar-cuenta", "pide una cuenta en REDCUMBRE para tu empresa (lo hace una persona)").action(
3081
+ (o) => correr(o, async (ctx) => {
3082
+ await solicitarCuenta(ctx);
3083
+ })
3084
+ );
3085
+ comando(programa, "doctor", "revisa la sesi\xF3n, la empresa, las llaves, las exclusiones de git y el documento del API").action((o) => correr(o, doctor));
3086
+ comando(programa, "panel", "abre el panel de la empresa del proyecto en el navegador").addOption(empresa()).addOption(sinNavegador()).action((o) => correr(o, (ctx) => panel(ctx, { empresa: o.empresa, sinNavegador: hayQueIrSinNavegador(Boolean(o.sinNavegador), process.env) })));
3087
+ var traducirUso = (c) => {
3088
+ c.usage(c.usage().replace("[options]", "[opciones]").replace("[command]", "[comando]"));
3089
+ c.commands.forEach(traducirUso);
3090
+ };
3091
+ programa.commands.forEach(traducirUso);
1049
3092
  await programa.parseAsync(process.argv);