@redcumbrecl/cli 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,3 @@
1
- #!/usr/bin/env node
2
-
3
1
  // src/cli.ts
4
2
  import { Command as Command3, Option as Option3 } from "commander";
5
3
 
@@ -14,7 +12,9 @@ var CODIGOS_DE_SALIDA = {
14
12
  api4xx: 6,
15
13
  api5xx: 7,
16
14
  modo: 8,
17
- verificacion: 9
15
+ verificacion: 9,
16
+ /** Lo emite el arranque (`src/arranque.ts`), no un comando: el Node es menor que el mínimo (#1490). */
17
+ node: 10
18
18
  };
19
19
  var CODIGO_DE_ERROR_POR_SALIDA = {
20
20
  1: "ERROR_DEL_CLI",
@@ -25,7 +25,8 @@ var CODIGO_DE_ERROR_POR_SALIDA = {
25
25
  6: "API_RECHAZO",
26
26
  7: "API_NO_DISPONIBLE",
27
27
  8: "PROHIBIDO_POR_EL_MODO",
28
- 9: "VERIFICACION_FALLIDA"
28
+ 9: "VERIFICACION_FALLIDA",
29
+ 10: "NODE_NO_SOPORTADO"
29
30
  };
30
31
  var IDENTIDAD_SIN_RESPUESTA = "IDENTIDAD_SIN_RESPUESTA";
31
32
  var ErrorCli = class extends Error {
@@ -351,7 +352,7 @@ function mensajeEntornoLlaveInvalido(valor) {
351
352
  return `El entorno \xAB${recibido}\xBB no existe. Usa ${ENTORNOS_LLAVE.map((e) => `\xAB${e}\xBB`).join(" o ")}.`;
352
353
  }
353
354
  var PAQUETE_DEL_CLI = "@redcumbrecl/cli";
354
- var COMANDO_DE_ACTUALIZACION_DEL_CLI = `npx ${PAQUETE_DEL_CLI}@latest`;
355
+ var COMANDO_DE_ACTUALIZACION_DEL_CLI = `npx ${PAQUETE_DEL_CLI}@latest instalar`;
355
356
  var CODIGO_CLI_DESACTUALIZADO = "CLI_DESACTUALIZADO";
356
357
  var ALCANCES_LLAVE_VALIDAFIRMA = ["carpetas", "cuenta"];
357
358
  var ALCANCE_LLAVE_VALIDAFIRMA_REGISTRY = {
@@ -396,6 +397,7 @@ var SOLICITUD_CUENTA_CAMPOS = [
396
397
  ];
397
398
  var SOLICITUD_CUENTA_FINALIDAD = "solo para crear tu cuenta y contactarte";
398
399
  var SOLICITUD_CUENTA_URL_PRIVACIDAD = "https://redcumbre.cl/privacidad";
400
+ var SOLICITUD_CUENTA_URL_FORMULARIO_SITIO = "https://docs.redcumbre.cl/solicitar-cuenta/";
399
401
  var SOLICITUD_CUENTA_TEXTO_INFORMACION = `REDCUMBRE usa estos datos ${SOLICITUD_CUENTA_FINALIDAD}.`;
400
402
  var SOLICITUD_CUENTA_AVISO = `REDCUMBRE usa estos datos ${SOLICITUD_CUENTA_FINALIDAD}. Pol\xEDtica de Privacidad: ${SOLICITUD_CUENTA_URL_PRIVACIDAD}`;
401
403
 
@@ -468,6 +470,7 @@ var SERVICIOS_DE_PASO_A_PRODUCCION = [
468
470
  "reactivarEmisorDte",
469
471
  "cancelarCertificacionEmisorDte",
470
472
  "registrarEmisorDteEnPortalMipyme",
473
+ "volverEmisorDteAlPortalMipyme",
471
474
  "archivarEmisorTributario",
472
475
  "reactivarEmisorTributario"
473
476
  ],
@@ -854,6 +857,112 @@ function parClaveValor(texto2) {
854
857
  return [texto2.slice(0, i), texto2.slice(i + 1)];
855
858
  }
856
859
 
860
+ // src/nucleo/aviso-version.ts
861
+ import fs3 from "node:fs";
862
+ import path3 from "node:path";
863
+ var PAQUETE_CLI = PAQUETE_DEL_CLI;
864
+ var REGISTRO_NPM = "https://registry.npmjs.org/";
865
+ var urlUltimaVersion = (registro = REGISTRO_NPM) => `${registro.replace(/\/+$/, "")}/${PAQUETE_CLI}/latest`;
866
+ var TIEMPO_MAXIMO_MS = 1500;
867
+ var UN_DIA_MS = 24 * 60 * 60 * 1e3;
868
+ var rutaMarcaVersion = (carpeta) => path3.join(carpeta, "aviso-version.json");
869
+ function leerMarca(carpeta) {
870
+ try {
871
+ const marca = JSON.parse(fs3.readFileSync(rutaMarcaVersion(carpeta), "utf8"));
872
+ return typeof marca.revisadoEn === "string" ? { revisadoEn: marca.revisadoEn, ultima: typeof marca.ultima === "string" ? marca.ultima : null } : null;
873
+ } catch {
874
+ return null;
875
+ }
876
+ }
877
+ function escribirMarca(carpeta, marca) {
878
+ try {
879
+ fs3.mkdirSync(carpeta, { recursive: true, mode: 448 });
880
+ fs3.writeFileSync(rutaMarcaVersion(carpeta), `${JSON.stringify(marca)}
881
+ `);
882
+ } catch {
883
+ }
884
+ }
885
+ function compararVersiones(a, b) {
886
+ const partes = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10));
887
+ const pa = partes(a);
888
+ const pb = partes(b);
889
+ if ([...pa, ...pb].some((n) => !Number.isFinite(n))) return 0;
890
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
891
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
892
+ if (d !== 0) return d > 0 ? 1 : -1;
893
+ }
894
+ return 0;
895
+ }
896
+ async function consultarRegistro(url, senal) {
897
+ const r = await fetch(url, { signal: senal, headers: { accept: "application/json" } });
898
+ if (!r.ok) return null;
899
+ const cuerpo = await r.json();
900
+ return typeof cuerpo.version === "string" ? cuerpo.version : null;
901
+ }
902
+ var COMANDO_ACTUALIZAR = "redcumbre actualizar";
903
+ var COMANDO_ACTUALIZAR_CONFIRMADO = `${COMANDO_ACTUALIZAR} --confirmar`;
904
+ async function ultimaVersionConocida(opciones) {
905
+ const marca = leerMarca(opciones.carpeta);
906
+ if (marca && opciones.ahora.getTime() - Date.parse(marca.revisadoEn) < UN_DIA_MS) return { ultima: marca.ultima, consultado: false };
907
+ let ultima = null;
908
+ try {
909
+ const senal = AbortSignal.timeout(TIEMPO_MAXIMO_MS);
910
+ ultima = opciones.consultar ? await opciones.consultar(senal) : await consultarRegistro(urlUltimaVersion(opciones.registro || void 0), senal);
911
+ } catch {
912
+ ultima = null;
913
+ }
914
+ escribirMarca(opciones.carpeta, { revisadoEn: opciones.ahora.toISOString(), ultima });
915
+ return { ultima, consultado: true };
916
+ }
917
+ async function avisarSiHayVersionNueva(opciones) {
918
+ const { ultima, consultado } = await ultimaVersionConocida(opciones);
919
+ if (consultado && ultima && compararVersiones(ultima, opciones.version) > 0) {
920
+ opciones.humano.write(`\u2139 Hay una versi\xF3n m\xE1s nueva del CLI: ${ultima} (tienes ${opciones.version}). Actual\xEDzala con \xAB${opciones.comando ?? COMANDO_ACTUALIZAR}\xBB, que deja al d\xEDa el CLI y la skill.
921
+ `);
922
+ }
923
+ }
924
+ async function actualizacionDisponible(opciones) {
925
+ const { ultima } = await ultimaVersionConocida(opciones);
926
+ if (!ultima || compararVersiones(ultima, opciones.version) <= 0) return null;
927
+ return { instalada: opciones.version, disponible: ultima, comando: COMANDO_ACTUALIZAR_CONFIRMADO };
928
+ }
929
+ var avisoDeActualizacion = (a) => `Hay una versi\xF3n m\xE1s nueva del CLI: ${a.disponible} (tienes ${a.instalada}). D\xEDselo a la persona y prop\xF3nle actualizar; si acepta, corre \xAB${a.comando}\xBB.`;
930
+ var SITIO_DOCS = PRODUCCION.docs;
931
+ var ARCHIVO_VERSION_MINIMA = "cli-version-minima.txt";
932
+ var COMANDO_DE_ACTUALIZACION = COMANDO_DE_ACTUALIZACION_DEL_CLI;
933
+ var VERSION_VALIDA = /^\d+\.\d+\.\d+$/;
934
+ function urlVersionMinima(env = process.env) {
935
+ return `${origenDeDocs(env)}/${ARCHIVO_VERSION_MINIMA}`;
936
+ }
937
+ async function leerArchivoMinimo(url, senal) {
938
+ const r = await fetch(url, { signal: senal, headers: { accept: "text/plain" }, credentials: "omit" });
939
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
940
+ return r.text();
941
+ }
942
+ async function exigirVersionMinima(opciones) {
943
+ const depurar = opciones.depurar ?? (() => void 0);
944
+ const url = urlVersionMinima(opciones.env);
945
+ let minima;
946
+ try {
947
+ const texto2 = await (opciones.consultar ?? leerArchivoMinimo)(url, AbortSignal.timeout(TIEMPO_MAXIMO_MS));
948
+ minima = texto2.trim();
949
+ } catch (error) {
950
+ depurar(`no pude leer la versi\xF3n m\xEDnima en ${url} (${error instanceof Error ? error.message : String(error)}); sigo sin comprobarla`);
951
+ return;
952
+ }
953
+ if (!VERSION_VALIDA.test(minima)) {
954
+ depurar(`la versi\xF3n m\xEDnima de ${url} no es una versi\xF3n (${JSON.stringify(minima.slice(0, 40))}); sigo sin comprobarla`);
955
+ return;
956
+ }
957
+ if (compararVersiones(minima, opciones.version) > 0) {
958
+ throw new ErrorCli(
959
+ `Este CLI (${opciones.version}) est\xE1 por debajo de la versi\xF3n m\xEDnima que se puede usar (${minima}). Actual\xEDzalo con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`,
960
+ 1,
961
+ { codigo: CODIGO_CLI_DESACTUALIZADO, comando: COMANDO_DE_ACTUALIZACION, datos: { version: opciones.version, minima } }
962
+ );
963
+ }
964
+ }
965
+
857
966
  // src/comandos/buscar.ts
858
967
  var SITIO_DE_DOCUMENTACION = PRODUCCION.docs;
859
968
  var RUTA_CON_LLAVE = "/global/busqueda";
@@ -903,7 +1012,7 @@ async function buscar(ctx, palabras) {
903
1012
  throw apuntandoAlSitio(error);
904
1013
  }
905
1014
  if (!Array.isArray(respuesta?.resultados)) {
906
- throw new ErrorCli("La b\xFAsqueda respondi\xF3 algo que el CLI no entiende (falta \xABresultados\xBB). Actualiza el CLI con \xABnpx @redcumbrecl/cli@latest\xBB y vuelve a intentarlo.", CODIGOS_DE_SALIDA.error, {
1015
+ throw new ErrorCli(`La b\xFAsqueda respondi\xF3 algo que el CLI no entiende (falta \xABresultados\xBB). Actualiza el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB y vuelve a intentarlo.`, CODIGOS_DE_SALIDA.error, {
907
1016
  codigo: "RESPUESTA_INESPERADA"
908
1017
  });
909
1018
  }
@@ -925,8 +1034,8 @@ async function buscar(ctx, palabras) {
925
1034
  }
926
1035
 
927
1036
  // src/comandos/api.ts
928
- import fs4 from "node:fs";
929
- import path4 from "node:path";
1037
+ import fs5 from "node:fs";
1038
+ import path5 from "node:path";
930
1039
 
931
1040
  // src/nucleo/confirmacion.ts
932
1041
  import { randomUUID } from "node:crypto";
@@ -1057,16 +1166,16 @@ function mostrarCobro(salida, cobro) {
1057
1166
  }
1058
1167
 
1059
1168
  // src/nucleo/documento.ts
1060
- import fs3 from "node:fs";
1061
- import path3 from "node:path";
1169
+ import fs4 from "node:fs";
1170
+ import path4 from "node:path";
1062
1171
  var METODOS = ["get", "post", "put", "patch", "delete"];
1063
- var rutaCopiaDocumento = (carpeta) => path3.join(carpeta, "api-docs.json");
1064
- var rutaEtagDocumento = (carpeta) => path3.join(carpeta, "api-docs.etag");
1172
+ var rutaCopiaDocumento = (carpeta) => path4.join(carpeta, "api-docs.json");
1173
+ var rutaEtagDocumento = (carpeta) => path4.join(carpeta, "api-docs.etag");
1065
1174
  function leerEtiqueta(carpeta) {
1066
1175
  const ruta = rutaEtagDocumento(carpeta);
1067
- if (!fs3.existsSync(ruta) || !fs3.existsSync(rutaCopiaDocumento(carpeta))) return null;
1176
+ if (!fs4.existsSync(ruta) || !fs4.existsSync(rutaCopiaDocumento(carpeta))) return null;
1068
1177
  try {
1069
- const datos = JSON.parse(fs3.readFileSync(ruta, "utf8"));
1178
+ const datos = JSON.parse(fs4.readFileSync(ruta, "utf8"));
1070
1179
  return typeof datos.api === "string" ? { api: datos.api, etag: typeof datos.etag === "string" ? datos.etag : null } : null;
1071
1180
  } catch {
1072
1181
  return null;
@@ -1074,15 +1183,15 @@ function leerEtiqueta(carpeta) {
1074
1183
  }
1075
1184
  function leerCopia(carpeta) {
1076
1185
  try {
1077
- return JSON.parse(fs3.readFileSync(rutaCopiaDocumento(carpeta), "utf8"));
1186
+ return JSON.parse(fs4.readFileSync(rutaCopiaDocumento(carpeta), "utf8"));
1078
1187
  } catch {
1079
1188
  return null;
1080
1189
  }
1081
1190
  }
1082
1191
  function guardarCopia(carpeta, api, texto2, etag) {
1083
- fs3.mkdirSync(carpeta, { recursive: true, mode: 448 });
1084
- fs3.writeFileSync(rutaCopiaDocumento(carpeta), texto2);
1085
- fs3.writeFileSync(rutaEtagDocumento(carpeta), `${JSON.stringify({ api, etag })}
1192
+ fs4.mkdirSync(carpeta, { recursive: true, mode: 448 });
1193
+ fs4.writeFileSync(rutaCopiaDocumento(carpeta), texto2);
1194
+ fs4.writeFileSync(rutaEtagDocumento(carpeta), `${JSON.stringify({ api, etag })}
1086
1195
  `);
1087
1196
  }
1088
1197
  var fechaLegible = (fecha) => fecha.toLocaleString("es-CL", { dateStyle: "medium", timeStyle: "short" });
@@ -1092,7 +1201,7 @@ async function cargarDocumento(cliente, carpeta, salida) {
1092
1201
  const usarCopiaSinRevalidar = (motivo) => {
1093
1202
  const crudo2 = copiaDelMismoApi ? leerCopia(carpeta) : null;
1094
1203
  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" });
1095
- const fecha = fs3.statSync(rutaCopiaDocumento(carpeta)).mtime;
1204
+ const fecha = fs4.statSync(rutaCopiaDocumento(carpeta)).mtime;
1096
1205
  salida.aviso(`${motivo} Uso la copia del documento del API del ${fechaLegible(fecha)}: puede no traer las operaciones m\xE1s nuevas.`);
1097
1206
  return { ...indexar(crudo2), copiaSinRevalidar: fecha };
1098
1207
  };
@@ -1184,13 +1293,51 @@ function buscarOperacion(documento, operationId) {
1184
1293
  const sugerencia = parecidas.length ? ` \xBFQuisiste decir ${parecidas.map((o) => o.operationId).join(", ")}?` : " Corre \xABredcumbre api buscar <texto>\xBB para encontrarla.";
1185
1294
  throw new ErrorCli(`El API no tiene la operaci\xF3n \xAB${operationId}\xBB.${sugerencia}`, CODIGOS_DE_SALIDA.uso, { codigo: "OPERACION_DESCONOCIDA" });
1186
1295
  }
1296
+ var sinTildes = (s) => s.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
1297
+ var PESO_CAMPO = { resumen: 10, operationId: 6, ruta: 6, etiquetas: 4, descripcion: 2 };
1298
+ var CALIDAD = { palabra: 1, raiz: 0.8, fragmento: 0.4 };
1299
+ var PESO_EXTRA = 0.1;
1300
+ var SUFIJOS = ["aciones", "acion", "adores", "ador", "amiento", "ables", "able", "ibles", "ible", "ados", "adas", "ado", "ada", "ando", "iendo", "ar", "er", "ir", "es", "s"];
1301
+ function raizDe(palabra) {
1302
+ for (const sufijo of SUFIJOS) if (palabra.endsWith(sufijo) && palabra.length - sufijo.length >= 4) return palabra.slice(0, -sufijo.length);
1303
+ return palabra;
1304
+ }
1305
+ function palabrasDe(texto2) {
1306
+ return sinTildes(texto2.replace(/([a-z\d])([A-Z])/g, "$1 $2")).split(/[^a-z\d]+/).filter(Boolean);
1307
+ }
1308
+ function calidadEn(termino, raizTermino, palabras, textoPlano) {
1309
+ let mejor = 0;
1310
+ for (const palabra of palabras) {
1311
+ if (palabra === termino) return CALIDAD.palabra;
1312
+ if (raizTermino.length >= 4 && raizDe(palabra).startsWith(raizTermino)) mejor = Math.max(mejor, CALIDAD.raiz);
1313
+ }
1314
+ if (mejor === 0 && termino.length >= 3 && textoPlano.includes(termino)) mejor = CALIDAD.fragmento;
1315
+ return mejor;
1316
+ }
1187
1317
  function buscarOperaciones(documento, consulta) {
1188
- const normalizar = (s) => s.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
1189
- const palabras = normalizar(consulta).split(/\s+/).filter(Boolean);
1190
- return documento.operaciones.filter((op) => {
1191
- const pajar = normalizar([op.operationId, op.resumen ?? "", op.descripcion ?? "", ...op.etiquetas].join(" "));
1192
- return palabras.every((p) => pajar.includes(p));
1318
+ const terminos = sinTildes(consulta).split(/\s+/).filter(Boolean);
1319
+ if (terminos.length === 0) return [];
1320
+ const raices = terminos.map(raizDe);
1321
+ const puntuadas = [];
1322
+ documento.operaciones.forEach((op, orden) => {
1323
+ const campos = {
1324
+ resumen: op.resumen ?? "",
1325
+ operationId: op.operationId,
1326
+ ruta: op.ruta,
1327
+ etiquetas: op.etiquetas.join(" "),
1328
+ descripcion: op.descripcion ?? ""
1329
+ };
1330
+ const indice = Object.keys(campos).map((campo) => ({ campo, palabras: palabrasDe(campos[campo]), plano: sinTildes(campos[campo]) }));
1331
+ let puntaje = 0;
1332
+ for (const [i, termino] of terminos.entries()) {
1333
+ const aportes = indice.map(({ campo, palabras, plano }) => PESO_CAMPO[campo] * calidadEn(termino, raices[i], palabras, plano)).filter((a) => a > 0);
1334
+ if (aportes.length === 0) return;
1335
+ const mejor = Math.max(...aportes);
1336
+ puntaje += mejor + PESO_EXTRA * (aportes.reduce((a, b) => a + b, 0) - mejor);
1337
+ }
1338
+ puntuadas.push({ op, puntaje, orden });
1193
1339
  });
1340
+ return puntuadas.sort((a, b) => b.puntaje - a.puntaje || a.orden - b.orden).map((p) => p.op);
1194
1341
  }
1195
1342
 
1196
1343
  // src/nucleo/cuerpo-sin-credenciales.ts
@@ -1205,6 +1352,105 @@ function exigirCuerpoDelCli(cuerpo) {
1205
1352
  }
1206
1353
  }
1207
1354
 
1355
+ // src/nucleo/contrato-del-cuerpo.ts
1356
+ var CODIGO_CUERPO_NO_CUMPLE_CONTRATO = "CUERPO_NO_CUMPLE_CONTRATO";
1357
+ var ERRORES_EN_EL_MENSAJE = 5;
1358
+ var esObjeto3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1359
+ function tiposDe(esquema) {
1360
+ const t = esquema.type;
1361
+ if (typeof t === "string") return [t];
1362
+ if (Array.isArray(t)) return t.filter((x) => typeof x === "string");
1363
+ return [];
1364
+ }
1365
+ var admiteNull = (esquema) => esquema.nullable === true || tiposDe(esquema).includes("null");
1366
+ var esTextoNumerico = (v) => typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v));
1367
+ function calzaConTipo(valor, tipo) {
1368
+ switch (tipo) {
1369
+ case "object":
1370
+ return esObjeto3(valor);
1371
+ case "array":
1372
+ return Array.isArray(valor);
1373
+ case "number":
1374
+ return typeof valor === "number" && Number.isFinite(valor) || esTextoNumerico(valor);
1375
+ case "integer":
1376
+ return typeof valor === "number" && Number.isInteger(valor) || esTextoNumerico(valor) && Number.isInteger(Number(valor));
1377
+ case "boolean":
1378
+ return typeof valor === "boolean" || valor === "true" || valor === "false";
1379
+ case "string":
1380
+ return typeof valor === "string" || typeof valor === "number" || typeof valor === "boolean";
1381
+ case "null":
1382
+ return valor === null;
1383
+ default:
1384
+ return true;
1385
+ }
1386
+ }
1387
+ var NOMBRE_DEL_TIPO = {
1388
+ object: "un objeto",
1389
+ array: "una lista",
1390
+ number: "un n\xFAmero",
1391
+ integer: "un n\xFAmero entero",
1392
+ boolean: "verdadero o falso",
1393
+ string: "un texto"
1394
+ };
1395
+ var unir = (ruta, clave) => ruta ? `${ruta}.${clave}` : clave;
1396
+ function revisar(valor, esquema, ruta, errores) {
1397
+ if (!esObjeto3(esquema)) return;
1398
+ if ("oneOf" in esquema || "anyOf" in esquema || "not" in esquema) return;
1399
+ if (typeof esquema.$ref === "string") return;
1400
+ if (Array.isArray(esquema.allOf)) for (const parte of esquema.allOf) revisar(valor, parte, ruta, errores);
1401
+ if (valor === null) {
1402
+ if (!admiteNull(esquema) && tiposDe(esquema).length > 0) errores.push({ ruta: ruta || "(cuerpo)", motivo: "no puede ser null" });
1403
+ return;
1404
+ }
1405
+ const tipos = tiposDe(esquema).filter((t) => t !== "null");
1406
+ if (tipos.length > 0 && !tipos.some((t) => calzaConTipo(valor, t))) {
1407
+ errores.push({ ruta: ruta || "(cuerpo)", motivo: `tiene que ser ${tipos.map((t) => NOMBRE_DEL_TIPO[t] ?? t).join(" o ")}` });
1408
+ return;
1409
+ }
1410
+ if (Array.isArray(esquema.enum) && esquema.enum.length > 0) {
1411
+ const admitidos = esquema.enum;
1412
+ if (!admitidos.some((a) => a === valor || typeof a === "string" && typeof valor !== "object" && a === String(valor))) {
1413
+ errores.push({ ruta: ruta || "(cuerpo)", motivo: `tiene que ser uno de: ${admitidos.map((a) => JSON.stringify(a)).join(", ")}` });
1414
+ }
1415
+ }
1416
+ if (typeof valor === "string" && typeof esquema.maxLength === "number") {
1417
+ const largo = [...valor].length;
1418
+ if (largo > esquema.maxLength) errores.push({ ruta: ruta || "(cuerpo)", motivo: `tiene ${largo} caracteres y el m\xE1ximo es ${esquema.maxLength}` });
1419
+ }
1420
+ if (Array.isArray(valor)) {
1421
+ if (typeof esquema.maxItems === "number" && valor.length > esquema.maxItems) {
1422
+ errores.push({ ruta: ruta || "(cuerpo)", motivo: `tiene ${valor.length} elementos y el m\xE1ximo es ${esquema.maxItems}` });
1423
+ }
1424
+ if (esObjeto3(esquema.items)) valor.forEach((v, i) => revisar(v, esquema.items, `${ruta}[${i}]`, errores));
1425
+ return;
1426
+ }
1427
+ if (esObjeto3(valor)) {
1428
+ const propiedades = esObjeto3(esquema.properties) ? esquema.properties : {};
1429
+ const requeridas = Array.isArray(esquema.required) ? esquema.required.filter((r) => typeof r === "string") : [];
1430
+ for (const campo of requeridas) {
1431
+ if (valor[campo] === void 0) errores.push({ ruta: unir(ruta, campo), motivo: "es obligatorio y no viene" });
1432
+ }
1433
+ for (const [campo, sub] of Object.entries(propiedades)) {
1434
+ if (valor[campo] === void 0) continue;
1435
+ if (valor[campo] === null && !requeridas.includes(campo)) continue;
1436
+ revisar(valor[campo], sub, unir(ruta, campo), errores);
1437
+ }
1438
+ }
1439
+ }
1440
+ function erroresDelCuerpo(cuerpo, esquema) {
1441
+ const errores = [];
1442
+ revisar(cuerpo, esquema, "", errores);
1443
+ return errores;
1444
+ }
1445
+ function exigirCuerpoSegunContrato(operationId, cuerpo, esquema) {
1446
+ const errores = erroresDelCuerpo(cuerpo, esquema);
1447
+ if (errores.length === 0) return;
1448
+ const nombrados = errores.slice(0, ERRORES_EN_EL_MENSAJE).map((e) => `${e.ruta} ${e.motivo}`);
1449
+ const resto = errores.length - nombrados.length;
1450
+ const mensaje = `El cuerpo no cumple el contrato de ${operationId}: ${nombrados.join("; ")}${resto > 0 ? `; y ${resto} m\xE1s` : ""}. No llam\xE9 al API. Los campos est\xE1n en \xABredcumbre api describir ${operationId}\xBB.`;
1451
+ throw new ErrorCli(mensaje, CODIGOS_DE_SALIDA.uso, { codigo: CODIGO_CUERPO_NO_CUMPLE_CONTRATO, datos: { errores } });
1452
+ }
1453
+
1208
1454
  // src/comandos/api.ts
1209
1455
  var MAXIMO_TODAS = 1e4;
1210
1456
  var RUTA_INSEGURA = /[\u0000-\u001f\u007f/\\]|\.\./;
@@ -1274,6 +1520,7 @@ async function apiEjecutar(ctx, operationId, opciones) {
1274
1520
  const campos = opciones.campos !== void 0 ? lista(opciones.campos, "--campos") : void 0;
1275
1521
  const idem = asegurarClaveDeIdempotencia(op, cuerpo, opciones.clave);
1276
1522
  if (idem) cuerpo = idem.cuerpo;
1523
+ if (op.cuerpo && cuerpo !== void 0) exigirCuerpoSegunContrato(op.operationId, cuerpo, resolverRefs(op.cuerpo.esquema, doc.componentes));
1277
1524
  if (opciones.ensayo) {
1278
1525
  ctx.salida.linea(`Ensayo: no llam\xE9 al API. Con la llave \xAB${llave.archivo.name}\xBB (${nombreDelModo(llave.entorno)}) de ${slug} har\xEDa:`);
1279
1526
  ctx.salida.linea(` ${op.metodo} ${ctx.cliente.url(ruta, query)}`);
@@ -1345,11 +1592,11 @@ function armarRuta(op, slug, params) {
1345
1592
  }
1346
1593
  function leerCuerpo(valor) {
1347
1594
  let texto2;
1348
- if (valor === "-") texto2 = fs4.readFileSync(0, "utf8");
1595
+ if (valor === "-") texto2 = fs5.readFileSync(0, "utf8");
1349
1596
  else if (valor.startsWith("@")) {
1350
1597
  const archivo = valor.slice(1);
1351
- if (!fs4.existsSync(archivo)) throw errorDeUso(`No encuentro el archivo del cuerpo: ${archivo}`);
1352
- texto2 = fs4.readFileSync(archivo, "utf8");
1598
+ if (!fs5.existsSync(archivo)) throw errorDeUso(`No encuentro el archivo del cuerpo: ${archivo}`);
1599
+ texto2 = fs5.readFileSync(archivo, "utf8");
1353
1600
  } else texto2 = valor;
1354
1601
  let cuerpo;
1355
1602
  try {
@@ -1388,8 +1635,8 @@ async function una(ctx, llave, op, ruta, query, cuerpo, salidaArchivo) {
1388
1635
  if (r.bytes === null) return r.json;
1389
1636
  const tipo = r.headers.get("content-type") ?? "application/octet-stream";
1390
1637
  const extension = tipo.includes("pdf") ? "pdf" : tipo.includes("xml") ? "xml" : tipo.includes("zip") ? "zip" : "bin";
1391
- const archivo = path4.resolve(ctx.cwd, salidaArchivo ?? `${op.operationId}.${extension}`);
1392
- fs4.writeFileSync(archivo, r.bytes);
1638
+ const archivo = path5.resolve(ctx.cwd, salidaArchivo ?? `${op.operationId}.${extension}`);
1639
+ fs5.writeFileSync(archivo, r.bytes);
1393
1640
  ctx.salida.linea(`\u2713 Guard\xE9 ${r.bytes.length} bytes en ${archivo}`);
1394
1641
  ctx.salida.resultado({ archivo, bytes: r.bytes.length, tipo });
1395
1642
  return void 0;
@@ -1436,114 +1683,6 @@ function recortar(valor, campos) {
1436
1683
  // src/comandos/doctor.ts
1437
1684
  import fs6 from "node:fs";
1438
1685
  import path6 from "node:path";
1439
-
1440
- // src/nucleo/aviso-version.ts
1441
- import fs5 from "node:fs";
1442
- import path5 from "node:path";
1443
- var PAQUETE_CLI = PAQUETE_DEL_CLI;
1444
- var REGISTRO_NPM = "https://registry.npmjs.org/";
1445
- var urlUltimaVersion = (registro = REGISTRO_NPM) => `${registro.replace(/\/+$/, "")}/${PAQUETE_CLI}/latest`;
1446
- var TIEMPO_MAXIMO_MS = 1500;
1447
- var UN_DIA_MS = 24 * 60 * 60 * 1e3;
1448
- var rutaMarcaVersion = (carpeta) => path5.join(carpeta, "aviso-version.json");
1449
- function leerMarca(carpeta) {
1450
- try {
1451
- const marca = JSON.parse(fs5.readFileSync(rutaMarcaVersion(carpeta), "utf8"));
1452
- return typeof marca.revisadoEn === "string" ? { revisadoEn: marca.revisadoEn, ultima: typeof marca.ultima === "string" ? marca.ultima : null } : null;
1453
- } catch {
1454
- return null;
1455
- }
1456
- }
1457
- function escribirMarca(carpeta, marca) {
1458
- try {
1459
- fs5.mkdirSync(carpeta, { recursive: true, mode: 448 });
1460
- fs5.writeFileSync(rutaMarcaVersion(carpeta), `${JSON.stringify(marca)}
1461
- `);
1462
- } catch {
1463
- }
1464
- }
1465
- function compararVersiones(a, b) {
1466
- const partes = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10));
1467
- const pa = partes(a);
1468
- const pb = partes(b);
1469
- if ([...pa, ...pb].some((n) => !Number.isFinite(n))) return 0;
1470
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1471
- const d = (pa[i] ?? 0) - (pb[i] ?? 0);
1472
- if (d !== 0) return d > 0 ? 1 : -1;
1473
- }
1474
- return 0;
1475
- }
1476
- async function consultarRegistro(url, senal) {
1477
- const r = await fetch(url, { signal: senal, headers: { accept: "application/json" } });
1478
- if (!r.ok) return null;
1479
- const cuerpo = await r.json();
1480
- return typeof cuerpo.version === "string" ? cuerpo.version : null;
1481
- }
1482
- var COMANDO_ACTUALIZAR = "redcumbre actualizar";
1483
- var COMANDO_ACTUALIZAR_CONFIRMADO = `${COMANDO_ACTUALIZAR} --confirmar`;
1484
- async function ultimaVersionConocida(opciones) {
1485
- const marca = leerMarca(opciones.carpeta);
1486
- if (marca && opciones.ahora.getTime() - Date.parse(marca.revisadoEn) < UN_DIA_MS) return { ultima: marca.ultima, consultado: false };
1487
- let ultima = null;
1488
- try {
1489
- const senal = AbortSignal.timeout(TIEMPO_MAXIMO_MS);
1490
- ultima = opciones.consultar ? await opciones.consultar(senal) : await consultarRegistro(urlUltimaVersion(opciones.registro || void 0), senal);
1491
- } catch {
1492
- ultima = null;
1493
- }
1494
- escribirMarca(opciones.carpeta, { revisadoEn: opciones.ahora.toISOString(), ultima });
1495
- return { ultima, consultado: true };
1496
- }
1497
- async function avisarSiHayVersionNueva(opciones) {
1498
- const { ultima, consultado } = await ultimaVersionConocida(opciones);
1499
- if (consultado && ultima && compararVersiones(ultima, opciones.version) > 0) {
1500
- opciones.humano.write(`\u2139 Hay una versi\xF3n m\xE1s nueva del CLI: ${ultima} (tienes ${opciones.version}). Actual\xEDzala con \xAB${COMANDO_ACTUALIZAR}\xBB, que deja al d\xEDa el CLI y la skill.
1501
- `);
1502
- }
1503
- }
1504
- async function actualizacionDisponible(opciones) {
1505
- const { ultima } = await ultimaVersionConocida(opciones);
1506
- if (!ultima || compararVersiones(ultima, opciones.version) <= 0) return null;
1507
- return { instalada: opciones.version, disponible: ultima, comando: COMANDO_ACTUALIZAR_CONFIRMADO };
1508
- }
1509
- var avisoDeActualizacion = (a) => `Hay una versi\xF3n m\xE1s nueva del CLI: ${a.disponible} (tienes ${a.instalada}). D\xEDselo a la persona y prop\xF3nle actualizar; si acepta, corre \xAB${a.comando}\xBB.`;
1510
- var SITIO_DOCS = PRODUCCION.docs;
1511
- var ARCHIVO_VERSION_MINIMA = "cli-version-minima.txt";
1512
- var COMANDO_DE_ACTUALIZACION = COMANDO_DE_ACTUALIZACION_DEL_CLI;
1513
- var VERSION_VALIDA = /^\d+\.\d+\.\d+$/;
1514
- function urlVersionMinima(env = process.env) {
1515
- return `${origenDeDocs(env)}/${ARCHIVO_VERSION_MINIMA}`;
1516
- }
1517
- async function leerArchivoMinimo(url, senal) {
1518
- const r = await fetch(url, { signal: senal, headers: { accept: "text/plain" }, credentials: "omit" });
1519
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
1520
- return r.text();
1521
- }
1522
- async function exigirVersionMinima(opciones) {
1523
- const depurar = opciones.depurar ?? (() => void 0);
1524
- const url = urlVersionMinima(opciones.env);
1525
- let minima;
1526
- try {
1527
- const texto2 = await (opciones.consultar ?? leerArchivoMinimo)(url, AbortSignal.timeout(TIEMPO_MAXIMO_MS));
1528
- minima = texto2.trim();
1529
- } catch (error) {
1530
- depurar(`no pude leer la versi\xF3n m\xEDnima en ${url} (${error instanceof Error ? error.message : String(error)}); sigo sin comprobarla`);
1531
- return;
1532
- }
1533
- if (!VERSION_VALIDA.test(minima)) {
1534
- depurar(`la versi\xF3n m\xEDnima de ${url} no es una versi\xF3n (${JSON.stringify(minima.slice(0, 40))}); sigo sin comprobarla`);
1535
- return;
1536
- }
1537
- if (compararVersiones(minima, opciones.version) > 0) {
1538
- throw new ErrorCli(
1539
- `Este CLI (${opciones.version}) est\xE1 por debajo de la versi\xF3n m\xEDnima que se puede usar (${minima}). Actual\xEDzalo con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`,
1540
- 1,
1541
- { codigo: CODIGO_CLI_DESACTUALIZADO, comando: COMANDO_DE_ACTUALIZACION, datos: { version: opciones.version, minima } }
1542
- );
1543
- }
1544
- }
1545
-
1546
- // src/comandos/doctor.ts
1547
1686
  async function doctor(ctx) {
1548
1687
  const { salida, proyecto } = ctx;
1549
1688
  const revisiones = [];
@@ -1637,8 +1776,8 @@ async function panel(ctx, opciones) {
1637
1776
  }
1638
1777
 
1639
1778
  // src/comandos/emisores.ts
1640
- import fs9 from "node:fs";
1641
- import path9 from "node:path";
1779
+ import fs10 from "node:fs";
1780
+ import path11 from "node:path";
1642
1781
 
1643
1782
  // src/comandos/emisores-operaciones.ts
1644
1783
  var RUT_FILTRO = { bandera: "--rut <rut>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "rut" } };
@@ -1899,19 +2038,6 @@ var OPERACIONES_EMISORES = [
1899
2038
  },
1900
2039
  {
1901
2040
  // 21
1902
- comando: ["dte", "certificacion", "solicitar"],
1903
- operationId: "crearSolicitudCertificacionBoletasEmisorDte",
1904
- metodo: "POST",
1905
- ruta: "/{tenantSlug}/emisores/{id}/solicitar-certificacion",
1906
- argumentos: ["id"],
1907
- banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
1908
- salida: "accion",
1909
- hecho: "Certificaci\xF3n solicitada.",
1910
- confirmacion: "escrita",
1911
- aviso: "Esto le pide al SII certificar al contribuyente, con el RUT de su representante legal."
1912
- },
1913
- {
1914
- // 22
1915
2041
  comando: ["dte", "certificacion", "certificar-tipos"],
1916
2042
  operationId: "crearSolicitudCertificacionTiposEmisorDte",
1917
2043
  metodo: "POST",
@@ -1924,7 +2050,7 @@ var OPERACIONES_EMISORES = [
1924
2050
  aviso: "Esto le pide al SII certificar al contribuyente, con el RUT de su representante legal."
1925
2051
  },
1926
2052
  {
1927
- // 23
2053
+ // 22
1928
2054
  comando: ["dte", "migrar"],
1929
2055
  operationId: "crearSolicitudMigracionEmisorDte",
1930
2056
  metodo: "POST",
@@ -1937,7 +2063,7 @@ var OPERACIONES_EMISORES = [
1937
2063
  aviso: "Esto le pide al SII migrar el sistema de facturaci\xF3n del contribuyente. Puede dejar sin uso los folios que tenga."
1938
2064
  },
1939
2065
  {
1940
- // 24
2066
+ // 23
1941
2067
  comando: ["dte", "certificacion", "desistir"],
1942
2068
  operationId: "cancelarCertificacionEmisorDte",
1943
2069
  metodo: "POST",
@@ -1950,7 +2076,7 @@ var OPERACIONES_EMISORES = [
1950
2076
  aviso: "Esto archiva el emisor y cierra sus solicitudes de certificaci\xF3n."
1951
2077
  },
1952
2078
  {
1953
- // 25
2079
+ // 24
1954
2080
  comando: ["dte", "mipyme", "habilitar"],
1955
2081
  operationId: "registrarEmisorDteEnPortalMipyme",
1956
2082
  metodo: "POST",
@@ -1963,7 +2089,7 @@ var OPERACIONES_EMISORES = [
1963
2089
  aviso: "Esto inscribe al contribuyente en el Portal MiPyme del SII. Puede dejar sin uso los folios de mercado que tenga."
1964
2090
  },
1965
2091
  {
1966
- // 26
2092
+ // 25
1967
2093
  comando: ["dte", "ambiente"],
1968
2094
  operationId: "cambiarAmbienteTipoEmisorDte",
1969
2095
  metodo: "PATCH",
@@ -1976,7 +2102,7 @@ var OPERACIONES_EMISORES = [
1976
2102
  aviso: "Esto cambia el ambiente del SII por el que sale ese tipo de documento."
1977
2103
  },
1978
2104
  {
1979
- // 27
2105
+ // 26
1980
2106
  comando: ["dte", "archivar"],
1981
2107
  operationId: "archivarEmisorDte",
1982
2108
  metodo: "DELETE",
@@ -1990,7 +2116,7 @@ var OPERACIONES_EMISORES = [
1990
2116
  aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
1991
2117
  },
1992
2118
  {
1993
- // 28
2119
+ // 27
1994
2120
  comando: ["tributarios", "archivar"],
1995
2121
  operationId: "archivarEmisorTributario",
1996
2122
  metodo: "DELETE",
@@ -2004,7 +2130,7 @@ var OPERACIONES_EMISORES = [
2004
2130
  aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
2005
2131
  },
2006
2132
  {
2007
- // 29
2133
+ // 28
2008
2134
  comando: ["tributarios", "listar"],
2009
2135
  operationId: "listarEmisoresTributarios",
2010
2136
  metodo: "GET",
@@ -2016,7 +2142,7 @@ var OPERACIONES_EMISORES = [
2016
2142
  confirmacion: "efecto"
2017
2143
  },
2018
2144
  {
2019
- // 30
2145
+ // 29
2020
2146
  comando: ["tributarios", "por-defecto"],
2021
2147
  operationId: "obtenerEmisorTributarioPorDefecto",
2022
2148
  metodo: "GET",
@@ -2027,7 +2153,7 @@ var OPERACIONES_EMISORES = [
2027
2153
  confirmacion: "efecto"
2028
2154
  },
2029
2155
  {
2030
- // 31
2156
+ // 30
2031
2157
  comando: ["tributarios", "existe"],
2032
2158
  operationId: "consultarRutEmisorTributario",
2033
2159
  metodo: "GET",
@@ -2038,7 +2164,7 @@ var OPERACIONES_EMISORES = [
2038
2164
  confirmacion: "efecto"
2039
2165
  },
2040
2166
  {
2041
- // 32
2167
+ // 31
2042
2168
  comando: ["tributarios", "ver"],
2043
2169
  operationId: "obtenerEmisorTributario",
2044
2170
  metodo: "GET",
@@ -2049,7 +2175,7 @@ var OPERACIONES_EMISORES = [
2049
2175
  confirmacion: "efecto"
2050
2176
  },
2051
2177
  {
2052
- // 33
2178
+ // 32
2053
2179
  comando: ["tributarios", "logo", "ver"],
2054
2180
  operationId: "obtenerLogoEmisorTributario",
2055
2181
  metodo: "GET",
@@ -2060,7 +2186,7 @@ var OPERACIONES_EMISORES = [
2060
2186
  confirmacion: "efecto"
2061
2187
  },
2062
2188
  {
2063
- // 34
2189
+ // 33
2064
2190
  comando: ["tributarios", "certificado"],
2065
2191
  operationId: "obtenerCertificadoEmisorTributario",
2066
2192
  metodo: "GET",
@@ -2071,7 +2197,7 @@ var OPERACIONES_EMISORES = [
2071
2197
  confirmacion: "efecto"
2072
2198
  },
2073
2199
  {
2074
- // 35
2200
+ // 34
2075
2201
  comando: ["tributarios", "editar"],
2076
2202
  operationId: "actualizarEmisorTributario",
2077
2203
  metodo: "PATCH",
@@ -2083,7 +2209,7 @@ var OPERACIONES_EMISORES = [
2083
2209
  confirmacion: "efecto"
2084
2210
  },
2085
2211
  {
2086
- // 36
2212
+ // 35
2087
2213
  comando: ["tributarios", "fijar-por-defecto"],
2088
2214
  operationId: "cambiarEmisorTributarioPorDefecto",
2089
2215
  metodo: "PATCH",
@@ -2095,7 +2221,7 @@ var OPERACIONES_EMISORES = [
2095
2221
  confirmacion: "efecto"
2096
2222
  },
2097
2223
  {
2098
- // 37
2224
+ // 36
2099
2225
  comando: ["tributarios", "reactivar"],
2100
2226
  operationId: "reactivarEmisorTributario",
2101
2227
  metodo: "PATCH",
@@ -2107,7 +2233,7 @@ var OPERACIONES_EMISORES = [
2107
2233
  confirmacion: "efecto"
2108
2234
  },
2109
2235
  {
2110
- // 38
2236
+ // 37
2111
2237
  comando: ["tributarios", "logo", "subir"],
2112
2238
  operationId: "actualizarLogoEmisorTributario",
2113
2239
  metodo: "POST",
@@ -2119,7 +2245,7 @@ var OPERACIONES_EMISORES = [
2119
2245
  confirmacion: "efecto"
2120
2246
  },
2121
2247
  {
2122
- // 39
2248
+ // 38
2123
2249
  comando: ["tributarios", "logo", "quitar"],
2124
2250
  operationId: "eliminarLogoEmisorTributario",
2125
2251
  metodo: "DELETE",
@@ -2131,7 +2257,7 @@ var OPERACIONES_EMISORES = [
2131
2257
  confirmacion: "efecto"
2132
2258
  },
2133
2259
  {
2134
- // 40
2260
+ // 39
2135
2261
  comando: ["sucursales", "listar"],
2136
2262
  operationId: "listarSucursalesEmisorDte",
2137
2263
  metodo: "GET",
@@ -2143,7 +2269,7 @@ var OPERACIONES_EMISORES = [
2143
2269
  confirmacion: "efecto"
2144
2270
  },
2145
2271
  {
2146
- // 41
2272
+ // 40
2147
2273
  comando: ["sucursales", "crear"],
2148
2274
  operationId: "crearSucursalEmisorDte",
2149
2275
  metodo: "POST",
@@ -2155,7 +2281,7 @@ var OPERACIONES_EMISORES = [
2155
2281
  confirmacion: "efecto"
2156
2282
  },
2157
2283
  {
2158
- // 42
2284
+ // 41
2159
2285
  comando: ["sucursales", "editar"],
2160
2286
  operationId: "actualizarSucursalEmisorDte",
2161
2287
  metodo: "PATCH",
@@ -2167,7 +2293,7 @@ var OPERACIONES_EMISORES = [
2167
2293
  confirmacion: "efecto"
2168
2294
  },
2169
2295
  {
2170
- // 43
2296
+ // 42
2171
2297
  comando: ["sucursales", "desactivar"],
2172
2298
  operationId: "desactivarSucursalEmisorDte",
2173
2299
  metodo: "DELETE",
@@ -2179,7 +2305,7 @@ var OPERACIONES_EMISORES = [
2179
2305
  confirmacion: "efecto"
2180
2306
  },
2181
2307
  {
2182
- // 44
2308
+ // 43
2183
2309
  comando: ["representantes", "listar"],
2184
2310
  operationId: "listarRepresentantesLegales",
2185
2311
  metodo: "GET",
@@ -2191,7 +2317,7 @@ var OPERACIONES_EMISORES = [
2191
2317
  confirmacion: "efecto"
2192
2318
  },
2193
2319
  {
2194
- // 45
2320
+ // 44
2195
2321
  comando: ["dte", "sincronizar"],
2196
2322
  operationId: "actualizarEmisorDteDesdeSii",
2197
2323
  metodo: "POST",
@@ -2202,7 +2328,7 @@ var OPERACIONES_EMISORES = [
2202
2328
  confirmacion: "efecto"
2203
2329
  },
2204
2330
  {
2205
- // 46
2331
+ // 45
2206
2332
  comando: ["dte", "credencial", "reintentar"],
2207
2333
  operationId: "reintentarCredencialPortalEmisorDte",
2208
2334
  metodo: "POST",
@@ -2213,7 +2339,7 @@ var OPERACIONES_EMISORES = [
2213
2339
  confirmacion: "efecto"
2214
2340
  },
2215
2341
  {
2216
- // 47
2342
+ // 46
2217
2343
  comando: ["tributarios", "credencial", "reintentar"],
2218
2344
  operationId: "reintentarCredencialEmisorTributario",
2219
2345
  metodo: "POST",
@@ -2224,7 +2350,7 @@ var OPERACIONES_EMISORES = [
2224
2350
  confirmacion: "efecto"
2225
2351
  },
2226
2352
  {
2227
- // 48
2353
+ // 47
2228
2354
  comando: ["revocar"],
2229
2355
  operationId: "revocarEmisorTokenizado",
2230
2356
  metodo: "POST",
@@ -2236,6 +2362,19 @@ var OPERACIONES_EMISORES = [
2236
2362
  hecho: "Emisor revocado.",
2237
2363
  confirmacion: "escrita",
2238
2364
  aviso: "Esto revoca la autorizaci\xF3n y elimina sus credenciales de inmediato."
2365
+ },
2366
+ {
2367
+ // 48
2368
+ comando: ["dte", "volver-a-mipyme"],
2369
+ operationId: "volverEmisorDteAlPortalMipyme",
2370
+ metodo: "POST",
2371
+ ruta: "/{tenantSlug}/emisores/{id}/volver-a-mipyme",
2372
+ argumentos: ["id"],
2373
+ banderas: [RUT_DE_CONFIRMACION],
2374
+ salida: "accion",
2375
+ hecho: "Emisor vuelto al Portal MiPyme.",
2376
+ confirmacion: "escrita",
2377
+ aviso: "Vuelves este RUT al Portal MiPyme en TODAS las empresas que lo usan: se inscribe ante el SII, sus emisores de facturaci\xF3n pasan a Portal MiPyme, se pierde la certificaci\xF3n propia de facturas (33, 34, 43, 46, 52, 56, 61) y se anulan sus folios de facturaci\xF3n de producci\xF3n. Volver a certificarlo puede tener costo. Las boletas no cambian."
2239
2378
  }
2240
2379
  ];
2241
2380
 
@@ -2769,27 +2908,106 @@ async function abrirCon(programa2, destino) {
2769
2908
  });
2770
2909
  }
2771
2910
 
2772
- // src/nucleo/skill.ts
2773
- import { createHash, randomBytes } from "node:crypto";
2911
+ // src/nucleo/instalacion-del-cli.ts
2912
+ import { spawnSync as spawnSync2 } from "node:child_process";
2774
2913
  import fs8 from "node:fs";
2775
2914
  import path8 from "node:path";
2776
2915
  import { fileURLToPath } from "node:url";
2916
+ var real = (ruta) => {
2917
+ try {
2918
+ return fs8.realpathSync(ruta);
2919
+ } catch {
2920
+ return null;
2921
+ }
2922
+ };
2923
+ var dentroDe = (ruta, carpeta) => ruta === carpeta || ruta.startsWith(carpeta + path8.sep);
2924
+ var correPorNpx = (bundle) => (real(bundle) ?? path8.resolve(bundle)).split(path8.sep).includes("_npx");
2925
+ function detectarInstalacion(bundle, raizGlobal) {
2926
+ const bundleReal = real(bundle) ?? path8.resolve(bundle);
2927
+ if (correPorNpx(bundleReal)) return { forma: "npx" };
2928
+ for (const [gestor, forma] of [["npm", "npm-global"], ["pnpm", "pnpm-global"]]) {
2929
+ const raiz = raizGlobal(gestor);
2930
+ const carpeta = raiz ? real(path8.join(raiz, ...PAQUETE_DEL_CLI.split("/"))) : null;
2931
+ if (carpeta && dentroDe(bundleReal, carpeta)) return { forma, carpetaDelPaquete: carpeta };
2932
+ }
2933
+ const marcaDeDependencia = ["node_modules", ...PAQUETE_DEL_CLI.split("/")].join(path8.sep);
2934
+ if (bundleReal.includes(`${path8.sep}${marcaDeDependencia}${path8.sep}`)) {
2935
+ return { forma: "no-reconocida", motivo: `el CLI est\xE1 instalado como dependencia de un proyecto (${bundleReal}): actual\xEDzalo con el gestor de ese proyecto, que es quien decide su versi\xF3n` };
2936
+ }
2937
+ return { forma: "no-reconocida", motivo: `el CLI que corre (${bundleReal}) no est\xE1 en la cach\xE9 de npx ni en la carpeta global de npm o de pnpm` };
2938
+ }
2939
+ function comandoDeActualizacion(forma, version, registro) {
2940
+ const paquete = `${PAQUETE_DEL_CLI}@${version}`;
2941
+ const conRegistro = registro ? [`--registry=${registro}`] : [];
2942
+ if (forma === "pnpm-global") return { comando: "pnpm", args: ["add", "--global", ...conRegistro, paquete] };
2943
+ return { comando: "npm", args: ["install", "--global", ...conRegistro, paquete] };
2944
+ }
2945
+ var legible = (c) => [c.comando, ...c.args].join(" ");
2946
+ var comandoInstalarPorNpx = (version, confirmado) => `npx ${PAQUETE_DEL_CLI}@${version} instalar${confirmado ? " --confirmar" : ""}`;
2947
+ var prefijoPorNpx = (version) => `npx ${PAQUETE_DEL_CLI}@${version}`;
2948
+ function ejecutarDeVerdad(comando2, args, opciones) {
2949
+ const r = spawnSync2(comando2, args, { cwd: opciones.cwd, env: opciones.env, encoding: "utf8", shell: process.platform === "win32", timeout: 10 * 6e4 });
2950
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? r.error.message : "") };
2951
+ }
2952
+ function entornoDeActualizacion(ctx) {
2953
+ const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
2954
+ return {
2955
+ bundle: fileURLToPath(import.meta.url),
2956
+ ejecutar: ejecutarDeVerdad,
2957
+ raizGlobal(gestor) {
2958
+ const r = ejecutarDeVerdad(gestor, ["root", "--global"], { cwd: ctx.cwd, env: ctx.env });
2959
+ const raiz = r.stdout.trim().split(/\r?\n/).pop() ?? "";
2960
+ return r.status === 0 && raiz ? raiz : null;
2961
+ },
2962
+ async consultarUltima() {
2963
+ const respuesta = await fetch(urlUltimaVersion(registro), { signal: AbortSignal.timeout(1e4), headers: { accept: "application/json" } });
2964
+ if (!respuesta.ok) throw new Error(`el registro respondi\xF3 ${respuesta.status}`);
2965
+ const cuerpo = await respuesta.json();
2966
+ return typeof cuerpo.version === "string" ? cuerpo.version : null;
2967
+ }
2968
+ };
2969
+ }
2970
+ var VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
2971
+ function entornoSinNpx(env) {
2972
+ const limpio = { ...env };
2973
+ for (const clave of Object.keys(limpio).filter((k) => k.toUpperCase() === "PATH")) {
2974
+ limpio[clave] = (limpio[clave] ?? "").split(path8.delimiter).filter((carpeta) => carpeta && !carpeta.split(/[\\/]/).includes("_npx")).join(path8.delimiter);
2975
+ }
2976
+ return limpio;
2977
+ }
2978
+ function versionEnElPath(entorno, opciones) {
2979
+ const r = entorno.ejecutar("redcumbre", ["--version"], { cwd: opciones.cwd, env: entornoSinNpx(opciones.env) });
2980
+ const version = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
2981
+ return r.status === 0 && VERSION.test(version) ? version : null;
2982
+ }
2983
+ function carpetaDeEjecutablesDeNpm(entorno, opciones) {
2984
+ const r = entorno.ejecutar("npm", ["prefix", "--global"], opciones);
2985
+ const prefijo = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
2986
+ if (r.status !== 0 || !prefijo) return null;
2987
+ return process.platform === "win32" ? prefijo : path8.join(prefijo, "bin");
2988
+ }
2989
+
2990
+ // src/nucleo/skill.ts
2991
+ import { createHash, randomBytes } from "node:crypto";
2992
+ import fs9 from "node:fs";
2993
+ import path9 from "node:path";
2994
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
2777
2995
  var NOMBRE_SKILL = "redcumbre";
2778
2996
  var MARCA_INICIO = "<!-- redcumbre:inicio -->";
2779
2997
  var MARCA_FIN = "<!-- redcumbre:fin -->";
2780
2998
  var sha256 = (texto2) => createHash("sha256").update(texto2).digest("hex");
2781
- function carpetaDeLaSkill(aqui = path8.dirname(fileURLToPath(import.meta.url))) {
2782
- const candidatas = [path8.join(aqui, "skill"), path8.join(aqui, "..", "skill"), path8.join(aqui, "..", "..", "skill")];
2999
+ function carpetaDeLaSkill(aqui = path9.dirname(fileURLToPath2(import.meta.url))) {
3000
+ const candidatas = [path9.join(aqui, "skill"), path9.join(aqui, "..", "skill"), path9.join(aqui, "..", "..", "skill")];
2783
3001
  for (const candidata of candidatas) {
2784
- if (fs8.existsSync(path8.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
3002
+ if (fs9.existsSync(path9.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
2785
3003
  }
2786
- throw new ErrorCli("El paquete del CLI est\xE1 incompleto: no encuentro la skill de REDCUMBRE. Reinstala el CLI con \xABnpx @redcumbrecl/cli@latest\xBB.", CODIGOS_DE_SALIDA.error, {
3004
+ throw new ErrorCli(`El paquete del CLI est\xE1 incompleto: no encuentro la skill de REDCUMBRE. Reinstala el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`, CODIGOS_DE_SALIDA.error, {
2787
3005
  codigo: "PAQUETE_INCOMPLETO"
2788
3006
  });
2789
3007
  }
2790
3008
  function contenidoEmpaquetado(fuente) {
2791
3009
  const carpeta = fuente ?? carpetaDeLaSkill();
2792
- return fs8.readFileSync(path8.join(carpeta, NOMBRE_SKILL, "SKILL.md"), "utf8");
3010
+ return fs9.readFileSync(path9.join(carpeta, NOMBRE_SKILL, "SKILL.md"), "utf8");
2793
3011
  }
2794
3012
  var LINEA_DE_VERSION = /^<!-- redcumbre-cli: (\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?) -->$/m;
2795
3013
  var FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---\r?\n/;
@@ -2797,7 +3015,7 @@ var lineaDeVersion = (version) => `<!-- redcumbre-cli: ${version} -->`;
2797
3015
  function contenidoParaInstalar(fuente, version) {
2798
3016
  const frontmatter = fuente.match(FRONTMATTER);
2799
3017
  if (!frontmatter) {
2800
- throw new ErrorCli("El paquete del CLI est\xE1 incompleto: la skill de REDCUMBRE no trae su frontmatter. Reinstala el CLI con \xABnpx @redcumbrecl/cli@latest\xBB.", CODIGOS_DE_SALIDA.error, {
3018
+ throw new ErrorCli(`El paquete del CLI est\xE1 incompleto: la skill de REDCUMBRE no trae su frontmatter. Reinstala el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`, CODIGOS_DE_SALIDA.error, {
2801
3019
  codigo: "PAQUETE_INCOMPLETO"
2802
3020
  });
2803
3021
  }
@@ -2808,14 +3026,38 @@ ${sinLinea}`;
2808
3026
  function versionDeLaSkill(texto2) {
2809
3027
  return texto2.match(LINEA_DE_VERSION)?.[1] ?? null;
2810
3028
  }
3029
+ var CODIGOS_TRANSITORIOS_WINDOWS = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
3030
+ function esperarSincrono(ms) {
3031
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
3032
+ }
3033
+ function esErrorTransitorioDeWindows(error) {
3034
+ const codigo = error?.code;
3035
+ return typeof codigo === "string" && CODIGOS_TRANSITORIOS_WINDOWS.has(codigo);
3036
+ }
3037
+ function conReintentoEnWindows(operacion, opciones = {}) {
3038
+ const { plataforma = process.platform, esperar = esperarSincrono, presupuestoMs = 2500 } = opciones;
3039
+ let espera = 10;
3040
+ let gastado = 0;
3041
+ for (; ; ) {
3042
+ try {
3043
+ return operacion();
3044
+ } catch (error) {
3045
+ if (plataforma !== "win32" || !esErrorTransitorioDeWindows(error) || gastado >= presupuestoMs) throw error;
3046
+ const ms = Math.min(espera, presupuestoMs - gastado);
3047
+ esperar(ms);
3048
+ gastado += ms;
3049
+ espera = Math.min(espera * 2, 100);
3050
+ }
3051
+ }
3052
+ }
2811
3053
  function escribirAtomico(ruta, contenido) {
2812
- fs8.mkdirSync(path8.dirname(ruta), { recursive: true });
3054
+ fs9.mkdirSync(path9.dirname(ruta), { recursive: true });
2813
3055
  const temporal = `${ruta}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
2814
3056
  try {
2815
- fs8.writeFileSync(temporal, contenido);
2816
- fs8.renameSync(temporal, ruta);
3057
+ fs9.writeFileSync(temporal, contenido);
3058
+ conReintentoEnWindows(() => fs9.renameSync(temporal, ruta));
2817
3059
  } catch (error) {
2818
- fs8.rmSync(temporal, { force: true });
3060
+ fs9.rmSync(temporal, { force: true });
2819
3061
  throw error;
2820
3062
  }
2821
3063
  }
@@ -2831,12 +3073,19 @@ function bloqueDeAgents() {
2831
3073
  MARCA_FIN
2832
3074
  ].join("\n");
2833
3075
  }
2834
- var rutaRegistroUsuario = (d) => path8.join(d.carpetaConfiguracion, "skill.json");
2835
- var rutaEstadoDelProyecto = (proyecto) => path8.join(proyecto, ".redcumbre", "estado.json");
3076
+ var rutaRegistroUsuario = (d) => path9.join(d.carpetaConfiguracion, "skill.json");
3077
+ var rutaEstadoDelProyecto = (proyecto) => path9.join(proyecto, ".redcumbre", "estado.json");
2836
3078
  function leerJson(ruta) {
2837
- if (!fs8.existsSync(ruta)) return null;
3079
+ if (!fs9.existsSync(ruta)) return null;
3080
+ let texto2;
3081
+ try {
3082
+ texto2 = conReintentoEnWindows(() => fs9.readFileSync(ruta, "utf8"));
3083
+ } catch (error) {
3084
+ if (esErrorTransitorioDeWindows(error)) throw error;
3085
+ return null;
3086
+ }
2838
3087
  try {
2839
- const dato = JSON.parse(fs8.readFileSync(ruta, "utf8"));
3088
+ const dato = JSON.parse(texto2);
2840
3089
  return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
2841
3090
  } catch {
2842
3091
  return null;
@@ -2863,13 +3112,13 @@ function guardarRegistroProyecto(proyecto, registro) {
2863
3112
  }
2864
3113
  function objetivos(d) {
2865
3114
  const lista2 = [
2866
- { id: "claude-usuario", archivo: path8.join(d.home, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
2867
- { id: "agents-usuario", archivo: path8.join(d.home, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3115
+ { id: "claude-usuario", archivo: path9.join(d.home, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3116
+ { id: "agents-usuario", archivo: path9.join(d.home, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
2868
3117
  ];
2869
3118
  if (d.proyecto) {
2870
3119
  lista2.push(
2871
- { id: "claude-proyecto", archivo: path8.join(d.proyecto, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
2872
- { id: "agents-proyecto", archivo: path8.join(d.proyecto, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3120
+ { id: "claude-proyecto", archivo: path9.join(d.proyecto, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3121
+ { id: "agents-proyecto", archivo: path9.join(d.proyecto, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
2873
3122
  );
2874
3123
  }
2875
3124
  return lista2;
@@ -2885,13 +3134,13 @@ function resumir2(rutas, quitada) {
2885
3134
  }
2886
3135
  function reconciliar(archivo, nuevo, registrado) {
2887
3136
  const hashNuevo = sha256(nuevo);
2888
- const existe = fs8.existsSync(archivo);
3137
+ const existe = fs9.existsSync(archivo);
2889
3138
  if (!existe) {
2890
3139
  if (registrado) return { accion: "borrada", hash: null };
2891
3140
  escribirAtomico(archivo, nuevo);
2892
3141
  return { accion: "instalada", hash: hashNuevo };
2893
3142
  }
2894
- const hashActual = sha256(fs8.readFileSync(archivo));
3143
+ const hashActual = sha256(conReintentoEnWindows(() => fs9.readFileSync(archivo)));
2895
3144
  if (registrado === void 0) {
2896
3145
  if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
2897
3146
  return { accion: "editada", hash: null };
@@ -2908,13 +3157,13 @@ function extraerBloque(texto2) {
2908
3157
  function reconciliarAgents(archivo, registro) {
2909
3158
  const bloque = bloqueDeAgents();
2910
3159
  const hashBloque = sha256(bloque);
2911
- if (!fs8.existsSync(archivo)) {
3160
+ if (!fs9.existsSync(archivo)) {
2912
3161
  if (registro) return { accion: "borrada", registro: null };
2913
3162
  escribirAtomico(archivo, `${bloque}
2914
3163
  `);
2915
3164
  return { accion: "instalada", registro: { sha256: hashBloque, creado: true } };
2916
3165
  }
2917
- const texto2 = fs8.readFileSync(archivo, "utf8");
3166
+ const texto2 = conReintentoEnWindows(() => fs9.readFileSync(archivo, "utf8"));
2918
3167
  const actual = extraerBloque(texto2);
2919
3168
  if (actual === null) {
2920
3169
  if (registro) return { accion: "borrada", registro: null };
@@ -2951,7 +3200,7 @@ function instalarSkill(opciones) {
2951
3200
  }
2952
3201
  }
2953
3202
  if (bloqueAgents && destinos.proyecto && proyecto && !usuario.quitada && !proyecto.quitada) {
2954
- const { accion, registro } = reconciliarAgents(path8.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
3203
+ const { accion, registro } = reconciliarAgents(path9.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
2955
3204
  rutas.push({ ruta: "AGENTS.md", accion });
2956
3205
  if (registro) proyecto.agents = registro;
2957
3206
  }
@@ -2960,11 +3209,11 @@ function instalarSkill(opciones) {
2960
3209
  return resumir2(rutas, rutas.length === 0 && Boolean(usuario.quitada || proyecto?.quitada));
2961
3210
  }
2962
3211
  function quitarArchivo(archivo, registrado) {
2963
- if (!fs8.existsSync(archivo)) return null;
2964
- if (registrado === void 0 || sha256(fs8.readFileSync(archivo)) !== registrado) return "editada";
2965
- fs8.rmSync(archivo);
2966
- const carpeta = path8.dirname(archivo);
2967
- if (fs8.readdirSync(carpeta).length === 0) fs8.rmdirSync(carpeta);
3212
+ if (!fs9.existsSync(archivo)) return null;
3213
+ if (registrado === void 0 || sha256(conReintentoEnWindows(() => fs9.readFileSync(archivo))) !== registrado) return "editada";
3214
+ fs9.rmSync(archivo);
3215
+ const carpeta = path9.dirname(archivo);
3216
+ if (fs9.readdirSync(carpeta).length === 0) fs9.rmdirSync(carpeta);
2968
3217
  return "quitada";
2969
3218
  }
2970
3219
  function quitarSkill(opciones) {
@@ -2979,16 +3228,16 @@ function quitarSkill(opciones) {
2979
3228
  if (accion) rutas.push({ ruta: objetivo.legible, accion });
2980
3229
  }
2981
3230
  if (destinos.proyecto && proyecto) {
2982
- const archivo = path8.join(destinos.proyecto, "AGENTS.md");
2983
- if (fs8.existsSync(archivo)) {
2984
- const texto2 = fs8.readFileSync(archivo, "utf8");
3231
+ const archivo = path9.join(destinos.proyecto, "AGENTS.md");
3232
+ if (fs9.existsSync(archivo)) {
3233
+ const texto2 = conReintentoEnWindows(() => fs9.readFileSync(archivo, "utf8"));
2985
3234
  const bloque = extraerBloque(texto2);
2986
3235
  if (bloque !== null) {
2987
3236
  if (!proyecto.agents || sha256(bloque) !== proyecto.agents.sha256) {
2988
3237
  rutas.push({ ruta: "AGENTS.md", accion: "editada" });
2989
3238
  } else {
2990
3239
  const resto = texto2.replace(regexBloque(), "").replace(/\n{3,}/g, "\n\n");
2991
- if (proyecto.agents.creado && resto.trim() === "") fs8.rmSync(archivo);
3240
+ if (proyecto.agents.creado && resto.trim() === "") fs9.rmSync(archivo);
2992
3241
  else escribirAtomico(archivo, resto.replace(/^\n+/, "").replace(/\n*$/, "\n"));
2993
3242
  rutas.push({ ruta: "AGENTS.md", accion: "quitada" });
2994
3243
  }
@@ -3011,8 +3260,8 @@ function renovarSkill(opciones) {
3011
3260
  const deUsuario = esDeUsuario(objetivo.id);
3012
3261
  const registro = deUsuario ? usuario : proyecto;
3013
3262
  if (usuario.quitada || registro.quitada) continue;
3014
- if (!fs8.existsSync(objetivo.archivo)) continue;
3015
- const actual = fs8.readFileSync(objetivo.archivo, "utf8");
3263
+ if (!fs9.existsSync(objetivo.archivo)) continue;
3264
+ const actual = conReintentoEnWindows(() => fs9.readFileSync(objetivo.archivo, "utf8"));
3016
3265
  const instalada2 = versionDeLaSkill(actual);
3017
3266
  if (instalada2 !== null && compararVersiones(version, instalada2) < 0) {
3018
3267
  rutas.push({ ruta: objetivo.legible, accion: "mas-nueva", instalada: instalada2 });
@@ -3158,6 +3407,106 @@ function sinRespuesta() {
3158
3407
  return new ErrorCli("La entrada se cerr\xF3 antes de que respondieras. No se hizo nada.", CODIGOS_DE_SALIDA.confirmacion);
3159
3408
  }
3160
3409
 
3410
+ // src/comandos/instalar.ts
3411
+ import path10 from "node:path";
3412
+ function estadoDeInstalacion(ctx, entorno) {
3413
+ if (!correPorNpx(entorno.bundle)) return { forma: "instalado" };
3414
+ const enElPath = versionEnElPath(entorno, { cwd: ctx.cwd, env: ctx.env });
3415
+ if (enElPath && compararVersiones(enElPath, ctx.version) >= 0) return { forma: "npx", enElPath, instalado: true };
3416
+ return { forma: "npx", enElPath, instalado: false };
3417
+ }
3418
+ function avisoDeInstalacion(version, estado2) {
3419
+ if (estado2.forma !== "npx") return null;
3420
+ const prefijo = prefijoPorNpx(version);
3421
+ if (estado2.instalado) {
3422
+ return {
3423
+ anexo: { version, enElPath: estado2.enElPath, instalado: true, comando: "redcumbre", prefijo },
3424
+ texto: `El CLI ya est\xE1 instalado en este computador (redcumbre ${estado2.enElPath}): usa \xABredcumbre \u2026\xBB en vez de \xAB${prefijo} \u2026\xBB.`,
3425
+ paraPersona: `\u2139 Ya tienes el CLI instalado (redcumbre ${estado2.enElPath}): usa \xABredcumbre \u2026\xBB en vez de npx.`
3426
+ };
3427
+ }
3428
+ const comando2 = comandoInstalarPorNpx(version, true);
3429
+ return {
3430
+ anexo: { version, enElPath: estado2.enElPath, instalado: false, comando: comando2, prefijo },
3431
+ texto: `El CLI corre por npx y no est\xE1 instalado en este computador${estado2.enElPath ? ` (el \xABredcumbre\xBB del PATH es la ${estado2.enElPath})` : ""}. D\xEDselo a la persona y prop\xF3nle instalarlo; si acepta, corre \xAB${comando2}\xBB. Mientras no est\xE9 instalado, donde un mensaje diga \xABredcumbre \u2026\xBB corre \xAB${prefijo} \u2026\xBB, con esta misma versi\xF3n.`,
3432
+ paraPersona: `\u2139 Est\xE1s usando el CLI por npx. Para dejarlo instalado y usar \xABredcumbre \u2026\xBB directo: \xAB${comandoInstalarPorNpx(version, false)}\xBB.`
3433
+ };
3434
+ }
3435
+ function errorDeInstalacion(comando2, corrida) {
3436
+ const salidaNpm = (corrida.stderr || corrida.stdout).trim();
3437
+ const detalle = salidaNpm.split(/\r?\n/).slice(-5).join(" \xB7 ");
3438
+ const permisos = /EACCES|EPERM|permission denied/i.test(salidaNpm) ? " npm no tiene permiso para escribir en su carpeta global: no lo corras con sudo; instala Node con nvm o configura un prefijo propio de npm (https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally) y vuelve a intentarlo." : "";
3439
+ return new ErrorCli(`No pude instalar el CLI: \xAB${legible(comando2)}\xBB termin\xF3 con ${corrida.status ?? "una se\xF1al"}${detalle ? ` (${detalle})` : ""}.${permisos} No cambi\xE9 nada m\xE1s.`, CODIGOS_DE_SALIDA.error, {
3440
+ codigo: "INSTALACION_FALLIDA",
3441
+ datos: { comando: legible(comando2) }
3442
+ });
3443
+ }
3444
+ function instalarConfirmado(ctx, entorno) {
3445
+ const { salida } = ctx;
3446
+ const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
3447
+ const comando2 = comandoDeActualizacion("npm-global", ctx.version, registro);
3448
+ const opciones = { cwd: ctx.cwd, env: ctx.env };
3449
+ salida.linea(`Instalando: ${legible(comando2)}`);
3450
+ const corrida = entorno.ejecutar(comando2.comando, comando2.args, opciones);
3451
+ if (corrida.status !== 0) throw errorDeInstalacion(comando2, corrida);
3452
+ const raiz = entorno.raizGlobal("npm");
3453
+ const bundle = raiz ? path10.join(raiz, ...PAQUETE_DEL_CLI.split("/"), "dist", "redcumbre.js") : null;
3454
+ const comprobada = bundle ? entorno.ejecutar(process.execPath, [bundle, "--version"], opciones) : null;
3455
+ if (!bundle || !comprobada || comprobada.status !== 0 || comprobada.stdout.trim() !== ctx.version) {
3456
+ throw new ErrorCli(
3457
+ `\xAB${legible(comando2)}\xBB termin\xF3 bien, pero el CLI de la carpeta global de npm (${raiz ?? "npm root --global no respondi\xF3"}) responde \xAB${comprobada?.stdout.trim() || comprobada?.stderr.trim() || "nada"}\xBB y no ${ctx.version}.`,
3458
+ CODIGOS_DE_SALIDA.error,
3459
+ { codigo: "INSTALACION_INCOMPLETA", datos: { version: ctx.version } }
3460
+ );
3461
+ }
3462
+ const enElPath = versionEnElPath(entorno, opciones);
3463
+ const carpeta = carpetaDeEjecutablesDeNpm(entorno, opciones);
3464
+ if (enElPath === ctx.version) {
3465
+ salida.linea(`\u2713 El CLI qued\xF3 instalado en la versi\xF3n ${ctx.version}: desde ahora usa \xABredcumbre \u2026\xBB.`);
3466
+ } else {
3467
+ salida.aviso(
3468
+ `El CLI qued\xF3 instalado en la versi\xF3n ${ctx.version}${carpeta ? ` en ${carpeta}` : ""}, pero ${enElPath ? `el \xABredcumbre\xBB que encuentra el PATH es la ${enElPath}` : "esa carpeta no est\xE1 en el PATH"}. Agrega ${carpeta ?? "la carpeta de ejecutables globales de npm (\xABnpm prefix --global\xBB)"} al PATH, antes que cualquier otra que tenga \xABredcumbre\xBB, y abre una terminal nueva. Mientras tanto usa \xAB${prefijoPorNpx(ctx.version)} \u2026\xBB.`
3469
+ );
3470
+ }
3471
+ return { ok: true, instalado: true, version: ctx.version, comando: legible(comando2), enElPath, carpeta };
3472
+ }
3473
+ async function instalar(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
3474
+ const { salida } = ctx;
3475
+ const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
3476
+ if (instalacion.forma === "npm-global" || instalacion.forma === "pnpm-global") {
3477
+ salida.linea(`El CLI ya est\xE1 instalado (${ctx.version}). Para pasar a una versi\xF3n m\xE1s nueva: \xABredcumbre actualizar\xBB.`);
3478
+ salida.resultado({ ok: true, instalado: false, motivo: "ya-instalado", version: ctx.version, forma: instalacion.forma });
3479
+ return;
3480
+ }
3481
+ if (instalacion.forma === "no-reconocida") {
3482
+ throw new ErrorCli(
3483
+ `No instal\xE9 nada: ${instalacion.motivo}. Para instalarlo a mano: \xABnpm install --global ${PAQUETE_DEL_CLI}@${ctx.version}\xBB.`,
3484
+ CODIGOS_DE_SALIDA.error,
3485
+ { codigo: "INSTALACION_NO_RECONOCIDA", datos: { version: ctx.version } }
3486
+ );
3487
+ }
3488
+ const enElPath = versionEnElPath(entorno, { cwd: ctx.cwd, env: ctx.env });
3489
+ if (enElPath && compararVersiones(enElPath, ctx.version) >= 0) {
3490
+ salida.linea(`El CLI ya est\xE1 instalado en este computador (redcumbre ${enElPath}): usa \xABredcumbre \u2026\xBB en vez de npx.`);
3491
+ salida.resultado({ ok: true, instalado: false, motivo: "ya-instalado", version: enElPath, forma: "npx" });
3492
+ return;
3493
+ }
3494
+ const comando2 = comandoDeActualizacion("npm-global", ctx.version, ctx.env.REDCUMBRE_NPM_REGISTRY || void 0);
3495
+ const confirmado = comandoInstalarPorNpx(ctx.version, true);
3496
+ const reemplaza = enElPath ? ` (reemplaza el redcumbre ${enElPath} del PATH)` : "";
3497
+ if (ctx.terminal) {
3498
+ if (!await ctx.terminal.confirmar(`\xBFInstalo el CLI ${ctx.version} en este computador con \xAB${legible(comando2)}\xBB${reemplaza}?`)) {
3499
+ throw faltaConfirmacion(`No confirmaste: no instal\xE9 nada. Cuando quieras: \xAB${comandoInstalarPorNpx(ctx.version, false)}\xBB.`, confirmado);
3500
+ }
3501
+ } else if (!opciones.confirmar) {
3502
+ throw faltaConfirmacion(
3503
+ `Instalar el CLI ${ctx.version}${reemplaza} instala un paquete en este computador y lo decide la persona. D\xEDselo y, si acepta, corre \xAB${confirmado}\xBB. No instal\xE9 nada.`,
3504
+ confirmado
3505
+ );
3506
+ }
3507
+ salida.resultado(instalarConfirmado(ctx, entorno));
3508
+ }
3509
+
3161
3510
  // src/comandos/registro.ts
3162
3511
  async function correr(globales, accion, opciones = {}) {
3163
3512
  const json2 = Boolean(globales.json);
@@ -3165,7 +3514,7 @@ async function correr(globales, accion, opciones = {}) {
3165
3514
  const salida = crearSalida(agente);
3166
3515
  const terminal = agente ? null : crearTerminal(process.stdin, process.stdout);
3167
3516
  try {
3168
- const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.5.0" });
3517
+ const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.6.0" });
3169
3518
  await exigirVersionMinima({
3170
3519
  version: ctx.version,
3171
3520
  env: process.env,
@@ -3176,15 +3525,29 @@ async function correr(globales, accion, opciones = {}) {
3176
3525
  `) : void 0;
3177
3526
  if (!opciones.revisaPorSuCuenta) {
3178
3527
  const consulta = { carpeta: ctx.carpetaConfiguracion, version: ctx.version, ahora: ctx.ahora(), registro: process.env.REDCUMBRE_NPM_REGISTRY };
3528
+ const entornoDelCli = entornoDeActualizacion(ctx);
3529
+ const porNpx = correPorNpx(entornoDelCli.bundle);
3530
+ const comandoActualizar = porNpx ? `${prefijoPorNpx(ctx.version)} actualizar` : void 0;
3179
3531
  if (!agente) {
3180
- await avisarSiHayVersionNueva({ ...consulta, humano: process.stderr });
3532
+ await avisarSiHayVersionNueva({ ...consulta, humano: process.stderr, comando: comandoActualizar });
3181
3533
  } else {
3182
3534
  const actualizacion = await actualizacionDisponible(consulta);
3183
3535
  if (actualizacion) {
3536
+ if (comandoActualizar) actualizacion.comando = `${comandoActualizar} --confirmar`;
3184
3537
  salida.anexar("actualizacion", actualizacion);
3185
3538
  salida.aviso(avisoDeActualizacion(actualizacion));
3186
3539
  }
3187
3540
  }
3541
+ if (porNpx) {
3542
+ const aviso = avisoDeInstalacion(ctx.version, estadoDeInstalacion(ctx, entornoDelCli));
3543
+ if (aviso && agente) {
3544
+ salida.anexar("instalacion", aviso.anexo);
3545
+ salida.aviso(aviso.texto);
3546
+ } else if (aviso && !opciones.ofreceInstalar) {
3547
+ process.stderr.write(`${aviso.paraPersona}
3548
+ `);
3549
+ }
3550
+ }
3188
3551
  renovarSkillAlCorrer({
3189
3552
  destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto: tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0 },
3190
3553
  version: ctx.version,
@@ -3297,12 +3660,12 @@ function entradasDe(ctx, fila, argumentos, opciones) {
3297
3660
  return { query, cuerpo, archivo };
3298
3661
  }
3299
3662
  function logoDe(ctx, ruta) {
3300
- const completa = path9.resolve(ctx.cwd, ruta);
3301
- const tipo = TIPOS_DE_LOGO[path9.extname(completa).toLowerCase()];
3302
- if (!tipo) throw errorDeUso(`El logo tiene que ser .jpg, .jpeg, .png, .gif o .webp; \xAB${path9.basename(completa)}\xBB no lo es. No llam\xE9 al API.`);
3303
- if (!fs9.existsSync(completa) || !fs9.statSync(completa).isFile()) throw errorDeUso(`No encuentro el archivo del logo: ${completa}`);
3304
- if (fs9.statSync(completa).size > MAXIMO_DEL_LOGO) throw errorDeUso(`El logo pesa m\xE1s de 2 MB: ${path9.basename(completa)}. Reduce la imagen y vuelve a intentarlo. No llam\xE9 al API.`);
3305
- return { ruta: completa, tipo, bytes: fs9.readFileSync(completa) };
3663
+ const completa = path11.resolve(ctx.cwd, ruta);
3664
+ const tipo = TIPOS_DE_LOGO[path11.extname(completa).toLowerCase()];
3665
+ if (!tipo) throw errorDeUso(`El logo tiene que ser .jpg, .jpeg, .png, .gif o .webp; \xAB${path11.basename(completa)}\xBB no lo es. No llam\xE9 al API.`);
3666
+ if (!fs10.existsSync(completa) || !fs10.statSync(completa).isFile()) throw errorDeUso(`No encuentro el archivo del logo: ${completa}`);
3667
+ if (fs10.statSync(completa).size > MAXIMO_DEL_LOGO) throw errorDeUso(`El logo pesa m\xE1s de 2 MB: ${path11.basename(completa)}. Reduce la imagen y vuelve a intentarlo. No llam\xE9 al API.`);
3668
+ return { ruta: completa, tipo, bytes: fs10.readFileSync(completa) };
3306
3669
  }
3307
3670
  var citar = (valor) => /^[\w.@:/=,+-]+$/.test(valor) ? valor : `'${valor.replace(/'/g, `'\\''`)}'`;
3308
3671
  function comandoDe2(fila, argumentos, opciones) {
@@ -3334,9 +3697,9 @@ async function correrOperacionDeEmisor(ctx, fila, argumentos, opciones) {
3334
3697
  ctx.salida.linea(`Ensayo: no llam\xE9 al API. Con la llave \xAB${llave.archivo.name}\xBB (${nombreDelModo(llave.entorno)}) de ${slug} har\xEDa:`);
3335
3698
  ctx.salida.linea(` ${op.metodo} ${ctx.cliente.url(ruta, query)}`);
3336
3699
  if (cuerpo !== void 0) ctx.salida.linea(` ${JSON.stringify(cuerpo)}`);
3337
- if (archivo) ctx.salida.linea(` multipart/form-data: logo=${path9.basename(archivo.ruta)} (${archivo.tipo}, ${archivo.bytes.length} bytes)`);
3700
+ if (archivo) ctx.salida.linea(` multipart/form-data: logo=${path11.basename(archivo.ruta)} (${archivo.tipo}, ${archivo.bytes.length} bytes)`);
3338
3701
  ctx.salida.resultado({
3339
- solicitud: { metodo: op.metodo, ruta, query, cuerpo: cuerpo ?? null, ...archivo ? { formulario: { logo: path9.basename(archivo.ruta) } } : {} },
3702
+ solicitud: { metodo: op.metodo, ruta, query, cuerpo: cuerpo ?? null, ...archivo ? { formulario: { logo: path11.basename(archivo.ruta) } } : {} },
3340
3703
  empresa: slug,
3341
3704
  llave: llave.archivo.name,
3342
3705
  modo: llave.entorno,
@@ -3367,7 +3730,7 @@ async function correrOperacionDeEmisor(ctx, fila, argumentos, opciones) {
3367
3730
  let formulario;
3368
3731
  if (archivo) {
3369
3732
  formulario = new FormData();
3370
- formulario.append("logo", new Blob([new Uint8Array(archivo.bytes)], { type: archivo.tipo }), path9.basename(archivo.ruta));
3733
+ formulario.append("logo", new Blob([new Uint8Array(archivo.bytes)], { type: archivo.tipo }), path11.basename(archivo.ruta));
3371
3734
  }
3372
3735
  respuesta = (await pedir2(ctx, llave, op, ruta, query, cuerpo, formulario)).json;
3373
3736
  }
@@ -3376,14 +3739,14 @@ async function correrOperacionDeEmisor(ctx, fila, argumentos, opciones) {
3376
3739
  if (cobro) mostrarCobro(ctx.salida, cobro);
3377
3740
  mostrar(ctx, fila, argumentos, opciones, slug, datos);
3378
3741
  }
3379
- var esObjeto3 = (valor) => typeof valor === "object" && valor !== null && !Array.isArray(valor);
3742
+ var esObjeto4 = (valor) => typeof valor === "object" && valor !== null && !Array.isArray(valor);
3380
3743
  var celda = (valor) => valor === null || valor === void 0 ? "" : typeof valor === "object" ? JSON.stringify(valor) : String(valor);
3381
3744
  function paginaDe(datos) {
3382
3745
  if (Array.isArray(datos)) return { items: datos, total: null };
3383
- if (esObjeto3(datos)) {
3746
+ if (esObjeto4(datos)) {
3384
3747
  const clave = ["data", "items", "resultados", "registros"].find((k) => Array.isArray(datos[k]));
3385
3748
  if (clave) {
3386
- const meta = esObjeto3(datos.meta) ? datos.meta : {};
3749
+ const meta = esObjeto4(datos.meta) ? datos.meta : {};
3387
3750
  const total = typeof datos.total === "number" ? datos.total : typeof meta.total === "number" ? meta.total : null;
3388
3751
  return { items: datos[clave], total };
3389
3752
  }
@@ -3403,7 +3766,7 @@ function mostrar(ctx, fila, argumentos, opciones, slug, datos) {
3403
3766
  const columnas = fila.columnas ?? [];
3404
3767
  if (items.length === 0) ctx.salida.linea(`${slug} no tiene emisores que coincidan.`);
3405
3768
  else {
3406
- const filas = items.map((item) => columnas.map((c) => celda(esObjeto3(item) ? item[c] : void 0)));
3769
+ const filas = items.map((item) => columnas.map((c) => celda(esObjeto4(item) ? item[c] : void 0)));
3407
3770
  const anchos = columnas.map((c, i) => Math.max(c.length, ...filas.map((f) => f[i].length)));
3408
3771
  const linea = (celdas) => celdas.map((c, i) => c.padEnd(anchos[i])).join(" ").trimEnd();
3409
3772
  ctx.salida.linea(linea(columnas));
@@ -3416,7 +3779,7 @@ function mostrar(ctx, fila, argumentos, opciones, slug, datos) {
3416
3779
  ctx.salida.resultado(datos);
3417
3780
  return;
3418
3781
  }
3419
- if (esObjeto3(datos)) for (const [clave, valor] of Object.entries(datos)) ctx.salida.linea(`${clave}: ${celda(valor)}`);
3782
+ if (esObjeto4(datos)) for (const [clave, valor] of Object.entries(datos)) ctx.salida.linea(`${clave}: ${celda(valor)}`);
3420
3783
  else ctx.salida.linea(datos === null || datos === void 0 ? "Sin datos." : celda(datos));
3421
3784
  ctx.salida.resultado(datos ?? { ok: true });
3422
3785
  }
@@ -3724,7 +4087,7 @@ async function canjear(ctx, o) {
3724
4087
  await canjearYMostrar(ctx, llave, llave.archivo.tenantSlug, op, codigo);
3725
4088
  }
3726
4089
  function declararTokenizar(programa2) {
3727
- const raiz = comando(programa2, "tokenizar", "inscribe un emisor: la persona autoriza el uso de sus credenciales del SII y el CLI canjea el c\xF3digo").option("--rut <rut>", "RUT del emisor (el API valida el d\xEDgito verificador)").option("--tipo <tipo>", "tributario o dte").option("--autenticacion <m\xE9todo>", "clave o certificado (obligatoria con --tipo tributario)").option("--correo <correo>", "correo de la persona que autoriza, para la sesi\xF3n que abres t\xFA").option("--invitar <correo>", "manda la invitaci\xF3n a ese correo y termina").option("--integracion <tipo>", "PORTAL_MIPYME o FULL_DTE (solo --tipo dte)").option("--boletas", "incluye el carril de boletas (solo --tipo dte)").option("--correo-empresa <correo>", "correo de la empresa (obligatoria con --tipo dte)").option("--contacto-correo <correo>", "correo de contacto para la certificaci\xF3n (solo --tipo dte)").option("--contacto-telefono <tel\xE9fono>", "tel\xE9fono de contacto para la certificaci\xF3n (solo --tipo dte)").option("--clave <clave>", "clave de idempotencia de la invitaci\xF3n, para reintentar sin duplicar (solo con --invitar)").option("--espera <minutos>", `minutos de espera de la autorizaci\xF3n, de 1 a 120 (${ESPERA_POR_OMISION_MIN} por omisi\xF3n)`).addOption(new Option2("--sin-navegador", "no abre el navegador: imprime la URL y pide pegar el c\xF3digo")).option("--produccion", "con la llave de producci\xF3n (pide confirmar lo que escribe)").option("--confirmar <slug>", "confirma en producci\xF3n sin preguntar, con el identificador de la empresa");
4090
+ const raiz = comando(programa2, "tokenizar", "inscribe un emisor: la persona autoriza el uso de sus credenciales del SII y el CLI canjea el c\xF3digo").option("--rut <rut>", "RUT del emisor (el API valida el d\xEDgito verificador)").option("--tipo <tipo>", "tributario o dte").option("--autenticacion <m\xE9todo>", "clave o certificado (obligatoria con --tipo tributario)").option("--correo <correo>", "correo de la persona que autoriza, para la sesi\xF3n que abres t\xFA").option("--invitar <correo>", "manda la invitaci\xF3n a ese correo y termina").option("--integracion <tipo>", "PORTAL_MIPYME o FULL_DTE (s\xF3lo --tipo dte). FULL_DTE, recomendado, emite y recibe DTE integrado. PORTAL_MIPYME es para bajo volumen y sin cargo fijo, y no emite boletas").option("--boletas", "crea adem\xE1s el emisor de boletas (SOLO_BOLETA), un carril aparte del de facturaci\xF3n (s\xF3lo --tipo dte)").option("--correo-empresa <correo>", "correo de la empresa (obligatoria con --tipo dte)").option("--contacto-correo <correo>", "correo de contacto para la certificaci\xF3n (solo --tipo dte)").option("--contacto-telefono <tel\xE9fono>", "tel\xE9fono de contacto para la certificaci\xF3n (solo --tipo dte)").option("--clave <clave>", "clave de idempotencia de la invitaci\xF3n, para reintentar sin duplicar (solo con --invitar)").option("--espera <minutos>", `minutos de espera de la autorizaci\xF3n, de 1 a 120 (${ESPERA_POR_OMISION_MIN} por omisi\xF3n)`).addOption(new Option2("--sin-navegador", "no abre el navegador: imprime la URL y pide pegar el c\xF3digo")).option("--produccion", "con la llave de producci\xF3n (pide confirmar lo que escribe)").option("--confirmar <slug>", "confirma en producci\xF3n sin preguntar, con el identificador de la empresa");
3728
4091
  raiz.action((_o, accion) => {
3729
4092
  const o = accion.optsWithGlobals();
3730
4093
  return correr(o, (ctx) => tokenizar(ctx, o));
@@ -3737,8 +4100,8 @@ function declararTokenizar(programa2) {
3737
4100
 
3738
4101
  // src/nucleo/guias.ts
3739
4102
  import { randomBytes as randomBytes2 } from "node:crypto";
3740
- import fs10 from "node:fs";
3741
- import path10 from "node:path";
4103
+ import fs11 from "node:fs";
4104
+ import path12 from "node:path";
3742
4105
  var CODIGO_GUIA_NO_DISPONIBLE = "GUIA_NO_DISPONIBLE";
3743
4106
  var TEMA_VALIDO = /^[a-z0-9][a-z0-9-]*$/;
3744
4107
  var COPIA_DEL_INDICE = "_indice";
@@ -3749,15 +4112,15 @@ var TIPOS_DE_FICHA = ["text/markdown", "text/plain", "application/octet-stream"]
3749
4112
  var PARECE_HTML = /^\s*<(?:!doctype\s+html|html[\s>])/i;
3750
4113
  var TIPOS_DEL_INDICE = ["application/json"];
3751
4114
  var TIPOS_DE_VERSION = ["text/plain"];
3752
- var carpetaDeGuias = (carpeta) => path10.join(carpeta, "guias");
3753
- var rutaTexto = (carpeta, nombre) => path10.join(carpetaDeGuias(carpeta), `${nombre}${nombre === COPIA_DEL_INDICE ? ".txt" : ".md"}`);
3754
- var rutaMarca = (carpeta, nombre) => path10.join(carpetaDeGuias(carpeta), `${nombre}.json`);
4115
+ var carpetaDeGuias = (carpeta) => path12.join(carpeta, "guias");
4116
+ var rutaTexto = (carpeta, nombre) => path12.join(carpetaDeGuias(carpeta), `${nombre}${nombre === COPIA_DEL_INDICE ? ".txt" : ".md"}`);
4117
+ var rutaMarca = (carpeta, nombre) => path12.join(carpetaDeGuias(carpeta), `${nombre}.json`);
3755
4118
  function leerCopia2(carpeta, nombre, origen2) {
3756
4119
  try {
3757
- const marca = JSON.parse(fs10.readFileSync(rutaMarca(carpeta, nombre), "utf8"));
4120
+ const marca = JSON.parse(fs11.readFileSync(rutaMarca(carpeta, nombre), "utf8"));
3758
4121
  if (!marca || marca.origen !== origen2 || typeof marca.version !== "string" || !marca.version) return null;
3759
4122
  const archivo = rutaTexto(carpeta, nombre);
3760
- return { texto: fs10.readFileSync(archivo, "utf8"), version: marca.version, fecha: fs10.statSync(archivo).mtime };
4123
+ return { texto: fs11.readFileSync(archivo, "utf8"), version: marca.version, fecha: fs11.statSync(archivo).mtime };
3761
4124
  } catch {
3762
4125
  return null;
3763
4126
  }
@@ -3765,22 +4128,22 @@ function leerCopia2(carpeta, nombre, origen2) {
3765
4128
  function escribirAtomico2(destino, contenido) {
3766
4129
  const temporal = `${destino}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
3767
4130
  try {
3768
- fs10.writeFileSync(temporal, contenido);
3769
- fs10.renameSync(temporal, destino);
4131
+ fs11.writeFileSync(temporal, contenido);
4132
+ fs11.renameSync(temporal, destino);
3770
4133
  } catch (error) {
3771
- fs10.rmSync(temporal, { force: true });
4134
+ fs11.rmSync(temporal, { force: true });
3772
4135
  throw error;
3773
4136
  }
3774
4137
  }
3775
4138
  function guardarCopia2(carpeta, nombre, origen2, version, texto2) {
3776
- fs10.mkdirSync(carpetaDeGuias(carpeta), { recursive: true, mode: 448 });
4139
+ fs11.mkdirSync(carpetaDeGuias(carpeta), { recursive: true, mode: 448 });
3777
4140
  escribirAtomico2(rutaTexto(carpeta, nombre), texto2);
3778
4141
  escribirAtomico2(rutaMarca(carpeta, nombre), `${JSON.stringify({ origen: origen2, version })}
3779
4142
  `);
3780
4143
  }
3781
4144
  function borrarCopia(carpeta, nombre) {
3782
- fs10.rmSync(rutaMarca(carpeta, nombre), { force: true });
3783
- fs10.rmSync(rutaTexto(carpeta, nombre), { force: true });
4145
+ fs11.rmSync(rutaMarca(carpeta, nombre), { force: true });
4146
+ fs11.rmSync(rutaTexto(carpeta, nombre), { force: true });
3784
4147
  }
3785
4148
  var fechaLegible2 = (fecha) => fecha.toLocaleString("es-CL", { dateStyle: "medium", timeStyle: "short" });
3786
4149
  var sinCopia = (que, motivo) => new ErrorCli(`${motivo} No tengo una copia local de ${que}: sin red no puedo entregarla. Vuelve a intentarlo con conexi\xF3n.`, CODIGOS_DE_SALIDA.api5xx, {
@@ -3859,8 +4222,8 @@ async function obtener(opciones, nombre, ruta, que, tipos, validar2 = () => void
3859
4222
  guardarCopia2(carpeta, nombre, cliente.api, version, r.texto);
3860
4223
  return { texto: r.texto, version, copiaSinRevalidar: null };
3861
4224
  }
3862
- var invalido = (que) => new ErrorCli(`${que} no tiene el formato esperado. Actualiza el CLI con \xABnpx @redcumbrecl/cli@latest\xBB y vuelve a intentarlo.`, CODIGOS_DE_SALIDA.api5xx, { codigo: "GUIA_INVALIDA" });
3863
- var respuestaInvalida = (motivo) => new ErrorCli(`${motivo} No es una gu\xEDa v\xE1lida y no guard\xE9 ninguna copia. Vuelve a intentarlo m\xE1s tarde o actualiza el CLI con \xABnpx @redcumbrecl/cli@latest\xBB.`, CODIGOS_DE_SALIDA.api5xx, {
4225
+ var invalido = (que) => new ErrorCli(`${que} no tiene el formato esperado. Actualiza el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB y vuelve a intentarlo.`, CODIGOS_DE_SALIDA.api5xx, { codigo: "GUIA_INVALIDA" });
4226
+ var respuestaInvalida = (motivo) => new ErrorCli(`${motivo} No es una gu\xEDa v\xE1lida y no guard\xE9 ninguna copia. Vuelve a intentarlo m\xE1s tarde o actualiza el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`, CODIGOS_DE_SALIDA.api5xx, {
3864
4227
  codigo: "GUIA_INVALIDA"
3865
4228
  });
3866
4229
  var esTexto = (valor) => typeof valor === "string" && valor.trim() !== "";
@@ -3978,7 +4341,7 @@ async function guia(ctx, tema) {
3978
4341
  }
3979
4342
 
3980
4343
  // src/comandos/init.ts
3981
- import path12 from "node:path";
4344
+ import path14 from "node:path";
3982
4345
 
3983
4346
  // src/comandos/instalar-llave.ts
3984
4347
  function negativaSinRol(ctx, proyecto, empresa2, entorno) {
@@ -4072,9 +4435,9 @@ function mostrarWhoami(salida, tenant, modo, encabezado) {
4072
4435
  }
4073
4436
 
4074
4437
  // src/comandos/mcp.ts
4075
- import fs11 from "node:fs";
4438
+ import fs12 from "node:fs";
4076
4439
  import os3 from "node:os";
4077
- import path11 from "node:path";
4440
+ import path13 from "node:path";
4078
4441
  var URL_MCP_REDCUMBRE = "https://mcp.redcumbre.cl";
4079
4442
  var NOMBRE_SERVIDOR_MCP = "redcumbre";
4080
4443
  var COMANDO_MCP_AGREGAR = "redcumbre mcp agregar";
@@ -4092,20 +4455,20 @@ var ASISTENTE_REGISTRY = {
4092
4455
  }
4093
4456
  };
4094
4457
  var ENTRADA = { type: "http", url: URL_MCP_REDCUMBRE };
4095
- var esObjeto4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4096
- var mismaEntrada = (v) => esObjeto4(v) && Object.keys(v).length === 2 && v.type === ENTRADA.type && v.url === ENTRADA.url;
4097
- var rutaConfigMcp = (asistente, home = os3.homedir()) => path11.join(home, ...ASISTENTE_REGISTRY[asistente].archivo);
4458
+ var esObjeto5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4459
+ var mismaEntrada = (v) => esObjeto5(v) && Object.keys(v).length === 2 && v.type === ENTRADA.type && v.url === ENTRADA.url;
4460
+ var rutaConfigMcp = (asistente, home = os3.homedir()) => path13.join(home, ...ASISTENTE_REGISTRY[asistente].archivo);
4098
4461
  function leerConfig(ruta) {
4099
- if (!fs11.existsSync(ruta)) return null;
4462
+ if (!fs12.existsSync(ruta)) return null;
4100
4463
  let actual;
4101
4464
  try {
4102
- actual = JSON.parse(fs11.readFileSync(ruta, "utf8"));
4465
+ actual = JSON.parse(fs12.readFileSync(ruta, "utf8"));
4103
4466
  } catch (error) {
4104
4467
  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, {
4105
4468
  codigo: "CONFIG_MCP_INVALIDA"
4106
4469
  });
4107
4470
  }
4108
- if (!esObjeto4(actual) || actual.mcpServers !== void 0 && !esObjeto4(actual.mcpServers)) {
4471
+ if (!esObjeto5(actual) || actual.mcpServers !== void 0 && !esObjeto5(actual.mcpServers)) {
4109
4472
  throw new ErrorCli(`${ruta} no tiene la forma { "mcpServers": { \u2026 } }: no lo modifiqu\xE9.`, CODIGOS_DE_SALIDA.error, { codigo: "CONFIG_MCP_INVALIDA" });
4110
4473
  }
4111
4474
  return actual;
@@ -4133,8 +4496,8 @@ function planQuitar(asistente, home) {
4133
4496
  function escribir(planes) {
4134
4497
  for (const p of planes) {
4135
4498
  if (p.contenido === void 0) continue;
4136
- fs11.mkdirSync(path11.dirname(p.ruta), { recursive: true });
4137
- fs11.writeFileSync(p.ruta, p.contenido);
4499
+ fs12.mkdirSync(path13.dirname(p.ruta), { recursive: true });
4500
+ fs12.writeFileSync(p.ruta, p.contenido);
4138
4501
  }
4139
4502
  }
4140
4503
  function asistentesPedidos(asistente) {
@@ -4253,19 +4616,19 @@ async function pedirCampo(ctx, terminal, campo, previo) {
4253
4616
  }
4254
4617
 
4255
4618
  // src/comandos/init.ts
4256
- async function init(ctx, opciones) {
4619
+ async function init(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
4257
4620
  const { salida } = ctx;
4258
4621
  const terminal = salida.json ? null : ctx.terminal;
4259
4622
  if (opciones.entorno !== void 0) {
4260
4623
  throw errorDeUso(`--entorno ya no existe: init s\xF3lo conecta la llave de prueba. Para pasar a producci\xF3n corre \xAB${COMANDO_PASAR_A_PRODUCCION}\xBB.`);
4261
4624
  }
4262
- let proyecto = path12.resolve(ctx.cwd, opciones.carpeta ?? ".");
4625
+ let proyecto = path14.resolve(ctx.cwd, opciones.carpeta ?? ".");
4263
4626
  const sesion = await ctx.sesion();
4264
4627
  const perfil = await sesion.usar((token) => ctx.cliente.perfil(token));
4265
4628
  if (perfil.empresas.length === 0) {
4266
4629
  if (!terminal) {
4267
4630
  throw new ErrorCli(
4268
- `Tu cuenta todav\xEDa no pertenece a ninguna empresa en REDCUMBRE. No envi\xE9 ninguna solicitud: pide la cuenta en https://docs.redcumbre.cl/solicitar-cuenta/ o corre \xAB${COMANDO_SOLICITAR_CUENTA}\xBB en una terminal.`,
4631
+ `Tu cuenta todav\xEDa no pertenece a ninguna empresa en REDCUMBRE. No envi\xE9 ninguna solicitud: pide la cuenta en ${SOLICITUD_CUENTA_URL_FORMULARIO_SITIO} o corre \xAB${COMANDO_SOLICITAR_CUENTA}\xBB en una terminal.`,
4269
4632
  CODIGOS_DE_SALIDA.error,
4270
4633
  { codigo: "SIN_EMPRESAS", comando: COMANDO_SOLICITAR_CUENTA }
4271
4634
  );
@@ -4283,7 +4646,7 @@ async function init(ctx, opciones) {
4283
4646
  const empresa2 = await elegirEmpresa(ctx, perfil.empresas, opciones.empresa);
4284
4647
  if (terminal && opciones.carpeta === void 0 && !tieneInstalacionDelCli(proyecto)) {
4285
4648
  const respuesta = await terminal.preguntar("\xBFD\xF3nde instalo la llave? [.]: ");
4286
- proyecto = path12.resolve(ctx.cwd, respuesta || ".");
4649
+ proyecto = path14.resolve(ctx.cwd, respuesta || ".");
4287
4650
  }
4288
4651
  const anterior = empresaAnterior(proyecto, empresa2.slug);
4289
4652
  const llave = await instalarLlave(ctx, proyecto, empresa2, "prueba");
@@ -4318,6 +4681,24 @@ async function init(ctx, opciones) {
4318
4681
  );
4319
4682
  }
4320
4683
  salida.linea(`\u2713 La llave de prueba funciona: ${comprobacion.tenant.nombre} (${comprobacion.tenant.slug}), modo de prueba.`);
4684
+ let cli;
4685
+ const estado2 = terminal ? estadoDeInstalacion(ctx, entorno) : null;
4686
+ if (terminal && estado2?.forma === "npx" && !estado2.instalado) {
4687
+ salida.linea();
4688
+ const reemplaza = estado2.enElPath ? ` (reemplaza el redcumbre ${estado2.enElPath} del PATH)` : "";
4689
+ if (await terminal.confirmar(`El CLI corre por npx. \xBFLo dejo instalado en este computador (versi\xF3n ${ctx.version})${reemplaza} para que uses \xABredcumbre \u2026\xBB directo?`)) {
4690
+ try {
4691
+ cli = instalarConfirmado(ctx, entorno);
4692
+ } catch (error) {
4693
+ if (!(error instanceof ErrorCli)) throw error;
4694
+ salida.aviso(`${error.message} El proyecto qued\xF3 conectado igual; puedes reintentarlo con \xAB${comandoInstalarPorNpx(ctx.version, false)}\xBB.`);
4695
+ cli = { instalado: false, codigo: error.codigo };
4696
+ }
4697
+ } else {
4698
+ salida.linea(`Cuando quieras dejarlo instalado: ${comandoInstalarPorNpx(ctx.version, false)}`);
4699
+ cli = { instalado: false, motivo: "no-confirmado" };
4700
+ }
4701
+ }
4321
4702
  salida.linea();
4322
4703
  salida.linea(`Para que tu asistente (Claude Code o Cursor) trabaje con REDCUMBRE: ${COMANDO_MCP_AGREGAR}`);
4323
4704
  salida.resultado({
@@ -4328,7 +4709,8 @@ async function init(ctx, opciones) {
4328
4709
  llave,
4329
4710
  skill: { rutas: skill.rutas, estado: skill.estado },
4330
4711
  comprobacion: { sandbox: true, tenant: { slug: comprobacion.tenant.slug, nombre: comprobacion.tenant.nombre } },
4331
- mcp: { comando: COMANDO_MCP_AGREGAR }
4712
+ mcp: { comando: COMANDO_MCP_AGREGAR },
4713
+ ...cli ? { cli } : {}
4332
4714
  });
4333
4715
  }
4334
4716
  async function elegirEmpresa(ctx, empresas, pedida) {
@@ -4435,7 +4817,7 @@ async function llamadas(ctx, opciones) {
4435
4817
  }
4436
4818
 
4437
4819
  // src/comandos/credenciales-reseller.ts
4438
- import path13 from "node:path";
4820
+ import path15 from "node:path";
4439
4821
  function declararOpcionesCrearCredencial(comando2) {
4440
4822
  return comando2.requiredOption("--tipo <tipo>", `${TIPOS_CREDENCIAL_RESELLER.join(" o ")}`).requiredOption("--entorno <entorno>", `${ENTORNOS_LLAVE.join(" o ")}`).requiredOption("--nombre <nombre>", "nombre de la credencial (3 a 191 caracteres)").option("--vence <fecha>", "vencimiento opcional, ISO 8601 (2027-12-31)").option("--empresa <slug>", "la empresa reseller");
4441
4823
  }
@@ -4465,7 +4847,7 @@ async function crearCredencial(ctx, opciones) {
4465
4847
  const sesion = await ctx.sesion();
4466
4848
  const creada = await sesion.usar((token) => ctx.cliente.crearCredencialReseller(token, slug, { nombre: opciones.nombre, tipo, entorno, venceEn }));
4467
4849
  const relativa = `keys/reseller-${slug}-${tipo}-${entorno}.json`;
4468
- const archivo = path13.join(ctx.proyecto, relativa);
4850
+ const archivo = path15.join(ctx.proyecto, relativa);
4469
4851
  asegurarExclusiones(ctx.proyecto, estaVersionado(ctx.proyecto, ".env"));
4470
4852
  escribirArchivoLlave(archivo, {
4471
4853
  tenantSlug: slug,
@@ -4489,7 +4871,7 @@ async function revocarCredencial(ctx, id, opciones) {
4489
4871
  }
4490
4872
 
4491
4873
  // src/comandos/llave-validafirma.ts
4492
- import path14 from "node:path";
4874
+ import path16 from "node:path";
4493
4875
  function declararOpcionesLlaveValidaFirma(comando2) {
4494
4876
  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 produccion").option("--confirmar <slug>", "con --modo produccion: el slug de la empresa; confirma la llave sin preguntar (obligatorio sin terminal o con --json)");
4495
4877
  }
@@ -4505,8 +4887,8 @@ async function llaveValidaFirma(ctx, opciones) {
4505
4887
  if (!esEntornoLlave(modoPedido)) throw errorDeUso(mensajeEntornoLlaveInvalido(modoPedido));
4506
4888
  const modo = modoPedido;
4507
4889
  const relativa = rutaRelativaLlaveValidaFirma(empresa2, alcance, modo);
4508
- const archivo = path14.resolve(ctx.proyecto, relativa);
4509
- if (path14.join(ctx.proyecto, "keys", path14.basename(relativa)) !== archivo || path14.basename(relativa) !== relativa.slice("keys/".length)) throw errorDeUso(`\xAB${empresa2}\xBB no es el identificador de una empresa (tenantSlug).`);
4890
+ const archivo = path16.resolve(ctx.proyecto, relativa);
4891
+ if (path16.join(ctx.proyecto, "keys", path16.basename(relativa)) !== archivo || path16.basename(relativa) !== relativa.slice("keys/".length)) throw errorDeUso(`\xAB${empresa2}\xBB no es el identificador de una empresa (tenantSlug).`);
4510
4892
  const comando2 = `redcumbre llaves validafirma --empresa ${empresa2} --alcance ${alcance} --modo ${modo}`;
4511
4893
  const comandoConfirmando = `${comando2} --confirmar ${empresa2}`;
4512
4894
  const modoEsperado = ENTORNO_LLAVE_REGISTRY[modo].isSandbox;
@@ -5206,8 +5588,8 @@ async function pasarAProduccion(ctx, opciones) {
5206
5588
  try {
5207
5589
  const prueba = leerLlave(proyecto, "prueba");
5208
5590
  const llaveId = prueba?.tenantSlug === slug ? await resolverLlaveId({ proyecto, sesion: ctx.sesion, cliente }, { entorno: "prueba", archivo: prueba, ruta: rutaLlave(proyecto, "prueba") }) ?? void 0 : void 0;
5209
- const revisar = (servicios2) => sesion.usar((token) => cliente.revisionPasoAProduccion(token, slug, llaveId, servicios2));
5210
- let revision = await revisar(pedidos);
5591
+ const revisar2 = (servicios2) => sesion.usar((token) => cliente.revisionPasoAProduccion(token, slug, llaveId, servicios2));
5592
+ let revision = await revisar2(pedidos);
5211
5593
  if (revision.servicios.length === 0) {
5212
5594
  if (!terminal) {
5213
5595
  throw faltaConfirmacion(
@@ -5216,11 +5598,11 @@ async function pasarAProduccion(ctx, opciones) {
5216
5598
  "PASO_A_PRODUCCION_REQUIERE_SERVICIOS"
5217
5599
  );
5218
5600
  }
5219
- revision = await revisar(await elegirServicios(terminal, "La llave de prueba no tiene llamadas. \xBFQu\xE9 servicios usa este proyecto?"));
5601
+ revision = await revisar2(await elegirServicios(terminal, "La llave de prueba no tiene llamadas. \xBFQu\xE9 servicios usa este proyecto?"));
5220
5602
  } else if (!pedidos && terminal && revision.servicios.some((s) => s.deducido)) {
5221
5603
  salida.linea("Por las llamadas de la llave de prueba, el proyecto usa:");
5222
5604
  for (const s of revision.servicios) salida.linea(` \xB7 ${s.nombre} (${s.codigo})`);
5223
- if (!await terminal.confirmar("\xBFSon esos los servicios del proyecto?")) revision = await revisar(await elegirServicios(terminal, "\xBFQu\xE9 servicios usa este proyecto?"));
5605
+ if (!await terminal.confirmar("\xBFSon esos los servicios del proyecto?")) revision = await revisar2(await elegirServicios(terminal, "\xBFQu\xE9 servicios usa este proyecto?"));
5224
5606
  }
5225
5607
  const servicios = revision.servicios.map((s) => s.codigo);
5226
5608
  mostrarRevision(ctx, revision);
@@ -5409,63 +5791,15 @@ async function logout(ctx) {
5409
5791
  }
5410
5792
 
5411
5793
  // src/comandos/actualizar.ts
5412
- import { spawnSync as spawnSync2 } from "node:child_process";
5413
- import fs12 from "node:fs";
5414
- import path15 from "node:path";
5415
- import { fileURLToPath as fileURLToPath2 } from "node:url";
5416
- var real = (ruta) => {
5794
+ import fs13 from "node:fs";
5795
+ import path17 from "node:path";
5796
+ var real2 = (ruta) => {
5417
5797
  try {
5418
- return fs12.realpathSync(ruta);
5798
+ return fs13.realpathSync(ruta);
5419
5799
  } catch {
5420
5800
  return null;
5421
5801
  }
5422
5802
  };
5423
- var dentroDe = (ruta, carpeta) => ruta === carpeta || ruta.startsWith(carpeta + path15.sep);
5424
- function detectarInstalacion(bundle, raizGlobal) {
5425
- const bundleReal = real(bundle) ?? path15.resolve(bundle);
5426
- const segmentos = bundleReal.split(path15.sep);
5427
- if (segmentos.includes("_npx")) return { forma: "npx" };
5428
- for (const [gestor, forma] of [["npm", "npm-global"], ["pnpm", "pnpm-global"]]) {
5429
- const raiz = raizGlobal(gestor);
5430
- const carpeta = raiz ? real(path15.join(raiz, ...PAQUETE_DEL_CLI.split("/"))) : null;
5431
- if (carpeta && dentroDe(bundleReal, carpeta)) return { forma, carpetaDelPaquete: carpeta };
5432
- }
5433
- const marcaDeDependencia = ["node_modules", ...PAQUETE_DEL_CLI.split("/")].join(path15.sep);
5434
- if (bundleReal.includes(`${path15.sep}${marcaDeDependencia}${path15.sep}`)) {
5435
- return { forma: "no-reconocida", motivo: `el CLI est\xE1 instalado como dependencia de un proyecto (${bundleReal}): actual\xEDzalo con el gestor de ese proyecto, que es quien decide su versi\xF3n` };
5436
- }
5437
- return { forma: "no-reconocida", motivo: `el CLI que corre (${bundleReal}) no est\xE1 en la cach\xE9 de npx ni en la carpeta global de npm o de pnpm` };
5438
- }
5439
- function comandoDeActualizacion(forma, version, registro) {
5440
- const paquete = `${PAQUETE_DEL_CLI}@${version}`;
5441
- const conRegistro = registro ? [`--registry=${registro}`] : [];
5442
- if (forma === "npm-global") return { comando: "npm", args: ["install", "--global", ...conRegistro, paquete] };
5443
- if (forma === "pnpm-global") return { comando: "pnpm", args: ["add", "--global", ...conRegistro, paquete] };
5444
- return { comando: "npx", args: ["--yes", ...conRegistro, paquete, "skill", "renovar", "--json"] };
5445
- }
5446
- var legible = (c) => [c.comando, ...c.args].join(" ");
5447
- function ejecutarDeVerdad(comando2, args, opciones) {
5448
- const r = spawnSync2(comando2, args, { cwd: opciones.cwd, env: opciones.env, encoding: "utf8", shell: process.platform === "win32", timeout: 10 * 6e4 });
5449
- return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? r.error.message : "") };
5450
- }
5451
- function entornoDeActualizacion(ctx) {
5452
- const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
5453
- return {
5454
- bundle: fileURLToPath2(import.meta.url),
5455
- ejecutar: ejecutarDeVerdad,
5456
- raizGlobal(gestor) {
5457
- const r = ejecutarDeVerdad(gestor, ["root", "--global"], { cwd: ctx.cwd, env: ctx.env });
5458
- const raiz = r.stdout.trim().split(/\r?\n/).pop() ?? "";
5459
- return r.status === 0 && raiz ? raiz : null;
5460
- },
5461
- async consultarUltima() {
5462
- const respuesta = await fetch(urlUltimaVersion(registro), { signal: AbortSignal.timeout(1e4), headers: { accept: "application/json" } });
5463
- if (!respuesta.ok) throw new Error(`el registro respondi\xF3 ${respuesta.status}`);
5464
- const cuerpo = await respuesta.json();
5465
- return typeof cuerpo.version === "string" ? cuerpo.version : null;
5466
- }
5467
- };
5468
- }
5469
5803
  function leerJson2(texto2) {
5470
5804
  try {
5471
5805
  const dato = JSON.parse(texto2);
@@ -5498,44 +5832,47 @@ async function actualizar(ctx, opciones, entorno = entornoDeActualizacion(ctx))
5498
5832
  const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
5499
5833
  if (instalacion.forma === "no-reconocida") {
5500
5834
  throw new ErrorCli(
5501
- `No actualic\xE9 nada: ${instalacion.motivo}. Para actualizarlo a mano: \xABnpm install --global ${PAQUETE_DEL_CLI}@${disponible}\xBB, \xABpnpm add --global ${PAQUETE_DEL_CLI}@${disponible}\xBB o, sin instalar, \xABnpx ${PAQUETE_DEL_CLI}@latest\xBB.`,
5835
+ `No actualic\xE9 nada: ${instalacion.motivo}. Para actualizarlo a mano: \xABnpm install --global ${PAQUETE_DEL_CLI}@${disponible}\xBB o \xABpnpm add --global ${PAQUETE_DEL_CLI}@${disponible}\xBB.`,
5502
5836
  CODIGOS_DE_SALIDA.error,
5503
5837
  { codigo: "INSTALACION_NO_RECONOCIDA", datos: { instalada: ctx.version, disponible } }
5504
5838
  );
5505
5839
  }
5506
5840
  const comando2 = comandoDeActualizacion(instalacion.forma, disponible, registro);
5841
+ const confirmado = instalacion.forma === "npx" ? `${prefijoPorNpx(ctx.version)} actualizar --confirmar` : COMANDO_ACTUALIZAR_CONFIRMADO;
5507
5842
  const pregunta = `\xBFActualizo el CLI de ${ctx.version} a ${disponible} con \xAB${legible(comando2)}\xBB? Tambi\xE9n renuevo la skill donde ya est\xE1.`;
5508
5843
  if (ctx.terminal) {
5509
- if (!await ctx.terminal.confirmar(pregunta)) throw faltaConfirmacion("No confirmaste: no actualic\xE9 nada.", COMANDO_ACTUALIZAR_CONFIRMADO);
5844
+ if (!await ctx.terminal.confirmar(pregunta)) throw faltaConfirmacion("No confirmaste: no actualic\xE9 nada.", confirmado);
5510
5845
  } else if (!opciones.confirmar) {
5511
5846
  throw faltaConfirmacion(
5512
- `Actualizar el CLI de ${ctx.version} a ${disponible} instala un paquete en este computador y lo decide la persona. D\xEDselo y, si acepta, corre \xAB${COMANDO_ACTUALIZAR_CONFIRMADO}\xBB. No actualic\xE9 nada.`,
5513
- COMANDO_ACTUALIZAR_CONFIRMADO
5847
+ `Actualizar el CLI de ${ctx.version} a ${disponible} instala un paquete en este computador y lo decide la persona. D\xEDselo y, si acepta, corre \xAB${confirmado}\xBB. No actualic\xE9 nada.`,
5848
+ confirmado
5514
5849
  );
5515
5850
  }
5516
5851
  salida.linea(`Actualizando: ${legible(comando2)}`);
5517
5852
  const corrida = entorno.ejecutar(comando2.comando, comando2.args, { cwd: ctx.cwd, env: ctx.env });
5518
- let skill = null;
5519
- if (instalacion.forma === "npx") {
5520
- if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
5521
- skill = leerJson2(corrida.stdout)?.skill ?? null;
5522
- } else {
5523
- if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
5524
- const bundleNuevo = path15.join(instalacion.carpetaDelPaquete, "dist", "cli.js");
5525
- const version = entorno.ejecutar(process.execPath, [bundleNuevo, "--version"], { cwd: ctx.cwd, env: ctx.env });
5526
- if (version.status !== 0 || version.stdout.trim() !== disponible) {
5527
- throw new ErrorCli(
5528
- `\xAB${legible(comando2)}\xBB termin\xF3 bien, pero el CLI de ${instalacion.carpetaDelPaquete} responde \xAB${version.stdout.trim() || version.stderr.trim()}\xBB y no ${disponible}. Revisa con \xABredcumbre --version\xBB.`,
5529
- CODIGOS_DE_SALIDA.error,
5530
- { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
5531
- );
5532
- }
5533
- const renovacion = entorno.ejecutar(process.execPath, [bundleNuevo, "skill", "renovar", "--json"], { cwd: ctx.cwd, env: ctx.env });
5534
- skill = renovacion.status === 0 ? leerJson2(renovacion.stdout)?.skill ?? null : null;
5535
- if (skill === null) salida.aviso(`El CLI qued\xF3 en la versi\xF3n ${disponible}, pero no pude renovar la skill: corre \xABredcumbre skill renovar\xBB.`);
5853
+ if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
5854
+ const raizNpm = instalacion.forma === "npx" ? entorno.raizGlobal("npm") : null;
5855
+ const carpetaDelPaquete = instalacion.forma === "npx" ? raizNpm ? real2(path17.join(raizNpm, ...PAQUETE_DEL_CLI.split("/"))) : null : instalacion.carpetaDelPaquete;
5856
+ if (!carpetaDelPaquete) {
5857
+ throw new ErrorCli(
5858
+ `\xAB${legible(comando2)}\xBB termin\xF3 bien, pero no encuentro el CLI en la carpeta global de npm (${raizNpm ?? "npm root --global no respondi\xF3"}). Revisa con \xABredcumbre --version\xBB.`,
5859
+ CODIGOS_DE_SALIDA.error,
5860
+ { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
5861
+ );
5862
+ }
5863
+ const bundleNuevo = path17.join(carpetaDelPaquete, "dist", "redcumbre.js");
5864
+ const version = entorno.ejecutar(process.execPath, [bundleNuevo, "--version"], { cwd: ctx.cwd, env: ctx.env });
5865
+ if (version.status !== 0 || version.stdout.trim() !== disponible) {
5866
+ throw new ErrorCli(
5867
+ `\xAB${legible(comando2)}\xBB termin\xF3 bien, pero el CLI de ${carpetaDelPaquete} responde \xAB${version.stdout.trim() || version.stderr.trim()}\xBB y no ${disponible}. Revisa con \xABredcumbre --version\xBB.`,
5868
+ CODIGOS_DE_SALIDA.error,
5869
+ { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
5870
+ );
5536
5871
  }
5537
- if (instalacion.forma === "npx") salida.linea(`Listo: la skill qued\xF3 con la versi\xF3n ${disponible}. La pr\xF3xima vez corre \xABnpx ${PAQUETE_DEL_CLI}@latest\xBB para usar la \xFAltima.`);
5538
- else salida.linea(`\u2713 El CLI qued\xF3 en la versi\xF3n ${disponible}.`);
5872
+ const renovacion = entorno.ejecutar(process.execPath, [bundleNuevo, "skill", "renovar", "--json"], { cwd: ctx.cwd, env: ctx.env });
5873
+ const skill = renovacion.status === 0 ? leerJson2(renovacion.stdout)?.skill ?? null : null;
5874
+ if (skill === null) salida.aviso(`El CLI qued\xF3 en la versi\xF3n ${disponible}, pero no pude renovar la skill: corre \xABredcumbre skill renovar\xBB.`);
5875
+ salida.linea(instalacion.forma === "npx" ? `\u2713 El CLI qued\xF3 instalado en la versi\xF3n ${disponible}: desde ahora usa \xABredcumbre \u2026\xBB en vez de npx.` : `\u2713 El CLI qued\xF3 en la versi\xF3n ${disponible}.`);
5539
5876
  salida.resultado({ ok: true, actualizado: true, instalada: ctx.version, disponible, forma: instalacion.forma, comando: legible(comando2), skill });
5540
5877
  }
5541
5878
  function errorDeActualizacion(comando2, corrida) {
@@ -5610,7 +5947,7 @@ function errorDeUsoEnEspanol(mensaje) {
5610
5947
  }
5611
5948
  var TITULOS_AYUDA = { "Usage:": "Uso:", "Options:": "Opciones:", "Commands:": "Comandos:", "Arguments:": "Argumentos:" };
5612
5949
  var sumar = (valor, anteriores) => [...anteriores, valor];
5613
- var programa = new Command3().name("redcumbre").description("El CLI de REDCUMBRE: conecta tu proyecto en el modo de prueba, opera la API y pasa a producci\xF3n cuando est\xE9s listo.").version("0.5.0", "-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)}
5950
+ var programa = new Command3().name("redcumbre").description("El CLI de REDCUMBRE: conecta tu proyecto en el modo de prueba, opera la API y pasa a producci\xF3n cuando est\xE9s listo.").version("0.6.0", "-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)}
5614
5951
  `) }).exitOverride((error) => {
5615
5952
  if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.code === "commander.help") process.exit(0);
5616
5953
  if (process.argv.includes("--json")) {
@@ -5621,7 +5958,7 @@ var programa = new Command3().name("redcumbre").description("El CLI de REDCUMBRE
5621
5958
  });
5622
5959
  var sinNavegador = () => new Option3("--sin-navegador", "no abre el navegador: imprime la URL");
5623
5960
  var empresa = () => new Option3("--empresa <slug>", "la empresa (tenantSlug); por omisi\xF3n, la del proyecto");
5624
- comando(programa, "init", "conecta el proyecto: llave de prueba, puntero en .env, skill del integrador y una comprobaci\xF3n con la llave (no escribe c\xF3digo)").addOption(empresa()).addOption(new Option3("--entorno <modo>", "retirada: para producci\xF3n usa pasar-a-produccion").hideHelp()).option("--carpeta <ruta>", "carpeta del proyecto (por omisi\xF3n, la actual)").addOption(sinNavegador()).action((o) => correr(o, (ctx) => init(ctx, o)));
5961
+ comando(programa, "init", "conecta el proyecto: llave de prueba, puntero en .env, skill del integrador y una comprobaci\xF3n con la llave (no escribe c\xF3digo)").addOption(empresa()).addOption(new Option3("--entorno <modo>", "retirada: para producci\xF3n usa pasar-a-produccion").hideHelp()).option("--carpeta <ruta>", "carpeta del proyecto (por omisi\xF3n, la actual)").addOption(sinNavegador()).action((o) => correr(o, (ctx) => init(ctx, o), { ofreceInstalar: true }));
5625
5962
  comando(programa, "pasar-a-produccion", "revisa que todo est\xE9 en orden y agrega la llave de producci\xF3n al proyecto (una persona escribe el slug; sin terminal, --confirmar <slug>)").addOption(empresa()).option("--servicios <lista>", "los servicios que activas en producci\xF3n, separados por coma").option("--confirmar <slug>", "confirma sin preguntar: el slug de la empresa (obligatorio sin terminal o con --json)").option("--instalar <comando>", "despu\xE9s de crear la llave, corre este comando con la llave s\xF3lo en REDCUMBRE_VALOR_LLAVE_PRODUCCION").option("--comprobar <comando>", "con --instalar: corre este comando sin la llave; tiene que imprimir el whoami de la empresa en producci\xF3n").addOption(sinNavegador()).action((o) => correr(o, (ctx) => pasarAProduccion(ctx, o)));
5626
5963
  comando(programa, "login", "inicia sesi\xF3n con tu cuenta de REDCUMBRE (sin terminal o sin navegador, entrega el enlace y el c\xF3digo para que la persona los apruebe)").option("--completar", "termina el login: espera hasta 90 segundos a que la persona apruebe el c\xF3digo y guarda la sesi\xF3n").addOption(sinNavegador()).action((o) => correr(o, (ctx) => login(ctx, o)));
5627
5964
  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));
@@ -5655,6 +5992,7 @@ comando(programa, "consumo", "lo consumido del plan y los topes del d\xEDa").opt
5655
5992
  var comandoSkill = programa.command("skill").description("la skill del integrador que el CLI instala en tus carpetas de skills");
5656
5993
  comando(comandoSkill, "quitar", "quita la skill de tus carpetas y del proyecto, y no la vuelve a instalar").action((o) => correr(o, (ctx) => skillQuitar(ctx), { revisaPorSuCuenta: true }));
5657
5994
  comando(comandoSkill, "renovar", "renueva la skill donde ya est\xE1 con la de esta versi\xF3n del CLI (no toca lo que editaste)").option("--reemplazar-editada", "reemplaza tambi\xE9n la skill que editaste o copiaste a mano (pide confirmar)").option("--confirmar", "sin terminal, confirma el reemplazo de la skill editada").action((o) => correr(o, (ctx) => skillRenovar(ctx, o), { revisaPorSuCuenta: true }));
5995
+ comando(programa, "instalar", "deja instalado en este computador el CLI que corre por npx, en la misma versi\xF3n (pide confirmar)").option("--confirmar", "sin terminal, confirma la instalaci\xF3n: corre s\xF3lo despu\xE9s de que la persona acept\xF3").action((o) => correr(o, (ctx) => instalar(ctx, o), { revisaPorSuCuenta: true }));
5658
5996
  comando(programa, "actualizar", "actualiza el CLI a la \xFAltima versi\xF3n publicada y renueva la skill (pide confirmar)").option("--confirmar", "sin terminal, confirma la actualizaci\xF3n: corre s\xF3lo despu\xE9s de que la persona acept\xF3").action((o) => correr(o, (ctx) => actualizar(ctx, o), { revisaPorSuCuenta: true }));
5659
5997
  var comandoMcp = programa.command("mcp").description("el servidor MCP de REDCUMBRE en tu asistente de c\xF3digo");
5660
5998
  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)));