@redcumbrecl/cli 0.6.7 → 0.6.9
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 +1981 -1833
- package/dist/postinstall.js +15 -0
- package/dist/skill/commands/issue.md +7 -0
- package/dist/skill/commands/tarifas.md +9 -0
- package/dist/skill/redcumbre/SKILL.md +8 -3
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -1831,1911 +1831,2021 @@ function recortar(valor, campos) {
|
|
|
1831
1831
|
}
|
|
1832
1832
|
|
|
1833
1833
|
// src/comandos/doctor.ts
|
|
1834
|
+
import fs7 from "node:fs";
|
|
1835
|
+
import path7 from "node:path";
|
|
1836
|
+
|
|
1837
|
+
// src/nucleo/skill.ts
|
|
1838
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
1834
1839
|
import fs6 from "node:fs";
|
|
1835
1840
|
import path6 from "node:path";
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
const
|
|
1844
|
-
|
|
1845
|
-
haySesion ? { revision: "sesion", ok: true, detalle: "Hay una sesi\xF3n iniciada en este computador." } : { revision: "sesion", ok: false, detalle: "No hay una sesi\xF3n iniciada en este computador.", comando: "redcumbre login" }
|
|
1846
|
-
);
|
|
1847
|
-
const estado2 = leerEstado(proyecto);
|
|
1848
|
-
let slug = null;
|
|
1849
|
-
if (estado2) {
|
|
1850
|
-
slug = estado2.tenantSlug;
|
|
1851
|
-
anotar({ revision: "empresa", ok: true, detalle: `El proyecto ${proyecto} apunta a la empresa ${slug}.` });
|
|
1852
|
-
} else {
|
|
1853
|
-
anotar({ revision: "empresa", ok: false, detalle: `La carpeta ${proyecto} no est\xE1 conectada con REDCUMBRE (falta .redcumbre/estado.json).`, comando: COMANDO_INIT });
|
|
1841
|
+
import { fileURLToPath } from "node:url";
|
|
1842
|
+
var NOMBRE_SKILL = "redcumbre";
|
|
1843
|
+
var MARCA_INICIO = "<!-- redcumbre:inicio -->";
|
|
1844
|
+
var MARCA_FIN = "<!-- redcumbre:fin -->";
|
|
1845
|
+
var sha256 = (texto2) => createHash("sha256").update(texto2).digest("hex");
|
|
1846
|
+
function carpetaDeLaSkill(aqui = path6.dirname(fileURLToPath(import.meta.url))) {
|
|
1847
|
+
const candidatas = [path6.join(aqui, "skill"), path6.join(aqui, "..", "skill"), path6.join(aqui, "..", "..", "skill")];
|
|
1848
|
+
for (const candidata of candidatas) {
|
|
1849
|
+
if (fs6.existsSync(path6.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
|
|
1854
1850
|
}
|
|
1855
|
-
|
|
1856
|
-
|
|
1851
|
+
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, {
|
|
1852
|
+
codigo: "PAQUETE_INCOMPLETO"
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
var ARCHIVO_FUENTE = {
|
|
1856
|
+
skill: [NOMBRE_SKILL, "SKILL.md"],
|
|
1857
|
+
tarifas: ["commands", "tarifas.md"],
|
|
1858
|
+
issue: ["commands", "issue.md"]
|
|
1859
|
+
};
|
|
1860
|
+
function contenidoEmpaquetado(fuenteDeRuta, fuente) {
|
|
1861
|
+
const carpeta = fuente ?? carpetaDeLaSkill();
|
|
1862
|
+
const archivo = path6.join(carpeta, ...ARCHIVO_FUENTE[fuenteDeRuta]);
|
|
1863
|
+
if (!fs6.existsSync(archivo)) {
|
|
1864
|
+
throw new ErrorCli(`El paquete del CLI est\xE1 incompleto: falta ${ARCHIVO_FUENTE[fuenteDeRuta].join("/")}. Reinstala el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`, CODIGOS_DE_SALIDA.error, {
|
|
1865
|
+
codigo: "PAQUETE_INCOMPLETO"
|
|
1866
|
+
});
|
|
1857
1867
|
}
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
const
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1868
|
+
return fs6.readFileSync(archivo, "utf8");
|
|
1869
|
+
}
|
|
1870
|
+
function contenidoPorFuente(version, fuente) {
|
|
1871
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1872
|
+
return (f) => {
|
|
1873
|
+
let texto2 = cache.get(f);
|
|
1874
|
+
if (texto2 === void 0) {
|
|
1875
|
+
texto2 = contenidoParaInstalar(contenidoEmpaquetado(f, fuente), version);
|
|
1876
|
+
cache.set(f, texto2);
|
|
1877
|
+
}
|
|
1878
|
+
return texto2;
|
|
1879
|
+
};
|
|
1880
|
+
}
|
|
1881
|
+
var LINEA_DE_VERSION = /^<!-- redcumbre-cli: (\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?) -->$/m;
|
|
1882
|
+
var FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---\r?\n/;
|
|
1883
|
+
var lineaDeVersion = (version) => `<!-- redcumbre-cli: ${version} -->`;
|
|
1884
|
+
function contenidoParaInstalar(fuente, version) {
|
|
1885
|
+
const frontmatter = fuente.match(FRONTMATTER);
|
|
1886
|
+
if (!frontmatter) {
|
|
1887
|
+
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, {
|
|
1888
|
+
codigo: "PAQUETE_INCOMPLETO"
|
|
1869
1889
|
});
|
|
1870
|
-
} else if (faltanExclusiones.length > 0) {
|
|
1871
|
-
anotar({ revision: "exclusiones", ok: false, detalle: `Al .gitignore le falta ${faltanExclusiones.join(" y ")}.`, comando: COMANDO_INIT });
|
|
1872
|
-
} else {
|
|
1873
|
-
anotar({ revision: "exclusiones", ok: true, detalle: "keys/ y .redcumbre/ est\xE1n fuera del control de versiones." });
|
|
1874
1890
|
}
|
|
1891
|
+
const sinLinea = fuente.slice(frontmatter[0].length).replace(/^<!-- redcumbre-cli: [^\n]* -->\r?\n/, "");
|
|
1892
|
+
return `${frontmatter[0]}${lineaDeVersion(version)}
|
|
1893
|
+
${sinLinea}`;
|
|
1894
|
+
}
|
|
1895
|
+
function versionDeLaSkill(texto2) {
|
|
1896
|
+
return texto2.match(LINEA_DE_VERSION)?.[1] ?? null;
|
|
1897
|
+
}
|
|
1898
|
+
var CODIGOS_TRANSITORIOS_WINDOWS = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
1899
|
+
function esperarSincrono(ms) {
|
|
1900
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
1901
|
+
}
|
|
1902
|
+
function esErrorTransitorioDeWindows(error) {
|
|
1903
|
+
const codigo = error?.code;
|
|
1904
|
+
return typeof codigo === "string" && CODIGOS_TRANSITORIOS_WINDOWS.has(codigo);
|
|
1905
|
+
}
|
|
1906
|
+
function conReintentoEnWindows(operacion, opciones = {}) {
|
|
1907
|
+
const { plataforma = process.platform, esperar = esperarSincrono, presupuestoMs = 2500 } = opciones;
|
|
1908
|
+
let espera = 10;
|
|
1909
|
+
let gastado = 0;
|
|
1910
|
+
for (; ; ) {
|
|
1911
|
+
try {
|
|
1912
|
+
return operacion();
|
|
1913
|
+
} catch (error) {
|
|
1914
|
+
if (plataforma !== "win32" || !esErrorTransitorioDeWindows(error) || gastado >= presupuestoMs) throw error;
|
|
1915
|
+
const ms = Math.min(espera, presupuestoMs - gastado);
|
|
1916
|
+
esperar(ms);
|
|
1917
|
+
gastado += ms;
|
|
1918
|
+
espera = Math.min(espera * 2, 100);
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
function escribirAtomico(ruta, contenido) {
|
|
1923
|
+
fs6.mkdirSync(path6.dirname(ruta), { recursive: true });
|
|
1924
|
+
const temporal = `${ruta}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
1875
1925
|
try {
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
revision: "documento",
|
|
1879
|
-
ok: true,
|
|
1880
|
-
detalle: documento.copiaSinRevalidar ? `Uso la copia del documento del API sin revalidar (${documento.operaciones.length} operaciones).` : `El documento del API est\xE1 al d\xEDa (${documento.operaciones.length} operaciones).`
|
|
1881
|
-
});
|
|
1926
|
+
fs6.writeFileSync(temporal, contenido);
|
|
1927
|
+
conReintentoEnWindows(() => fs6.renameSync(temporal, ruta));
|
|
1882
1928
|
} catch (error) {
|
|
1883
|
-
|
|
1929
|
+
fs6.rmSync(temporal, { force: true });
|
|
1930
|
+
throw error;
|
|
1884
1931
|
}
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1932
|
+
}
|
|
1933
|
+
function bloqueDeAgents() {
|
|
1934
|
+
return [
|
|
1935
|
+
MARCA_INICIO,
|
|
1936
|
+
"## REDCUMBRE",
|
|
1937
|
+
"",
|
|
1938
|
+
"Este proyecto se integra con la API de REDCUMBRE por medio del CLI `redcumbre`. Antes de tocar la integraci\xF3n lee la",
|
|
1939
|
+
"skill `redcumbre` (`.agents/skills/redcumbre/SKILL.md`). En resumen: busca la operaci\xF3n (`redcumbre buscar`), lee su",
|
|
1940
|
+
"contrato (`redcumbre api describir`), pru\xE9bala con `--ensayo`, consulta las fichas (`redcumbre guia`) y verifica el",
|
|
1941
|
+
"sitio (`redcumbre prueba verificar`). No leas ni imprimas `keys/`. Pasar a producci\xF3n lo confirma una persona.",
|
|
1942
|
+
"Si la persona escribe `redcumbre:tarifas` o `redcumbre:issue`, sigue las secciones 9 y 8 de la skill.",
|
|
1943
|
+
"H\xE1blale a la persona en espa\xF1ol, salvo que ella te escriba en otro idioma.",
|
|
1944
|
+
MARCA_FIN
|
|
1945
|
+
].join("\n");
|
|
1946
|
+
}
|
|
1947
|
+
var rutaRegistroUsuario = (d) => path6.join(d.carpetaConfiguracion, "skill.json");
|
|
1948
|
+
var rutaEstadoDelProyecto = (proyecto) => path6.join(proyecto, ".redcumbre", "estado.json");
|
|
1949
|
+
function leerJson(ruta) {
|
|
1950
|
+
if (!fs6.existsSync(ruta)) return null;
|
|
1951
|
+
let texto2;
|
|
1952
|
+
try {
|
|
1953
|
+
texto2 = conReintentoEnWindows(() => fs6.readFileSync(ruta, "utf8"));
|
|
1954
|
+
} catch (error) {
|
|
1955
|
+
if (esErrorTransitorioDeWindows(error)) throw error;
|
|
1956
|
+
return null;
|
|
1957
|
+
}
|
|
1958
|
+
try {
|
|
1959
|
+
const dato = JSON.parse(texto2);
|
|
1960
|
+
return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
|
|
1961
|
+
} catch {
|
|
1962
|
+
return null;
|
|
1896
1963
|
}
|
|
1897
|
-
salida.linea("Todo en orden.");
|
|
1898
|
-
salida.resultado({ ok: true, proyecto, revisiones, faltantes: [], version });
|
|
1899
1964
|
}
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1965
|
+
function escribirJson(ruta, dato) {
|
|
1966
|
+
escribirAtomico(ruta, `${JSON.stringify(dato, null, 2)}
|
|
1967
|
+
`);
|
|
1968
|
+
}
|
|
1969
|
+
function leerRegistroUsuario(d) {
|
|
1970
|
+
return leerJson(rutaRegistroUsuario(d)) ?? {};
|
|
1971
|
+
}
|
|
1972
|
+
function guardarRegistroUsuario(d, registro) {
|
|
1973
|
+
escribirJson(rutaRegistroUsuario(d), registro);
|
|
1974
|
+
}
|
|
1975
|
+
function leerRegistroProyecto(proyecto) {
|
|
1976
|
+
const estado2 = leerJson(rutaEstadoDelProyecto(proyecto));
|
|
1977
|
+
return estado2?.skill ?? {};
|
|
1978
|
+
}
|
|
1979
|
+
function guardarRegistroProyecto(proyecto, registro) {
|
|
1980
|
+
const ruta = rutaEstadoDelProyecto(proyecto);
|
|
1981
|
+
const estado2 = leerJson(ruta) ?? {};
|
|
1982
|
+
escribirJson(ruta, { ...estado2, skill: registro });
|
|
1983
|
+
}
|
|
1984
|
+
var COMANDOS = ["tarifas", "issue"];
|
|
1985
|
+
function objetivos(d) {
|
|
1986
|
+
const deAmbito = (raiz, ambito, prefijo) => [
|
|
1987
|
+
{ id: `claude-${ambito}`, archivo: path6.join(raiz, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `${prefijo}.claude/skills/${NOMBRE_SKILL}/SKILL.md`, fuente: "skill" },
|
|
1988
|
+
{ id: `agents-${ambito}`, archivo: path6.join(raiz, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `${prefijo}.agents/skills/${NOMBRE_SKILL}/SKILL.md`, fuente: "skill" },
|
|
1989
|
+
...COMANDOS.map(
|
|
1990
|
+
(comando2) => ({
|
|
1991
|
+
id: `claude-${ambito}-${comando2}`,
|
|
1992
|
+
archivo: path6.join(raiz, ".claude", "commands", NOMBRE_SKILL, `${comando2}.md`),
|
|
1993
|
+
legible: `${prefijo}.claude/commands/${NOMBRE_SKILL}/${comando2}.md`,
|
|
1994
|
+
fuente: comando2
|
|
1995
|
+
})
|
|
1996
|
+
)
|
|
1997
|
+
];
|
|
1998
|
+
const lista2 = deAmbito(d.home, "usuario", "~/");
|
|
1999
|
+
if (d.proyecto) lista2.push(...deAmbito(d.proyecto, "proyecto", ""));
|
|
2000
|
+
return lista2;
|
|
2001
|
+
}
|
|
2002
|
+
var esDeUsuario = (id) => id.includes("-usuario");
|
|
2003
|
+
function resumir2(rutas, quitada) {
|
|
2004
|
+
let estado2 = "sin-cambios";
|
|
2005
|
+
if (quitada) estado2 = "quitada";
|
|
2006
|
+
else if (rutas.some((r) => r.accion === "editada")) estado2 = "editada";
|
|
2007
|
+
else if (rutas.some((r) => r.accion === "reemplazada-editada")) estado2 = "reemplazada-editada";
|
|
2008
|
+
else if (rutas.some((r) => r.accion === "instalada")) estado2 = "instalada";
|
|
2009
|
+
else if (rutas.some((r) => r.accion === "actualizada")) estado2 = "actualizada";
|
|
2010
|
+
return { estado: estado2, rutas };
|
|
2011
|
+
}
|
|
2012
|
+
var marcaDeTiempoDeLaCopia = (ahora) => ahora.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
|
|
2013
|
+
function guardarCopiaDeLoEditado(archivo, ahora) {
|
|
2014
|
+
const base = `${archivo}.editada-${marcaDeTiempoDeLaCopia(ahora)}`;
|
|
2015
|
+
for (let n = 1; n < 100; n++) {
|
|
2016
|
+
const destino = n === 1 ? base : `${base}-${n}`;
|
|
2017
|
+
try {
|
|
2018
|
+
conReintentoEnWindows(() => fs6.copyFileSync(archivo, destino, fs6.constants.COPYFILE_EXCL));
|
|
2019
|
+
return path6.resolve(destino);
|
|
2020
|
+
} catch (error) {
|
|
2021
|
+
if (error.code === "EEXIST") continue;
|
|
2022
|
+
throw error;
|
|
2023
|
+
}
|
|
1907
2024
|
}
|
|
1908
|
-
|
|
1909
|
-
|
|
2025
|
+
throw new Error(`ya hay demasiadas copias de ${archivo} con la misma hora`);
|
|
2026
|
+
}
|
|
2027
|
+
var motivoDe = (error) => error instanceof Error ? error.message : String(error);
|
|
2028
|
+
function reconciliar(archivo, nuevo, registrado, ahora) {
|
|
2029
|
+
const hashNuevo = sha256(nuevo);
|
|
2030
|
+
const existe = fs6.existsSync(archivo);
|
|
2031
|
+
if (!existe) {
|
|
2032
|
+
if (registrado) return { accion: "borrada", hash: null };
|
|
2033
|
+
escribirAtomico(archivo, nuevo);
|
|
2034
|
+
return { accion: "instalada", hash: hashNuevo };
|
|
2035
|
+
}
|
|
2036
|
+
const hashActual = sha256(conReintentoEnWindows(() => fs6.readFileSync(archivo)));
|
|
2037
|
+
if (registrado === void 0) {
|
|
2038
|
+
if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
|
|
2039
|
+
return reemplazarConCopia(archivo, nuevo, hashNuevo, ahora);
|
|
1910
2040
|
}
|
|
2041
|
+
if (hashActual !== registrado) return hashActual === hashNuevo ? { accion: "sin-cambios", hash: hashNuevo } : reemplazarConCopia(archivo, nuevo, hashNuevo, ahora);
|
|
2042
|
+
if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
|
|
2043
|
+
escribirAtomico(archivo, nuevo);
|
|
2044
|
+
return { accion: "actualizada", hash: hashNuevo };
|
|
2045
|
+
}
|
|
2046
|
+
function reemplazarConCopia(archivo, nuevo, hashNuevo, ahora) {
|
|
2047
|
+
let copia;
|
|
1911
2048
|
try {
|
|
1912
|
-
|
|
1913
|
-
if (r.estado === "rechazada") return { revision, ok: false, detalle: `La API rechaza la ${nombre} (${ruta}): fue revocada o venci\xF3.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_PRODUCCION };
|
|
1914
|
-
if (r.sandbox !== (entorno === "prueba")) {
|
|
1915
|
-
return { revision, ok: false, detalle: `El archivo ${ruta} no trae una ${nombre}: seg\xFAn la API es de otro modo.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_PRODUCCION };
|
|
1916
|
-
}
|
|
1917
|
-
return { revision, ok: true, detalle: `La ${nombre} funciona (${r.tenant.nombre}).` };
|
|
2049
|
+
copia = guardarCopiaDeLoEditado(archivo, ahora);
|
|
1918
2050
|
} catch (error) {
|
|
1919
|
-
return {
|
|
2051
|
+
return { accion: "editada", hash: null, error: motivoDe(error) };
|
|
1920
2052
|
}
|
|
2053
|
+
escribirAtomico(archivo, nuevo);
|
|
2054
|
+
return { accion: "reemplazada-editada", hash: hashNuevo, copia };
|
|
1921
2055
|
}
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
const abierto = opciones.sinNavegador ? false : await ctx.abrir(url);
|
|
1926
|
-
ctx.salida.linea(abierto ? `Abr\xED el panel de ${slug} en el navegador: ${url}` : `El panel de ${slug}: ${url}`);
|
|
1927
|
-
ctx.salida.resultado({ ok: true, empresa: slug, url, abierto });
|
|
2056
|
+
var regexBloque = () => new RegExp(`${MARCA_INICIO.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${MARCA_FIN.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
|
|
2057
|
+
function extraerBloque(texto2) {
|
|
2058
|
+
return texto2.match(regexBloque())?.[0] ?? null;
|
|
1928
2059
|
}
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
var INTEGRACION_FILTRO = { bandera: "--integracion <tipo>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "tipoIntegracion" } };
|
|
1938
|
-
var CREDENCIAL_FILTRO = { bandera: "--credencial <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "credencialEstado" } };
|
|
1939
|
-
var ACTIVO_FILTRO = { bandera: "--activo <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "activo" }, valores: ["true", "false"] };
|
|
1940
|
-
var TRIBUTARIA_FILTRO = { bandera: "--tributaria <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "esTributaria" }, valores: ["true", "false"] };
|
|
1941
|
-
var LIMITE = { bandera: "--limite <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "limit" } };
|
|
1942
|
-
var DESDE = { bandera: "--desde <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "offset" } };
|
|
1943
|
-
var TODAS = { bandera: "--todas", obligatoria: false, tipo: "interruptor", destino: { en: "ninguno" } };
|
|
1944
|
-
var INCLUIR_ARCHIVADOS = { bandera: "--incluir-archivados", obligatoria: false, tipo: "interruptor", destino: { en: "consulta", nombre: "includeInactive", valorFijo: "true" } };
|
|
1945
|
-
var CUERPO_OBLIGATORIO = { bandera: "--cuerpo <json|@archivo|->", obligatoria: true, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
|
|
1946
|
-
var CUERPO_OPCIONAL = { bandera: "--cuerpo <json|@archivo|->", obligatoria: false, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
|
|
1947
|
-
var ARCHIVO_LOGO = { bandera: "--archivo <ruta>", obligatoria: true, tipo: "archivo", destino: { en: "formulario", nombre: "logo" } };
|
|
1948
|
-
var TIPOS_DE_CERTIFICACION = { bandera: "--tipos <lista>", obligatoria: true, tipo: "lista-de-enteros", destino: { en: "cuerpo", nombre: "tiposDte" } };
|
|
1949
|
-
var CORREO_DE_CONTACTO = { bandera: "--correo <correo>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "emailContacto" } };
|
|
1950
|
-
var TELEFONO_DE_CONTACTO = { bandera: "--telefono <tel\xE9fono>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "telefonoContacto" } };
|
|
1951
|
-
var RUT_DE_CONFIRMACION = { bandera: "--rut <rut>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "confirmacionRut" } };
|
|
1952
|
-
var MOTIVO_OPCIONAL = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivo" } };
|
|
1953
|
-
var TIPO_DTE_DEL_AMBIENTE = { bandera: "--tipo-dte <n>", obligatoria: true, tipo: "entero", destino: { en: "cuerpo", nombre: "tipoDte" } };
|
|
1954
|
-
var AMBIENTE_DEL_TIPO = { bandera: "--ambiente <CERTIFICACION|PRODUCCION>", obligatoria: true, tipo: "ambiente", destino: { en: "cuerpo", nombre: "ambiente" }, valores: ["CERTIFICACION", "PRODUCCION"] };
|
|
1955
|
-
var TIPO_DE_EMISOR_A_REVOCAR = { bandera: "--tipo <tributario|dte>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "tipoEmisor" }, valores: ["tributario", "dte"] };
|
|
1956
|
-
var MOTIVO_DE_REVOCACION = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivoRevocacion" } };
|
|
1957
|
-
var OPERACIONES_EMISORES = [
|
|
1958
|
-
{
|
|
1959
|
-
// 1
|
|
1960
|
-
comando: ["dte", "listar"],
|
|
1961
|
-
operationId: "listarEmisoresDte",
|
|
1962
|
-
metodo: "GET",
|
|
1963
|
-
ruta: "/{tenantSlug}/emisores",
|
|
1964
|
-
argumentos: [],
|
|
1965
|
-
banderas: [RUT_FILTRO, ESTADO_FILTRO, INTEGRACION_FILTRO, LIMITE, DESDE, TODAS],
|
|
1966
|
-
salida: "tabla",
|
|
1967
|
-
columnas: ["emisorId", "rut", "razonSocial", "tipoIntegracion", "estado"],
|
|
1968
|
-
confirmacion: "efecto"
|
|
1969
|
-
},
|
|
1970
|
-
{
|
|
1971
|
-
// 2
|
|
1972
|
-
comando: ["dte", "por-defecto"],
|
|
1973
|
-
operationId: "listarEmisoresDtePorDefecto",
|
|
1974
|
-
metodo: "GET",
|
|
1975
|
-
ruta: "/{tenantSlug}/emisores/default",
|
|
1976
|
-
argumentos: [],
|
|
1977
|
-
banderas: [],
|
|
1978
|
-
salida: "tabla",
|
|
1979
|
-
columnas: ["emisorId", "rut", "razonSocial", "tipoIntegracion"],
|
|
1980
|
-
confirmacion: "efecto"
|
|
1981
|
-
},
|
|
1982
|
-
{
|
|
1983
|
-
// 3
|
|
1984
|
-
comando: ["dte", "existe"],
|
|
1985
|
-
operationId: "verificarRutEmisorDte",
|
|
1986
|
-
metodo: "GET",
|
|
1987
|
-
ruta: "/{tenantSlug}/emisores/check-rut/{rut}",
|
|
1988
|
-
argumentos: ["rut"],
|
|
1989
|
-
banderas: [],
|
|
1990
|
-
salida: "ficha",
|
|
1991
|
-
confirmacion: "efecto"
|
|
1992
|
-
},
|
|
1993
|
-
{
|
|
1994
|
-
// 4
|
|
1995
|
-
comando: ["dte", "ver"],
|
|
1996
|
-
operationId: "obtenerEmisorDte",
|
|
1997
|
-
metodo: "GET",
|
|
1998
|
-
ruta: "/{tenantSlug}/emisores/{id}",
|
|
1999
|
-
argumentos: ["id"],
|
|
2000
|
-
banderas: [INCLUIR_ARCHIVADOS],
|
|
2001
|
-
salida: "ficha",
|
|
2002
|
-
confirmacion: "efecto"
|
|
2003
|
-
},
|
|
2004
|
-
{
|
|
2005
|
-
// 5
|
|
2006
|
-
comando: ["dte", "certificacion", "verificar"],
|
|
2007
|
-
operationId: "verificarCertificacionTipoEmisorDte",
|
|
2008
|
-
metodo: "GET",
|
|
2009
|
-
ruta: "/{tenantSlug}/emisores/{id}/verificar-certificacion/{tipoDte}",
|
|
2010
|
-
argumentos: ["id", "tipoDte"],
|
|
2011
|
-
banderas: [],
|
|
2012
|
-
salida: "ficha",
|
|
2013
|
-
confirmacion: "efecto"
|
|
2014
|
-
},
|
|
2015
|
-
{
|
|
2016
|
-
// 6
|
|
2017
|
-
comando: ["dte", "certificacion", "tipos"],
|
|
2018
|
-
operationId: "listarTiposCertificablesEmisorDte",
|
|
2019
|
-
metodo: "GET",
|
|
2020
|
-
ruta: "/{tenantSlug}/emisores/{id}/tipos-dte-certificables",
|
|
2021
|
-
argumentos: ["id"],
|
|
2022
|
-
banderas: [],
|
|
2023
|
-
salida: "ficha",
|
|
2024
|
-
confirmacion: "efecto"
|
|
2025
|
-
},
|
|
2026
|
-
{
|
|
2027
|
-
// 7
|
|
2028
|
-
comando: ["dte", "certificacion", "estado"],
|
|
2029
|
-
operationId: "consultarEstadoCertificacionRutEmisorDte",
|
|
2030
|
-
metodo: "GET",
|
|
2031
|
-
ruta: "/{tenantSlug}/emisores/{id}/estado-certificacion-rut",
|
|
2032
|
-
argumentos: ["id"],
|
|
2033
|
-
banderas: [],
|
|
2034
|
-
salida: "ficha",
|
|
2035
|
-
confirmacion: "efecto"
|
|
2036
|
-
},
|
|
2037
|
-
{
|
|
2038
|
-
// 8
|
|
2039
|
-
comando: ["dte", "mipyme", "estado"],
|
|
2040
|
-
operationId: "consultarEstadoMipymeEmisorDte",
|
|
2041
|
-
metodo: "GET",
|
|
2042
|
-
ruta: "/{tenantSlug}/emisores/{id}/mipyme/estado",
|
|
2043
|
-
argumentos: ["id"],
|
|
2044
|
-
banderas: [],
|
|
2045
|
-
salida: "ficha",
|
|
2046
|
-
confirmacion: "efecto"
|
|
2047
|
-
},
|
|
2048
|
-
{
|
|
2049
|
-
// 9
|
|
2050
|
-
comando: ["dte", "solicitudes"],
|
|
2051
|
-
operationId: "listarSolicitudesCertificacionEmisorDte",
|
|
2052
|
-
metodo: "GET",
|
|
2053
|
-
ruta: "/{tenantSlug}/emisores/{id}/solicitudes",
|
|
2054
|
-
argumentos: ["id"],
|
|
2055
|
-
banderas: [],
|
|
2056
|
-
salida: "tabla",
|
|
2057
|
-
columnas: ["solicitudId", "tipoSolicitud", "estado", "solicitadoEn"],
|
|
2058
|
-
confirmacion: "efecto"
|
|
2059
|
-
},
|
|
2060
|
-
{
|
|
2061
|
-
// 10
|
|
2062
|
-
comando: ["dte", "logo", "ver"],
|
|
2063
|
-
operationId: "obtenerLogoEmisorDte",
|
|
2064
|
-
metodo: "GET",
|
|
2065
|
-
ruta: "/{tenantSlug}/emisores/{id}/logo",
|
|
2066
|
-
argumentos: ["id"],
|
|
2067
|
-
banderas: [],
|
|
2068
|
-
salida: "ficha",
|
|
2069
|
-
confirmacion: "efecto"
|
|
2070
|
-
},
|
|
2071
|
-
{
|
|
2072
|
-
// 11
|
|
2073
|
-
comando: ["dte", "editar"],
|
|
2074
|
-
operationId: "actualizarEmisorDte",
|
|
2075
|
-
metodo: "PATCH",
|
|
2076
|
-
ruta: "/{tenantSlug}/emisores/{id}",
|
|
2077
|
-
argumentos: ["id"],
|
|
2078
|
-
banderas: [CUERPO_OBLIGATORIO],
|
|
2079
|
-
salida: "accion",
|
|
2080
|
-
hecho: "Emisor actualizado.",
|
|
2081
|
-
confirmacion: "efecto"
|
|
2082
|
-
},
|
|
2083
|
-
{
|
|
2084
|
-
// 12
|
|
2085
|
-
comando: ["dte", "fijar-por-defecto"],
|
|
2086
|
-
operationId: "asignarEmisorDtePorDefecto",
|
|
2087
|
-
metodo: "PATCH",
|
|
2088
|
-
ruta: "/{tenantSlug}/emisores/{id}/set-default",
|
|
2089
|
-
argumentos: ["id"],
|
|
2090
|
-
banderas: [],
|
|
2091
|
-
salida: "accion",
|
|
2092
|
-
hecho: "Emisor fijado por defecto.",
|
|
2093
|
-
confirmacion: "efecto"
|
|
2094
|
-
},
|
|
2095
|
-
{
|
|
2096
|
-
// 13
|
|
2097
|
-
comando: ["dte", "reactivar"],
|
|
2098
|
-
operationId: "reactivarEmisorDte",
|
|
2099
|
-
metodo: "PATCH",
|
|
2100
|
-
ruta: "/{tenantSlug}/emisores/{id}/reactivate",
|
|
2101
|
-
argumentos: ["id"],
|
|
2102
|
-
banderas: [CUERPO_OPCIONAL],
|
|
2103
|
-
salida: "accion",
|
|
2104
|
-
hecho: "Emisor reactivado.",
|
|
2105
|
-
confirmacion: "efecto"
|
|
2106
|
-
},
|
|
2107
|
-
{
|
|
2108
|
-
// 14
|
|
2109
|
-
comando: ["dte", "tipos-integracion", "crear"],
|
|
2110
|
-
operationId: "crearTipoIntegracionEmisorDte",
|
|
2111
|
-
metodo: "POST",
|
|
2112
|
-
ruta: "/{tenantSlug}/emisores/{id}/tipos-integracion",
|
|
2113
|
-
argumentos: ["id"],
|
|
2114
|
-
banderas: [CUERPO_OBLIGATORIO],
|
|
2115
|
-
salida: "accion",
|
|
2116
|
-
hecho: "Tipo de integraci\xF3n creado.",
|
|
2117
|
-
confirmacion: "efecto"
|
|
2118
|
-
},
|
|
2119
|
-
{
|
|
2120
|
-
// 15
|
|
2121
|
-
comando: ["dte", "tipos-integracion", "editar"],
|
|
2122
|
-
operationId: "actualizarTipoIntegracionEmisorDte",
|
|
2123
|
-
metodo: "PATCH",
|
|
2124
|
-
ruta: "/{tenantSlug}/emisores/{id}/tipos-integracion/{tiId}",
|
|
2125
|
-
argumentos: ["id", "tiId"],
|
|
2126
|
-
banderas: [CUERPO_OBLIGATORIO],
|
|
2127
|
-
salida: "accion",
|
|
2128
|
-
hecho: "Tipo de integraci\xF3n actualizado.",
|
|
2129
|
-
confirmacion: "efecto"
|
|
2130
|
-
},
|
|
2131
|
-
{
|
|
2132
|
-
// 16
|
|
2133
|
-
comando: ["dte", "logo", "subir"],
|
|
2134
|
-
operationId: "actualizarLogoEmisorDte",
|
|
2135
|
-
metodo: "POST",
|
|
2136
|
-
ruta: "/{tenantSlug}/emisores/{id}/logo",
|
|
2137
|
-
argumentos: ["id"],
|
|
2138
|
-
banderas: [ARCHIVO_LOGO],
|
|
2139
|
-
salida: "accion",
|
|
2140
|
-
hecho: "Logo actualizado.",
|
|
2141
|
-
confirmacion: "efecto"
|
|
2142
|
-
},
|
|
2143
|
-
{
|
|
2144
|
-
// 17
|
|
2145
|
-
comando: ["dte", "logo", "quitar"],
|
|
2146
|
-
operationId: "eliminarLogoEmisorDte",
|
|
2147
|
-
metodo: "DELETE",
|
|
2148
|
-
ruta: "/{tenantSlug}/emisores/{id}/logo",
|
|
2149
|
-
argumentos: ["id"],
|
|
2150
|
-
banderas: [],
|
|
2151
|
-
salida: "accion",
|
|
2152
|
-
hecho: "Logo eliminado.",
|
|
2153
|
-
confirmacion: "efecto"
|
|
2154
|
-
},
|
|
2155
|
-
{
|
|
2156
|
-
// 18
|
|
2157
|
-
comando: ["dte", "info-pago", "guardar"],
|
|
2158
|
-
operationId: "actualizarInfoPagoEmisorDte",
|
|
2159
|
-
metodo: "PUT",
|
|
2160
|
-
ruta: "/{tenantSlug}/emisores/{id}/info-pago",
|
|
2161
|
-
argumentos: ["id"],
|
|
2162
|
-
banderas: [CUERPO_OBLIGATORIO],
|
|
2163
|
-
salida: "accion",
|
|
2164
|
-
hecho: "Informaci\xF3n de pago guardada.",
|
|
2165
|
-
confirmacion: "efecto"
|
|
2166
|
-
},
|
|
2167
|
-
{
|
|
2168
|
-
// 19
|
|
2169
|
-
comando: ["dte", "info-pago", "quitar"],
|
|
2170
|
-
operationId: "eliminarInfoPagoEmisorDte",
|
|
2171
|
-
metodo: "DELETE",
|
|
2172
|
-
ruta: "/{tenantSlug}/emisores/{id}/info-pago",
|
|
2173
|
-
argumentos: ["id"],
|
|
2174
|
-
banderas: [],
|
|
2175
|
-
salida: "accion",
|
|
2176
|
-
hecho: "Informaci\xF3n de pago eliminada.",
|
|
2177
|
-
confirmacion: "efecto"
|
|
2178
|
-
},
|
|
2179
|
-
{
|
|
2180
|
-
// 20
|
|
2181
|
-
comando: ["dte", "resolver-conflictos"],
|
|
2182
|
-
operationId: "resolverConflictosEmisorDte",
|
|
2183
|
-
metodo: "POST",
|
|
2184
|
-
ruta: "/{tenantSlug}/emisores/{id}/resolver-conflictos",
|
|
2185
|
-
argumentos: ["id"],
|
|
2186
|
-
banderas: [CUERPO_OBLIGATORIO],
|
|
2187
|
-
salida: "accion",
|
|
2188
|
-
hecho: "Conflictos resueltos.",
|
|
2189
|
-
confirmacion: "efecto"
|
|
2190
|
-
},
|
|
2191
|
-
{
|
|
2192
|
-
// 21
|
|
2193
|
-
comando: ["dte", "certificacion", "certificar-tipos"],
|
|
2194
|
-
operationId: "crearSolicitudCertificacionTiposEmisorDte",
|
|
2195
|
-
metodo: "POST",
|
|
2196
|
-
ruta: "/{tenantSlug}/emisores/{id}/certificar-tipos",
|
|
2197
|
-
argumentos: ["id"],
|
|
2198
|
-
banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
|
|
2199
|
-
salida: "accion",
|
|
2200
|
-
hecho: "Certificaci\xF3n de tipos solicitada.",
|
|
2201
|
-
confirmacion: "escrita",
|
|
2202
|
-
aviso: "Esto le pide al SII certificar al contribuyente, con el RUT de su representante legal."
|
|
2203
|
-
},
|
|
2204
|
-
{
|
|
2205
|
-
// 22
|
|
2206
|
-
comando: ["dte", "migrar"],
|
|
2207
|
-
operationId: "crearSolicitudMigracionEmisorDte",
|
|
2208
|
-
metodo: "POST",
|
|
2209
|
-
ruta: "/{tenantSlug}/emisores/{id}/migrar",
|
|
2210
|
-
argumentos: ["id"],
|
|
2211
|
-
banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
|
|
2212
|
-
salida: "accion",
|
|
2213
|
-
hecho: "Migraci\xF3n solicitada.",
|
|
2214
|
-
confirmacion: "escrita",
|
|
2215
|
-
aviso: "Esto le pide al SII migrar el sistema de facturaci\xF3n del contribuyente. Puede dejar sin uso los folios que tenga."
|
|
2216
|
-
},
|
|
2217
|
-
{
|
|
2218
|
-
// 23
|
|
2219
|
-
comando: ["dte", "certificacion", "desistir"],
|
|
2220
|
-
operationId: "cancelarCertificacionEmisorDte",
|
|
2221
|
-
metodo: "POST",
|
|
2222
|
-
ruta: "/{tenantSlug}/emisores/{id}/desistir-certificacion",
|
|
2223
|
-
argumentos: ["id"],
|
|
2224
|
-
banderas: [RUT_DE_CONFIRMACION, MOTIVO_OPCIONAL],
|
|
2225
|
-
salida: "accion",
|
|
2226
|
-
hecho: "Desististe de la certificaci\xF3n.",
|
|
2227
|
-
confirmacion: "escrita",
|
|
2228
|
-
aviso: "Esto archiva el emisor y cierra sus solicitudes de certificaci\xF3n."
|
|
2229
|
-
},
|
|
2230
|
-
{
|
|
2231
|
-
// 24
|
|
2232
|
-
comando: ["dte", "mipyme", "habilitar"],
|
|
2233
|
-
operationId: "registrarEmisorDteEnPortalMipyme",
|
|
2234
|
-
metodo: "POST",
|
|
2235
|
-
ruta: "/{tenantSlug}/emisores/{id}/mipyme/habilitar",
|
|
2236
|
-
argumentos: ["id"],
|
|
2237
|
-
banderas: [],
|
|
2238
|
-
salida: "accion",
|
|
2239
|
-
hecho: "Portal MiPyme habilitado.",
|
|
2240
|
-
confirmacion: "escrita",
|
|
2241
|
-
aviso: "Esto inscribe al contribuyente en el Portal MiPyme del SII. Puede dejar sin uso los folios de mercado que tenga."
|
|
2242
|
-
},
|
|
2243
|
-
{
|
|
2244
|
-
// 25
|
|
2245
|
-
comando: ["dte", "ambiente"],
|
|
2246
|
-
operationId: "cambiarAmbienteTipoEmisorDte",
|
|
2247
|
-
metodo: "PATCH",
|
|
2248
|
-
ruta: "/{tenantSlug}/emisores/{id}/ambiente",
|
|
2249
|
-
argumentos: ["id"],
|
|
2250
|
-
banderas: [TIPO_DTE_DEL_AMBIENTE, AMBIENTE_DEL_TIPO],
|
|
2251
|
-
salida: "accion",
|
|
2252
|
-
hecho: "Ambiente cambiado.",
|
|
2253
|
-
confirmacion: "escrita",
|
|
2254
|
-
aviso: "Esto cambia el ambiente del SII por el que sale ese tipo de documento."
|
|
2255
|
-
},
|
|
2256
|
-
{
|
|
2257
|
-
// 26
|
|
2258
|
-
comando: ["dte", "archivar"],
|
|
2259
|
-
operationId: "archivarEmisorDte",
|
|
2260
|
-
metodo: "DELETE",
|
|
2261
|
-
ruta: "/{tenantSlug}/emisores/{id}",
|
|
2262
|
-
argumentos: ["id"],
|
|
2263
|
-
banderas: [RUT_DE_CONFIRMACION],
|
|
2264
|
-
salida: "accion",
|
|
2265
|
-
hecho: "Emisor archivado.",
|
|
2266
|
-
archiva: true,
|
|
2267
|
-
confirmacion: "escrita",
|
|
2268
|
-
aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
|
|
2269
|
-
},
|
|
2270
|
-
{
|
|
2271
|
-
// 27
|
|
2272
|
-
comando: ["tributarios", "archivar"],
|
|
2273
|
-
operationId: "archivarEmisorTributario",
|
|
2274
|
-
metodo: "DELETE",
|
|
2275
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}",
|
|
2276
|
-
argumentos: ["id"],
|
|
2277
|
-
banderas: [],
|
|
2278
|
-
salida: "accion",
|
|
2279
|
-
hecho: "Emisor archivado.",
|
|
2280
|
-
archiva: true,
|
|
2281
|
-
confirmacion: "escrita",
|
|
2282
|
-
aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
|
|
2283
|
-
},
|
|
2284
|
-
{
|
|
2285
|
-
// 28
|
|
2286
|
-
comando: ["tributarios", "listar"],
|
|
2287
|
-
operationId: "listarEmisoresTributarios",
|
|
2288
|
-
metodo: "GET",
|
|
2289
|
-
ruta: "/{tenantSlug}/emisores-tributarios",
|
|
2290
|
-
argumentos: [],
|
|
2291
|
-
banderas: [RUT_FILTRO, ESTADO_FILTRO, CREDENCIAL_FILTRO, LIMITE, DESDE, TODAS],
|
|
2292
|
-
salida: "tabla",
|
|
2293
|
-
columnas: ["emisorId", "rut", "razonSocial", "estado", "credencialEstado"],
|
|
2294
|
-
confirmacion: "efecto"
|
|
2295
|
-
},
|
|
2296
|
-
{
|
|
2297
|
-
// 29
|
|
2298
|
-
comando: ["tributarios", "por-defecto"],
|
|
2299
|
-
operationId: "obtenerEmisorTributarioPorDefecto",
|
|
2300
|
-
metodo: "GET",
|
|
2301
|
-
ruta: "/{tenantSlug}/emisores-tributarios/default",
|
|
2302
|
-
argumentos: [],
|
|
2303
|
-
banderas: [],
|
|
2304
|
-
salida: "ficha",
|
|
2305
|
-
confirmacion: "efecto"
|
|
2306
|
-
},
|
|
2307
|
-
{
|
|
2308
|
-
// 30
|
|
2309
|
-
comando: ["tributarios", "existe"],
|
|
2310
|
-
operationId: "consultarRutEmisorTributario",
|
|
2311
|
-
metodo: "GET",
|
|
2312
|
-
ruta: "/{tenantSlug}/emisores-tributarios/check-rut/{rut}",
|
|
2313
|
-
argumentos: ["rut"],
|
|
2314
|
-
banderas: [],
|
|
2315
|
-
salida: "ficha",
|
|
2316
|
-
confirmacion: "efecto"
|
|
2317
|
-
},
|
|
2318
|
-
{
|
|
2319
|
-
// 31
|
|
2320
|
-
comando: ["tributarios", "ver"],
|
|
2321
|
-
operationId: "obtenerEmisorTributario",
|
|
2322
|
-
metodo: "GET",
|
|
2323
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}",
|
|
2324
|
-
argumentos: ["id"],
|
|
2325
|
-
banderas: [INCLUIR_ARCHIVADOS],
|
|
2326
|
-
salida: "ficha",
|
|
2327
|
-
confirmacion: "efecto"
|
|
2328
|
-
},
|
|
2329
|
-
{
|
|
2330
|
-
// 32
|
|
2331
|
-
comando: ["tributarios", "logo", "ver"],
|
|
2332
|
-
operationId: "obtenerLogoEmisorTributario",
|
|
2333
|
-
metodo: "GET",
|
|
2334
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
|
|
2335
|
-
argumentos: ["id"],
|
|
2336
|
-
banderas: [],
|
|
2337
|
-
salida: "ficha",
|
|
2338
|
-
confirmacion: "efecto"
|
|
2339
|
-
},
|
|
2340
|
-
{
|
|
2341
|
-
// 33
|
|
2342
|
-
comando: ["tributarios", "certificado"],
|
|
2343
|
-
operationId: "obtenerCertificadoEmisorTributario",
|
|
2344
|
-
metodo: "GET",
|
|
2345
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}/certificado",
|
|
2346
|
-
argumentos: ["id"],
|
|
2347
|
-
banderas: [],
|
|
2348
|
-
salida: "ficha",
|
|
2349
|
-
confirmacion: "efecto"
|
|
2350
|
-
},
|
|
2351
|
-
{
|
|
2352
|
-
// 34
|
|
2353
|
-
comando: ["tributarios", "editar"],
|
|
2354
|
-
operationId: "actualizarEmisorTributario",
|
|
2355
|
-
metodo: "PATCH",
|
|
2356
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}",
|
|
2357
|
-
argumentos: ["id"],
|
|
2358
|
-
banderas: [CUERPO_OBLIGATORIO],
|
|
2359
|
-
salida: "accion",
|
|
2360
|
-
hecho: "Emisor actualizado.",
|
|
2361
|
-
confirmacion: "efecto"
|
|
2362
|
-
},
|
|
2363
|
-
{
|
|
2364
|
-
// 35
|
|
2365
|
-
comando: ["tributarios", "fijar-por-defecto"],
|
|
2366
|
-
operationId: "cambiarEmisorTributarioPorDefecto",
|
|
2367
|
-
metodo: "PATCH",
|
|
2368
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}/set-default",
|
|
2369
|
-
argumentos: ["id"],
|
|
2370
|
-
banderas: [],
|
|
2371
|
-
salida: "accion",
|
|
2372
|
-
hecho: "Emisor fijado por defecto.",
|
|
2373
|
-
confirmacion: "efecto"
|
|
2374
|
-
},
|
|
2375
|
-
{
|
|
2376
|
-
// 36
|
|
2377
|
-
comando: ["tributarios", "reactivar"],
|
|
2378
|
-
operationId: "reactivarEmisorTributario",
|
|
2379
|
-
metodo: "PATCH",
|
|
2380
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}/reactivate",
|
|
2381
|
-
argumentos: ["id"],
|
|
2382
|
-
banderas: [CUERPO_OPCIONAL],
|
|
2383
|
-
salida: "accion",
|
|
2384
|
-
hecho: "Emisor reactivado.",
|
|
2385
|
-
confirmacion: "efecto"
|
|
2386
|
-
},
|
|
2387
|
-
{
|
|
2388
|
-
// 37
|
|
2389
|
-
comando: ["tributarios", "logo", "subir"],
|
|
2390
|
-
operationId: "actualizarLogoEmisorTributario",
|
|
2391
|
-
metodo: "POST",
|
|
2392
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
|
|
2393
|
-
argumentos: ["id"],
|
|
2394
|
-
banderas: [ARCHIVO_LOGO],
|
|
2395
|
-
salida: "accion",
|
|
2396
|
-
hecho: "Logo actualizado.",
|
|
2397
|
-
confirmacion: "efecto"
|
|
2398
|
-
},
|
|
2399
|
-
{
|
|
2400
|
-
// 38
|
|
2401
|
-
comando: ["tributarios", "logo", "quitar"],
|
|
2402
|
-
operationId: "eliminarLogoEmisorTributario",
|
|
2403
|
-
metodo: "DELETE",
|
|
2404
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
|
|
2405
|
-
argumentos: ["id"],
|
|
2406
|
-
banderas: [],
|
|
2407
|
-
salida: "accion",
|
|
2408
|
-
hecho: "Logo eliminado.",
|
|
2409
|
-
confirmacion: "efecto"
|
|
2410
|
-
},
|
|
2411
|
-
{
|
|
2412
|
-
// 39
|
|
2413
|
-
comando: ["sucursales", "listar"],
|
|
2414
|
-
operationId: "listarSucursalesEmisorDte",
|
|
2415
|
-
metodo: "GET",
|
|
2416
|
-
ruta: "/{tenantSlug}/dte/emisores/{emisorId}/sucursales",
|
|
2417
|
-
argumentos: ["emisorId"],
|
|
2418
|
-
banderas: [ACTIVO_FILTRO, TRIBUTARIA_FILTRO, LIMITE, DESDE, TODAS],
|
|
2419
|
-
salida: "tabla",
|
|
2420
|
-
columnas: ["sucursalId", "nombre", "direccion", "comuna", "ciudad"],
|
|
2421
|
-
confirmacion: "efecto"
|
|
2422
|
-
},
|
|
2423
|
-
{
|
|
2424
|
-
// 40
|
|
2425
|
-
comando: ["sucursales", "crear"],
|
|
2426
|
-
operationId: "crearSucursalEmisorDte",
|
|
2427
|
-
metodo: "POST",
|
|
2428
|
-
ruta: "/{tenantSlug}/dte/emisores/{emisorId}/sucursales",
|
|
2429
|
-
argumentos: ["emisorId"],
|
|
2430
|
-
banderas: [CUERPO_OBLIGATORIO],
|
|
2431
|
-
salida: "accion",
|
|
2432
|
-
hecho: "Sucursal creada.",
|
|
2433
|
-
confirmacion: "efecto"
|
|
2434
|
-
},
|
|
2435
|
-
{
|
|
2436
|
-
// 41
|
|
2437
|
-
comando: ["sucursales", "editar"],
|
|
2438
|
-
operationId: "actualizarSucursalEmisorDte",
|
|
2439
|
-
metodo: "PATCH",
|
|
2440
|
-
ruta: "/{tenantSlug}/dte/sucursales/{sucursalId}",
|
|
2441
|
-
argumentos: ["sucursalId"],
|
|
2442
|
-
banderas: [CUERPO_OBLIGATORIO],
|
|
2443
|
-
salida: "accion",
|
|
2444
|
-
hecho: "Sucursal actualizada.",
|
|
2445
|
-
confirmacion: "efecto"
|
|
2446
|
-
},
|
|
2447
|
-
{
|
|
2448
|
-
// 42
|
|
2449
|
-
comando: ["sucursales", "desactivar"],
|
|
2450
|
-
operationId: "desactivarSucursalEmisorDte",
|
|
2451
|
-
metodo: "DELETE",
|
|
2452
|
-
ruta: "/{tenantSlug}/dte/sucursales/{sucursalId}",
|
|
2453
|
-
argumentos: ["sucursalId"],
|
|
2454
|
-
banderas: [],
|
|
2455
|
-
salida: "accion",
|
|
2456
|
-
hecho: "Sucursal desactivada.",
|
|
2457
|
-
confirmacion: "efecto"
|
|
2458
|
-
},
|
|
2459
|
-
{
|
|
2460
|
-
// 43
|
|
2461
|
-
comando: ["representantes", "listar"],
|
|
2462
|
-
operationId: "listarRepresentantesLegales",
|
|
2463
|
-
metodo: "GET",
|
|
2464
|
-
ruta: "/{tenantSlug}/representantes-legales",
|
|
2465
|
-
argumentos: [],
|
|
2466
|
-
banderas: [RUT_FILTRO, LIMITE, DESDE, TODAS],
|
|
2467
|
-
salida: "tabla",
|
|
2468
|
-
columnas: ["rut", "nombre", "certVigente", "certValidoHasta", "emisoresCount"],
|
|
2469
|
-
confirmacion: "efecto"
|
|
2470
|
-
},
|
|
2471
|
-
{
|
|
2472
|
-
// 44
|
|
2473
|
-
comando: ["dte", "sincronizar"],
|
|
2474
|
-
operationId: "actualizarEmisorDteDesdeSii",
|
|
2475
|
-
metodo: "POST",
|
|
2476
|
-
ruta: "/{tenantSlug}/emisores/{id}/sincronizar",
|
|
2477
|
-
argumentos: ["id"],
|
|
2478
|
-
banderas: [],
|
|
2479
|
-
salida: "ficha",
|
|
2480
|
-
confirmacion: "efecto"
|
|
2481
|
-
},
|
|
2482
|
-
{
|
|
2483
|
-
// 45
|
|
2484
|
-
comando: ["dte", "credencial", "reintentar"],
|
|
2485
|
-
operationId: "reintentarCredencialPortalEmisorDte",
|
|
2486
|
-
metodo: "POST",
|
|
2487
|
-
ruta: "/{tenantSlug}/emisores/{id}/credencial-portal/reintentar",
|
|
2488
|
-
argumentos: ["id"],
|
|
2489
|
-
banderas: [],
|
|
2490
|
-
salida: "ficha",
|
|
2491
|
-
confirmacion: "efecto"
|
|
2492
|
-
},
|
|
2493
|
-
{
|
|
2494
|
-
// 46
|
|
2495
|
-
comando: ["tributarios", "credencial", "reintentar"],
|
|
2496
|
-
operationId: "reintentarCredencialEmisorTributario",
|
|
2497
|
-
metodo: "POST",
|
|
2498
|
-
ruta: "/{tenantSlug}/emisores-tributarios/{id}/credencial/reintentar",
|
|
2499
|
-
argumentos: ["id"],
|
|
2500
|
-
banderas: [],
|
|
2501
|
-
salida: "ficha",
|
|
2502
|
-
confirmacion: "efecto"
|
|
2503
|
-
},
|
|
2504
|
-
{
|
|
2505
|
-
// 47
|
|
2506
|
-
comando: ["revocar"],
|
|
2507
|
-
operationId: "revocarEmisorTokenizado",
|
|
2508
|
-
metodo: "POST",
|
|
2509
|
-
ruta: "/{tenantSlug}/tokenizacion/revoke",
|
|
2510
|
-
argumentos: ["id"],
|
|
2511
|
-
argumentoACuerpo: "emisorId",
|
|
2512
|
-
banderas: [TIPO_DE_EMISOR_A_REVOCAR, MOTIVO_DE_REVOCACION],
|
|
2513
|
-
salida: "accion",
|
|
2514
|
-
hecho: "Emisor revocado.",
|
|
2515
|
-
confirmacion: "escrita",
|
|
2516
|
-
aviso: "Esto revoca la autorizaci\xF3n y elimina sus credenciales de inmediato."
|
|
2517
|
-
},
|
|
2518
|
-
{
|
|
2519
|
-
// 48
|
|
2520
|
-
comando: ["dte", "volver-a-mipyme"],
|
|
2521
|
-
operationId: "volverEmisorDteAlPortalMipyme",
|
|
2522
|
-
metodo: "POST",
|
|
2523
|
-
ruta: "/{tenantSlug}/emisores/{id}/volver-a-mipyme",
|
|
2524
|
-
argumentos: ["id"],
|
|
2525
|
-
banderas: [RUT_DE_CONFIRMACION],
|
|
2526
|
-
salida: "accion",
|
|
2527
|
-
hecho: "Emisor vuelto al Portal MiPyme.",
|
|
2528
|
-
confirmacion: "escrita",
|
|
2529
|
-
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."
|
|
2530
|
-
}
|
|
2531
|
-
];
|
|
2532
|
-
|
|
2533
|
-
// src/comandos/registro.ts
|
|
2534
|
-
import { Option } from "commander";
|
|
2535
|
-
|
|
2536
|
-
// src/nucleo/actualizacion-del-cli.ts
|
|
2537
|
-
import fs8 from "node:fs";
|
|
2538
|
-
import path8 from "node:path";
|
|
2539
|
-
|
|
2540
|
-
// src/nucleo/bienvenida.ts
|
|
2541
|
-
var TITULO_DE_BIENVENIDA = "BIENVENIDO A REDCUMBRE";
|
|
2542
|
-
var ETIQUETA_DEL_AVISO = "AVISO IMPORTANTE";
|
|
2543
|
-
var AVISO_DE_COBROS = "En modo de prueba nada se cobra, en modo de producci\xF3n las acciones se cobran de acuerdo a tu plan. Siempre puedes consultar con redcumbre:tarifas los precios de todas tus operaciones o en el panel web en la secci\xF3n Mi suscripci\xF3n.";
|
|
2544
|
-
var ANCHO_PLANO = 80;
|
|
2545
|
-
var ANCHO_DEL_RECUADRO = 76;
|
|
2546
|
-
var RELLENO = 2;
|
|
2547
|
-
var LETRAS = {
|
|
2548
|
-
R: [" ____ ", "| _ \\ ", "| |_) |", "| _ < ", "|_| \\_\\"],
|
|
2549
|
-
E: [" _____ ", "| ____|", "| _| ", "| |___ ", "|_____|"],
|
|
2550
|
-
D: [" ____ ", "| _ \\ ", "| | | |", "| |_| |", "|____/ "],
|
|
2551
|
-
C: [" ____ ", " / ___|", "| | ", "| |___ ", " \\____|"],
|
|
2552
|
-
U: [" _ _ ", "| | | |", "| | | |", "| |_| |", " \\___/ "],
|
|
2553
|
-
M: [" __ __ ", "| \\/ |", "| |\\/| |", "| | | |", "|_| |_|"],
|
|
2554
|
-
B: [" ____ ", "| __ ) ", "| _ \\ ", "| |_) |", "|____/ "]
|
|
2555
|
-
};
|
|
2556
|
-
var LOGO = [0, 1, 2, 3, 4].map(
|
|
2557
|
-
(fila) => [..."REDCUMBRE"].map((letra) => LETRAS[letra][fila]).join(" ").replace(/\s+$/, "")
|
|
2558
|
-
);
|
|
2559
|
-
var ANSI = {
|
|
2560
|
-
reset: "\x1B[0m",
|
|
2561
|
-
negrita: "\x1B[1m",
|
|
2562
|
-
rojoBrillante: "\x1B[91m",
|
|
2563
|
-
amarilloBrillante: "\x1B[93m",
|
|
2564
|
-
etiqueta: "\x1B[1;97;41m"
|
|
2565
|
-
};
|
|
2566
|
-
function envolver(texto2, ancho) {
|
|
2567
|
-
const lineas = [];
|
|
2568
|
-
let actual = "";
|
|
2569
|
-
for (const palabra of texto2.split(/\s+/).filter(Boolean)) {
|
|
2570
|
-
if (actual && actual.length + 1 + palabra.length > ancho) {
|
|
2571
|
-
lineas.push(actual);
|
|
2572
|
-
actual = palabra;
|
|
2573
|
-
} else {
|
|
2574
|
-
actual = actual ? `${actual} ${palabra}` : palabra;
|
|
2575
|
-
}
|
|
2576
|
-
}
|
|
2577
|
-
if (actual) lineas.push(actual);
|
|
2578
|
-
return lineas;
|
|
2579
|
-
}
|
|
2580
|
-
var tituloConVersion = (version) => `${TITULO_DE_BIENVENIDA} \xB7 CLI ${version}`;
|
|
2581
|
-
var AVISO_EN_TEXTO = `${ETIQUETA_DEL_AVISO}: ${AVISO_DE_COBROS}`;
|
|
2582
|
-
function textoPlanoDeBienvenida(version) {
|
|
2583
|
-
return [...envolver(tituloConVersion(version), ANCHO_PLANO), ...envolver(AVISO_EN_TEXTO, ANCHO_PLANO)].join("\n");
|
|
2584
|
-
}
|
|
2585
|
-
var ANCHO_INTERIOR = ANCHO_DEL_RECUADRO - 2 - 2 * RELLENO;
|
|
2586
|
-
var ANCHO_DE_LA_PANTALLA = Math.max(ANCHO_DEL_RECUADRO, ...LOGO.map((l) => l.length));
|
|
2587
|
-
function pantallaDeBienvenida(version, { color }) {
|
|
2588
|
-
const pintar = (codigo, texto2) => color ? `${codigo}${texto2}${ANSI.reset}` : texto2;
|
|
2589
|
-
const relleno = " ".repeat(RELLENO);
|
|
2590
|
-
const borde = (texto2) => pintar(ANSI.amarilloBrillante, texto2);
|
|
2591
|
-
const interior = (texto2, visible = texto2) => `${borde("\u2551")}${relleno}${texto2}${" ".repeat(ANCHO_INTERIOR - visible.length)}${relleno}${borde("\u2551")}`;
|
|
2592
|
-
const lineas = [];
|
|
2593
|
-
for (const fila of LOGO) lineas.push(pintar(ANSI.rojoBrillante, fila));
|
|
2594
|
-
lineas.push("");
|
|
2595
|
-
lineas.push(pintar(ANSI.negrita, tituloConVersion(version)));
|
|
2596
|
-
lineas.push("");
|
|
2597
|
-
lineas.push(borde(`\u2554${"\u2550".repeat(ANCHO_DEL_RECUADRO - 2)}\u2557`));
|
|
2598
|
-
lineas.push(interior(pintar(ANSI.etiqueta, ` ${ETIQUETA_DEL_AVISO} `), ` ${ETIQUETA_DEL_AVISO} `));
|
|
2599
|
-
for (const linea of envolver(AVISO_DE_COBROS, ANCHO_INTERIOR)) lineas.push(interior(linea));
|
|
2600
|
-
lineas.push(borde(`\u255A${"\u2550".repeat(ANCHO_DEL_RECUADRO - 2)}\u255D`));
|
|
2601
|
-
return lineas.join("\n");
|
|
2602
|
-
}
|
|
2603
|
-
function mostrarBienvenida(salida, version, entorno) {
|
|
2604
|
-
const plano = textoPlanoDeBienvenida(version);
|
|
2605
|
-
if (salida.json) {
|
|
2606
|
-
salida.anexar("bienvenida", { titulo: TITULO_DE_BIENVENIDA, aviso: AVISO_EN_TEXTO, version, texto: plano });
|
|
2607
|
-
salida.linea();
|
|
2608
|
-
salida.linea(plano);
|
|
2609
|
-
return;
|
|
2610
|
-
}
|
|
2611
|
-
const sinColor = (entorno.env.NO_COLOR ?? "") !== "" || entorno.env.TERM === "dumb";
|
|
2612
|
-
const angosta = entorno.columnas !== void 0 && entorno.columnas < ANCHO_DE_LA_PANTALLA;
|
|
2613
|
-
salida.linea();
|
|
2614
|
-
salida.linea(sinColor || angosta ? plano : pantallaDeBienvenida(version, { color: true }));
|
|
2615
|
-
salida.linea();
|
|
2616
|
-
}
|
|
2617
|
-
|
|
2618
|
-
// src/nucleo/instalacion-del-cli.ts
|
|
2619
|
-
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
2620
|
-
import fs7 from "node:fs";
|
|
2621
|
-
import path7 from "node:path";
|
|
2622
|
-
import { fileURLToPath } from "node:url";
|
|
2623
|
-
var real = (ruta) => {
|
|
2624
|
-
try {
|
|
2625
|
-
return fs7.realpathSync(ruta);
|
|
2626
|
-
} catch {
|
|
2627
|
-
return null;
|
|
2060
|
+
function reconciliarAgents(archivo, registro) {
|
|
2061
|
+
const bloque = bloqueDeAgents();
|
|
2062
|
+
const hashBloque = sha256(bloque);
|
|
2063
|
+
if (!fs6.existsSync(archivo)) {
|
|
2064
|
+
if (registro) return { accion: "borrada", registro: null };
|
|
2065
|
+
escribirAtomico(archivo, `${bloque}
|
|
2066
|
+
`);
|
|
2067
|
+
return { accion: "instalada", registro: { sha256: hashBloque, creado: true } };
|
|
2628
2068
|
}
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
const carpeta = raiz ? real(path7.join(raiz, ...PAQUETE_DEL_CLI.split("/"))) : null;
|
|
2638
|
-
if (carpeta && dentroDe(bundleReal, carpeta)) return { forma, carpetaDelPaquete: carpeta };
|
|
2069
|
+
const texto2 = conReintentoEnWindows(() => fs6.readFileSync(archivo, "utf8"));
|
|
2070
|
+
const actual = extraerBloque(texto2);
|
|
2071
|
+
if (actual === null) {
|
|
2072
|
+
if (registro) return { accion: "borrada", registro: null };
|
|
2073
|
+
const separador = texto2.length === 0 ? "" : texto2.endsWith("\n\n") ? "" : texto2.endsWith("\n") ? "\n" : "\n\n";
|
|
2074
|
+
escribirAtomico(archivo, `${texto2}${separador}${bloque}
|
|
2075
|
+
`);
|
|
2076
|
+
return { accion: "instalada", registro: { sha256: hashBloque, creado: false } };
|
|
2639
2077
|
}
|
|
2640
|
-
const
|
|
2641
|
-
if (
|
|
2642
|
-
return {
|
|
2078
|
+
const hashActual = sha256(actual);
|
|
2079
|
+
if (!registro) {
|
|
2080
|
+
if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { sha256: hashBloque, creado: false } };
|
|
2081
|
+
return { accion: "editada", registro: null };
|
|
2643
2082
|
}
|
|
2644
|
-
return {
|
|
2645
|
-
}
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
const conRegistro = registro ? [`--registry=${registro}`] : [];
|
|
2649
|
-
if (forma === "pnpm-global") return { comando: "pnpm", args: ["add", "--global", ...conRegistro, paquete] };
|
|
2650
|
-
return { comando: "npm", args: ["install", "--global", ...conRegistro, paquete] };
|
|
2651
|
-
}
|
|
2652
|
-
var legible = (c) => [c.comando, ...c.args].join(" ");
|
|
2653
|
-
var comandoInstalarPorNpx = (version) => `npx ${PAQUETE_DEL_CLI}@${version} instalar`;
|
|
2654
|
-
var prefijoPorNpx = (version) => `npx ${PAQUETE_DEL_CLI}@${version}`;
|
|
2655
|
-
function ejecutarDeVerdad(comando2, args, opciones) {
|
|
2656
|
-
const r = spawnSync2(comando2, args, { cwd: opciones.cwd, env: opciones.env, encoding: "utf8", shell: process.platform === "win32", timeout: 10 * 6e4 });
|
|
2657
|
-
return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? r.error.message : "") };
|
|
2083
|
+
if (hashActual !== registro.sha256) return { accion: "editada", registro: null };
|
|
2084
|
+
if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { ...registro, sha256: hashBloque } };
|
|
2085
|
+
escribirAtomico(archivo, texto2.replace(regexBloque(), () => bloque));
|
|
2086
|
+
return { accion: "actualizada", registro: { ...registro, sha256: hashBloque } };
|
|
2658
2087
|
}
|
|
2659
|
-
function
|
|
2660
|
-
const
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2088
|
+
function instalarSkill(opciones) {
|
|
2089
|
+
const { destinos, bloqueAgents } = opciones;
|
|
2090
|
+
const ahora = opciones.ahora ?? /* @__PURE__ */ new Date();
|
|
2091
|
+
const contenido = contenidoPorFuente(opciones.version, opciones.fuente);
|
|
2092
|
+
const usuario = leerRegistroUsuario(destinos);
|
|
2093
|
+
const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
|
|
2094
|
+
const rutas = [];
|
|
2095
|
+
for (const objetivo of objetivos(destinos)) {
|
|
2096
|
+
const deUsuario = esDeUsuario(objetivo.id);
|
|
2097
|
+
const registro = deUsuario ? usuario : proyecto;
|
|
2098
|
+
if (usuario.quitada || registro.quitada) continue;
|
|
2099
|
+
const previo = registro.rutas?.[objetivo.id]?.sha256;
|
|
2100
|
+
const { accion, hash, copia, error } = reconciliar(objetivo.archivo, contenido(objetivo.fuente), previo, ahora);
|
|
2101
|
+
rutas.push({ ruta: objetivo.legible, accion, ...copia ? { copia } : {}, ...error ? { error } : {} });
|
|
2102
|
+
if (hash) {
|
|
2103
|
+
registro.rutas = { ...registro.rutas ?? {}, [objetivo.id]: { sha256: hash } };
|
|
2674
2104
|
}
|
|
2675
|
-
};
|
|
2676
|
-
}
|
|
2677
|
-
var VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
2678
|
-
function entornoSinNpx(env) {
|
|
2679
|
-
const limpio = { ...env };
|
|
2680
|
-
for (const clave of Object.keys(limpio).filter((k) => k.toUpperCase() === "PATH")) {
|
|
2681
|
-
limpio[clave] = (limpio[clave] ?? "").split(path7.delimiter).filter((carpeta) => carpeta && !carpeta.split(/[\\/]/).includes("_npx")).join(path7.delimiter);
|
|
2682
|
-
}
|
|
2683
|
-
return limpio;
|
|
2684
|
-
}
|
|
2685
|
-
function versionEnElPath(entorno, opciones) {
|
|
2686
|
-
const r = entorno.ejecutar("redcumbre", ["--version"], { cwd: opciones.cwd, env: entornoSinNpx(opciones.env) });
|
|
2687
|
-
const version = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
|
|
2688
|
-
return r.status === 0 && VERSION.test(version) ? version : null;
|
|
2689
|
-
}
|
|
2690
|
-
function carpetaDeEjecutablesDeNpm(entorno, opciones) {
|
|
2691
|
-
const r = entorno.ejecutar("npm", ["prefix", "--global"], opciones);
|
|
2692
|
-
const prefijo = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
|
|
2693
|
-
if (r.status !== 0 || !prefijo) return null;
|
|
2694
|
-
return process.platform === "win32" ? prefijo : path7.join(prefijo, "bin");
|
|
2695
|
-
}
|
|
2696
|
-
|
|
2697
|
-
// src/nucleo/actualizacion-del-cli.ts
|
|
2698
|
-
var real2 = (ruta) => {
|
|
2699
|
-
try {
|
|
2700
|
-
return fs8.realpathSync(ruta);
|
|
2701
|
-
} catch {
|
|
2702
|
-
return null;
|
|
2703
|
-
}
|
|
2704
|
-
};
|
|
2705
|
-
function leerJson(texto2) {
|
|
2706
|
-
try {
|
|
2707
|
-
const dato = JSON.parse(texto2);
|
|
2708
|
-
return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
|
|
2709
|
-
} catch {
|
|
2710
|
-
return null;
|
|
2711
|
-
}
|
|
2712
|
-
}
|
|
2713
|
-
function errorDeActualizacion(comando2, corrida) {
|
|
2714
|
-
const detalle = (corrida.stderr || corrida.stdout).trim().split(/\r?\n/).slice(-5).join(" \xB7 ");
|
|
2715
|
-
return new ErrorCli(`No pude actualizar el CLI: \xAB${legible(comando2)}\xBB termin\xF3 con ${corrida.status ?? "una se\xF1al"}${detalle ? ` (${detalle})` : ""}. No cambi\xE9 nada m\xE1s.`, CODIGOS_DE_SALIDA.error, {
|
|
2716
|
-
codigo: "ACTUALIZACION_FALLIDA",
|
|
2717
|
-
datos: { comando: legible(comando2) }
|
|
2718
|
-
});
|
|
2719
|
-
}
|
|
2720
|
-
function actualizarElCli(ctx, entorno, disponible, informar) {
|
|
2721
|
-
const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
|
|
2722
|
-
const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
|
|
2723
|
-
if (instalacion.forma === "no-reconocida") {
|
|
2724
|
-
throw new ErrorCli(
|
|
2725
|
-
`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.`,
|
|
2726
|
-
CODIGOS_DE_SALIDA.error,
|
|
2727
|
-
{ codigo: "INSTALACION_NO_RECONOCIDA", datos: { instalada: ctx.version, disponible } }
|
|
2728
|
-
);
|
|
2729
|
-
}
|
|
2730
|
-
const comando2 = comandoDeActualizacion(instalacion.forma, disponible, registro);
|
|
2731
|
-
informar(`Actualizando: ${legible(comando2)}`);
|
|
2732
|
-
const corrida = entorno.ejecutar(comando2.comando, comando2.args, { cwd: ctx.cwd, env: ctx.env });
|
|
2733
|
-
if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
|
|
2734
|
-
const raizNpm = instalacion.forma === "npx" ? entorno.raizGlobal("npm") : null;
|
|
2735
|
-
const carpetaDelPaquete = instalacion.forma === "npx" ? raizNpm ? real2(path8.join(raizNpm, ...PAQUETE_DEL_CLI.split("/"))) : null : instalacion.carpetaDelPaquete;
|
|
2736
|
-
if (!carpetaDelPaquete) {
|
|
2737
|
-
throw new ErrorCli(
|
|
2738
|
-
`\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.`,
|
|
2739
|
-
CODIGOS_DE_SALIDA.error,
|
|
2740
|
-
{ codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
|
|
2741
|
-
);
|
|
2742
2105
|
}
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
`\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.`,
|
|
2748
|
-
CODIGOS_DE_SALIDA.error,
|
|
2749
|
-
{ codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
|
|
2750
|
-
);
|
|
2106
|
+
if (bloqueAgents && destinos.proyecto && proyecto && !usuario.quitada && !proyecto.quitada) {
|
|
2107
|
+
const { accion, registro } = reconciliarAgents(path6.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
|
|
2108
|
+
rutas.push({ ruta: "AGENTS.md", accion });
|
|
2109
|
+
if (registro) proyecto.agents = registro;
|
|
2751
2110
|
}
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
return
|
|
2755
|
-
}
|
|
2756
|
-
function resumirLaSkill(skill) {
|
|
2757
|
-
const rutas = Array.isArray(skill?.rutas) ? skill.rutas : [];
|
|
2758
|
-
const copias = rutas.flatMap((r) => r.accion === "reemplazada-editada" && typeof r.copia === "string" ? [r.copia] : []);
|
|
2759
|
-
return { renovadas: rutas.filter((r) => r.accion === "renovada" || r.accion === "reemplazada-editada").length, copias };
|
|
2111
|
+
if (!usuario.quitada && rutas.some((r) => r.ruta.startsWith("~"))) guardarRegistroUsuario(destinos, usuario);
|
|
2112
|
+
if (destinos.proyecto && proyecto && !proyecto.quitada && rutas.some((r) => !r.ruta.startsWith("~"))) guardarRegistroProyecto(destinos.proyecto, proyecto);
|
|
2113
|
+
return resumir2(rutas, rutas.length === 0 && Boolean(usuario.quitada || proyecto?.quitada));
|
|
2760
2114
|
}
|
|
2761
|
-
function
|
|
2762
|
-
if (
|
|
2763
|
-
if (
|
|
2764
|
-
|
|
2115
|
+
function quitarArchivo(archivo, registrado) {
|
|
2116
|
+
if (!fs6.existsSync(archivo)) return null;
|
|
2117
|
+
if (registrado === void 0 || sha256(conReintentoEnWindows(() => fs6.readFileSync(archivo))) !== registrado) return "editada";
|
|
2118
|
+
fs6.rmSync(archivo);
|
|
2119
|
+
const carpeta = path6.dirname(archivo);
|
|
2120
|
+
if (fs6.readdirSync(carpeta).length === 0) fs6.rmdirSync(carpeta);
|
|
2121
|
+
return "quitada";
|
|
2765
2122
|
}
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
const
|
|
2769
|
-
const
|
|
2770
|
-
const
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
const
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
ahora: ctx.ahora(),
|
|
2777
|
-
registro: ctx.env.REDCUMBRE_NPM_REGISTRY,
|
|
2778
|
-
consultar: opciones.consultar,
|
|
2779
|
-
sinMarca: opciones.consultaSinMarca
|
|
2780
|
-
});
|
|
2781
|
-
if (opciones.consultaSinMarca) ctx.versionDelRegistro = { ultima };
|
|
2782
|
-
actualizacion = ultima && compararVersiones(ultima, ctx.version) > 0 ? { instalada: ctx.version, disponible: ultima, comando: COMANDO_ACTUALIZAR } : null;
|
|
2783
|
-
} catch (error) {
|
|
2784
|
-
depurar(`no pude leer la marca de versi\xF3n: ${motivoDe(error)}`);
|
|
2785
|
-
return false;
|
|
2786
|
-
}
|
|
2787
|
-
if (!actualizacion) return false;
|
|
2788
|
-
const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
|
|
2789
|
-
if (instalacion.forma === "no-reconocida") {
|
|
2790
|
-
depurar(`hay una versi\xF3n m\xE1s nueva del CLI (${actualizacion.disponible}), pero no la instalo: ${instalacion.motivo}`);
|
|
2791
|
-
return false;
|
|
2792
|
-
}
|
|
2793
|
-
const porNpx = instalacion.forma === "npx";
|
|
2794
|
-
const comandoManual = porNpx ? `${prefijoPorNpx(ctx.version)} actualizar` : COMANDO_ACTUALIZAR;
|
|
2795
|
-
const { instalada: instalada2, disponible } = actualizacion;
|
|
2796
|
-
actualizacion.comando = comandoManual;
|
|
2797
|
-
const fallo2 = (error, avisarEnTerminal) => {
|
|
2798
|
-
if (agente) {
|
|
2799
|
-
salida.anexar("actualizacion", { instalada: instalada2, disponible, actualizado: false, comando: comandoManual, ...error ? { error } : {} });
|
|
2800
|
-
salida.avisoAlAgente(avisoDeActualizacion(actualizacion, error?.mensaje));
|
|
2801
|
-
} else if (avisarEnTerminal) {
|
|
2802
|
-
err.write(`\u26A0 No pude actualizar el CLI solo${error ? ` (${error.mensaje})` : ""}. Actual\xEDzalo con \xAB${comandoManual}\xBB.
|
|
2803
|
-
`);
|
|
2804
|
-
}
|
|
2805
|
-
};
|
|
2806
|
-
if (yaSeIntento(ctx.carpetaConfiguracion, disponible, ctx.ahora())) {
|
|
2807
|
-
depurar(`ya intent\xE9 actualizar el CLI a ${disponible} en las \xFAltimas 24 h; no lo reintento`);
|
|
2808
|
-
fallo2(null, false);
|
|
2809
|
-
return false;
|
|
2123
|
+
function quitarSkill(opciones) {
|
|
2124
|
+
const { destinos } = opciones;
|
|
2125
|
+
const usuario = leerRegistroUsuario(destinos);
|
|
2126
|
+
const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
|
|
2127
|
+
const rutas = [];
|
|
2128
|
+
for (const objetivo of objetivos(destinos)) {
|
|
2129
|
+
const registro = esDeUsuario(objetivo.id) ? usuario : proyecto;
|
|
2130
|
+
const previo = registro.rutas?.[objetivo.id]?.sha256;
|
|
2131
|
+
const accion = quitarArchivo(objetivo.archivo, previo);
|
|
2132
|
+
if (accion) rutas.push({ ruta: objetivo.legible, accion });
|
|
2810
2133
|
}
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
err.write(`\u2713 Actualic\xE9 el CLI de ${instalada2} a ${disponible}${r.skill === null ? "" : ` y ${textoDeLaSkillRenovada(resumen)}`}.
|
|
2827
|
-
`);
|
|
2828
|
-
for (const copia of resumen.copias) err.write(`\u2139 Tu versi\xF3n editada de la skill qued\xF3 en ${copia}.
|
|
2829
|
-
`);
|
|
2830
|
-
mostrarBienvenida(salida, disponible, { env: ctx.env, columnas: salida.humano.columns });
|
|
2134
|
+
if (destinos.proyecto && proyecto) {
|
|
2135
|
+
const archivo = path6.join(destinos.proyecto, "AGENTS.md");
|
|
2136
|
+
if (fs6.existsSync(archivo)) {
|
|
2137
|
+
const texto2 = conReintentoEnWindows(() => fs6.readFileSync(archivo, "utf8"));
|
|
2138
|
+
const bloque = extraerBloque(texto2);
|
|
2139
|
+
if (bloque !== null) {
|
|
2140
|
+
if (!proyecto.agents || sha256(bloque) !== proyecto.agents.sha256) {
|
|
2141
|
+
rutas.push({ ruta: "AGENTS.md", accion: "editada" });
|
|
2142
|
+
} else {
|
|
2143
|
+
const resto = texto2.replace(regexBloque(), "").replace(/\n{3,}/g, "\n\n");
|
|
2144
|
+
if (proyecto.agents.creado && resto.trim() === "") fs6.rmSync(archivo);
|
|
2145
|
+
else escribirAtomico(archivo, resto.replace(/^\n+/, "").replace(/\n*$/, "\n"));
|
|
2146
|
+
rutas.push({ ruta: "AGENTS.md", accion: "quitada" });
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2831
2149
|
}
|
|
2832
|
-
return true;
|
|
2833
|
-
} catch (error) {
|
|
2834
|
-
const codigo = error instanceof ErrorCli && error.codigo ? error.codigo : "ACTUALIZACION_FALLIDA";
|
|
2835
|
-
depurar(`la auto-actualizaci\xF3n a ${disponible} fall\xF3 (${codigo}): ${motivoDe(error)}`);
|
|
2836
|
-
fallo2({ codigo, mensaje: motivoDe(error) }, true);
|
|
2837
|
-
return false;
|
|
2838
2150
|
}
|
|
2151
|
+
guardarRegistroUsuario(destinos, { quitada: true, rutas: {} });
|
|
2152
|
+
if (destinos.proyecto && proyecto) guardarRegistroProyecto(destinos.proyecto, { quitada: true, rutas: {}, agents: void 0 });
|
|
2153
|
+
return { estado: "quitada", rutas };
|
|
2839
2154
|
}
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
import { setTimeout as setTimeoutAbortable } from "node:timers/promises";
|
|
2850
|
-
import * as oidc from "openid-client";
|
|
2851
|
-
|
|
2852
|
-
// src/nucleo/retorno-local.ts
|
|
2853
|
-
import http from "node:http";
|
|
2854
|
-
function paginaListo(titulo, texto2) {
|
|
2855
|
-
return `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>REDCUMBRE</title>
|
|
2856
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
2857
|
-
<style>body{font-family:system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:Canvas;color:CanvasText}
|
|
2858
|
-
main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;opacity:.8}</style></head>
|
|
2859
|
-
<body><main><h1>${titulo}</h1><p>${texto2}</p></main></body></html>`;
|
|
2860
|
-
}
|
|
2861
|
-
async function abrirRetornoLocal(opciones) {
|
|
2862
|
-
let resolver;
|
|
2863
|
-
let rechazar;
|
|
2864
|
-
const recibido = new Promise((ok, falla) => {
|
|
2865
|
-
resolver = ok;
|
|
2866
|
-
rechazar = falla;
|
|
2867
|
-
});
|
|
2868
|
-
recibido.catch(() => void 0);
|
|
2869
|
-
const servidor = http.createServer((req, res) => {
|
|
2870
|
-
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
2871
|
-
if (url.pathname !== "/callback") {
|
|
2872
|
-
res.writeHead(404).end();
|
|
2873
|
-
return;
|
|
2155
|
+
function renovarSkill(opciones) {
|
|
2156
|
+
const { destinos, version } = opciones;
|
|
2157
|
+
const ahora = opciones.ahora ?? /* @__PURE__ */ new Date();
|
|
2158
|
+
if (opciones.reponerQuitada) {
|
|
2159
|
+
const previoUsuario = leerRegistroUsuario(destinos);
|
|
2160
|
+
if (previoUsuario.quitada) guardarRegistroUsuario(destinos, { ...previoUsuario, quitada: void 0 });
|
|
2161
|
+
if (destinos.proyecto) {
|
|
2162
|
+
const previoProyecto = leerRegistroProyecto(destinos.proyecto);
|
|
2163
|
+
if (previoProyecto.quitada) guardarRegistroProyecto(destinos.proyecto, { ...previoProyecto, quitada: void 0 });
|
|
2874
2164
|
}
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2165
|
+
}
|
|
2166
|
+
const usuario = leerRegistroUsuario(destinos);
|
|
2167
|
+
const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
|
|
2168
|
+
const rutas = [];
|
|
2169
|
+
const cambiosUsuario = {};
|
|
2170
|
+
const cambiosProyecto = {};
|
|
2171
|
+
const contenido = contenidoPorFuente(version, opciones.fuente);
|
|
2172
|
+
for (const objetivo of objetivos(destinos)) {
|
|
2173
|
+
const deUsuario = esDeUsuario(objetivo.id);
|
|
2174
|
+
const registro = deUsuario ? usuario : proyecto;
|
|
2175
|
+
if (usuario.quitada || registro.quitada) continue;
|
|
2176
|
+
const registrado = (registro.rutas ?? {})[objetivo.id]?.sha256;
|
|
2177
|
+
if (!fs6.existsSync(objetivo.archivo)) {
|
|
2178
|
+
const texto2 = contenido(objetivo.fuente);
|
|
2179
|
+
escribirAtomico(objetivo.archivo, texto2);
|
|
2180
|
+
(deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = sha256(texto2);
|
|
2181
|
+
rutas.push({ ruta: objetivo.legible, accion: "instalada", instalada: version });
|
|
2182
|
+
continue;
|
|
2878
2183
|
}
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
if (
|
|
2900
|
-
|
|
2184
|
+
const actual = conReintentoEnWindows(() => fs6.readFileSync(objetivo.archivo, "utf8"));
|
|
2185
|
+
const instalada2 = versionDeLaSkill(actual);
|
|
2186
|
+
if (instalada2 !== null && compararVersiones(version, instalada2) < 0) {
|
|
2187
|
+
rutas.push({ ruta: objetivo.legible, accion: "mas-nueva", instalada: instalada2 });
|
|
2188
|
+
continue;
|
|
2189
|
+
}
|
|
2190
|
+
const nuevo = contenido(objetivo.fuente);
|
|
2191
|
+
const hashNuevo = sha256(nuevo);
|
|
2192
|
+
const hashActual = sha256(actual);
|
|
2193
|
+
if (hashActual === hashNuevo) {
|
|
2194
|
+
if (registrado !== hashNuevo) (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
|
|
2195
|
+
rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: version });
|
|
2196
|
+
continue;
|
|
2197
|
+
}
|
|
2198
|
+
const editada = registrado === void 0 || hashActual !== registrado;
|
|
2199
|
+
if (instalada2 !== null && compararVersiones(version, instalada2) === 0 && !editada) {
|
|
2200
|
+
rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: instalada2 });
|
|
2201
|
+
continue;
|
|
2202
|
+
}
|
|
2203
|
+
let copia;
|
|
2204
|
+
if (editada) {
|
|
2205
|
+
try {
|
|
2206
|
+
copia = guardarCopiaDeLoEditado(objetivo.archivo, ahora);
|
|
2207
|
+
} catch (error) {
|
|
2208
|
+
rutas.push({ ruta: objetivo.legible, accion: "desactualizada", instalada: instalada2, error: motivoDe(error) });
|
|
2209
|
+
continue;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
escribirAtomico(objetivo.archivo, nuevo);
|
|
2213
|
+
(deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
|
|
2214
|
+
rutas.push(copia ? { ruta: objetivo.legible, accion: "reemplazada-editada", instalada: instalada2, copia } : { ruta: objetivo.legible, accion: "renovada", instalada: instalada2 });
|
|
2901
2215
|
}
|
|
2902
|
-
|
|
2903
|
-
|
|
2216
|
+
if (Object.keys(cambiosUsuario).length > 0) {
|
|
2217
|
+
const vigente = leerRegistroUsuario(destinos);
|
|
2218
|
+
if (!vigente.quitada) guardarRegistroUsuario(destinos, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosUsuario) } });
|
|
2219
|
+
}
|
|
2220
|
+
if (Object.keys(cambiosProyecto).length > 0 && destinos.proyecto) {
|
|
2221
|
+
const vigente = leerRegistroProyecto(destinos.proyecto);
|
|
2222
|
+
if (!vigente.quitada) guardarRegistroProyecto(destinos.proyecto, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosProyecto) } });
|
|
2223
|
+
}
|
|
2224
|
+
return { version, rutas };
|
|
2904
2225
|
}
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2226
|
+
var aRutas = (cambios) => Object.fromEntries(Object.entries(cambios).map(([id, sha]) => [id, { sha256: sha }]));
|
|
2227
|
+
var COMANDO_SKILL_RENOVAR = "redcumbre skill renovar";
|
|
2228
|
+
function nombreDeLoInstalado(ruta) {
|
|
2229
|
+
const comando2 = ruta.match(/\.claude\/commands\/redcumbre\/([^/]+)\.md$/)?.[1];
|
|
2230
|
+
return comando2 ? `el comando /${NOMBRE_SKILL}:${comando2}` : "la skill de REDCUMBRE";
|
|
2908
2231
|
}
|
|
2909
|
-
function
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
`La carpeta de configuraci\xF3n (${carpeta}) est\xE1 dentro del proyecto: ah\xED no guardo tu sesi\xF3n. Corre el comando con XDG_CONFIG_HOME fuera del proyecto.`
|
|
2914
|
-
);
|
|
2232
|
+
function deLaVersion(ruta, prep, version) {
|
|
2233
|
+
const comando2 = nombreDeLoInstalado(ruta).startsWith("el comando");
|
|
2234
|
+
const que = prep === "a" ? comando2 ? "al" : "a la" : comando2 ? "por el" : "por la";
|
|
2235
|
+
return `${que} de la versi\xF3n ${version}`;
|
|
2915
2236
|
}
|
|
2916
|
-
|
|
2917
|
-
ruta;
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2237
|
+
function avisoDeRenovacion(r, version) {
|
|
2238
|
+
const que = nombreDeLoInstalado(r.ruta);
|
|
2239
|
+
const suyo = que.startsWith("el comando") ? "Tu versi\xF3n editada del comando" : "Tu versi\xF3n editada de la skill";
|
|
2240
|
+
if (r.accion === "instalada") return `Instal\xE9 ${que} en ${r.ruta}.`;
|
|
2241
|
+
if (r.accion === "renovada") return `Renov\xE9 ${que} en ${r.ruta} ${deLaVersion(r.ruta, "a", version)}.`;
|
|
2242
|
+
if (r.accion === "reemplazada-editada") return `Reemplac\xE9 ${que} en ${r.ruta} ${deLaVersion(r.ruta, "por", version)}. ${suyo} qued\xF3 en ${r.copia}.`;
|
|
2243
|
+
if (r.accion === "desactualizada") {
|
|
2244
|
+
const la = que.startsWith("el comando") ? "lo" : "la";
|
|
2245
|
+
return `${que[0].toUpperCase()}${que.slice(1)} en ${r.ruta} tiene cambios tuyos (o no ${la} instal\xF3 el CLI) y no pude guardar su copia (${r.error}): no ${la} toqu\xE9. Corre \xAB${COMANDO_SKILL_RENOVAR}\xBB cuando se pueda escribir en esa carpeta.`;
|
|
2924
2246
|
}
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2247
|
+
return null;
|
|
2248
|
+
}
|
|
2249
|
+
function renovarSkillAlCorrer(opciones) {
|
|
2250
|
+
try {
|
|
2251
|
+
const informe = renovarSkill({ destinos: opciones.destinos, version: opciones.version, ahora: opciones.ahora });
|
|
2252
|
+
for (const r of informe.rutas.filter((x) => x.accion === "instalada" || x.accion === "renovada" || x.accion === "reemplazada-editada")) opciones.avisar(avisoDeRenovacion(r, informe.version));
|
|
2253
|
+
const desactualizadas = informe.rutas.filter((x) => x.accion === "desactualizada");
|
|
2254
|
+
if (desactualizadas.length === 0) return;
|
|
2255
|
+
const hoy = opciones.ahora.toISOString().slice(0, 10);
|
|
2256
|
+
const usuario = leerRegistroUsuario(opciones.destinos);
|
|
2257
|
+
if (usuario.avisoDesactualizadaEn === hoy) return;
|
|
2258
|
+
for (const r of desactualizadas) opciones.avisar(avisoDeRenovacion(r, informe.version));
|
|
2259
|
+
guardarRegistroUsuario(opciones.destinos, { ...usuario, avisoDesactualizadaEn: hoy });
|
|
2260
|
+
} catch (error) {
|
|
2261
|
+
opciones.depurar?.(`no pude revisar la skill instalada (${error instanceof Error ? error.message : String(error)}); el comando sigue`);
|
|
2928
2262
|
}
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2263
|
+
}
|
|
2264
|
+
function revisarSkillInstalada(opciones) {
|
|
2265
|
+
const { destinos, version } = opciones;
|
|
2266
|
+
const usuario = leerRegistroUsuario(destinos);
|
|
2267
|
+
const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
|
|
2268
|
+
if (usuario.quitada || proyecto?.quitada) return { quitada: true, rutas: [] };
|
|
2269
|
+
const contenido = contenidoPorFuente(version, opciones.fuente);
|
|
2270
|
+
const rutas = [];
|
|
2271
|
+
for (const objetivo of objetivos(destinos).filter((o) => o.id.startsWith("claude-"))) {
|
|
2272
|
+
const deUsuario = esDeUsuario(objetivo.id);
|
|
2273
|
+
const registro = deUsuario ? usuario : proyecto;
|
|
2274
|
+
const registrado = (registro.rutas ?? {})[objetivo.id]?.sha256;
|
|
2275
|
+
const informar = (estado2) => rutas.push({ id: objetivo.id, ruta: objetivo.legible, ambito: deUsuario ? "usuario" : "proyecto", estado: estado2 });
|
|
2276
|
+
if (!fs6.existsSync(objetivo.archivo)) {
|
|
2277
|
+
if (registrado === void 0) informar("falta");
|
|
2278
|
+
continue;
|
|
2279
|
+
}
|
|
2280
|
+
const actual = conReintentoEnWindows(() => fs6.readFileSync(objetivo.archivo, "utf8"));
|
|
2281
|
+
const instalada2 = versionDeLaSkill(actual);
|
|
2282
|
+
if (instalada2 !== null && compararVersiones(version, instalada2) < 0) {
|
|
2283
|
+
informar("mas-nueva");
|
|
2284
|
+
continue;
|
|
2285
|
+
}
|
|
2286
|
+
if (sha256(actual) === sha256(contenido(objetivo.fuente))) {
|
|
2287
|
+
informar("al-dia");
|
|
2288
|
+
continue;
|
|
2289
|
+
}
|
|
2290
|
+
const editada = registrado === void 0 || sha256(actual) !== registrado;
|
|
2291
|
+
if (editada) informar("editada");
|
|
2292
|
+
else informar(instalada2 !== null && compararVersiones(version, instalada2) === 0 ? "al-dia" : "desactualizada");
|
|
2933
2293
|
}
|
|
2934
|
-
|
|
2935
|
-
|
|
2294
|
+
return { quitada: false, rutas };
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
// src/comandos/doctor.ts
|
|
2298
|
+
async function doctor(ctx) {
|
|
2299
|
+
const { salida, proyecto } = ctx;
|
|
2300
|
+
const revisiones = [];
|
|
2301
|
+
const anotar = (r) => {
|
|
2302
|
+
revisiones.push(r);
|
|
2303
|
+
salida.linea(`${r.ok ? "\u2713" : r.opcional ? "\xB7" : "\u2717"} ${r.detalle}${!r.ok && r.comando ? ` \u2192 ${r.comando}` : ""}`);
|
|
2304
|
+
};
|
|
2305
|
+
const haySesion = await ctx.haySesion();
|
|
2306
|
+
anotar(
|
|
2307
|
+
haySesion ? { revision: "sesion", ok: true, detalle: "Hay una sesi\xF3n iniciada en este computador." } : { revision: "sesion", ok: false, detalle: "No hay una sesi\xF3n iniciada en este computador.", comando: "redcumbre login" }
|
|
2308
|
+
);
|
|
2309
|
+
const estado2 = leerEstado(proyecto);
|
|
2310
|
+
let slug = null;
|
|
2311
|
+
if (estado2) {
|
|
2312
|
+
slug = estado2.tenantSlug;
|
|
2313
|
+
anotar({ revision: "empresa", ok: true, detalle: `El proyecto ${proyecto} apunta a la empresa ${slug}.` });
|
|
2314
|
+
} else {
|
|
2315
|
+
anotar({ revision: "empresa", ok: false, detalle: `La carpeta ${proyecto} no est\xE1 conectada con REDCUMBRE (falta .redcumbre/estado.json).`, comando: COMANDO_INIT });
|
|
2936
2316
|
}
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
constructor(entrada) {
|
|
2940
|
-
this.entrada = entrada;
|
|
2317
|
+
for (const entorno of ENTORNOS_LLAVE) {
|
|
2318
|
+
anotar(await revisarLlave(ctx, entorno, slug));
|
|
2941
2319
|
}
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2320
|
+
const gitignore = path7.join(proyecto, ".gitignore");
|
|
2321
|
+
const lineas = new Set((fs7.existsSync(gitignore) ? fs7.readFileSync(gitignore, "utf8") : "").split(/\r?\n/).map((l) => l.trim()));
|
|
2322
|
+
const faltanExclusiones = ["keys/", ".redcumbre/"].filter((l) => !lineas.has(l) && !lineas.has(`/${l}`));
|
|
2323
|
+
const versionadas = ENTORNOS_LLAVE.map((e) => path7.relative(proyecto, rutaDeLaLlave(proyecto, e, ctx.env))).filter(
|
|
2324
|
+
(relativa) => fs7.existsSync(path7.join(proyecto, relativa)) && estaVersionado(proyecto, relativa)
|
|
2325
|
+
);
|
|
2326
|
+
if (versionadas.length > 0) {
|
|
2327
|
+
anotar({
|
|
2328
|
+
revision: "exclusiones",
|
|
2329
|
+
ok: false,
|
|
2330
|
+
detalle: `La llave est\xE1 en el control de versiones (${versionadas.join(", ")}): s\xE1cala con \xABgit rm --cached ${versionadas.join(" ")}\xBB y rev\xF3cala en la web, porque qued\xF3 en el historial.`
|
|
2331
|
+
});
|
|
2332
|
+
} else if (faltanExclusiones.length > 0) {
|
|
2333
|
+
anotar({ revision: "exclusiones", ok: false, detalle: `Al .gitignore le falta ${faltanExclusiones.join(" y ")}.`, comando: COMANDO_INIT });
|
|
2334
|
+
} else {
|
|
2335
|
+
anotar({ revision: "exclusiones", ok: true, detalle: "keys/ y .redcumbre/ est\xE1n fuera del control de versiones." });
|
|
2946
2336
|
}
|
|
2947
|
-
|
|
2948
|
-
|
|
2337
|
+
anotar(revisarSkill(ctx));
|
|
2338
|
+
try {
|
|
2339
|
+
const documento = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, salida);
|
|
2340
|
+
anotar({
|
|
2341
|
+
revision: "documento",
|
|
2342
|
+
ok: true,
|
|
2343
|
+
detalle: documento.copiaSinRevalidar ? `Uso la copia del documento del API sin revalidar (${documento.operaciones.length} operaciones).` : `El documento del API est\xE1 al d\xEDa (${documento.operaciones.length} operaciones).`
|
|
2344
|
+
});
|
|
2345
|
+
} catch (error) {
|
|
2346
|
+
anotar({ revision: "documento", ok: false, detalle: `No pude leer el documento del API: ${error instanceof Error ? error.message : String(error)}` });
|
|
2949
2347
|
}
|
|
2950
|
-
|
|
2951
|
-
|
|
2348
|
+
const disponible = ctx.versionDelRegistro ? ctx.versionDelRegistro.ultima : (await ultimaVersionConocida({ carpeta: ctx.carpetaConfiguracion, version: ctx.version, ahora: ctx.ahora(), registro: ctx.env.REDCUMBRE_NPM_REGISTRY, sinMarca: true })).ultima;
|
|
2349
|
+
const version = { instalada: ctx.version, disponible };
|
|
2350
|
+
if (disponible === null) salida.linea("\xB7 No pude consultar la \xFAltima versi\xF3n del CLI.");
|
|
2351
|
+
else if (compararVersiones(disponible, ctx.version) > 0) salida.linea(`\xB7 Hay una versi\xF3n m\xE1s nueva del CLI: ${disponible} (tienes ${ctx.version}). Actual\xEDzala con \xAB${COMANDO_ACTUALIZAR}\xBB.`);
|
|
2352
|
+
else salida.linea(`\u2713 El CLI est\xE1 en la \xFAltima versi\xF3n (${ctx.version}).`);
|
|
2353
|
+
const faltantes = revisiones.filter((r) => !r.ok && !r.opcional).map((r) => ({ revision: r.revision, detalle: r.detalle, ...r.comando ? { comando: r.comando } : {} }));
|
|
2354
|
+
if (faltantes.length > 0) {
|
|
2355
|
+
throw new ErrorCli(`Hay ${faltantes.length === 1 ? "una cosa que arreglar" : `${faltantes.length} cosas que arreglar`} en el proyecto.`, CODIGOS_DE_SALIDA.error, {
|
|
2356
|
+
codigo: "DOCTOR_CON_FALTANTES",
|
|
2357
|
+
datos: { revisiones, faltantes, version }
|
|
2358
|
+
});
|
|
2952
2359
|
}
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
return
|
|
2360
|
+
salida.linea("Todo en orden.");
|
|
2361
|
+
salida.resultado({ ok: true, proyecto, revisiones, faltantes: [], version });
|
|
2362
|
+
}
|
|
2363
|
+
async function revisarLlave(ctx, entorno, slug) {
|
|
2364
|
+
const revision = `llave-${entorno}`;
|
|
2365
|
+
const nombre = etiquetaLlave(entorno);
|
|
2366
|
+
const ruta = path7.relative(ctx.proyecto, rutaDeLaLlave(ctx.proyecto, entorno, ctx.env)) || rutaDeLaLlave(ctx.proyecto, entorno, ctx.env);
|
|
2367
|
+
const archivo = llaveDelEntorno(ctx.proyecto, entorno, ctx.env);
|
|
2368
|
+
if (!archivo) {
|
|
2369
|
+
return entorno === "prueba" ? { revision, ok: false, detalle: `Falta la ${nombre} (${ruta}).`, comando: COMANDO_INIT } : { revision, ok: false, opcional: true, detalle: `El proyecto todav\xEDa no tiene ${nombre}.`, comando: COMANDO_PASAR_A_PRODUCCION };
|
|
2963
2370
|
}
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2371
|
+
if (slug && archivo.tenantSlug !== slug) {
|
|
2372
|
+
return { revision, ok: false, detalle: `La ${nombre} es de ${archivo.tenantSlug}, pero el proyecto apunta a ${slug}.`, comando: COMANDO_INIT };
|
|
2373
|
+
}
|
|
2374
|
+
try {
|
|
2375
|
+
const r = await ctx.cliente.whoami(archivo.token, archivo.tenantSlug);
|
|
2376
|
+
if (r.estado === "rechazada") return { revision, ok: false, detalle: `La API rechaza la ${nombre} (${ruta}): fue revocada o venci\xF3.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_PRODUCCION };
|
|
2377
|
+
if (r.sandbox !== (entorno === "prueba")) {
|
|
2378
|
+
return { revision, ok: false, detalle: `El archivo ${ruta} no trae una ${nombre}: seg\xFAn la API es de otro modo.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_PRODUCCION };
|
|
2379
|
+
}
|
|
2380
|
+
return { revision, ok: true, detalle: `La ${nombre} funciona (${r.tenant.nombre}).` };
|
|
2381
|
+
} catch (error) {
|
|
2382
|
+
return { revision, ok: false, detalle: `No pude comprobar la ${nombre}: ${error instanceof Error ? error.message : String(error)}` };
|
|
2969
2383
|
}
|
|
2970
|
-
};
|
|
2971
|
-
var DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
2972
|
-
function esperarAbortable(ms, signal) {
|
|
2973
|
-
return setTimeoutAbortable(ms, void 0, { signal });
|
|
2974
|
-
}
|
|
2975
|
-
function comoPar(respuesta) {
|
|
2976
|
-
if (!respuesta.refresh_token) throw new ErrorCli("El servidor de identidad no devolvi\xF3 un refresh token.");
|
|
2977
|
-
const segundos = respuesta.expiresIn();
|
|
2978
|
-
if (segundos === void 0) throw new ErrorCli("El servidor de identidad no dijo cu\xE1ndo vence el token.");
|
|
2979
|
-
return {
|
|
2980
|
-
access_token: respuesta.access_token,
|
|
2981
|
-
refresh_token: respuesta.refresh_token,
|
|
2982
|
-
expira: new Date(Date.now() + segundos * 1e3).toISOString()
|
|
2983
|
-
};
|
|
2984
|
-
}
|
|
2985
|
-
function refreshInvalido(codigo, descripcion) {
|
|
2986
|
-
return codigo === "invalid_grant" || codigo === "invalid_request" && /RefreshToken/i.test(descripcion ?? "");
|
|
2987
|
-
}
|
|
2988
|
-
function esRefreshInvalido(error) {
|
|
2989
|
-
return error instanceof oidc.ResponseBodyError && refreshInvalido(error.error, error.error_description);
|
|
2990
2384
|
}
|
|
2991
|
-
function
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2385
|
+
async function panel(ctx, opciones) {
|
|
2386
|
+
const slug = empresaDelProyecto(ctx, opciones.empresa);
|
|
2387
|
+
const url = `${ctx.servidores.web}${rutaDeEmpresa(slug, "/dashboard")}`;
|
|
2388
|
+
const abierto = opciones.sinNavegador ? false : await ctx.abrir(url);
|
|
2389
|
+
ctx.salida.linea(abierto ? `Abr\xED el panel de ${slug} en el navegador: ${url}` : `El panel de ${slug}: ${url}`);
|
|
2390
|
+
ctx.salida.resultado({ ok: true, empresa: slug, url, abierto });
|
|
2996
2391
|
}
|
|
2997
|
-
function
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
const
|
|
3001
|
-
|
|
2392
|
+
function revisarSkill(ctx) {
|
|
2393
|
+
const destinos = { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto: tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0 };
|
|
2394
|
+
try {
|
|
2395
|
+
const informe = revisarSkillInstalada({ destinos, version: ctx.version });
|
|
2396
|
+
if (informe.quitada) {
|
|
2397
|
+
return { revision: "skill", ok: true, detalle: "Quitaste la skill de REDCUMBRE con \xABredcumbre skill quitar\xBB: no se instala ni se renueva." };
|
|
2398
|
+
}
|
|
2399
|
+
const pendientes = informe.rutas.filter((r) => r.estado !== "al-dia" && r.estado !== "mas-nueva");
|
|
2400
|
+
if (pendientes.length === 0) {
|
|
2401
|
+
return { revision: "skill", ok: true, detalle: "La skill de REDCUMBRE y los comandos /redcumbre:tarifas y /redcumbre:issue est\xE1n al d\xEDa." };
|
|
2402
|
+
}
|
|
2403
|
+
const detalle = pendientes.map((r) => `${r.ruta} (${r.estado === "falta" ? "falta" : r.estado === "editada" ? "tiene cambios tuyos" : "de una versi\xF3n anterior"})`).join(", ");
|
|
2404
|
+
const faltaLaDelProyecto = pendientes.some((r) => r.id === "claude-proyecto" && r.estado === "falta");
|
|
2405
|
+
return { revision: "skill", ok: false, opcional: true, detalle: `Hay que renovar la skill o los comandos de Claude Code: ${detalle}.`, comando: faltaLaDelProyecto ? COMANDO_INIT : COMANDO_SKILL_RENOVAR };
|
|
2406
|
+
} catch (error) {
|
|
2407
|
+
return { revision: "skill", ok: false, opcional: true, detalle: `No pude revisar la skill de REDCUMBRE: ${error instanceof Error ? error.message : String(error)}`, comando: COMANDO_SKILL_RENOVAR };
|
|
3002
2408
|
}
|
|
3003
|
-
|
|
3004
|
-
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
// src/comandos/emisores.ts
|
|
2412
|
+
import fs11 from "node:fs";
|
|
2413
|
+
import path12 from "node:path";
|
|
2414
|
+
|
|
2415
|
+
// src/comandos/emisores-operaciones.ts
|
|
2416
|
+
var RUT_FILTRO = { bandera: "--rut <rut>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "rut" } };
|
|
2417
|
+
var ESTADO_FILTRO = { bandera: "--estado <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "estado" } };
|
|
2418
|
+
var INTEGRACION_FILTRO = { bandera: "--integracion <tipo>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "tipoIntegracion" } };
|
|
2419
|
+
var CREDENCIAL_FILTRO = { bandera: "--credencial <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "credencialEstado" } };
|
|
2420
|
+
var ACTIVO_FILTRO = { bandera: "--activo <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "activo" }, valores: ["true", "false"] };
|
|
2421
|
+
var TRIBUTARIA_FILTRO = { bandera: "--tributaria <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "esTributaria" }, valores: ["true", "false"] };
|
|
2422
|
+
var LIMITE = { bandera: "--limite <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "limit" } };
|
|
2423
|
+
var DESDE = { bandera: "--desde <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "offset" } };
|
|
2424
|
+
var TODAS = { bandera: "--todas", obligatoria: false, tipo: "interruptor", destino: { en: "ninguno" } };
|
|
2425
|
+
var INCLUIR_ARCHIVADOS = { bandera: "--incluir-archivados", obligatoria: false, tipo: "interruptor", destino: { en: "consulta", nombre: "includeInactive", valorFijo: "true" } };
|
|
2426
|
+
var CUERPO_OBLIGATORIO = { bandera: "--cuerpo <json|@archivo|->", obligatoria: true, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
|
|
2427
|
+
var CUERPO_OPCIONAL = { bandera: "--cuerpo <json|@archivo|->", obligatoria: false, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
|
|
2428
|
+
var ARCHIVO_LOGO = { bandera: "--archivo <ruta>", obligatoria: true, tipo: "archivo", destino: { en: "formulario", nombre: "logo" } };
|
|
2429
|
+
var TIPOS_DE_CERTIFICACION = { bandera: "--tipos <lista>", obligatoria: true, tipo: "lista-de-enteros", destino: { en: "cuerpo", nombre: "tiposDte" } };
|
|
2430
|
+
var CORREO_DE_CONTACTO = { bandera: "--correo <correo>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "emailContacto" } };
|
|
2431
|
+
var TELEFONO_DE_CONTACTO = { bandera: "--telefono <tel\xE9fono>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "telefonoContacto" } };
|
|
2432
|
+
var RUT_DE_CONFIRMACION = { bandera: "--rut <rut>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "confirmacionRut" } };
|
|
2433
|
+
var MOTIVO_OPCIONAL = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivo" } };
|
|
2434
|
+
var TIPO_DTE_DEL_AMBIENTE = { bandera: "--tipo-dte <n>", obligatoria: true, tipo: "entero", destino: { en: "cuerpo", nombre: "tipoDte" } };
|
|
2435
|
+
var AMBIENTE_DEL_TIPO = { bandera: "--ambiente <CERTIFICACION|PRODUCCION>", obligatoria: true, tipo: "ambiente", destino: { en: "cuerpo", nombre: "ambiente" }, valores: ["CERTIFICACION", "PRODUCCION"] };
|
|
2436
|
+
var TIPO_DE_EMISOR_A_REVOCAR = { bandera: "--tipo <tributario|dte>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "tipoEmisor" }, valores: ["tributario", "dte"] };
|
|
2437
|
+
var MOTIVO_DE_REVOCACION = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivoRevocacion" } };
|
|
2438
|
+
var OPERACIONES_EMISORES = [
|
|
2439
|
+
{
|
|
2440
|
+
// 1
|
|
2441
|
+
comando: ["dte", "listar"],
|
|
2442
|
+
operationId: "listarEmisoresDte",
|
|
2443
|
+
metodo: "GET",
|
|
2444
|
+
ruta: "/{tenantSlug}/emisores",
|
|
2445
|
+
argumentos: [],
|
|
2446
|
+
banderas: [RUT_FILTRO, ESTADO_FILTRO, INTEGRACION_FILTRO, LIMITE, DESDE, TODAS],
|
|
2447
|
+
salida: "tabla",
|
|
2448
|
+
columnas: ["emisorId", "rut", "razonSocial", "tipoIntegracion", "estado"],
|
|
2449
|
+
confirmacion: "efecto"
|
|
2450
|
+
},
|
|
2451
|
+
{
|
|
2452
|
+
// 2
|
|
2453
|
+
comando: ["dte", "por-defecto"],
|
|
2454
|
+
operationId: "listarEmisoresDtePorDefecto",
|
|
2455
|
+
metodo: "GET",
|
|
2456
|
+
ruta: "/{tenantSlug}/emisores/default",
|
|
2457
|
+
argumentos: [],
|
|
2458
|
+
banderas: [],
|
|
2459
|
+
salida: "tabla",
|
|
2460
|
+
columnas: ["emisorId", "rut", "razonSocial", "tipoIntegracion"],
|
|
2461
|
+
confirmacion: "efecto"
|
|
2462
|
+
},
|
|
2463
|
+
{
|
|
2464
|
+
// 3
|
|
2465
|
+
comando: ["dte", "existe"],
|
|
2466
|
+
operationId: "verificarRutEmisorDte",
|
|
2467
|
+
metodo: "GET",
|
|
2468
|
+
ruta: "/{tenantSlug}/emisores/check-rut/{rut}",
|
|
2469
|
+
argumentos: ["rut"],
|
|
2470
|
+
banderas: [],
|
|
2471
|
+
salida: "ficha",
|
|
2472
|
+
confirmacion: "efecto"
|
|
2473
|
+
},
|
|
2474
|
+
{
|
|
2475
|
+
// 4
|
|
2476
|
+
comando: ["dte", "ver"],
|
|
2477
|
+
operationId: "obtenerEmisorDte",
|
|
2478
|
+
metodo: "GET",
|
|
2479
|
+
ruta: "/{tenantSlug}/emisores/{id}",
|
|
2480
|
+
argumentos: ["id"],
|
|
2481
|
+
banderas: [INCLUIR_ARCHIVADOS],
|
|
2482
|
+
salida: "ficha",
|
|
2483
|
+
confirmacion: "efecto"
|
|
2484
|
+
},
|
|
2485
|
+
{
|
|
2486
|
+
// 5
|
|
2487
|
+
comando: ["dte", "certificacion", "verificar"],
|
|
2488
|
+
operationId: "verificarCertificacionTipoEmisorDte",
|
|
2489
|
+
metodo: "GET",
|
|
2490
|
+
ruta: "/{tenantSlug}/emisores/{id}/verificar-certificacion/{tipoDte}",
|
|
2491
|
+
argumentos: ["id", "tipoDte"],
|
|
2492
|
+
banderas: [],
|
|
2493
|
+
salida: "ficha",
|
|
2494
|
+
confirmacion: "efecto"
|
|
2495
|
+
},
|
|
2496
|
+
{
|
|
2497
|
+
// 6
|
|
2498
|
+
comando: ["dte", "certificacion", "tipos"],
|
|
2499
|
+
operationId: "listarTiposCertificablesEmisorDte",
|
|
2500
|
+
metodo: "GET",
|
|
2501
|
+
ruta: "/{tenantSlug}/emisores/{id}/tipos-dte-certificables",
|
|
2502
|
+
argumentos: ["id"],
|
|
2503
|
+
banderas: [],
|
|
2504
|
+
salida: "ficha",
|
|
2505
|
+
confirmacion: "efecto"
|
|
2506
|
+
},
|
|
2507
|
+
{
|
|
2508
|
+
// 7
|
|
2509
|
+
comando: ["dte", "certificacion", "estado"],
|
|
2510
|
+
operationId: "consultarEstadoCertificacionRutEmisorDte",
|
|
2511
|
+
metodo: "GET",
|
|
2512
|
+
ruta: "/{tenantSlug}/emisores/{id}/estado-certificacion-rut",
|
|
2513
|
+
argumentos: ["id"],
|
|
2514
|
+
banderas: [],
|
|
2515
|
+
salida: "ficha",
|
|
2516
|
+
confirmacion: "efecto"
|
|
2517
|
+
},
|
|
2518
|
+
{
|
|
2519
|
+
// 8
|
|
2520
|
+
comando: ["dte", "mipyme", "estado"],
|
|
2521
|
+
operationId: "consultarEstadoMipymeEmisorDte",
|
|
2522
|
+
metodo: "GET",
|
|
2523
|
+
ruta: "/{tenantSlug}/emisores/{id}/mipyme/estado",
|
|
2524
|
+
argumentos: ["id"],
|
|
2525
|
+
banderas: [],
|
|
2526
|
+
salida: "ficha",
|
|
2527
|
+
confirmacion: "efecto"
|
|
2528
|
+
},
|
|
2529
|
+
{
|
|
2530
|
+
// 9
|
|
2531
|
+
comando: ["dte", "solicitudes"],
|
|
2532
|
+
operationId: "listarSolicitudesCertificacionEmisorDte",
|
|
2533
|
+
metodo: "GET",
|
|
2534
|
+
ruta: "/{tenantSlug}/emisores/{id}/solicitudes",
|
|
2535
|
+
argumentos: ["id"],
|
|
2536
|
+
banderas: [],
|
|
2537
|
+
salida: "tabla",
|
|
2538
|
+
columnas: ["solicitudId", "tipoSolicitud", "estado", "solicitadoEn"],
|
|
2539
|
+
confirmacion: "efecto"
|
|
2540
|
+
},
|
|
2541
|
+
{
|
|
2542
|
+
// 10
|
|
2543
|
+
comando: ["dte", "logo", "ver"],
|
|
2544
|
+
operationId: "obtenerLogoEmisorDte",
|
|
2545
|
+
metodo: "GET",
|
|
2546
|
+
ruta: "/{tenantSlug}/emisores/{id}/logo",
|
|
2547
|
+
argumentos: ["id"],
|
|
2548
|
+
banderas: [],
|
|
2549
|
+
salida: "ficha",
|
|
2550
|
+
confirmacion: "efecto"
|
|
2551
|
+
},
|
|
2552
|
+
{
|
|
2553
|
+
// 11
|
|
2554
|
+
comando: ["dte", "editar"],
|
|
2555
|
+
operationId: "actualizarEmisorDte",
|
|
2556
|
+
metodo: "PATCH",
|
|
2557
|
+
ruta: "/{tenantSlug}/emisores/{id}",
|
|
2558
|
+
argumentos: ["id"],
|
|
2559
|
+
banderas: [CUERPO_OBLIGATORIO],
|
|
2560
|
+
salida: "accion",
|
|
2561
|
+
hecho: "Emisor actualizado.",
|
|
2562
|
+
confirmacion: "efecto"
|
|
2563
|
+
},
|
|
2564
|
+
{
|
|
2565
|
+
// 12
|
|
2566
|
+
comando: ["dte", "fijar-por-defecto"],
|
|
2567
|
+
operationId: "asignarEmisorDtePorDefecto",
|
|
2568
|
+
metodo: "PATCH",
|
|
2569
|
+
ruta: "/{tenantSlug}/emisores/{id}/set-default",
|
|
2570
|
+
argumentos: ["id"],
|
|
2571
|
+
banderas: [],
|
|
2572
|
+
salida: "accion",
|
|
2573
|
+
hecho: "Emisor fijado por defecto.",
|
|
2574
|
+
confirmacion: "efecto"
|
|
2575
|
+
},
|
|
2576
|
+
{
|
|
2577
|
+
// 13
|
|
2578
|
+
comando: ["dte", "reactivar"],
|
|
2579
|
+
operationId: "reactivarEmisorDte",
|
|
2580
|
+
metodo: "PATCH",
|
|
2581
|
+
ruta: "/{tenantSlug}/emisores/{id}/reactivate",
|
|
2582
|
+
argumentos: ["id"],
|
|
2583
|
+
banderas: [CUERPO_OPCIONAL],
|
|
2584
|
+
salida: "accion",
|
|
2585
|
+
hecho: "Emisor reactivado.",
|
|
2586
|
+
confirmacion: "efecto"
|
|
2587
|
+
},
|
|
2588
|
+
{
|
|
2589
|
+
// 14
|
|
2590
|
+
comando: ["dte", "tipos-integracion", "crear"],
|
|
2591
|
+
operationId: "crearTipoIntegracionEmisorDte",
|
|
2592
|
+
metodo: "POST",
|
|
2593
|
+
ruta: "/{tenantSlug}/emisores/{id}/tipos-integracion",
|
|
2594
|
+
argumentos: ["id"],
|
|
2595
|
+
banderas: [CUERPO_OBLIGATORIO],
|
|
2596
|
+
salida: "accion",
|
|
2597
|
+
hecho: "Tipo de integraci\xF3n creado.",
|
|
2598
|
+
confirmacion: "efecto"
|
|
2599
|
+
},
|
|
2600
|
+
{
|
|
2601
|
+
// 15
|
|
2602
|
+
comando: ["dte", "tipos-integracion", "editar"],
|
|
2603
|
+
operationId: "actualizarTipoIntegracionEmisorDte",
|
|
2604
|
+
metodo: "PATCH",
|
|
2605
|
+
ruta: "/{tenantSlug}/emisores/{id}/tipos-integracion/{tiId}",
|
|
2606
|
+
argumentos: ["id", "tiId"],
|
|
2607
|
+
banderas: [CUERPO_OBLIGATORIO],
|
|
2608
|
+
salida: "accion",
|
|
2609
|
+
hecho: "Tipo de integraci\xF3n actualizado.",
|
|
2610
|
+
confirmacion: "efecto"
|
|
2611
|
+
},
|
|
2612
|
+
{
|
|
2613
|
+
// 16
|
|
2614
|
+
comando: ["dte", "logo", "subir"],
|
|
2615
|
+
operationId: "actualizarLogoEmisorDte",
|
|
2616
|
+
metodo: "POST",
|
|
2617
|
+
ruta: "/{tenantSlug}/emisores/{id}/logo",
|
|
2618
|
+
argumentos: ["id"],
|
|
2619
|
+
banderas: [ARCHIVO_LOGO],
|
|
2620
|
+
salida: "accion",
|
|
2621
|
+
hecho: "Logo actualizado.",
|
|
2622
|
+
confirmacion: "efecto"
|
|
2623
|
+
},
|
|
2624
|
+
{
|
|
2625
|
+
// 17
|
|
2626
|
+
comando: ["dte", "logo", "quitar"],
|
|
2627
|
+
operationId: "eliminarLogoEmisorDte",
|
|
2628
|
+
metodo: "DELETE",
|
|
2629
|
+
ruta: "/{tenantSlug}/emisores/{id}/logo",
|
|
2630
|
+
argumentos: ["id"],
|
|
2631
|
+
banderas: [],
|
|
2632
|
+
salida: "accion",
|
|
2633
|
+
hecho: "Logo eliminado.",
|
|
2634
|
+
confirmacion: "efecto"
|
|
2635
|
+
},
|
|
2636
|
+
{
|
|
2637
|
+
// 18
|
|
2638
|
+
comando: ["dte", "info-pago", "guardar"],
|
|
2639
|
+
operationId: "actualizarInfoPagoEmisorDte",
|
|
2640
|
+
metodo: "PUT",
|
|
2641
|
+
ruta: "/{tenantSlug}/emisores/{id}/info-pago",
|
|
2642
|
+
argumentos: ["id"],
|
|
2643
|
+
banderas: [CUERPO_OBLIGATORIO],
|
|
2644
|
+
salida: "accion",
|
|
2645
|
+
hecho: "Informaci\xF3n de pago guardada.",
|
|
2646
|
+
confirmacion: "efecto"
|
|
2647
|
+
},
|
|
2648
|
+
{
|
|
2649
|
+
// 19
|
|
2650
|
+
comando: ["dte", "info-pago", "quitar"],
|
|
2651
|
+
operationId: "eliminarInfoPagoEmisorDte",
|
|
2652
|
+
metodo: "DELETE",
|
|
2653
|
+
ruta: "/{tenantSlug}/emisores/{id}/info-pago",
|
|
2654
|
+
argumentos: ["id"],
|
|
2655
|
+
banderas: [],
|
|
2656
|
+
salida: "accion",
|
|
2657
|
+
hecho: "Informaci\xF3n de pago eliminada.",
|
|
2658
|
+
confirmacion: "efecto"
|
|
2659
|
+
},
|
|
2660
|
+
{
|
|
2661
|
+
// 20
|
|
2662
|
+
comando: ["dte", "resolver-conflictos"],
|
|
2663
|
+
operationId: "resolverConflictosEmisorDte",
|
|
2664
|
+
metodo: "POST",
|
|
2665
|
+
ruta: "/{tenantSlug}/emisores/{id}/resolver-conflictos",
|
|
2666
|
+
argumentos: ["id"],
|
|
2667
|
+
banderas: [CUERPO_OBLIGATORIO],
|
|
2668
|
+
salida: "accion",
|
|
2669
|
+
hecho: "Conflictos resueltos.",
|
|
2670
|
+
confirmacion: "efecto"
|
|
2671
|
+
},
|
|
2672
|
+
{
|
|
2673
|
+
// 21
|
|
2674
|
+
comando: ["dte", "certificacion", "certificar-tipos"],
|
|
2675
|
+
operationId: "crearSolicitudCertificacionTiposEmisorDte",
|
|
2676
|
+
metodo: "POST",
|
|
2677
|
+
ruta: "/{tenantSlug}/emisores/{id}/certificar-tipos",
|
|
2678
|
+
argumentos: ["id"],
|
|
2679
|
+
banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
|
|
2680
|
+
salida: "accion",
|
|
2681
|
+
hecho: "Certificaci\xF3n de tipos solicitada.",
|
|
2682
|
+
confirmacion: "escrita",
|
|
2683
|
+
aviso: "Esto le pide al SII certificar al contribuyente, con el RUT de su representante legal."
|
|
2684
|
+
},
|
|
2685
|
+
{
|
|
2686
|
+
// 22
|
|
2687
|
+
comando: ["dte", "migrar"],
|
|
2688
|
+
operationId: "crearSolicitudMigracionEmisorDte",
|
|
2689
|
+
metodo: "POST",
|
|
2690
|
+
ruta: "/{tenantSlug}/emisores/{id}/migrar",
|
|
2691
|
+
argumentos: ["id"],
|
|
2692
|
+
banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
|
|
2693
|
+
salida: "accion",
|
|
2694
|
+
hecho: "Migraci\xF3n solicitada.",
|
|
2695
|
+
confirmacion: "escrita",
|
|
2696
|
+
aviso: "Esto le pide al SII migrar el sistema de facturaci\xF3n del contribuyente. Puede dejar sin uso los folios que tenga."
|
|
2697
|
+
},
|
|
2698
|
+
{
|
|
2699
|
+
// 23
|
|
2700
|
+
comando: ["dte", "certificacion", "desistir"],
|
|
2701
|
+
operationId: "cancelarCertificacionEmisorDte",
|
|
2702
|
+
metodo: "POST",
|
|
2703
|
+
ruta: "/{tenantSlug}/emisores/{id}/desistir-certificacion",
|
|
2704
|
+
argumentos: ["id"],
|
|
2705
|
+
banderas: [RUT_DE_CONFIRMACION, MOTIVO_OPCIONAL],
|
|
2706
|
+
salida: "accion",
|
|
2707
|
+
hecho: "Desististe de la certificaci\xF3n.",
|
|
2708
|
+
confirmacion: "escrita",
|
|
2709
|
+
aviso: "Esto archiva el emisor y cierra sus solicitudes de certificaci\xF3n."
|
|
2710
|
+
},
|
|
2711
|
+
{
|
|
2712
|
+
// 24
|
|
2713
|
+
comando: ["dte", "mipyme", "habilitar"],
|
|
2714
|
+
operationId: "registrarEmisorDteEnPortalMipyme",
|
|
2715
|
+
metodo: "POST",
|
|
2716
|
+
ruta: "/{tenantSlug}/emisores/{id}/mipyme/habilitar",
|
|
2717
|
+
argumentos: ["id"],
|
|
2718
|
+
banderas: [],
|
|
2719
|
+
salida: "accion",
|
|
2720
|
+
hecho: "Portal MiPyme habilitado.",
|
|
2721
|
+
confirmacion: "escrita",
|
|
2722
|
+
aviso: "Esto inscribe al contribuyente en el Portal MiPyme del SII. Puede dejar sin uso los folios de mercado que tenga."
|
|
2723
|
+
},
|
|
2724
|
+
{
|
|
2725
|
+
// 25
|
|
2726
|
+
comando: ["dte", "ambiente"],
|
|
2727
|
+
operationId: "cambiarAmbienteTipoEmisorDte",
|
|
2728
|
+
metodo: "PATCH",
|
|
2729
|
+
ruta: "/{tenantSlug}/emisores/{id}/ambiente",
|
|
2730
|
+
argumentos: ["id"],
|
|
2731
|
+
banderas: [TIPO_DTE_DEL_AMBIENTE, AMBIENTE_DEL_TIPO],
|
|
2732
|
+
salida: "accion",
|
|
2733
|
+
hecho: "Ambiente cambiado.",
|
|
2734
|
+
confirmacion: "escrita",
|
|
2735
|
+
aviso: "Esto cambia el ambiente del SII por el que sale ese tipo de documento."
|
|
2736
|
+
},
|
|
2737
|
+
{
|
|
2738
|
+
// 26
|
|
2739
|
+
comando: ["dte", "archivar"],
|
|
2740
|
+
operationId: "archivarEmisorDte",
|
|
2741
|
+
metodo: "DELETE",
|
|
2742
|
+
ruta: "/{tenantSlug}/emisores/{id}",
|
|
2743
|
+
argumentos: ["id"],
|
|
2744
|
+
banderas: [RUT_DE_CONFIRMACION],
|
|
2745
|
+
salida: "accion",
|
|
2746
|
+
hecho: "Emisor archivado.",
|
|
2747
|
+
archiva: true,
|
|
2748
|
+
confirmacion: "escrita",
|
|
2749
|
+
aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
|
|
2750
|
+
},
|
|
2751
|
+
{
|
|
2752
|
+
// 27
|
|
2753
|
+
comando: ["tributarios", "archivar"],
|
|
2754
|
+
operationId: "archivarEmisorTributario",
|
|
2755
|
+
metodo: "DELETE",
|
|
2756
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}",
|
|
2757
|
+
argumentos: ["id"],
|
|
2758
|
+
banderas: [],
|
|
2759
|
+
salida: "accion",
|
|
2760
|
+
hecho: "Emisor archivado.",
|
|
2761
|
+
archiva: true,
|
|
2762
|
+
confirmacion: "escrita",
|
|
2763
|
+
aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
|
|
2764
|
+
},
|
|
2765
|
+
{
|
|
2766
|
+
// 28
|
|
2767
|
+
comando: ["tributarios", "listar"],
|
|
2768
|
+
operationId: "listarEmisoresTributarios",
|
|
2769
|
+
metodo: "GET",
|
|
2770
|
+
ruta: "/{tenantSlug}/emisores-tributarios",
|
|
2771
|
+
argumentos: [],
|
|
2772
|
+
banderas: [RUT_FILTRO, ESTADO_FILTRO, CREDENCIAL_FILTRO, LIMITE, DESDE, TODAS],
|
|
2773
|
+
salida: "tabla",
|
|
2774
|
+
columnas: ["emisorId", "rut", "razonSocial", "estado", "credencialEstado"],
|
|
2775
|
+
confirmacion: "efecto"
|
|
2776
|
+
},
|
|
2777
|
+
{
|
|
2778
|
+
// 29
|
|
2779
|
+
comando: ["tributarios", "por-defecto"],
|
|
2780
|
+
operationId: "obtenerEmisorTributarioPorDefecto",
|
|
2781
|
+
metodo: "GET",
|
|
2782
|
+
ruta: "/{tenantSlug}/emisores-tributarios/default",
|
|
2783
|
+
argumentos: [],
|
|
2784
|
+
banderas: [],
|
|
2785
|
+
salida: "ficha",
|
|
2786
|
+
confirmacion: "efecto"
|
|
2787
|
+
},
|
|
2788
|
+
{
|
|
2789
|
+
// 30
|
|
2790
|
+
comando: ["tributarios", "existe"],
|
|
2791
|
+
operationId: "consultarRutEmisorTributario",
|
|
2792
|
+
metodo: "GET",
|
|
2793
|
+
ruta: "/{tenantSlug}/emisores-tributarios/check-rut/{rut}",
|
|
2794
|
+
argumentos: ["rut"],
|
|
2795
|
+
banderas: [],
|
|
2796
|
+
salida: "ficha",
|
|
2797
|
+
confirmacion: "efecto"
|
|
2798
|
+
},
|
|
2799
|
+
{
|
|
2800
|
+
// 31
|
|
2801
|
+
comando: ["tributarios", "ver"],
|
|
2802
|
+
operationId: "obtenerEmisorTributario",
|
|
2803
|
+
metodo: "GET",
|
|
2804
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}",
|
|
2805
|
+
argumentos: ["id"],
|
|
2806
|
+
banderas: [INCLUIR_ARCHIVADOS],
|
|
2807
|
+
salida: "ficha",
|
|
2808
|
+
confirmacion: "efecto"
|
|
2809
|
+
},
|
|
2810
|
+
{
|
|
2811
|
+
// 32
|
|
2812
|
+
comando: ["tributarios", "logo", "ver"],
|
|
2813
|
+
operationId: "obtenerLogoEmisorTributario",
|
|
2814
|
+
metodo: "GET",
|
|
2815
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
|
|
2816
|
+
argumentos: ["id"],
|
|
2817
|
+
banderas: [],
|
|
2818
|
+
salida: "ficha",
|
|
2819
|
+
confirmacion: "efecto"
|
|
2820
|
+
},
|
|
2821
|
+
{
|
|
2822
|
+
// 33
|
|
2823
|
+
comando: ["tributarios", "certificado"],
|
|
2824
|
+
operationId: "obtenerCertificadoEmisorTributario",
|
|
2825
|
+
metodo: "GET",
|
|
2826
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}/certificado",
|
|
2827
|
+
argumentos: ["id"],
|
|
2828
|
+
banderas: [],
|
|
2829
|
+
salida: "ficha",
|
|
2830
|
+
confirmacion: "efecto"
|
|
2831
|
+
},
|
|
2832
|
+
{
|
|
2833
|
+
// 34
|
|
2834
|
+
comando: ["tributarios", "editar"],
|
|
2835
|
+
operationId: "actualizarEmisorTributario",
|
|
2836
|
+
metodo: "PATCH",
|
|
2837
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}",
|
|
2838
|
+
argumentos: ["id"],
|
|
2839
|
+
banderas: [CUERPO_OBLIGATORIO],
|
|
2840
|
+
salida: "accion",
|
|
2841
|
+
hecho: "Emisor actualizado.",
|
|
2842
|
+
confirmacion: "efecto"
|
|
2843
|
+
},
|
|
2844
|
+
{
|
|
2845
|
+
// 35
|
|
2846
|
+
comando: ["tributarios", "fijar-por-defecto"],
|
|
2847
|
+
operationId: "cambiarEmisorTributarioPorDefecto",
|
|
2848
|
+
metodo: "PATCH",
|
|
2849
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}/set-default",
|
|
2850
|
+
argumentos: ["id"],
|
|
2851
|
+
banderas: [],
|
|
2852
|
+
salida: "accion",
|
|
2853
|
+
hecho: "Emisor fijado por defecto.",
|
|
2854
|
+
confirmacion: "efecto"
|
|
2855
|
+
},
|
|
2856
|
+
{
|
|
2857
|
+
// 36
|
|
2858
|
+
comando: ["tributarios", "reactivar"],
|
|
2859
|
+
operationId: "reactivarEmisorTributario",
|
|
2860
|
+
metodo: "PATCH",
|
|
2861
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}/reactivate",
|
|
2862
|
+
argumentos: ["id"],
|
|
2863
|
+
banderas: [CUERPO_OPCIONAL],
|
|
2864
|
+
salida: "accion",
|
|
2865
|
+
hecho: "Emisor reactivado.",
|
|
2866
|
+
confirmacion: "efecto"
|
|
2867
|
+
},
|
|
2868
|
+
{
|
|
2869
|
+
// 37
|
|
2870
|
+
comando: ["tributarios", "logo", "subir"],
|
|
2871
|
+
operationId: "actualizarLogoEmisorTributario",
|
|
2872
|
+
metodo: "POST",
|
|
2873
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
|
|
2874
|
+
argumentos: ["id"],
|
|
2875
|
+
banderas: [ARCHIVO_LOGO],
|
|
2876
|
+
salida: "accion",
|
|
2877
|
+
hecho: "Logo actualizado.",
|
|
2878
|
+
confirmacion: "efecto"
|
|
2879
|
+
},
|
|
2880
|
+
{
|
|
2881
|
+
// 38
|
|
2882
|
+
comando: ["tributarios", "logo", "quitar"],
|
|
2883
|
+
operationId: "eliminarLogoEmisorTributario",
|
|
2884
|
+
metodo: "DELETE",
|
|
2885
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
|
|
2886
|
+
argumentos: ["id"],
|
|
2887
|
+
banderas: [],
|
|
2888
|
+
salida: "accion",
|
|
2889
|
+
hecho: "Logo eliminado.",
|
|
2890
|
+
confirmacion: "efecto"
|
|
2891
|
+
},
|
|
2892
|
+
{
|
|
2893
|
+
// 39
|
|
2894
|
+
comando: ["sucursales", "listar"],
|
|
2895
|
+
operationId: "listarSucursalesEmisorDte",
|
|
2896
|
+
metodo: "GET",
|
|
2897
|
+
ruta: "/{tenantSlug}/dte/emisores/{emisorId}/sucursales",
|
|
2898
|
+
argumentos: ["emisorId"],
|
|
2899
|
+
banderas: [ACTIVO_FILTRO, TRIBUTARIA_FILTRO, LIMITE, DESDE, TODAS],
|
|
2900
|
+
salida: "tabla",
|
|
2901
|
+
columnas: ["sucursalId", "nombre", "direccion", "comuna", "ciudad"],
|
|
2902
|
+
confirmacion: "efecto"
|
|
2903
|
+
},
|
|
2904
|
+
{
|
|
2905
|
+
// 40
|
|
2906
|
+
comando: ["sucursales", "crear"],
|
|
2907
|
+
operationId: "crearSucursalEmisorDte",
|
|
2908
|
+
metodo: "POST",
|
|
2909
|
+
ruta: "/{tenantSlug}/dte/emisores/{emisorId}/sucursales",
|
|
2910
|
+
argumentos: ["emisorId"],
|
|
2911
|
+
banderas: [CUERPO_OBLIGATORIO],
|
|
2912
|
+
salida: "accion",
|
|
2913
|
+
hecho: "Sucursal creada.",
|
|
2914
|
+
confirmacion: "efecto"
|
|
2915
|
+
},
|
|
2916
|
+
{
|
|
2917
|
+
// 41
|
|
2918
|
+
comando: ["sucursales", "editar"],
|
|
2919
|
+
operationId: "actualizarSucursalEmisorDte",
|
|
2920
|
+
metodo: "PATCH",
|
|
2921
|
+
ruta: "/{tenantSlug}/dte/sucursales/{sucursalId}",
|
|
2922
|
+
argumentos: ["sucursalId"],
|
|
2923
|
+
banderas: [CUERPO_OBLIGATORIO],
|
|
2924
|
+
salida: "accion",
|
|
2925
|
+
hecho: "Sucursal actualizada.",
|
|
2926
|
+
confirmacion: "efecto"
|
|
2927
|
+
},
|
|
2928
|
+
{
|
|
2929
|
+
// 42
|
|
2930
|
+
comando: ["sucursales", "desactivar"],
|
|
2931
|
+
operationId: "desactivarSucursalEmisorDte",
|
|
2932
|
+
metodo: "DELETE",
|
|
2933
|
+
ruta: "/{tenantSlug}/dte/sucursales/{sucursalId}",
|
|
2934
|
+
argumentos: ["sucursalId"],
|
|
2935
|
+
banderas: [],
|
|
2936
|
+
salida: "accion",
|
|
2937
|
+
hecho: "Sucursal desactivada.",
|
|
2938
|
+
confirmacion: "efecto"
|
|
2939
|
+
},
|
|
2940
|
+
{
|
|
2941
|
+
// 43
|
|
2942
|
+
comando: ["representantes", "listar"],
|
|
2943
|
+
operationId: "listarRepresentantesLegales",
|
|
2944
|
+
metodo: "GET",
|
|
2945
|
+
ruta: "/{tenantSlug}/representantes-legales",
|
|
2946
|
+
argumentos: [],
|
|
2947
|
+
banderas: [RUT_FILTRO, LIMITE, DESDE, TODAS],
|
|
2948
|
+
salida: "tabla",
|
|
2949
|
+
columnas: ["rut", "nombre", "certVigente", "certValidoHasta", "emisoresCount"],
|
|
2950
|
+
confirmacion: "efecto"
|
|
2951
|
+
},
|
|
2952
|
+
{
|
|
2953
|
+
// 44
|
|
2954
|
+
comando: ["dte", "sincronizar"],
|
|
2955
|
+
operationId: "actualizarEmisorDteDesdeSii",
|
|
2956
|
+
metodo: "POST",
|
|
2957
|
+
ruta: "/{tenantSlug}/emisores/{id}/sincronizar",
|
|
2958
|
+
argumentos: ["id"],
|
|
2959
|
+
banderas: [],
|
|
2960
|
+
salida: "ficha",
|
|
2961
|
+
confirmacion: "efecto"
|
|
2962
|
+
},
|
|
2963
|
+
{
|
|
2964
|
+
// 45
|
|
2965
|
+
comando: ["dte", "credencial", "reintentar"],
|
|
2966
|
+
operationId: "reintentarCredencialPortalEmisorDte",
|
|
2967
|
+
metodo: "POST",
|
|
2968
|
+
ruta: "/{tenantSlug}/emisores/{id}/credencial-portal/reintentar",
|
|
2969
|
+
argumentos: ["id"],
|
|
2970
|
+
banderas: [],
|
|
2971
|
+
salida: "ficha",
|
|
2972
|
+
confirmacion: "efecto"
|
|
2973
|
+
},
|
|
2974
|
+
{
|
|
2975
|
+
// 46
|
|
2976
|
+
comando: ["tributarios", "credencial", "reintentar"],
|
|
2977
|
+
operationId: "reintentarCredencialEmisorTributario",
|
|
2978
|
+
metodo: "POST",
|
|
2979
|
+
ruta: "/{tenantSlug}/emisores-tributarios/{id}/credencial/reintentar",
|
|
2980
|
+
argumentos: ["id"],
|
|
2981
|
+
banderas: [],
|
|
2982
|
+
salida: "ficha",
|
|
2983
|
+
confirmacion: "efecto"
|
|
2984
|
+
},
|
|
2985
|
+
{
|
|
2986
|
+
// 47
|
|
2987
|
+
comando: ["revocar"],
|
|
2988
|
+
operationId: "revocarEmisorTokenizado",
|
|
2989
|
+
metodo: "POST",
|
|
2990
|
+
ruta: "/{tenantSlug}/tokenizacion/revoke",
|
|
2991
|
+
argumentos: ["id"],
|
|
2992
|
+
argumentoACuerpo: "emisorId",
|
|
2993
|
+
banderas: [TIPO_DE_EMISOR_A_REVOCAR, MOTIVO_DE_REVOCACION],
|
|
2994
|
+
salida: "accion",
|
|
2995
|
+
hecho: "Emisor revocado.",
|
|
2996
|
+
confirmacion: "escrita",
|
|
2997
|
+
aviso: "Esto revoca la autorizaci\xF3n y elimina sus credenciales de inmediato."
|
|
2998
|
+
},
|
|
2999
|
+
{
|
|
3000
|
+
// 48
|
|
3001
|
+
comando: ["dte", "volver-a-mipyme"],
|
|
3002
|
+
operationId: "volverEmisorDteAlPortalMipyme",
|
|
3003
|
+
metodo: "POST",
|
|
3004
|
+
ruta: "/{tenantSlug}/emisores/{id}/volver-a-mipyme",
|
|
3005
|
+
argumentos: ["id"],
|
|
3006
|
+
banderas: [RUT_DE_CONFIRMACION],
|
|
3007
|
+
salida: "accion",
|
|
3008
|
+
hecho: "Emisor vuelto al Portal MiPyme.",
|
|
3009
|
+
confirmacion: "escrita",
|
|
3010
|
+
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."
|
|
3005
3011
|
}
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
async revocar(refreshToken) {
|
|
3051
|
-
try {
|
|
3052
|
-
await oidc.tokenRevocation(await config(), refreshToken, { token_type_hint: "refresh_token" });
|
|
3053
|
-
} catch (error) {
|
|
3054
|
-
throw errorDeIdentidad(error);
|
|
3055
|
-
}
|
|
3056
|
-
},
|
|
3057
|
-
async exigeIss() {
|
|
3058
|
-
return (await config()).serverMetadata().authorization_response_iss_parameter_supported === true;
|
|
3059
|
-
},
|
|
3060
|
-
async iniciarDispositivo() {
|
|
3061
|
-
try {
|
|
3062
|
-
const respuesta = await oidc.initiateDeviceAuthorization(await config(), { scope: SCOPE });
|
|
3063
|
-
if (!respuesta.verification_uri_complete) throw new ErrorCli("El servidor de identidad no devolvi\xF3 la direcci\xF3n completa para aprobar el acceso.");
|
|
3064
|
-
return {
|
|
3065
|
-
deviceCode: respuesta.device_code,
|
|
3066
|
-
userCode: respuesta.user_code,
|
|
3067
|
-
url: respuesta.verification_uri_complete,
|
|
3068
|
-
intervalo: respuesta.interval ?? 5,
|
|
3069
|
-
venceEnSegundos: respuesta.expires_in
|
|
3070
|
-
};
|
|
3071
|
-
} catch (error) {
|
|
3072
|
-
throw errorDeIdentidad(error);
|
|
3073
|
-
}
|
|
3074
|
-
},
|
|
3075
|
-
async esperarDispositivo(pendiente, esperaMs) {
|
|
3076
|
-
const techo = AbortSignal.timeout(esperaMs);
|
|
3077
|
-
const venceEn = new Date(pendiente.venceEn).getTime();
|
|
3078
|
-
let intervalo = pendiente.intervalo;
|
|
3079
|
-
senalDeEspera = techo;
|
|
3080
|
-
try {
|
|
3081
|
-
for (; ; ) {
|
|
3082
|
-
try {
|
|
3083
|
-
await esperarAbortable(intervalo * 1e3, techo);
|
|
3084
|
-
} catch (error) {
|
|
3085
|
-
if (techo.aborted) return { estado: "pendiente" };
|
|
3086
|
-
throw error;
|
|
3087
|
-
}
|
|
3088
|
-
if (Date.now() >= venceEn) return { estado: "vencido" };
|
|
3089
|
-
try {
|
|
3090
|
-
const respuesta = await oidc.genericGrantRequest(await config(), DEVICE_CODE_GRANT, { device_code: pendiente.deviceCode });
|
|
3091
|
-
return { estado: "aprobado", par: comoPar(respuesta) };
|
|
3092
|
-
} catch (error) {
|
|
3093
|
-
if (techo.aborted) return { estado: "pendiente" };
|
|
3094
|
-
if (error instanceof oidc.ResponseBodyError) {
|
|
3095
|
-
if (error.error === "authorization_pending") continue;
|
|
3096
|
-
if (error.error === "slow_down") {
|
|
3097
|
-
intervalo += 5;
|
|
3098
|
-
continue;
|
|
3099
|
-
}
|
|
3100
|
-
if (error.error === "expired_token") return { estado: "vencido" };
|
|
3101
|
-
if (error.error === "access_denied") return { estado: "rechazado" };
|
|
3102
|
-
}
|
|
3103
|
-
throw errorDeIdentidad(error);
|
|
3104
|
-
}
|
|
3105
|
-
}
|
|
3106
|
-
} finally {
|
|
3107
|
-
senalDeEspera = void 0;
|
|
3108
|
-
}
|
|
3012
|
+
];
|
|
3013
|
+
|
|
3014
|
+
// src/comandos/registro.ts
|
|
3015
|
+
import { Option } from "commander";
|
|
3016
|
+
|
|
3017
|
+
// src/nucleo/actualizacion-del-cli.ts
|
|
3018
|
+
import fs9 from "node:fs";
|
|
3019
|
+
import path9 from "node:path";
|
|
3020
|
+
|
|
3021
|
+
// src/nucleo/bienvenida.ts
|
|
3022
|
+
var TITULO_DE_BIENVENIDA = "BIENVENIDO A REDCUMBRE";
|
|
3023
|
+
var ETIQUETA_DEL_AVISO = "AVISO IMPORTANTE";
|
|
3024
|
+
var AVISO_DE_COBROS = "En modo de prueba nada se cobra, en modo de producci\xF3n las acciones se cobran de acuerdo a tu plan. Siempre puedes consultar con redcumbre:tarifas los precios de todas tus operaciones o en el panel web en la secci\xF3n Mi suscripci\xF3n.";
|
|
3025
|
+
var ANCHO_PLANO = 80;
|
|
3026
|
+
var ANCHO_DEL_RECUADRO = 76;
|
|
3027
|
+
var RELLENO = 2;
|
|
3028
|
+
var LETRAS = {
|
|
3029
|
+
R: [" ____ ", "| _ \\ ", "| |_) |", "| _ < ", "|_| \\_\\"],
|
|
3030
|
+
E: [" _____ ", "| ____|", "| _| ", "| |___ ", "|_____|"],
|
|
3031
|
+
D: [" ____ ", "| _ \\ ", "| | | |", "| |_| |", "|____/ "],
|
|
3032
|
+
C: [" ____ ", " / ___|", "| | ", "| |___ ", " \\____|"],
|
|
3033
|
+
U: [" _ _ ", "| | | |", "| | | |", "| |_| |", " \\___/ "],
|
|
3034
|
+
M: [" __ __ ", "| \\/ |", "| |\\/| |", "| | | |", "|_| |_|"],
|
|
3035
|
+
B: [" ____ ", "| __ ) ", "| _ \\ ", "| |_) |", "|____/ "]
|
|
3036
|
+
};
|
|
3037
|
+
var LOGO = [0, 1, 2, 3, 4].map(
|
|
3038
|
+
(fila) => [..."REDCUMBRE"].map((letra) => LETRAS[letra][fila]).join(" ").replace(/\s+$/, "")
|
|
3039
|
+
);
|
|
3040
|
+
var ANSI = {
|
|
3041
|
+
reset: "\x1B[0m",
|
|
3042
|
+
negrita: "\x1B[1m",
|
|
3043
|
+
rojoBrillante: "\x1B[91m",
|
|
3044
|
+
amarilloBrillante: "\x1B[93m",
|
|
3045
|
+
etiqueta: "\x1B[1;97;41m"
|
|
3046
|
+
};
|
|
3047
|
+
function envolver(texto2, ancho) {
|
|
3048
|
+
const lineas = [];
|
|
3049
|
+
let actual = "";
|
|
3050
|
+
for (const palabra of texto2.split(/\s+/).filter(Boolean)) {
|
|
3051
|
+
if (actual && actual.length + 1 + palabra.length > ancho) {
|
|
3052
|
+
lineas.push(actual);
|
|
3053
|
+
actual = palabra;
|
|
3054
|
+
} else {
|
|
3055
|
+
actual = actual ? `${actual} ${palabra}` : palabra;
|
|
3109
3056
|
}
|
|
3110
|
-
}
|
|
3057
|
+
}
|
|
3058
|
+
if (actual) lineas.push(actual);
|
|
3059
|
+
return lineas;
|
|
3111
3060
|
}
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3061
|
+
var tituloConVersion = (version) => `${TITULO_DE_BIENVENIDA} \xB7 CLI ${version}`;
|
|
3062
|
+
var AVISO_EN_TEXTO = `${ETIQUETA_DEL_AVISO}: ${AVISO_DE_COBROS}`;
|
|
3063
|
+
function textoPlanoDeBienvenida(version) {
|
|
3064
|
+
return [...envolver(tituloConVersion(version), ANCHO_PLANO), ...envolver(AVISO_EN_TEXTO, ANCHO_PLANO)].join("\n");
|
|
3115
3065
|
}
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3066
|
+
var ANCHO_INTERIOR = ANCHO_DEL_RECUADRO - 2 - 2 * RELLENO;
|
|
3067
|
+
var ANCHO_DE_LA_PANTALLA = Math.max(ANCHO_DEL_RECUADRO, ...LOGO.map((l) => l.length));
|
|
3068
|
+
function pantallaDeBienvenida(version, { color }) {
|
|
3069
|
+
const pintar = (codigo, texto2) => color ? `${codigo}${texto2}${ANSI.reset}` : texto2;
|
|
3070
|
+
const relleno = " ".repeat(RELLENO);
|
|
3071
|
+
const borde = (texto2) => pintar(ANSI.amarilloBrillante, texto2);
|
|
3072
|
+
const interior = (texto2, visible = texto2) => `${borde("\u2551")}${relleno}${texto2}${" ".repeat(ANCHO_INTERIOR - visible.length)}${relleno}${borde("\u2551")}`;
|
|
3073
|
+
const lineas = [];
|
|
3074
|
+
for (const fila of LOGO) lineas.push(pintar(ANSI.rojoBrillante, fila));
|
|
3075
|
+
lineas.push("");
|
|
3076
|
+
lineas.push(pintar(ANSI.negrita, tituloConVersion(version)));
|
|
3077
|
+
lineas.push("");
|
|
3078
|
+
lineas.push(borde(`\u2554${"\u2550".repeat(ANCHO_DEL_RECUADRO - 2)}\u2557`));
|
|
3079
|
+
lineas.push(interior(pintar(ANSI.etiqueta, ` ${ETIQUETA_DEL_AVISO} `), ` ${ETIQUETA_DEL_AVISO} `));
|
|
3080
|
+
for (const linea of envolver(AVISO_DE_COBROS, ANCHO_INTERIOR)) lineas.push(interior(linea));
|
|
3081
|
+
lineas.push(borde(`\u255A${"\u2550".repeat(ANCHO_DEL_RECUADRO - 2)}\u255D`));
|
|
3082
|
+
return lineas.join("\n");
|
|
3120
3083
|
}
|
|
3121
|
-
|
|
3122
|
-
const
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3084
|
+
function mostrarBienvenida(salida, version, entorno) {
|
|
3085
|
+
const plano = textoPlanoDeBienvenida(version);
|
|
3086
|
+
if (salida.json) {
|
|
3087
|
+
salida.anexar("bienvenida", { titulo: TITULO_DE_BIENVENIDA, aviso: AVISO_EN_TEXTO, version, texto: plano });
|
|
3088
|
+
salida.linea();
|
|
3089
|
+
salida.linea(plano);
|
|
3090
|
+
return;
|
|
3091
|
+
}
|
|
3092
|
+
const sinColor = (entorno.env.NO_COLOR ?? "") !== "" || entorno.env.TERM === "dumb";
|
|
3093
|
+
const angosta = entorno.columnas !== void 0 && entorno.columnas < ANCHO_DE_LA_PANTALLA;
|
|
3094
|
+
salida.linea();
|
|
3095
|
+
salida.linea(sinColor || angosta ? plano : pantallaDeBienvenida(version, { color: true }));
|
|
3096
|
+
salida.linea();
|
|
3131
3097
|
}
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
});
|
|
3140
|
-
const redirectUri = `http://127.0.0.1:${local.puerto}/callback`;
|
|
3098
|
+
|
|
3099
|
+
// src/nucleo/instalacion-del-cli.ts
|
|
3100
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
3101
|
+
import fs8 from "node:fs";
|
|
3102
|
+
import path8 from "node:path";
|
|
3103
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
3104
|
+
var real = (ruta) => {
|
|
3141
3105
|
try {
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3106
|
+
return fs8.realpathSync(ruta);
|
|
3107
|
+
} catch {
|
|
3108
|
+
return null;
|
|
3109
|
+
}
|
|
3110
|
+
};
|
|
3111
|
+
var dentroDe = (ruta, carpeta) => ruta === carpeta || ruta.startsWith(carpeta + path8.sep);
|
|
3112
|
+
var correPorNpx = (bundle) => (real(bundle) ?? path8.resolve(bundle)).split(path8.sep).includes("_npx");
|
|
3113
|
+
function detectarInstalacion(bundle, raizGlobal) {
|
|
3114
|
+
const bundleReal = real(bundle) ?? path8.resolve(bundle);
|
|
3115
|
+
if (correPorNpx(bundleReal)) return { forma: "npx" };
|
|
3116
|
+
for (const [gestor, forma] of [["npm", "npm-global"], ["pnpm", "pnpm-global"]]) {
|
|
3117
|
+
const raiz = raizGlobal(gestor);
|
|
3118
|
+
const carpeta = raiz ? real(path8.join(raiz, ...PAQUETE_DEL_CLI.split("/"))) : null;
|
|
3119
|
+
if (carpeta && dentroDe(bundleReal, carpeta)) return { forma, carpetaDelPaquete: carpeta };
|
|
3120
|
+
}
|
|
3121
|
+
const marcaDeDependencia = ["node_modules", ...PAQUETE_DEL_CLI.split("/")].join(path8.sep);
|
|
3122
|
+
if (bundleReal.includes(`${path8.sep}${marcaDeDependencia}${path8.sep}`)) {
|
|
3123
|
+
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` };
|
|
3153
3124
|
}
|
|
3125
|
+
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` };
|
|
3154
3126
|
}
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3127
|
+
function comandoDeActualizacion(forma, version, registro) {
|
|
3128
|
+
const paquete = `${PAQUETE_DEL_CLI}@${version}`;
|
|
3129
|
+
const conRegistro = registro ? [`--registry=${registro}`] : [];
|
|
3130
|
+
if (forma === "pnpm-global") return { comando: "pnpm", args: ["add", "--global", ...conRegistro, paquete] };
|
|
3131
|
+
return { comando: "npm", args: ["install", "--global", ...conRegistro, paquete] };
|
|
3158
3132
|
}
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
const venceEn = new Date(Date.now() + solicitud.venceEnSegundos * 1e3).toISOString();
|
|
3166
|
-
const desenlace = await identidad.esperarDispositivo({ deviceCode: solicitud.deviceCode, intervalo: solicitud.intervalo, venceEn }, solicitud.venceEnSegundos * 1e3);
|
|
3167
|
-
if (desenlace.estado === "aprobado") return desenlace.par;
|
|
3168
|
-
throw errorDelDesenlace(desenlace.estado);
|
|
3133
|
+
var legible = (c) => [c.comando, ...c.args].join(" ");
|
|
3134
|
+
var comandoInstalarPorNpx = (version) => `npx ${PAQUETE_DEL_CLI}@${version} instalar`;
|
|
3135
|
+
var prefijoPorNpx = (version) => `npx ${PAQUETE_DEL_CLI}@${version}`;
|
|
3136
|
+
function ejecutarDeVerdad(comando2, args, opciones) {
|
|
3137
|
+
const r = spawnSync2(comando2, args, { cwd: opciones.cwd, env: opciones.env, encoding: "utf8", shell: process.platform === "win32", timeout: 10 * 6e4 });
|
|
3138
|
+
return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? r.error.message : "") };
|
|
3169
3139
|
}
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3140
|
+
function entornoDeActualizacion(ctx) {
|
|
3141
|
+
const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
|
|
3142
|
+
return {
|
|
3143
|
+
bundle: fileURLToPath2(import.meta.url),
|
|
3144
|
+
ejecutar: ejecutarDeVerdad,
|
|
3145
|
+
raizGlobal(gestor) {
|
|
3146
|
+
const r = ejecutarDeVerdad(gestor, ["root", "--global"], { cwd: ctx.cwd, env: ctx.env });
|
|
3147
|
+
const raiz = r.stdout.trim().split(/\r?\n/).pop() ?? "";
|
|
3148
|
+
return r.status === 0 && raiz ? raiz : null;
|
|
3149
|
+
},
|
|
3150
|
+
async consultarUltima() {
|
|
3151
|
+
const respuesta = await fetch(urlUltimaVersion(registro), { signal: AbortSignal.timeout(1e4), headers: { accept: "application/json" } });
|
|
3152
|
+
if (!respuesta.ok) throw new Error(`el registro respondi\xF3 ${respuesta.status}`);
|
|
3153
|
+
const cuerpo = await respuesta.json();
|
|
3154
|
+
return typeof cuerpo.version === "string" ? cuerpo.version : null;
|
|
3155
|
+
}
|
|
3156
|
+
};
|
|
3157
|
+
}
|
|
3158
|
+
var VARIABLE_SKILL_DEL_LLAMADOR = "REDCUMBRE_SKILL_DEL_LLAMADOR";
|
|
3159
|
+
var entornoDelHijo = (env) => ({ ...env, [VARIABLE_SKILL_DEL_LLAMADOR]: "1" });
|
|
3160
|
+
var VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
3161
|
+
function entornoSinNpx(env) {
|
|
3162
|
+
const limpio = { ...env };
|
|
3163
|
+
for (const clave of Object.keys(limpio).filter((k) => k.toUpperCase() === "PATH")) {
|
|
3164
|
+
limpio[clave] = (limpio[clave] ?? "").split(path8.delimiter).filter((carpeta) => carpeta && !carpeta.split(/[\\/]/).includes("_npx")).join(path8.delimiter);
|
|
3179
3165
|
}
|
|
3180
|
-
|
|
3181
|
-
return volverAEmpezar("La persona rechaz\xF3 el acceso.", "LOGIN_RECHAZADO");
|
|
3166
|
+
return limpio;
|
|
3182
3167
|
}
|
|
3183
|
-
function
|
|
3184
|
-
const
|
|
3185
|
-
|
|
3168
|
+
function versionEnElPath(entorno, opciones) {
|
|
3169
|
+
const r = entorno.ejecutar("redcumbre", ["--version"], { cwd: opciones.cwd, env: entornoSinNpx(entornoDelHijo(opciones.env)) });
|
|
3170
|
+
const version = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
|
|
3171
|
+
return r.status === 0 && VERSION.test(version) ? version : null;
|
|
3172
|
+
}
|
|
3173
|
+
function carpetaDeEjecutablesDeNpm(entorno, opciones) {
|
|
3174
|
+
const r = entorno.ejecutar("npm", ["prefix", "--global"], opciones);
|
|
3175
|
+
const prefijo = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
|
|
3176
|
+
if (r.status !== 0 || !prefijo) return null;
|
|
3177
|
+
return process.platform === "win32" ? prefijo : path8.join(prefijo, "bin");
|
|
3178
|
+
}
|
|
3179
|
+
|
|
3180
|
+
// src/nucleo/actualizacion-del-cli.ts
|
|
3181
|
+
var real2 = (ruta) => {
|
|
3186
3182
|
try {
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
|
|
3183
|
+
return fs9.realpathSync(ruta);
|
|
3184
|
+
} catch {
|
|
3185
|
+
return null;
|
|
3186
|
+
}
|
|
3187
|
+
};
|
|
3188
|
+
function leerJson2(texto2) {
|
|
3189
|
+
try {
|
|
3190
|
+
const dato = JSON.parse(texto2);
|
|
3191
|
+
return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
|
|
3192
3192
|
} catch {
|
|
3193
3193
|
return null;
|
|
3194
3194
|
}
|
|
3195
3195
|
}
|
|
3196
|
-
function
|
|
3197
|
-
const
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
}
|
|
3202
|
-
function borrarLoginPendiente(carpeta) {
|
|
3203
|
-
const ruta = rutaLoginPendiente(carpeta);
|
|
3204
|
-
const habia = fs9.existsSync(ruta);
|
|
3205
|
-
fs9.rmSync(ruta, { force: true });
|
|
3206
|
-
return habia;
|
|
3207
|
-
}
|
|
3208
|
-
async function iniciarLoginDeDispositivo(identidad, carpeta, proyecto, ahora = /* @__PURE__ */ new Date()) {
|
|
3209
|
-
exigirFueraDelProyecto(carpeta, proyecto);
|
|
3210
|
-
const vigente = leerLoginPendiente(carpeta);
|
|
3211
|
-
if (vigente && new Date(vigente.venceEn).getTime() > ahora.getTime()) return { url: vigente.url, codigo: vigente.userCode, vence: vigente.venceEn };
|
|
3212
|
-
borrarLoginPendiente(carpeta);
|
|
3213
|
-
const solicitud = await identidad.iniciarDispositivo();
|
|
3214
|
-
const venceEn = new Date(ahora.getTime() + solicitud.venceEnSegundos * 1e3).toISOString();
|
|
3215
|
-
guardarLoginPendiente(carpeta, {
|
|
3216
|
-
deviceCode: solicitud.deviceCode,
|
|
3217
|
-
userCode: solicitud.userCode,
|
|
3218
|
-
url: solicitud.url,
|
|
3219
|
-
intervalo: solicitud.intervalo,
|
|
3220
|
-
venceEn,
|
|
3221
|
-
clientId: CLIENTE_OIDC.clientId
|
|
3196
|
+
function errorDeActualizacion(comando2, corrida) {
|
|
3197
|
+
const detalle = (corrida.stderr || corrida.stdout).trim().split(/\r?\n/).slice(-5).join(" \xB7 ");
|
|
3198
|
+
return new ErrorCli(`No pude actualizar el CLI: \xAB${legible(comando2)}\xBB termin\xF3 con ${corrida.status ?? "una se\xF1al"}${detalle ? ` (${detalle})` : ""}. No cambi\xE9 nada m\xE1s.`, CODIGOS_DE_SALIDA.error, {
|
|
3199
|
+
codigo: "ACTUALIZACION_FALLIDA",
|
|
3200
|
+
datos: { comando: legible(comando2) }
|
|
3222
3201
|
});
|
|
3223
|
-
return { url: solicitud.url, codigo: solicitud.userCode, vence: venceEn };
|
|
3224
3202
|
}
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3203
|
+
function actualizarElCli(ctx, entorno, disponible, informar) {
|
|
3204
|
+
const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
|
|
3205
|
+
const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
|
|
3206
|
+
if (instalacion.forma === "no-reconocida") {
|
|
3207
|
+
throw new ErrorCli(
|
|
3208
|
+
`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.`,
|
|
3209
|
+
CODIGOS_DE_SALIDA.error,
|
|
3210
|
+
{ codigo: "INSTALACION_NO_RECONOCIDA", datos: { instalada: ctx.version, disponible } }
|
|
3211
|
+
);
|
|
3233
3212
|
}
|
|
3234
|
-
const
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3213
|
+
const comando2 = comandoDeActualizacion(instalacion.forma, disponible, registro);
|
|
3214
|
+
informar(`Actualizando: ${legible(comando2)}`);
|
|
3215
|
+
const corrida = entorno.ejecutar(comando2.comando, comando2.args, { cwd: ctx.cwd, env: entornoDelHijo(ctx.env) });
|
|
3216
|
+
if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
|
|
3217
|
+
const raizNpm = instalacion.forma === "npx" ? entorno.raizGlobal("npm") : null;
|
|
3218
|
+
const carpetaDelPaquete = instalacion.forma === "npx" ? raizNpm ? real2(path9.join(raizNpm, ...PAQUETE_DEL_CLI.split("/"))) : null : instalacion.carpetaDelPaquete;
|
|
3219
|
+
if (!carpetaDelPaquete) {
|
|
3220
|
+
throw new ErrorCli(
|
|
3221
|
+
`\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.`,
|
|
3222
|
+
CODIGOS_DE_SALIDA.error,
|
|
3223
|
+
{ codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
|
|
3224
|
+
);
|
|
3239
3225
|
}
|
|
3240
|
-
|
|
3241
|
-
|
|
3226
|
+
const bundleNuevo = path9.join(carpetaDelPaquete, "dist", "redcumbre.js");
|
|
3227
|
+
const version = entorno.ejecutar(process.execPath, [bundleNuevo, "--version"], { cwd: ctx.cwd, env: entornoDelHijo(ctx.env) });
|
|
3228
|
+
if (version.status !== 0 || version.stdout.trim() !== disponible) {
|
|
3229
|
+
throw new ErrorCli(
|
|
3230
|
+
`\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.`,
|
|
3231
|
+
CODIGOS_DE_SALIDA.error,
|
|
3232
|
+
{ codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
|
|
3233
|
+
);
|
|
3234
|
+
}
|
|
3235
|
+
const renovacion = entorno.ejecutar(process.execPath, [bundleNuevo, "skill", "renovar", "--json"], { cwd: ctx.cwd, env: entornoDelHijo(ctx.env) });
|
|
3236
|
+
const skill = renovacion.status === 0 ? leerJson2(renovacion.stdout)?.skill ?? null : null;
|
|
3237
|
+
return { forma: instalacion.forma, comando: legible(comando2), skill };
|
|
3242
3238
|
}
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3239
|
+
function resumirLaSkill(skill) {
|
|
3240
|
+
const rutas = Array.isArray(skill?.rutas) ? skill.rutas : [];
|
|
3241
|
+
const copias = rutas.flatMap((r) => r.accion === "reemplazada-editada" && typeof r.copia === "string" ? [r.copia] : []);
|
|
3242
|
+
return { renovadas: rutas.filter((r) => r.accion === "renovada" || r.accion === "instalada" || r.accion === "reemplazada-editada").length, copias };
|
|
3243
|
+
}
|
|
3244
|
+
function textoDeLaSkillRenovada(resumen) {
|
|
3245
|
+
if (resumen.copias.length > 0) return `reemplac\xE9 la skill; tu versi\xF3n editada de la skill qued\xF3 en ${resumen.copias.join(" y ")}`;
|
|
3246
|
+
if (resumen.renovadas > 0) return "renov\xE9 la skill";
|
|
3247
|
+
return "no hab\xEDa una skill instalada por el CLI que renovar";
|
|
3248
|
+
}
|
|
3249
|
+
var motivoDe2 = (error) => error instanceof Error ? error.message : String(error);
|
|
3250
|
+
async function autoactualizarElCli(ctx, opciones) {
|
|
3251
|
+
const { entorno, salida, agente } = opciones;
|
|
3252
|
+
const depurar = opciones.depurar ?? (() => void 0);
|
|
3253
|
+
const err = opciones.stderr ?? process.stderr;
|
|
3254
|
+
let actualizacion;
|
|
3255
|
+
try {
|
|
3256
|
+
const { ultima } = await ultimaVersionConocida({
|
|
3257
|
+
carpeta: ctx.carpetaConfiguracion,
|
|
3258
|
+
version: ctx.version,
|
|
3259
|
+
ahora: ctx.ahora(),
|
|
3260
|
+
registro: ctx.env.REDCUMBRE_NPM_REGISTRY,
|
|
3261
|
+
consultar: opciones.consultar,
|
|
3262
|
+
sinMarca: opciones.consultaSinMarca
|
|
3263
|
+
});
|
|
3264
|
+
if (opciones.consultaSinMarca) ctx.versionDelRegistro = { ultima };
|
|
3265
|
+
actualizacion = ultima && compararVersiones(ultima, ctx.version) > 0 ? { instalada: ctx.version, disponible: ultima, comando: COMANDO_ACTUALIZAR } : null;
|
|
3266
|
+
} catch (error) {
|
|
3267
|
+
depurar(`no pude leer la marca de versi\xF3n: ${motivoDe2(error)}`);
|
|
3268
|
+
return false;
|
|
3249
3269
|
}
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
return par;
|
|
3270
|
+
if (!actualizacion) return false;
|
|
3271
|
+
const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
|
|
3272
|
+
if (instalacion.forma === "no-reconocida") {
|
|
3273
|
+
depurar(`hay una versi\xF3n m\xE1s nueva del CLI (${actualizacion.disponible}), pero no la instalo: ${instalacion.motivo}`);
|
|
3274
|
+
return false;
|
|
3256
3275
|
}
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
|
|
3268
|
-
} catch (error) {
|
|
3269
|
-
if (!(error instanceof ErrorRefreshInvalido)) throw error;
|
|
3270
|
-
this.almacen.borrar();
|
|
3271
|
-
this.salida.linea("Tu sesi\xF3n anterior venci\xF3 o se cerr\xF3. Inicia sesi\xF3n de nuevo.");
|
|
3272
|
-
this.actual = await this.entrar();
|
|
3276
|
+
const porNpx = instalacion.forma === "npx";
|
|
3277
|
+
const comandoManual = porNpx ? `${prefijoPorNpx(ctx.version)} actualizar` : COMANDO_ACTUALIZAR;
|
|
3278
|
+
const { instalada: instalada2, disponible } = actualizacion;
|
|
3279
|
+
actualizacion.comando = comandoManual;
|
|
3280
|
+
const fallo2 = (error, avisarEnTerminal) => {
|
|
3281
|
+
if (agente) {
|
|
3282
|
+
salida.anexar("actualizacion", { instalada: instalada2, disponible, actualizado: false, comando: comandoManual, ...error ? { error } : {} });
|
|
3283
|
+
salida.avisoAlAgente(avisoDeActualizacion(actualizacion, error?.mensaje));
|
|
3284
|
+
} else if (avisarEnTerminal) {
|
|
3285
|
+
err.write(`\u26A0 No pude actualizar el CLI solo${error ? ` (${error.mensaje})` : ""}. Actual\xEDzalo con \xAB${comandoManual}\xBB.
|
|
3286
|
+
`);
|
|
3273
3287
|
}
|
|
3274
|
-
|
|
3288
|
+
};
|
|
3289
|
+
if (yaSeIntento(ctx.carpetaConfiguracion, disponible, ctx.ahora())) {
|
|
3290
|
+
depurar(`ya intent\xE9 actualizar el CLI a ${disponible} en las \xFAltimas 24 h; no lo reintento`);
|
|
3291
|
+
fallo2(null, false);
|
|
3292
|
+
return false;
|
|
3275
3293
|
}
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3284
|
-
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
}
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3294
|
+
marcarIntento(ctx.carpetaConfiguracion, disponible, ctx.ahora());
|
|
3295
|
+
try {
|
|
3296
|
+
const r = actualizarElCli(ctx, entorno, disponible, (texto2) => {
|
|
3297
|
+
if (!agente) err.write(`${texto2}
|
|
3298
|
+
`);
|
|
3299
|
+
});
|
|
3300
|
+
const resumen = resumirLaSkill(r.skill);
|
|
3301
|
+
if (agente) {
|
|
3302
|
+
salida.anexar("actualizacion", { instalada: instalada2, disponible, actualizado: true, forma: r.forma, comando: r.comando, skill: r.skill });
|
|
3303
|
+
salida.avisoAlAgente(
|
|
3304
|
+
r.skill === null ? `Actualic\xE9 el CLI de ${instalada2} a ${disponible}, sin preguntarle a nadie, pero no pude renovar la skill: corre \xABredcumbre skill renovar\xBB. Este comando corri\xF3 con la ${instalada2}; los siguientes usan la ${disponible}.` : `Actualic\xE9 el CLI de ${instalada2} a ${disponible} y ${textoDeLaSkillRenovada(resumen)}, sin preguntarle a nadie. Este comando corri\xF3 con la ${instalada2}; los siguientes usan la ${disponible}.${resumen.renovadas > 0 ? " Vuelve a leer la skill \xABredcumbre\xBB si la tienes cargada." : ""}`
|
|
3305
|
+
);
|
|
3306
|
+
} else {
|
|
3307
|
+
if (r.skill === null) err.write(`\u26A0 El CLI qued\xF3 en la versi\xF3n ${disponible}, pero no pude renovar la skill: corre \xABredcumbre skill renovar\xBB.
|
|
3308
|
+
`);
|
|
3309
|
+
err.write(`\u2713 Actualic\xE9 el CLI de ${instalada2} a ${disponible}${r.skill === null ? "" : ` y ${textoDeLaSkillRenovada(resumen)}`}.
|
|
3310
|
+
`);
|
|
3311
|
+
for (const copia of resumen.copias) err.write(`\u2139 Tu versi\xF3n editada de la skill qued\xF3 en ${copia}.
|
|
3312
|
+
`);
|
|
3313
|
+
mostrarBienvenida(salida, disponible, { env: ctx.env, columnas: salida.humano.columns });
|
|
3295
3314
|
}
|
|
3296
|
-
}
|
|
3297
|
-
/** `logout`: revoca el refresh token (RFC 7009) y borra lo local. */
|
|
3298
|
-
async cerrar() {
|
|
3299
|
-
const guardada = this.almacen.leer();
|
|
3300
|
-
if (!guardada) return false;
|
|
3301
|
-
await this.identidad.revocar(guardada.refresh_token);
|
|
3302
|
-
this.almacen.borrar();
|
|
3303
3315
|
return true;
|
|
3316
|
+
} catch (error) {
|
|
3317
|
+
const codigo = error instanceof ErrorCli && error.codigo ? error.codigo : "ACTUALIZACION_FALLIDA";
|
|
3318
|
+
depurar(`la auto-actualizaci\xF3n a ${disponible} fall\xF3 (${codigo}): ${motivoDe2(error)}`);
|
|
3319
|
+
fallo2({ codigo, mensaje: motivoDe2(error) }, true);
|
|
3320
|
+
return false;
|
|
3304
3321
|
}
|
|
3305
|
-
}
|
|
3322
|
+
}
|
|
3306
3323
|
|
|
3307
3324
|
// src/nucleo/contexto.ts
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
};
|
|
3327
|
-
return {
|
|
3328
|
-
salida,
|
|
3329
|
-
terminal,
|
|
3330
|
-
cliente: new ClienteApi(destinos.api),
|
|
3331
|
-
servidores: destinos,
|
|
3332
|
-
carpetaConfiguracion: carpeta,
|
|
3333
|
-
home: os2.homedir(),
|
|
3334
|
-
cwd: opciones.cwd,
|
|
3335
|
-
proyecto,
|
|
3336
|
-
env,
|
|
3337
|
-
version: opciones.version,
|
|
3338
|
-
identidad,
|
|
3339
|
-
ahora: () => /* @__PURE__ */ new Date(),
|
|
3340
|
-
abrir,
|
|
3341
|
-
almacen: elAlmacen,
|
|
3342
|
-
async haySesion() {
|
|
3343
|
-
return (await elAlmacen()).leer() !== null;
|
|
3344
|
-
},
|
|
3345
|
-
sesion() {
|
|
3346
|
-
sesion ??= elAlmacen().then(
|
|
3347
|
-
(a) => new Sesion(a, identidad, salida, async () => {
|
|
3348
|
-
if (!terminal) throw sinSesionEnModoAgente();
|
|
3349
|
-
return iniciarSesion(identidad, salida, {
|
|
3350
|
-
sinNavegador: hayQueIrSinNavegador(opciones.sinNavegador, env),
|
|
3351
|
-
abrirNavegador: abrir
|
|
3352
|
-
});
|
|
3353
|
-
})
|
|
3354
|
-
);
|
|
3355
|
-
return sesion;
|
|
3356
|
-
}
|
|
3357
|
-
};
|
|
3325
|
+
import os2 from "node:os";
|
|
3326
|
+
|
|
3327
|
+
// src/nucleo/sesion.ts
|
|
3328
|
+
import { spawn } from "node:child_process";
|
|
3329
|
+
import fs10 from "node:fs";
|
|
3330
|
+
import os from "node:os";
|
|
3331
|
+
import path10 from "node:path";
|
|
3332
|
+
import { setTimeout as setTimeoutAbortable } from "node:timers/promises";
|
|
3333
|
+
import * as oidc from "openid-client";
|
|
3334
|
+
|
|
3335
|
+
// src/nucleo/retorno-local.ts
|
|
3336
|
+
import http from "node:http";
|
|
3337
|
+
function paginaListo(titulo, texto2) {
|
|
3338
|
+
return `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>REDCUMBRE</title>
|
|
3339
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
3340
|
+
<style>body{font-family:system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:Canvas;color:CanvasText}
|
|
3341
|
+
main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;opacity:.8}</style></head>
|
|
3342
|
+
<body><main><h1>${titulo}</h1><p>${texto2}</p></main></body></html>`;
|
|
3358
3343
|
}
|
|
3359
|
-
async function
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3344
|
+
async function abrirRetornoLocal(opciones) {
|
|
3345
|
+
let resolver;
|
|
3346
|
+
let rechazar;
|
|
3347
|
+
const recibido = new Promise((ok, falla) => {
|
|
3348
|
+
resolver = ok;
|
|
3349
|
+
rechazar = falla;
|
|
3365
3350
|
});
|
|
3351
|
+
recibido.catch(() => void 0);
|
|
3352
|
+
const servidor = http.createServer((req, res) => {
|
|
3353
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
3354
|
+
if (url.pathname !== "/callback") {
|
|
3355
|
+
res.writeHead(404).end();
|
|
3356
|
+
return;
|
|
3357
|
+
}
|
|
3358
|
+
if (opciones.aceptar && !opciones.aceptar(url)) {
|
|
3359
|
+
res.writeHead(400).end();
|
|
3360
|
+
return;
|
|
3361
|
+
}
|
|
3362
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(opciones.pagina);
|
|
3363
|
+
resolver(url);
|
|
3364
|
+
});
|
|
3365
|
+
await new Promise((ok) => servidor.listen(0, "127.0.0.1", ok));
|
|
3366
|
+
const { port } = servidor.address();
|
|
3367
|
+
let espera;
|
|
3368
|
+
const cerrar = () => {
|
|
3369
|
+
clearTimeout(espera);
|
|
3370
|
+
servidor.close();
|
|
3371
|
+
};
|
|
3372
|
+
espera = setTimeout(() => {
|
|
3373
|
+
cerrar();
|
|
3374
|
+
rechazar(new ErrorCli(opciones.mensajeDeEspera));
|
|
3375
|
+
}, opciones.esperaMs);
|
|
3376
|
+
return { puerto: port, recibido, cerrar };
|
|
3366
3377
|
}
|
|
3367
3378
|
|
|
3368
|
-
// src/nucleo/
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
var NOMBRE_SKILL = "redcumbre";
|
|
3374
|
-
var MARCA_INICIO = "<!-- redcumbre:inicio -->";
|
|
3375
|
-
var MARCA_FIN = "<!-- redcumbre:fin -->";
|
|
3376
|
-
var sha256 = (texto2) => createHash("sha256").update(texto2).digest("hex");
|
|
3377
|
-
function carpetaDeLaSkill(aqui = path10.dirname(fileURLToPath2(import.meta.url))) {
|
|
3378
|
-
const candidatas = [path10.join(aqui, "skill"), path10.join(aqui, "..", "skill"), path10.join(aqui, "..", "..", "skill")];
|
|
3379
|
-
for (const candidata of candidatas) {
|
|
3380
|
-
if (fs10.existsSync(path10.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
|
|
3379
|
+
// src/nucleo/sesion.ts
|
|
3380
|
+
function carpetaDeConfiguracion(env = process.env, plataforma = process.platform) {
|
|
3381
|
+
if (plataforma === "win32") {
|
|
3382
|
+
if (!env.APPDATA) throw new ErrorCli("No encuentro %APPDATA%: no tengo d\xF3nde guardar la sesi\xF3n.");
|
|
3383
|
+
return path10.join(env.APPDATA, "redcumbre");
|
|
3381
3384
|
}
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
});
|
|
3385
|
+
const base = env.XDG_CONFIG_HOME || path10.join(os.homedir(), ".config");
|
|
3386
|
+
return path10.join(base, "redcumbre");
|
|
3385
3387
|
}
|
|
3386
|
-
function
|
|
3387
|
-
const
|
|
3388
|
-
return
|
|
3388
|
+
function estaDentro(base, ruta) {
|
|
3389
|
+
const relativa = path10.relative(path10.resolve(base), path10.resolve(ruta));
|
|
3390
|
+
return !relativa.startsWith("..") && !path10.isAbsolute(relativa);
|
|
3389
3391
|
}
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
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, {
|
|
3397
|
-
codigo: "PAQUETE_INCOMPLETO"
|
|
3398
|
-
});
|
|
3399
|
-
}
|
|
3400
|
-
const sinLinea = fuente.slice(frontmatter[0].length).replace(/^<!-- redcumbre-cli: [^\n]* -->\r?\n/, "");
|
|
3401
|
-
return `${frontmatter[0]}${lineaDeVersion(version)}
|
|
3402
|
-
${sinLinea}`;
|
|
3392
|
+
function exigirFueraDelProyecto(carpeta, proyecto, personal = os.homedir()) {
|
|
3393
|
+
if (!estaDentro(proyecto, carpeta)) return;
|
|
3394
|
+
if (estaDentro(proyecto, personal) && !tieneInstalacionDelCli(proyecto)) return;
|
|
3395
|
+
throw new ErrorCli(
|
|
3396
|
+
`La carpeta de configuraci\xF3n (${carpeta}) est\xE1 dentro del proyecto: ah\xED no guardo tu sesi\xF3n. Corre el comando con XDG_CONFIG_HOME fuera del proyecto.`
|
|
3397
|
+
);
|
|
3403
3398
|
}
|
|
3404
|
-
|
|
3405
|
-
|
|
3399
|
+
var AlmacenArchivo = class {
|
|
3400
|
+
ruta;
|
|
3401
|
+
descripcion;
|
|
3402
|
+
/** `proyecto`: la carpeta donde corre el CLI; la sesión nunca puede quedar debajo de ella. */
|
|
3403
|
+
constructor(carpeta, proyecto) {
|
|
3404
|
+
this.ruta = path10.join(carpeta, "sesion.json");
|
|
3405
|
+
exigirFueraDelProyecto(carpeta, proyecto);
|
|
3406
|
+
this.descripcion = `el archivo ${this.ruta} (permisos 0600)`;
|
|
3407
|
+
}
|
|
3408
|
+
leer() {
|
|
3409
|
+
if (!fs10.existsSync(this.ruta)) return null;
|
|
3410
|
+
return JSON.parse(fs10.readFileSync(this.ruta, "utf8"));
|
|
3411
|
+
}
|
|
3412
|
+
guardar(par) {
|
|
3413
|
+
fs10.mkdirSync(path10.dirname(this.ruta), { recursive: true, mode: 448 });
|
|
3414
|
+
fs10.writeFileSync(this.ruta, JSON.stringify(par), { mode: 384 });
|
|
3415
|
+
fs10.chmodSync(this.ruta, 384);
|
|
3416
|
+
}
|
|
3417
|
+
borrar() {
|
|
3418
|
+
fs10.rmSync(this.ruta, { force: true });
|
|
3419
|
+
}
|
|
3420
|
+
};
|
|
3421
|
+
var AlmacenLlavero = class {
|
|
3422
|
+
constructor(entrada) {
|
|
3423
|
+
this.entrada = entrada;
|
|
3424
|
+
}
|
|
3425
|
+
descripcion = `el llavero del sistema (servicio ${SERVICIO_LLAVERO})`;
|
|
3426
|
+
leer() {
|
|
3427
|
+
const valor = this.entrada.getPassword();
|
|
3428
|
+
return valor ? JSON.parse(valor) : null;
|
|
3429
|
+
}
|
|
3430
|
+
guardar(par) {
|
|
3431
|
+
this.entrada.setPassword(JSON.stringify(par));
|
|
3432
|
+
}
|
|
3433
|
+
borrar() {
|
|
3434
|
+
this.entrada.deletePassword();
|
|
3435
|
+
}
|
|
3436
|
+
};
|
|
3437
|
+
async function elegirAlmacen(proyecto, env = process.env) {
|
|
3438
|
+
if (env.REDCUMBRE_SESION_EN_ARCHIVO === "1") return new AlmacenArchivo(carpetaDeConfiguracion(env), proyecto);
|
|
3439
|
+
try {
|
|
3440
|
+
const { Entry } = await import("@napi-rs/keyring");
|
|
3441
|
+
const entrada = new Entry(SERVICIO_LLAVERO, "sesion");
|
|
3442
|
+
entrada.getPassword();
|
|
3443
|
+
return new AlmacenLlavero(entrada);
|
|
3444
|
+
} catch {
|
|
3445
|
+
return new AlmacenArchivo(carpetaDeConfiguracion(env), proyecto);
|
|
3446
|
+
}
|
|
3406
3447
|
}
|
|
3407
|
-
var
|
|
3408
|
-
|
|
3409
|
-
|
|
3448
|
+
var ErrorRefreshInvalido = class extends Error {
|
|
3449
|
+
constructor() {
|
|
3450
|
+
super("La sesi\xF3n guardada ya no es v\xE1lida.");
|
|
3451
|
+
this.name = "ErrorRefreshInvalido";
|
|
3452
|
+
}
|
|
3453
|
+
};
|
|
3454
|
+
var DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
3455
|
+
function esperarAbortable(ms, signal) {
|
|
3456
|
+
return setTimeoutAbortable(ms, void 0, { signal });
|
|
3410
3457
|
}
|
|
3411
|
-
function
|
|
3412
|
-
|
|
3413
|
-
|
|
3458
|
+
function comoPar(respuesta) {
|
|
3459
|
+
if (!respuesta.refresh_token) throw new ErrorCli("El servidor de identidad no devolvi\xF3 un refresh token.");
|
|
3460
|
+
const segundos = respuesta.expiresIn();
|
|
3461
|
+
if (segundos === void 0) throw new ErrorCli("El servidor de identidad no dijo cu\xE1ndo vence el token.");
|
|
3462
|
+
return {
|
|
3463
|
+
access_token: respuesta.access_token,
|
|
3464
|
+
refresh_token: respuesta.refresh_token,
|
|
3465
|
+
expira: new Date(Date.now() + segundos * 1e3).toISOString()
|
|
3466
|
+
};
|
|
3414
3467
|
}
|
|
3415
|
-
function
|
|
3416
|
-
|
|
3417
|
-
let espera = 10;
|
|
3418
|
-
let gastado = 0;
|
|
3419
|
-
for (; ; ) {
|
|
3420
|
-
try {
|
|
3421
|
-
return operacion();
|
|
3422
|
-
} catch (error) {
|
|
3423
|
-
if (plataforma !== "win32" || !esErrorTransitorioDeWindows(error) || gastado >= presupuestoMs) throw error;
|
|
3424
|
-
const ms = Math.min(espera, presupuestoMs - gastado);
|
|
3425
|
-
esperar(ms);
|
|
3426
|
-
gastado += ms;
|
|
3427
|
-
espera = Math.min(espera * 2, 100);
|
|
3428
|
-
}
|
|
3429
|
-
}
|
|
3468
|
+
function refreshInvalido(codigo, descripcion) {
|
|
3469
|
+
return codigo === "invalid_grant" || codigo === "invalid_request" && /RefreshToken/i.test(descripcion ?? "");
|
|
3430
3470
|
}
|
|
3431
|
-
function
|
|
3432
|
-
|
|
3433
|
-
const temporal = `${ruta}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
3434
|
-
try {
|
|
3435
|
-
fs10.writeFileSync(temporal, contenido);
|
|
3436
|
-
conReintentoEnWindows(() => fs10.renameSync(temporal, ruta));
|
|
3437
|
-
} catch (error) {
|
|
3438
|
-
fs10.rmSync(temporal, { force: true });
|
|
3439
|
-
throw error;
|
|
3440
|
-
}
|
|
3471
|
+
function esRefreshInvalido(error) {
|
|
3472
|
+
return error instanceof oidc.ResponseBodyError && refreshInvalido(error.error, error.error_description);
|
|
3441
3473
|
}
|
|
3442
|
-
function
|
|
3443
|
-
return
|
|
3444
|
-
|
|
3445
|
-
|
|
3446
|
-
|
|
3447
|
-
"Este proyecto se integra con la API de REDCUMBRE por medio del CLI `redcumbre`. Antes de tocar la integraci\xF3n lee la",
|
|
3448
|
-
"skill `redcumbre` (`.agents/skills/redcumbre/SKILL.md`). En resumen: busca la operaci\xF3n (`redcumbre buscar`), lee su",
|
|
3449
|
-
"contrato (`redcumbre api describir`), pru\xE9bala con `--ensayo`, consulta las fichas (`redcumbre guia`) y verifica el",
|
|
3450
|
-
"sitio (`redcumbre prueba verificar`). No leas ni imprimas `keys/`. Pasar a producci\xF3n lo confirma una persona.",
|
|
3451
|
-
"H\xE1blale a la persona en espa\xF1ol, salvo que ella te escriba en otro idioma.",
|
|
3452
|
-
MARCA_FIN
|
|
3453
|
-
].join("\n");
|
|
3474
|
+
function sinRespuestaDelIdp(error) {
|
|
3475
|
+
if (error instanceof ErrorCli) return false;
|
|
3476
|
+
if (error instanceof oidc.ResponseBodyError) return error.status >= 500;
|
|
3477
|
+
if (error instanceof oidc.AuthorizationResponseError || error instanceof oidc.WWWAuthenticateChallengeError) return false;
|
|
3478
|
+
return true;
|
|
3454
3479
|
}
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
try {
|
|
3461
|
-
texto2 = conReintentoEnWindows(() => fs10.readFileSync(ruta, "utf8"));
|
|
3462
|
-
} catch (error) {
|
|
3463
|
-
if (esErrorTransitorioDeWindows(error)) throw error;
|
|
3464
|
-
return null;
|
|
3480
|
+
function errorDeIdentidad(error) {
|
|
3481
|
+
if (error instanceof ErrorCli) return error;
|
|
3482
|
+
if (sinRespuestaDelIdp(error)) {
|
|
3483
|
+
const detalle = error instanceof Error ? error.cause instanceof Error ? error.cause.message : error.message : String(error);
|
|
3484
|
+
return identidadSinRespuesta(`No pude hablar con ${CLIENTE_OIDC.issuer} (${detalle}). Revisa tu conexi\xF3n y vuelve a intentarlo: lo que ten\xEDas guardado sigue igual.`);
|
|
3465
3485
|
}
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
|
|
3469
|
-
} catch {
|
|
3470
|
-
return null;
|
|
3486
|
+
if (error instanceof oidc.ResponseBodyError) {
|
|
3487
|
+
return new ErrorCli(`El servidor de identidad rechaz\xF3 la operaci\xF3n: ${error.error}${error.error_description ? ` (${error.error_description})` : ""}.`);
|
|
3471
3488
|
}
|
|
3489
|
+
return new ErrorCli(`El servidor de identidad rechaz\xF3 la operaci\xF3n: ${error instanceof Error ? error.message : String(error)}.`);
|
|
3472
3490
|
}
|
|
3473
|
-
function
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3491
|
+
function identidadOidc(cliente = CLIENTE_OIDC) {
|
|
3492
|
+
let configuracion = null;
|
|
3493
|
+
let senalDeEspera;
|
|
3494
|
+
const config = () => {
|
|
3495
|
+
const emisor = new URL(cliente.issuer);
|
|
3496
|
+
const opciones = emisor.protocol === "http:" && emisor.hostname === "127.0.0.1" ? { execute: [oidc.allowInsecureRequests] } : void 0;
|
|
3497
|
+
configuracion ??= oidc.discovery(emisor, cliente.clientId, void 0, oidc.None(), opciones).then((c) => {
|
|
3498
|
+
c[oidc.customFetch] = (url, init2) => fetch(url, senalDeEspera ? { ...init2, signal: init2.signal ? AbortSignal.any([init2.signal, senalDeEspera]) : senalDeEspera } : init2);
|
|
3499
|
+
return c;
|
|
3500
|
+
}).catch((error) => {
|
|
3501
|
+
configuracion = null;
|
|
3502
|
+
throw errorDeIdentidad(error);
|
|
3503
|
+
});
|
|
3504
|
+
return configuracion;
|
|
3505
|
+
};
|
|
3506
|
+
return {
|
|
3507
|
+
async urlDeAutorizacion(redirectUri, pkce) {
|
|
3508
|
+
return oidc.buildAuthorizationUrl(await config(), {
|
|
3509
|
+
redirect_uri: redirectUri,
|
|
3510
|
+
scope: SCOPE,
|
|
3511
|
+
code_challenge: pkce.desafio,
|
|
3512
|
+
code_challenge_method: "S256",
|
|
3513
|
+
state: pkce.estado
|
|
3514
|
+
}).toString();
|
|
3515
|
+
},
|
|
3516
|
+
async canjear(retorno, pkce) {
|
|
3517
|
+
try {
|
|
3518
|
+
return comoPar(await oidc.authorizationCodeGrant(await config(), retorno, { pkceCodeVerifier: pkce.verificador, expectedState: pkce.estado }));
|
|
3519
|
+
} catch (error) {
|
|
3520
|
+
if (error instanceof ErrorCli) throw error;
|
|
3521
|
+
throw errorDeIdentidad(error);
|
|
3522
|
+
}
|
|
3523
|
+
},
|
|
3524
|
+
async renovar(refreshToken) {
|
|
3525
|
+
try {
|
|
3526
|
+
return comoPar(await oidc.refreshTokenGrant(await config(), refreshToken));
|
|
3527
|
+
} catch (error) {
|
|
3528
|
+
if (esRefreshInvalido(error)) throw new ErrorRefreshInvalido();
|
|
3529
|
+
if (error instanceof ErrorCli) throw error;
|
|
3530
|
+
throw errorDeIdentidad(error);
|
|
3531
|
+
}
|
|
3532
|
+
},
|
|
3533
|
+
async revocar(refreshToken) {
|
|
3534
|
+
try {
|
|
3535
|
+
await oidc.tokenRevocation(await config(), refreshToken, { token_type_hint: "refresh_token" });
|
|
3536
|
+
} catch (error) {
|
|
3537
|
+
throw errorDeIdentidad(error);
|
|
3538
|
+
}
|
|
3539
|
+
},
|
|
3540
|
+
async exigeIss() {
|
|
3541
|
+
return (await config()).serverMetadata().authorization_response_iss_parameter_supported === true;
|
|
3542
|
+
},
|
|
3543
|
+
async iniciarDispositivo() {
|
|
3544
|
+
try {
|
|
3545
|
+
const respuesta = await oidc.initiateDeviceAuthorization(await config(), { scope: SCOPE });
|
|
3546
|
+
if (!respuesta.verification_uri_complete) throw new ErrorCli("El servidor de identidad no devolvi\xF3 la direcci\xF3n completa para aprobar el acceso.");
|
|
3547
|
+
return {
|
|
3548
|
+
deviceCode: respuesta.device_code,
|
|
3549
|
+
userCode: respuesta.user_code,
|
|
3550
|
+
url: respuesta.verification_uri_complete,
|
|
3551
|
+
intervalo: respuesta.interval ?? 5,
|
|
3552
|
+
venceEnSegundos: respuesta.expires_in
|
|
3553
|
+
};
|
|
3554
|
+
} catch (error) {
|
|
3555
|
+
throw errorDeIdentidad(error);
|
|
3556
|
+
}
|
|
3557
|
+
},
|
|
3558
|
+
async esperarDispositivo(pendiente, esperaMs) {
|
|
3559
|
+
const techo = AbortSignal.timeout(esperaMs);
|
|
3560
|
+
const venceEn = new Date(pendiente.venceEn).getTime();
|
|
3561
|
+
let intervalo = pendiente.intervalo;
|
|
3562
|
+
senalDeEspera = techo;
|
|
3563
|
+
try {
|
|
3564
|
+
for (; ; ) {
|
|
3565
|
+
try {
|
|
3566
|
+
await esperarAbortable(intervalo * 1e3, techo);
|
|
3567
|
+
} catch (error) {
|
|
3568
|
+
if (techo.aborted) return { estado: "pendiente" };
|
|
3569
|
+
throw error;
|
|
3570
|
+
}
|
|
3571
|
+
if (Date.now() >= venceEn) return { estado: "vencido" };
|
|
3572
|
+
try {
|
|
3573
|
+
const respuesta = await oidc.genericGrantRequest(await config(), DEVICE_CODE_GRANT, { device_code: pendiente.deviceCode });
|
|
3574
|
+
return { estado: "aprobado", par: comoPar(respuesta) };
|
|
3575
|
+
} catch (error) {
|
|
3576
|
+
if (techo.aborted) return { estado: "pendiente" };
|
|
3577
|
+
if (error instanceof oidc.ResponseBodyError) {
|
|
3578
|
+
if (error.error === "authorization_pending") continue;
|
|
3579
|
+
if (error.error === "slow_down") {
|
|
3580
|
+
intervalo += 5;
|
|
3581
|
+
continue;
|
|
3582
|
+
}
|
|
3583
|
+
if (error.error === "expired_token") return { estado: "vencido" };
|
|
3584
|
+
if (error.error === "access_denied") return { estado: "rechazado" };
|
|
3585
|
+
}
|
|
3586
|
+
throw errorDeIdentidad(error);
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
3589
|
+
} finally {
|
|
3590
|
+
senalDeEspera = void 0;
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
};
|
|
3479
3594
|
}
|
|
3480
|
-
function
|
|
3481
|
-
|
|
3595
|
+
async function crearPkce() {
|
|
3596
|
+
const verificador = oidc.randomPKCECodeVerifier();
|
|
3597
|
+
return { verificador, desafio: await oidc.calculatePKCECodeChallenge(verificador), estado: oidc.randomState() };
|
|
3482
3598
|
}
|
|
3483
|
-
function
|
|
3484
|
-
|
|
3485
|
-
|
|
3599
|
+
function hayQueIrSinNavegador(pedido, env = process.env, plataforma = process.platform) {
|
|
3600
|
+
if (pedido) return true;
|
|
3601
|
+
if (env.SSH_CONNECTION || env.SSH_TTY) return true;
|
|
3602
|
+
return plataforma === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
|
|
3486
3603
|
}
|
|
3487
|
-
function
|
|
3488
|
-
const
|
|
3489
|
-
|
|
3490
|
-
|
|
3604
|
+
async function abrirNavegadorDelSistema(url) {
|
|
3605
|
+
const [comando2, argumentos] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
|
|
3606
|
+
return new Promise((resolver) => {
|
|
3607
|
+
const hijo = spawn(comando2, argumentos, { stdio: "ignore", detached: true });
|
|
3608
|
+
hijo.once("error", () => resolver(false));
|
|
3609
|
+
hijo.once("spawn", () => {
|
|
3610
|
+
hijo.unref();
|
|
3611
|
+
resolver(true);
|
|
3612
|
+
});
|
|
3613
|
+
});
|
|
3491
3614
|
}
|
|
3492
|
-
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3615
|
+
var PAGINA_LISTO = paginaListo("Listo, ya iniciaste sesi\xF3n", "Ya puedes cerrar esta ventana y volver a la terminal.");
|
|
3616
|
+
async function loginConLoopback(identidad, salida, opciones) {
|
|
3617
|
+
const pkce = await crearPkce();
|
|
3618
|
+
const local = await abrirRetornoLocal({
|
|
3619
|
+
pagina: PAGINA_LISTO,
|
|
3620
|
+
esperaMs: opciones.esperaMs ?? 3e5,
|
|
3621
|
+
mensajeDeEspera: "No lleg\xF3 la autorizaci\xF3n del navegador en 5 minutos. Vuelve a correr el comando."
|
|
3622
|
+
});
|
|
3623
|
+
const redirectUri = `http://127.0.0.1:${local.puerto}/callback`;
|
|
3624
|
+
try {
|
|
3625
|
+
const url = await identidad.urlDeAutorizacion(redirectUri, pkce);
|
|
3626
|
+
const abierto = await (opciones.abrirNavegador ?? abrirNavegadorDelSistema)(url);
|
|
3627
|
+
salida.linea(abierto ? "Abr\xED tu navegador para que inicies sesi\xF3n. Si no se abri\xF3, abre esta URL:" : "Abre esta URL en tu navegador para iniciar sesi\xF3n:");
|
|
3628
|
+
salida.linea(url);
|
|
3629
|
+
const vuelta = await local.recibido;
|
|
3630
|
+
const recibida = new URL(`${redirectUri}${vuelta.search}`);
|
|
3631
|
+
const error = recibida.searchParams.get("error");
|
|
3632
|
+
if (error) throw new ErrorCli(`El inicio de sesi\xF3n no se complet\xF3: ${error}.`);
|
|
3633
|
+
return await identidad.canjear(recibida, pkce);
|
|
3634
|
+
} finally {
|
|
3635
|
+
local.cerrar();
|
|
3502
3636
|
}
|
|
3503
|
-
return lista2;
|
|
3504
3637
|
}
|
|
3505
|
-
var
|
|
3506
|
-
function
|
|
3507
|
-
|
|
3508
|
-
if (quitada) estado2 = "quitada";
|
|
3509
|
-
else if (rutas.some((r) => r.accion === "editada")) estado2 = "editada";
|
|
3510
|
-
else if (rutas.some((r) => r.accion === "reemplazada-editada")) estado2 = "reemplazada-editada";
|
|
3511
|
-
else if (rutas.some((r) => r.accion === "instalada")) estado2 = "instalada";
|
|
3512
|
-
else if (rutas.some((r) => r.accion === "actualizada")) estado2 = "actualizada";
|
|
3513
|
-
return { estado: estado2, rutas };
|
|
3638
|
+
var AVISO_DE_APROBACION = "Este acceso es para el CLI de REDCUMBRE. Apru\xE9balo solo si t\xFA lo pediste: no apruebes un c\xF3digo que no pediste.";
|
|
3639
|
+
async function iniciarSesion(identidad, salida, opciones) {
|
|
3640
|
+
return opciones.sinNavegador ? loginDeDispositivoEnLinea(identidad, salida) : loginConLoopback(identidad, salida, opciones);
|
|
3514
3641
|
}
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
|
|
3524
|
-
|
|
3525
|
-
throw error;
|
|
3526
|
-
}
|
|
3527
|
-
}
|
|
3528
|
-
throw new Error(`ya hay demasiadas copias de ${archivo} con la misma hora`);
|
|
3642
|
+
async function loginDeDispositivoEnLinea(identidad, salida) {
|
|
3643
|
+
const solicitud = await identidad.iniciarDispositivo();
|
|
3644
|
+
salida.linea("Abre esta direcci\xF3n en un navegador y aprueba el acceso:");
|
|
3645
|
+
salida.linea(solicitud.url);
|
|
3646
|
+
salida.linea(`El c\xF3digo que tiene que mostrar es ${solicitud.userCode}.`);
|
|
3647
|
+
salida.linea(AVISO_DE_APROBACION);
|
|
3648
|
+
const venceEn = new Date(Date.now() + solicitud.venceEnSegundos * 1e3).toISOString();
|
|
3649
|
+
const desenlace = await identidad.esperarDispositivo({ deviceCode: solicitud.deviceCode, intervalo: solicitud.intervalo, venceEn }, solicitud.venceEnSegundos * 1e3);
|
|
3650
|
+
if (desenlace.estado === "aprobado") return desenlace.par;
|
|
3651
|
+
throw errorDelDesenlace(desenlace.estado);
|
|
3529
3652
|
}
|
|
3530
|
-
var
|
|
3531
|
-
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
if (
|
|
3535
|
-
|
|
3536
|
-
|
|
3537
|
-
|
|
3538
|
-
|
|
3539
|
-
const hashActual = sha256(conReintentoEnWindows(() => fs10.readFileSync(archivo)));
|
|
3540
|
-
if (registrado === void 0) {
|
|
3541
|
-
if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
|
|
3542
|
-
return reemplazarConCopia(archivo, nuevo, hashNuevo, ahora);
|
|
3653
|
+
var ESPERA_DE_COMPLETAR_MS = 9e4;
|
|
3654
|
+
var rutaLoginPendiente = (carpeta) => path10.join(carpeta, "login-pendiente.json");
|
|
3655
|
+
var volverAEmpezar = (motivo, codigo) => new ErrorCli(`${motivo} Vuelve a empezar con \xABredcumbre login\xBB.`, CODIGOS_DE_SALIDA.sesion, { codigo, comando: "redcumbre login" });
|
|
3656
|
+
function errorDelDesenlace(estado2) {
|
|
3657
|
+
if (estado2 === "pendiente") {
|
|
3658
|
+
return new ErrorCli("Nadie aprob\xF3 el acceso todav\xEDa. Cuando la persona lo apruebe, repite \xABredcumbre login --completar\xBB: sigue siendo el mismo c\xF3digo.", CODIGOS_DE_SALIDA.sesion, {
|
|
3659
|
+
codigo: "LOGIN_PENDIENTE",
|
|
3660
|
+
comando: "redcumbre login --completar"
|
|
3661
|
+
});
|
|
3543
3662
|
}
|
|
3544
|
-
if (
|
|
3545
|
-
|
|
3546
|
-
escribirAtomico(archivo, nuevo);
|
|
3547
|
-
return { accion: "actualizada", hash: hashNuevo };
|
|
3663
|
+
if (estado2 === "vencido") return volverAEmpezar("El c\xF3digo venci\xF3 antes de que lo aprobaran.", "LOGIN_PENDIENTE_VENCIDO");
|
|
3664
|
+
return volverAEmpezar("La persona rechaz\xF3 el acceso.", "LOGIN_RECHAZADO");
|
|
3548
3665
|
}
|
|
3549
|
-
function
|
|
3550
|
-
|
|
3666
|
+
function leerLoginPendiente(carpeta) {
|
|
3667
|
+
const ruta = rutaLoginPendiente(carpeta);
|
|
3668
|
+
if (!fs10.existsSync(ruta)) return null;
|
|
3551
3669
|
try {
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
3670
|
+
const d = JSON.parse(fs10.readFileSync(ruta, "utf8"));
|
|
3671
|
+
const textos = ["deviceCode", "userCode", "url", "venceEn", "clientId"];
|
|
3672
|
+
if (!textos.every((k) => typeof d[k] === "string") || typeof d.intervalo !== "number") return null;
|
|
3673
|
+
if (d.clientId !== CLIENTE_OIDC.clientId || Number.isNaN(new Date(d.venceEn).getTime())) return null;
|
|
3674
|
+
return d;
|
|
3675
|
+
} catch {
|
|
3676
|
+
return null;
|
|
3555
3677
|
}
|
|
3556
|
-
escribirAtomico(archivo, nuevo);
|
|
3557
|
-
return { accion: "reemplazada-editada", hash: hashNuevo, copia };
|
|
3558
|
-
}
|
|
3559
|
-
var regexBloque = () => new RegExp(`${MARCA_INICIO.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${MARCA_FIN.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
|
|
3560
|
-
function extraerBloque(texto2) {
|
|
3561
|
-
return texto2.match(regexBloque())?.[0] ?? null;
|
|
3562
3678
|
}
|
|
3563
|
-
function
|
|
3564
|
-
const
|
|
3565
|
-
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
escribirAtomico(archivo, `${bloque}
|
|
3569
|
-
`);
|
|
3570
|
-
return { accion: "instalada", registro: { sha256: hashBloque, creado: true } };
|
|
3571
|
-
}
|
|
3572
|
-
const texto2 = conReintentoEnWindows(() => fs10.readFileSync(archivo, "utf8"));
|
|
3573
|
-
const actual = extraerBloque(texto2);
|
|
3574
|
-
if (actual === null) {
|
|
3575
|
-
if (registro) return { accion: "borrada", registro: null };
|
|
3576
|
-
const separador = texto2.length === 0 ? "" : texto2.endsWith("\n\n") ? "" : texto2.endsWith("\n") ? "\n" : "\n\n";
|
|
3577
|
-
escribirAtomico(archivo, `${texto2}${separador}${bloque}
|
|
3578
|
-
`);
|
|
3579
|
-
return { accion: "instalada", registro: { sha256: hashBloque, creado: false } };
|
|
3580
|
-
}
|
|
3581
|
-
const hashActual = sha256(actual);
|
|
3582
|
-
if (!registro) {
|
|
3583
|
-
if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { sha256: hashBloque, creado: false } };
|
|
3584
|
-
return { accion: "editada", registro: null };
|
|
3585
|
-
}
|
|
3586
|
-
if (hashActual !== registro.sha256) return { accion: "editada", registro: null };
|
|
3587
|
-
if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { ...registro, sha256: hashBloque } };
|
|
3588
|
-
escribirAtomico(archivo, texto2.replace(regexBloque(), () => bloque));
|
|
3589
|
-
return { accion: "actualizada", registro: { ...registro, sha256: hashBloque } };
|
|
3679
|
+
function guardarLoginPendiente(carpeta, pendiente) {
|
|
3680
|
+
const ruta = rutaLoginPendiente(carpeta);
|
|
3681
|
+
fs10.mkdirSync(carpeta, { recursive: true, mode: 448 });
|
|
3682
|
+
fs10.writeFileSync(ruta, JSON.stringify(pendiente), { mode: 384 });
|
|
3683
|
+
fs10.chmodSync(ruta, 384);
|
|
3590
3684
|
}
|
|
3591
|
-
function
|
|
3592
|
-
const
|
|
3593
|
-
const
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
|
|
3597
|
-
const rutas = [];
|
|
3598
|
-
for (const objetivo of objetivos(destinos)) {
|
|
3599
|
-
const deUsuario = esDeUsuario(objetivo.id);
|
|
3600
|
-
const registro = deUsuario ? usuario : proyecto;
|
|
3601
|
-
if (usuario.quitada || registro.quitada) continue;
|
|
3602
|
-
const previo = registro.rutas?.[objetivo.id]?.sha256;
|
|
3603
|
-
const { accion, hash, copia, error } = reconciliar(objetivo.archivo, nuevo, previo, ahora);
|
|
3604
|
-
rutas.push({ ruta: objetivo.legible, accion, ...copia ? { copia } : {}, ...error ? { error } : {} });
|
|
3605
|
-
if (hash) {
|
|
3606
|
-
registro.rutas = { ...registro.rutas ?? {}, [objetivo.id]: { sha256: hash } };
|
|
3607
|
-
}
|
|
3608
|
-
}
|
|
3609
|
-
if (bloqueAgents && destinos.proyecto && proyecto && !usuario.quitada && !proyecto.quitada) {
|
|
3610
|
-
const { accion, registro } = reconciliarAgents(path10.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
|
|
3611
|
-
rutas.push({ ruta: "AGENTS.md", accion });
|
|
3612
|
-
if (registro) proyecto.agents = registro;
|
|
3613
|
-
}
|
|
3614
|
-
if (!usuario.quitada && rutas.some((r) => r.ruta.startsWith("~"))) guardarRegistroUsuario(destinos, usuario);
|
|
3615
|
-
if (destinos.proyecto && proyecto && !proyecto.quitada && rutas.some((r) => !r.ruta.startsWith("~"))) guardarRegistroProyecto(destinos.proyecto, proyecto);
|
|
3616
|
-
return resumir2(rutas, rutas.length === 0 && Boolean(usuario.quitada || proyecto?.quitada));
|
|
3685
|
+
function borrarLoginPendiente(carpeta) {
|
|
3686
|
+
const ruta = rutaLoginPendiente(carpeta);
|
|
3687
|
+
const habia = fs10.existsSync(ruta);
|
|
3688
|
+
fs10.rmSync(ruta, { force: true });
|
|
3689
|
+
return habia;
|
|
3617
3690
|
}
|
|
3618
|
-
function
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3691
|
+
async function iniciarLoginDeDispositivo(identidad, carpeta, proyecto, ahora = /* @__PURE__ */ new Date()) {
|
|
3692
|
+
exigirFueraDelProyecto(carpeta, proyecto);
|
|
3693
|
+
const vigente = leerLoginPendiente(carpeta);
|
|
3694
|
+
if (vigente && new Date(vigente.venceEn).getTime() > ahora.getTime()) return { url: vigente.url, codigo: vigente.userCode, vence: vigente.venceEn };
|
|
3695
|
+
borrarLoginPendiente(carpeta);
|
|
3696
|
+
const solicitud = await identidad.iniciarDispositivo();
|
|
3697
|
+
const venceEn = new Date(ahora.getTime() + solicitud.venceEnSegundos * 1e3).toISOString();
|
|
3698
|
+
guardarLoginPendiente(carpeta, {
|
|
3699
|
+
deviceCode: solicitud.deviceCode,
|
|
3700
|
+
userCode: solicitud.userCode,
|
|
3701
|
+
url: solicitud.url,
|
|
3702
|
+
intervalo: solicitud.intervalo,
|
|
3703
|
+
venceEn,
|
|
3704
|
+
clientId: CLIENTE_OIDC.clientId
|
|
3705
|
+
});
|
|
3706
|
+
return { url: solicitud.url, codigo: solicitud.userCode, vence: venceEn };
|
|
3625
3707
|
}
|
|
3626
|
-
function
|
|
3627
|
-
|
|
3628
|
-
|
|
3629
|
-
const
|
|
3630
|
-
|
|
3631
|
-
|
|
3632
|
-
|
|
3633
|
-
|
|
3634
|
-
const accion = quitarArchivo(objetivo.archivo, previo);
|
|
3635
|
-
if (accion) rutas.push({ ruta: objetivo.legible, accion });
|
|
3636
|
-
}
|
|
3637
|
-
if (destinos.proyecto && proyecto) {
|
|
3638
|
-
const archivo = path10.join(destinos.proyecto, "AGENTS.md");
|
|
3639
|
-
if (fs10.existsSync(archivo)) {
|
|
3640
|
-
const texto2 = conReintentoEnWindows(() => fs10.readFileSync(archivo, "utf8"));
|
|
3641
|
-
const bloque = extraerBloque(texto2);
|
|
3642
|
-
if (bloque !== null) {
|
|
3643
|
-
if (!proyecto.agents || sha256(bloque) !== proyecto.agents.sha256) {
|
|
3644
|
-
rutas.push({ ruta: "AGENTS.md", accion: "editada" });
|
|
3645
|
-
} else {
|
|
3646
|
-
const resto = texto2.replace(regexBloque(), "").replace(/\n{3,}/g, "\n\n");
|
|
3647
|
-
if (proyecto.agents.creado && resto.trim() === "") fs10.rmSync(archivo);
|
|
3648
|
-
else escribirAtomico(archivo, resto.replace(/^\n+/, "").replace(/\n*$/, "\n"));
|
|
3649
|
-
rutas.push({ ruta: "AGENTS.md", accion: "quitada" });
|
|
3650
|
-
}
|
|
3651
|
-
}
|
|
3652
|
-
}
|
|
3708
|
+
async function completarLogin(identidad, almacen, carpeta, proyecto, ahora = /* @__PURE__ */ new Date(), esperaMs = ESPERA_DE_COMPLETAR_MS) {
|
|
3709
|
+
exigirFueraDelProyecto(carpeta, proyecto);
|
|
3710
|
+
if (almacen.leer() !== null) return "ya-habia-sesion";
|
|
3711
|
+
const pendiente = leerLoginPendiente(carpeta);
|
|
3712
|
+
if (!pendiente) throw volverAEmpezar("No hay un inicio de sesi\xF3n pendiente.", "SIN_SESION");
|
|
3713
|
+
if (new Date(pendiente.venceEn).getTime() <= ahora.getTime()) {
|
|
3714
|
+
borrarLoginPendiente(carpeta);
|
|
3715
|
+
throw errorDelDesenlace("vencido");
|
|
3653
3716
|
}
|
|
3654
|
-
|
|
3655
|
-
if (
|
|
3656
|
-
|
|
3717
|
+
const desenlace = await identidad.esperarDispositivo({ deviceCode: pendiente.deviceCode, intervalo: pendiente.intervalo, venceEn: pendiente.venceEn }, esperaMs);
|
|
3718
|
+
if (desenlace.estado === "aprobado") {
|
|
3719
|
+
almacen.guardar(desenlace.par);
|
|
3720
|
+
borrarLoginPendiente(carpeta);
|
|
3721
|
+
return "iniciada";
|
|
3722
|
+
}
|
|
3723
|
+
if (desenlace.estado !== "pendiente") borrarLoginPendiente(carpeta);
|
|
3724
|
+
throw errorDelDesenlace(desenlace.estado);
|
|
3657
3725
|
}
|
|
3658
|
-
|
|
3659
|
-
|
|
3660
|
-
|
|
3661
|
-
|
|
3662
|
-
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
if (
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
const hashNuevo = sha256(nuevo);
|
|
3680
|
-
const hashActual = sha256(actual);
|
|
3681
|
-
const registrado = (registro.rutas ?? {})[objetivo.id]?.sha256;
|
|
3682
|
-
if (hashActual === hashNuevo) {
|
|
3683
|
-
if (registrado !== hashNuevo) (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
|
|
3684
|
-
rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: version });
|
|
3685
|
-
continue;
|
|
3726
|
+
var Sesion = class {
|
|
3727
|
+
constructor(almacen, identidad, salida, login2) {
|
|
3728
|
+
this.almacen = almacen;
|
|
3729
|
+
this.identidad = identidad;
|
|
3730
|
+
this.salida = salida;
|
|
3731
|
+
this.login = login2;
|
|
3732
|
+
}
|
|
3733
|
+
actual = null;
|
|
3734
|
+
async entrar() {
|
|
3735
|
+
const par = await this.login();
|
|
3736
|
+
this.almacen.guardar(par);
|
|
3737
|
+
this.salida.linea(`Sesi\xF3n iniciada. Qued\xF3 guardada en ${this.almacen.descripcion}.`);
|
|
3738
|
+
return par;
|
|
3739
|
+
}
|
|
3740
|
+
/** El access token de esta corrida: renueva siempre la sesión guardada y guarda el par rotado. */
|
|
3741
|
+
async token() {
|
|
3742
|
+
if (this.actual) return this.actual.access_token;
|
|
3743
|
+
const guardada = this.almacen.leer();
|
|
3744
|
+
if (!guardada) {
|
|
3745
|
+
this.actual = await this.entrar();
|
|
3746
|
+
return this.actual.access_token;
|
|
3686
3747
|
}
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
3748
|
+
try {
|
|
3749
|
+
this.actual = await this.identidad.renovar(guardada.refresh_token);
|
|
3750
|
+
this.almacen.guardar(this.actual);
|
|
3751
|
+
} catch (error) {
|
|
3752
|
+
if (!(error instanceof ErrorRefreshInvalido)) throw error;
|
|
3753
|
+
this.almacen.borrar();
|
|
3754
|
+
this.salida.linea("Tu sesi\xF3n anterior venci\xF3 o se cerr\xF3. Inicia sesi\xF3n de nuevo.");
|
|
3755
|
+
this.actual = await this.entrar();
|
|
3691
3756
|
}
|
|
3692
|
-
|
|
3693
|
-
|
|
3757
|
+
return this.actual.access_token;
|
|
3758
|
+
}
|
|
3759
|
+
/**
|
|
3760
|
+
* Corre `operacion` con el token de la sesión. Si el API responde 401, borra la sesión, pide login y
|
|
3761
|
+
* la repite UNA vez con el token nuevo; nunca reintenta con el mismo (`CA-33`).
|
|
3762
|
+
*/
|
|
3763
|
+
async usar(operacion) {
|
|
3764
|
+
try {
|
|
3765
|
+
return await operacion(await this.token());
|
|
3766
|
+
} catch (error) {
|
|
3767
|
+
if (!(error instanceof ErrorSesionRechazada)) throw error;
|
|
3768
|
+
this.almacen.borrar();
|
|
3769
|
+
this.actual = null;
|
|
3770
|
+
this.salida.linea("La plataforma rechaz\xF3 tu sesi\xF3n (por ejemplo, porque cambiaste tu contrase\xF1a). Inicia sesi\xF3n de nuevo.");
|
|
3771
|
+
this.actual = await this.entrar();
|
|
3694
3772
|
try {
|
|
3695
|
-
|
|
3696
|
-
} catch (
|
|
3697
|
-
|
|
3698
|
-
|
|
3773
|
+
return await operacion(this.actual.access_token);
|
|
3774
|
+
} catch (otra) {
|
|
3775
|
+
if (otra instanceof ErrorSesionRechazada) throw new ErrorCli("La plataforma volvi\xF3 a rechazar la sesi\xF3n reci\xE9n iniciada. Escr\xEDbenos a soporte con la hora del intento.");
|
|
3776
|
+
throw otra;
|
|
3699
3777
|
}
|
|
3700
3778
|
}
|
|
3701
|
-
escribirAtomico(objetivo.archivo, nuevo);
|
|
3702
|
-
(deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
|
|
3703
|
-
rutas.push(copia ? { ruta: objetivo.legible, accion: "reemplazada-editada", instalada: instalada2, copia } : { ruta: objetivo.legible, accion: "renovada", instalada: instalada2 });
|
|
3704
|
-
}
|
|
3705
|
-
if (Object.keys(cambiosUsuario).length > 0) {
|
|
3706
|
-
const vigente = leerRegistroUsuario(destinos);
|
|
3707
|
-
if (!vigente.quitada) guardarRegistroUsuario(destinos, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosUsuario) } });
|
|
3708
|
-
}
|
|
3709
|
-
if (Object.keys(cambiosProyecto).length > 0 && destinos.proyecto) {
|
|
3710
|
-
const vigente = leerRegistroProyecto(destinos.proyecto);
|
|
3711
|
-
if (!vigente.quitada) guardarRegistroProyecto(destinos.proyecto, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosProyecto) } });
|
|
3712
3779
|
}
|
|
3713
|
-
|
|
3714
|
-
|
|
3715
|
-
|
|
3716
|
-
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
if (r.accion === "desactualizada") {
|
|
3721
|
-
return `La skill de REDCUMBRE en ${r.ruta} tiene cambios tuyos (o no la instal\xF3 el CLI) y no pude guardar su copia (${r.error}): no la toqu\xE9. Corre \xAB${COMANDO_SKILL_RENOVAR}\xBB cuando se pueda escribir en esa carpeta.`;
|
|
3780
|
+
/** `logout`: revoca el refresh token (RFC 7009) y borra lo local. */
|
|
3781
|
+
async cerrar() {
|
|
3782
|
+
const guardada = this.almacen.leer();
|
|
3783
|
+
if (!guardada) return false;
|
|
3784
|
+
await this.identidad.revocar(guardada.refresh_token);
|
|
3785
|
+
this.almacen.borrar();
|
|
3786
|
+
return true;
|
|
3722
3787
|
}
|
|
3723
|
-
|
|
3788
|
+
};
|
|
3789
|
+
|
|
3790
|
+
// src/nucleo/contexto.ts
|
|
3791
|
+
var sinSesionEnModoAgente = () => new ErrorCli(
|
|
3792
|
+
"No hay una sesi\xF3n iniciada y en modo agente no puedo esperar a que la persona inicie sesi\xF3n. Corre \xABredcumbre login\xBB, p\xEDdele a la persona que apruebe el acceso en la direcci\xF3n que responde y termina con \xABredcumbre login --completar\xBB.",
|
|
3793
|
+
CODIGOS_DE_SALIDA.sesion,
|
|
3794
|
+
{ codigo: "SIN_SESION", comando: "redcumbre login" }
|
|
3795
|
+
);
|
|
3796
|
+
function crearContexto(opciones) {
|
|
3797
|
+
const { salida, terminal, env } = opciones;
|
|
3798
|
+
const destinos = servidores(env);
|
|
3799
|
+
const proyecto = raizDelProyecto(opciones.cwd);
|
|
3800
|
+
const carpeta = carpetaDeConfiguracion(env);
|
|
3801
|
+
const identidad = identidadOidc();
|
|
3802
|
+
let almacen = null;
|
|
3803
|
+
let sesion = null;
|
|
3804
|
+
const elAlmacen = () => almacen ??= elegirAlmacen(proyecto, env);
|
|
3805
|
+
const abrir = async (destino) => {
|
|
3806
|
+
const propio = env.REDCUMBRE_ABRIR;
|
|
3807
|
+
if (propio) return abrirCon(propio, destino);
|
|
3808
|
+
return abrirNavegadorDelSistema(destino);
|
|
3809
|
+
};
|
|
3810
|
+
return {
|
|
3811
|
+
salida,
|
|
3812
|
+
terminal,
|
|
3813
|
+
cliente: new ClienteApi(destinos.api),
|
|
3814
|
+
servidores: destinos,
|
|
3815
|
+
carpetaConfiguracion: carpeta,
|
|
3816
|
+
home: os2.homedir(),
|
|
3817
|
+
cwd: opciones.cwd,
|
|
3818
|
+
proyecto,
|
|
3819
|
+
env,
|
|
3820
|
+
version: opciones.version,
|
|
3821
|
+
identidad,
|
|
3822
|
+
ahora: () => /* @__PURE__ */ new Date(),
|
|
3823
|
+
abrir,
|
|
3824
|
+
almacen: elAlmacen,
|
|
3825
|
+
async haySesion() {
|
|
3826
|
+
return (await elAlmacen()).leer() !== null;
|
|
3827
|
+
},
|
|
3828
|
+
sesion() {
|
|
3829
|
+
sesion ??= elAlmacen().then(
|
|
3830
|
+
(a) => new Sesion(a, identidad, salida, async () => {
|
|
3831
|
+
if (!terminal) throw sinSesionEnModoAgente();
|
|
3832
|
+
return iniciarSesion(identidad, salida, {
|
|
3833
|
+
sinNavegador: hayQueIrSinNavegador(opciones.sinNavegador, env),
|
|
3834
|
+
abrirNavegador: abrir
|
|
3835
|
+
});
|
|
3836
|
+
})
|
|
3837
|
+
);
|
|
3838
|
+
return sesion;
|
|
3839
|
+
}
|
|
3840
|
+
};
|
|
3724
3841
|
}
|
|
3725
|
-
function
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
const usuario = leerRegistroUsuario(opciones.destinos);
|
|
3733
|
-
if (usuario.avisoDesactualizadaEn === hoy) return;
|
|
3734
|
-
for (const r of desactualizadas) opciones.avisar(avisoDeRenovacion(r, informe.version));
|
|
3735
|
-
guardarRegistroUsuario(opciones.destinos, { ...usuario, avisoDesactualizadaEn: hoy });
|
|
3736
|
-
} catch (error) {
|
|
3737
|
-
opciones.depurar?.(`no pude revisar la skill instalada (${error instanceof Error ? error.message : String(error)}); el comando sigue`);
|
|
3738
|
-
}
|
|
3842
|
+
async function abrirCon(programa2, destino) {
|
|
3843
|
+
const { spawn: spawn4 } = await import("node:child_process");
|
|
3844
|
+
return new Promise((resolver) => {
|
|
3845
|
+
const hijo = spawn4(programa2, [destino], { stdio: "ignore" });
|
|
3846
|
+
hijo.once("error", () => resolver(false));
|
|
3847
|
+
hijo.once("exit", (codigo) => resolver(codigo === 0));
|
|
3848
|
+
});
|
|
3739
3849
|
}
|
|
3740
3850
|
|
|
3741
3851
|
// src/nucleo/terminal.ts
|
|
@@ -3823,6 +3933,45 @@ function sinRespuesta() {
|
|
|
3823
3933
|
|
|
3824
3934
|
// src/comandos/instalar.ts
|
|
3825
3935
|
import path11 from "node:path";
|
|
3936
|
+
|
|
3937
|
+
// src/comandos/skill.ts
|
|
3938
|
+
async function skillQuitar(ctx) {
|
|
3939
|
+
const { salida } = ctx;
|
|
3940
|
+
const proyecto = tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0;
|
|
3941
|
+
const informe = quitarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto } });
|
|
3942
|
+
for (const r of informe.rutas) {
|
|
3943
|
+
if (r.accion === "quitada") salida.linea(`\u2713 Quit\xE9 ${r.ruta}.`);
|
|
3944
|
+
else if (r.accion === "editada") salida.aviso(`${r.ruta} tiene cambios tuyos: no lo borr\xE9.`);
|
|
3945
|
+
}
|
|
3946
|
+
if (informe.rutas.length === 0) salida.linea("No hab\xEDa nada de la skill que quitar.");
|
|
3947
|
+
salida.linea("La skill qued\xF3 quitada: ning\xFAn comando la vuelve a instalar, salvo \xABredcumbre instalar\xBB o \xABredcumbre skill renovar\xBB.");
|
|
3948
|
+
salida.resultado({ ok: true, skill: { rutas: informe.rutas, estado: informe.estado } });
|
|
3949
|
+
}
|
|
3950
|
+
var TEXTO_SKILL_QUITADA_PARA_AGENTE = "La skill est\xE1 quitada (\xABredcumbre skill quitar\xBB): para volver a instalarla, corre \xABredcumbre instalar\xBB.";
|
|
3951
|
+
function informarRenovacion(salida, informe, textoSinRutas) {
|
|
3952
|
+
for (const r of informe.rutas) {
|
|
3953
|
+
const aviso = avisoDeRenovacion(r, informe.version);
|
|
3954
|
+
if (r.accion === "renovada" || r.accion === "instalada") salida.linea(`\u2713 ${aviso}`);
|
|
3955
|
+
else if (r.accion === "reemplazada-editada") {
|
|
3956
|
+
salida.linea(`\u2713 Reemplac\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta} ${deLaVersion(r.ruta, "por", informe.version)}.`);
|
|
3957
|
+
salida.aviso(`${r.ruta.includes("/commands/") ? "Tu versi\xF3n editada del comando" : "Tu versi\xF3n editada de la skill"} qued\xF3 en ${r.copia}.`);
|
|
3958
|
+
} else if (aviso) salida.aviso(aviso);
|
|
3959
|
+
}
|
|
3960
|
+
if (informe.rutas.length === 0) salida.linea(textoSinRutas);
|
|
3961
|
+
else if (informe.rutas.every((r) => r.accion === "al-dia" || r.accion === "mas-nueva")) salida.linea(`La skill y los comandos /redcumbre:* ya est\xE1n al d\xEDa con la versi\xF3n ${informe.version}.`);
|
|
3962
|
+
}
|
|
3963
|
+
async function skillRenovar(ctx, _opciones) {
|
|
3964
|
+
const { salida } = ctx;
|
|
3965
|
+
const proyecto = tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0;
|
|
3966
|
+
const destinos = { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto };
|
|
3967
|
+
const agente = salida.json;
|
|
3968
|
+
const reponerQuitada = !agente && ctx.env[VARIABLE_SKILL_DEL_LLAMADOR] !== "1";
|
|
3969
|
+
const informe = renovarSkill({ destinos, version: ctx.version, ahora: ctx.ahora(), reponerQuitada });
|
|
3970
|
+
informarRenovacion(salida, informe, agente ? TEXTO_SKILL_QUITADA_PARA_AGENTE : "La skill est\xE1 quitada (\xABredcumbre skill quitar\xBB): no la toqu\xE9.");
|
|
3971
|
+
salida.resultado({ ok: true, skill: { version: informe.version, rutas: informe.rutas } });
|
|
3972
|
+
}
|
|
3973
|
+
|
|
3974
|
+
// src/comandos/instalar.ts
|
|
3826
3975
|
function estadoDeInstalacion(ctx, entorno) {
|
|
3827
3976
|
if (!correPorNpx(entorno.bundle)) return { forma: "instalado" };
|
|
3828
3977
|
const enElPath = versionEnElPath(entorno, { cwd: ctx.cwd, env: ctx.env });
|
|
@@ -3861,7 +4010,7 @@ function instalarConfirmado(ctx, entorno) {
|
|
|
3861
4010
|
const { salida } = ctx;
|
|
3862
4011
|
const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
|
|
3863
4012
|
const comando2 = comandoDeActualizacion("npm-global", ctx.version, registro);
|
|
3864
|
-
const opciones = { cwd: ctx.cwd, env: ctx.env };
|
|
4013
|
+
const opciones = { cwd: ctx.cwd, env: entornoDelHijo(ctx.env) };
|
|
3865
4014
|
salida.linea(`Instalando: ${legible(comando2)}`);
|
|
3866
4015
|
const corrida = entorno.ejecutar(comando2.comando, comando2.args, opciones);
|
|
3867
4016
|
if (corrida.status !== 0) throw errorDeInstalacion(comando2, corrida);
|
|
@@ -3890,15 +4039,8 @@ function renovarLaSkill(ctx) {
|
|
|
3890
4039
|
const { salida } = ctx;
|
|
3891
4040
|
const proyecto = tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0;
|
|
3892
4041
|
try {
|
|
3893
|
-
const informe = renovarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto }, version: ctx.version, ahora: ctx.ahora() });
|
|
3894
|
-
|
|
3895
|
-
const aviso = avisoDeRenovacion(r, informe.version);
|
|
3896
|
-
if (r.accion === "renovada") salida.linea(`\u2713 ${aviso}`);
|
|
3897
|
-
else if (r.accion === "reemplazada-editada") {
|
|
3898
|
-
salida.linea(`\u2713 Reemplac\xE9 la skill de REDCUMBRE en ${r.ruta} por la de la versi\xF3n ${informe.version}.`);
|
|
3899
|
-
salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`);
|
|
3900
|
-
} else if (aviso) salida.aviso(aviso);
|
|
3901
|
-
}
|
|
4042
|
+
const informe = renovarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto }, version: ctx.version, ahora: ctx.ahora(), reponerQuitada: true });
|
|
4043
|
+
informarRenovacion(salida, informe, "No hab\xEDa nada de la skill que instalar.");
|
|
3902
4044
|
return { version: informe.version, rutas: informe.rutas };
|
|
3903
4045
|
} catch (error) {
|
|
3904
4046
|
salida.aviso(`El CLI qued\xF3 en la versi\xF3n ${ctx.version}, pero no pude renovar la skill (${error instanceof Error ? error.message : String(error)}): corre \xAB${COMANDO_SKILL_RENOVAR}\xBB.`);
|
|
@@ -3938,7 +4080,7 @@ async function correr(globales, accion, opciones = {}) {
|
|
|
3938
4080
|
const salida = crearSalida(agente);
|
|
3939
4081
|
const terminal = agente ? null : crearTerminal(process.stdin, process.stdout);
|
|
3940
4082
|
try {
|
|
3941
|
-
const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.6.
|
|
4083
|
+
const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.6.9" });
|
|
3942
4084
|
await exigirVersionMinima({
|
|
3943
4085
|
version: ctx.version,
|
|
3944
4086
|
env: process.env,
|
|
@@ -3982,6 +4124,29 @@ async function correr(globales, accion, opciones = {}) {
|
|
|
3982
4124
|
terminal?.cerrar();
|
|
3983
4125
|
}
|
|
3984
4126
|
}
|
|
4127
|
+
var skillRenovadaSinComando = false;
|
|
4128
|
+
function renovarLaSkillSinComando(argv, version) {
|
|
4129
|
+
if (skillRenovadaSinComando || process.env[VARIABLE_SKILL_DEL_LLAMADOR] === "1") return;
|
|
4130
|
+
skillRenovadaSinComando = true;
|
|
4131
|
+
try {
|
|
4132
|
+
const agente = esModoAgente(argv.includes("--json"));
|
|
4133
|
+
const salida = crearSalida(agente);
|
|
4134
|
+
const ctx = crearContexto({ salida, terminal: null, sinNavegador: false, cwd: process.cwd(), env: process.env, version });
|
|
4135
|
+
const depurar = process.env.REDCUMBRE_DEBUG ? (mensaje) => process.stderr.write(`debug: ${mensaje}
|
|
4136
|
+
`) : void 0;
|
|
4137
|
+
renovarSkillAlCorrer({
|
|
4138
|
+
destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto: tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0 },
|
|
4139
|
+
version,
|
|
4140
|
+
ahora: ctx.ahora(),
|
|
4141
|
+
avisar: (texto2) => {
|
|
4142
|
+
if (!agente) process.stderr.write(`\u26A0 ${texto2}
|
|
4143
|
+
`);
|
|
4144
|
+
},
|
|
4145
|
+
depurar
|
|
4146
|
+
});
|
|
4147
|
+
} catch {
|
|
4148
|
+
}
|
|
4149
|
+
}
|
|
3985
4150
|
var json = () => new Option("--json", "modo agente: no pregunta y deja un solo JSON en stdout (nunca el secreto de la llave)");
|
|
3986
4151
|
var comando = (padre, nombre, descripcion) => padre.command(nombre).description(descripcion).addOption(json());
|
|
3987
4152
|
|
|
@@ -5081,8 +5246,8 @@ async function init(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
|
|
|
5081
5246
|
}
|
|
5082
5247
|
for (const r of skill.rutas) {
|
|
5083
5248
|
if (r.accion === "reemplazada-editada") {
|
|
5084
|
-
salida.linea(`\u2713 Reemplac\xE9
|
|
5085
|
-
salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`);
|
|
5249
|
+
salida.linea(`\u2713 Reemplac\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta} ${deLaVersion(r.ruta, "por", ctx.version)}.`);
|
|
5250
|
+
salida.aviso(`Tu versi\xF3n editada ${r.ruta.includes("/commands/") ? "del comando" : "de la skill"} qued\xF3 en ${r.copia}.`);
|
|
5086
5251
|
}
|
|
5087
5252
|
if (r.accion === "editada") {
|
|
5088
5253
|
salida.aviso(
|
|
@@ -6288,10 +6453,10 @@ function instalarSkillDeUsuario(ctx) {
|
|
|
6288
6453
|
try {
|
|
6289
6454
|
const informe = instalarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home }, bloqueAgents: false, version: ctx.version, ahora: ctx.ahora() });
|
|
6290
6455
|
for (const r of informe.rutas) {
|
|
6291
|
-
if (r.accion === "instalada") ctx.salida.linea(`\u2713 Instal\xE9
|
|
6456
|
+
if (r.accion === "instalada") ctx.salida.linea(`\u2713 Instal\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta}.`);
|
|
6292
6457
|
if (r.accion === "reemplazada-editada") {
|
|
6293
|
-
ctx.salida.linea(`\u2713 Reemplac\xE9
|
|
6294
|
-
ctx.salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`);
|
|
6458
|
+
ctx.salida.linea(`\u2713 Reemplac\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta} ${deLaVersion(r.ruta, "por", ctx.version)}.`);
|
|
6459
|
+
ctx.salida.aviso(`Tu versi\xF3n editada ${r.ruta.includes("/commands/") ? "del comando" : "de la skill"} qued\xF3 en ${r.copia}.`);
|
|
6295
6460
|
}
|
|
6296
6461
|
if (r.accion === "editada") ctx.salida.aviso(`${r.ruta} tiene cambios tuyos y no pude guardar su copia (${r.error ?? "es parte de tu AGENTS.md"}): no lo toqu\xE9.`);
|
|
6297
6462
|
}
|
|
@@ -6329,7 +6494,16 @@ async function actualizar(ctx, _opciones, entorno = entornoDeActualizacion(ctx))
|
|
|
6329
6494
|
}
|
|
6330
6495
|
if (compararVersiones(disponible, ctx.version) <= 0) {
|
|
6331
6496
|
salida.linea(`Ya est\xE1s en la \xFAltima versi\xF3n del CLI (${ctx.version}).`);
|
|
6332
|
-
|
|
6497
|
+
let skill2 = null;
|
|
6498
|
+
try {
|
|
6499
|
+
const proyecto = tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0;
|
|
6500
|
+
const informe = renovarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto }, version: ctx.version, ahora: ctx.ahora() });
|
|
6501
|
+
informarRenovacion(salida, informe, "La skill est\xE1 quitada (\xABredcumbre skill quitar\xBB): no la toqu\xE9.");
|
|
6502
|
+
skill2 = { version: informe.version, rutas: informe.rutas };
|
|
6503
|
+
} catch (error) {
|
|
6504
|
+
salida.aviso(`No pude dejar al d\xEDa la skill (${error instanceof Error ? error.message : String(error)}): corre \xAB${COMANDO_SKILL_RENOVAR}\xBB.`);
|
|
6505
|
+
}
|
|
6506
|
+
salida.resultado({ ok: true, actualizado: false, instalada: ctx.version, disponible, skill: skill2 });
|
|
6333
6507
|
return;
|
|
6334
6508
|
}
|
|
6335
6509
|
const { forma, comando: comando2, skill } = actualizarElCli(ctx, entorno, disponible, (texto2) => salida.linea(texto2));
|
|
@@ -6340,37 +6514,6 @@ async function actualizar(ctx, _opciones, entorno = entornoDeActualizacion(ctx))
|
|
|
6340
6514
|
salida.resultado({ ok: true, actualizado: true, instalada: ctx.version, disponible, forma, comando: comando2, skill });
|
|
6341
6515
|
}
|
|
6342
6516
|
|
|
6343
|
-
// src/comandos/skill.ts
|
|
6344
|
-
async function skillQuitar(ctx) {
|
|
6345
|
-
const { salida } = ctx;
|
|
6346
|
-
const proyecto = tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0;
|
|
6347
|
-
const informe = quitarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto } });
|
|
6348
|
-
for (const r of informe.rutas) {
|
|
6349
|
-
if (r.accion === "quitada") salida.linea(`\u2713 Quit\xE9 ${r.ruta}.`);
|
|
6350
|
-
else if (r.accion === "editada") salida.aviso(`${r.ruta} tiene cambios tuyos: no lo borr\xE9.`);
|
|
6351
|
-
}
|
|
6352
|
-
if (informe.rutas.length === 0) salida.linea("No hab\xEDa nada de la skill que quitar.");
|
|
6353
|
-
salida.linea("La skill qued\xF3 quitada: \xABlogin\xBB e \xABinit\xBB no la vuelven a instalar.");
|
|
6354
|
-
salida.resultado({ ok: true, skill: { rutas: informe.rutas, estado: informe.estado } });
|
|
6355
|
-
}
|
|
6356
|
-
async function skillRenovar(ctx, _opciones) {
|
|
6357
|
-
const { salida } = ctx;
|
|
6358
|
-
const proyecto = tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0;
|
|
6359
|
-
const destinos = { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto };
|
|
6360
|
-
const informe = renovarSkill({ destinos, version: ctx.version, ahora: ctx.ahora() });
|
|
6361
|
-
for (const r of informe.rutas) {
|
|
6362
|
-
const aviso = avisoDeRenovacion(r, informe.version);
|
|
6363
|
-
if (r.accion === "renovada") salida.linea(`\u2713 ${aviso}`);
|
|
6364
|
-
else if (r.accion === "reemplazada-editada") {
|
|
6365
|
-
salida.linea(`\u2713 Reemplac\xE9 la skill de REDCUMBRE en ${r.ruta} por la de la versi\xF3n ${informe.version}.`);
|
|
6366
|
-
salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`);
|
|
6367
|
-
} else if (aviso) salida.aviso(aviso);
|
|
6368
|
-
}
|
|
6369
|
-
if (informe.rutas.length === 0) salida.linea("No hay una skill instalada por el CLI que renovar (o la quitaste con \xABredcumbre skill quitar\xBB).");
|
|
6370
|
-
else if (informe.rutas.every((r) => r.accion === "al-dia" || r.accion === "mas-nueva")) salida.linea(`La skill ya est\xE1 al d\xEDa con la versi\xF3n ${informe.version}.`);
|
|
6371
|
-
salida.resultado({ ok: true, skill: { version: informe.version, rutas: informe.rutas } });
|
|
6372
|
-
}
|
|
6373
|
-
|
|
6374
6517
|
// src/cli.ts
|
|
6375
6518
|
var ERRORES_DE_USO = [
|
|
6376
6519
|
[/unknown command '(.+)'/, (c) => `El comando \xAB${c}\xBB no existe.`],
|
|
@@ -6390,7 +6533,7 @@ function errorDeUsoEnEspanol(mensaje) {
|
|
|
6390
6533
|
}
|
|
6391
6534
|
var TITULOS_AYUDA = { "Usage:": "Uso:", "Options:": "Opciones:", "Commands:": "Comandos:", "Arguments:": "Argumentos:" };
|
|
6392
6535
|
var sumar = (valor, anteriores) => [...anteriores, valor];
|
|
6393
|
-
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.
|
|
6536
|
+
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.9", "-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)}
|
|
6394
6537
|
`) }).exitOverride((error) => {
|
|
6395
6538
|
if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.code === "commander.help") process.exit(0);
|
|
6396
6539
|
if (process.argv.includes("--json")) {
|
|
@@ -6399,6 +6542,11 @@ var programa = new Command3().name("redcumbre").description("El CLI de REDCUMBRE
|
|
|
6399
6542
|
}
|
|
6400
6543
|
process.exit(CODIGOS_DE_SALIDA.uso);
|
|
6401
6544
|
});
|
|
6545
|
+
programa.prependListener("option:version", () => renovarLaSkillSinComando(process.argv, programa.version()));
|
|
6546
|
+
programa.addHelpText("beforeAll", () => {
|
|
6547
|
+
renovarLaSkillSinComando(process.argv, programa.version());
|
|
6548
|
+
return "";
|
|
6549
|
+
});
|
|
6402
6550
|
var sinNavegador = () => new Option3("--sin-navegador", "no abre el navegador: imprime la URL");
|
|
6403
6551
|
var empresa = () => new Option3("--empresa <slug>", "la empresa (tenantSlug); por omisi\xF3n, la del proyecto");
|
|
6404
6552
|
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), { instalaPorSuCuenta: true, primerContacto: true }));
|
|
@@ -6434,10 +6582,10 @@ declararEmisores(programa);
|
|
|
6434
6582
|
comando(programa, "tarifas", "el precio de cada operaci\xF3n en tu plan: lo incluido, la siguiente unidad y su tramo").argument("[operacion]", "el operationId de una operaci\xF3n; sin \xE9l, todas").option("--produccion", "el de la llave de producci\xF3n").action((operacion, o) => correr(o, (ctx) => tarifas(ctx, operacion, o)));
|
|
6435
6583
|
comando(programa, "consumo", "lo consumido del plan y los topes del d\xEDa").option("--produccion", "el de la llave de producci\xF3n").action((o) => correr(o, (ctx) => consumo(ctx, o)));
|
|
6436
6584
|
var comandoSkill = programa.command("skill").description("la skill del integrador que el CLI instala en tus carpetas de skills");
|
|
6437
|
-
comando(comandoSkill, "quitar", "quita la skill de tus carpetas y del proyecto
|
|
6438
|
-
comando(comandoSkill, "renovar", "renueva la skill
|
|
6439
|
-
comando(programa, "instalar", "deja instalado en este computador el CLI que corre por npx, en la misma versi\xF3n,
|
|
6440
|
-
comando(programa, "actualizar", "actualiza el CLI a la \xFAltima versi\xF3n publicada y
|
|
6585
|
+
comando(comandoSkill, "quitar", "quita la skill y los comandos /redcumbre:* de tus carpetas y del proyecto; no se vuelven a instalar salvo con \xABinstalar\xBB o \xABskill renovar\xBB").action((o) => correr(o, (ctx) => skillQuitar(ctx), { revisaPorSuCuenta: true }));
|
|
6586
|
+
comando(comandoSkill, "renovar", "instala o renueva la skill y los comandos /redcumbre:* con los de esta versi\xF3n del CLI (si los editaste, guarda tu copia al lado)").option("--reemplazar-editada", "se acepta por compatibilidad; ya no hace falta").option("--confirmar", "se acepta por compatibilidad; ya no hace falta").action((o) => correr(o, (ctx) => skillRenovar(ctx, o), { revisaPorSuCuenta: true }));
|
|
6587
|
+
comando(programa, "instalar", "deja instalado en este computador el CLI que corre por npx, en la misma versi\xF3n, e instala la skill y los comandos /redcumbre:*").option("--confirmar", "se acepta por compatibilidad; ya no hace falta").action((o) => correr(o, (ctx) => instalar(ctx, o), { revisaPorSuCuenta: true }));
|
|
6588
|
+
comando(programa, "actualizar", "actualiza el CLI a la \xFAltima versi\xF3n publicada y deja al d\xEDa la skill y los comandos /redcumbre:*").option("--confirmar", "se acepta por compatibilidad; ya no hace falta").action((o) => correr(o, (ctx) => actualizar(ctx, o), { revisaPorSuCuenta: true }));
|
|
6441
6589
|
var comandoMcp = programa.command("mcp").description("el servidor MCP de REDCUMBRE en tu asistente de c\xF3digo");
|
|
6442
6590
|
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)));
|
|
6443
6591
|
comando(comandoMcp, "quitar", "quita el servidor MCP de la configuraci\xF3n de tu asistente").option("--asistente <asistente>", ASISTENTES_MCP.join(" o ")).action((o) => correr(o, (ctx) => mcpQuitar(ctx, o)));
|