textoneitor 0.0.0-stage → 1.2.2
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/LICENSE +101 -0
- package/LICENSE-AGPL-3.0 +661 -0
- package/README.md +69 -2
- package/dist/api/index.d.ts +34 -0
- package/dist/api/index.js +98 -0
- package/dist/baseline/index.d.ts +20 -0
- package/dist/baseline/index.js +81 -0
- package/dist/bundle/dist/cli.mjs +29893 -0
- package/dist/bundle/package.json +6 -0
- package/dist/bundle/rulepack/rulepack.json +1496 -0
- package/dist/bundle/rules/situaciones.yml +27 -0
- package/dist/cli/benchmark.d.ts +89 -0
- package/dist/cli/benchmark.js +185 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +377 -0
- package/dist/config/core.d.ts +55 -0
- package/dist/config/core.js +244 -0
- package/dist/config/glob.d.ts +2 -0
- package/dist/config/glob.js +72 -0
- package/dist/config/index.d.ts +8 -0
- package/dist/config/index.js +38 -0
- package/dist/config/situaciones.d.ts +17 -0
- package/dist/config/situaciones.js +43 -0
- package/dist/contracts/index.d.ts +238 -0
- package/dist/contracts/index.js +4 -0
- package/dist/document/index.d.ts +10 -0
- package/dist/document/index.js +70 -0
- package/dist/document/text.d.ts +22 -0
- package/dist/document/text.js +91 -0
- package/dist/document/tokenize.d.ts +4 -0
- package/dist/document/tokenize.js +59 -0
- package/dist/markdown/index.d.ts +7 -0
- package/dist/markdown/index.js +178 -0
- package/dist/paths.d.ts +4 -0
- package/dist/paths.js +14 -0
- package/dist/reporters/index.d.ts +29 -0
- package/dist/reporters/index.js +182 -0
- package/dist/rules/compiler/build.d.ts +1 -0
- package/dist/rules/compiler/build.js +46 -0
- package/dist/rules/compiler/index.d.ts +40 -0
- package/dist/rules/compiler/index.js +343 -0
- package/dist/rules/compiler/safety.d.ts +16 -0
- package/dist/rules/compiler/safety.js +124 -0
- package/dist/rules/detectors/index.d.ts +4 -0
- package/dist/rules/detectors/index.js +651 -0
- package/dist/rules/detectors/shared.d.ts +30 -0
- package/dist/rules/detectors/shared.js +87 -0
- package/dist/rules/runtime/index.d.ts +17 -0
- package/dist/rules/runtime/index.js +74 -0
- package/dist/runner/index.d.ts +18 -0
- package/dist/runner/index.js +176 -0
- package/dist/runner/lint-text.d.ts +19 -0
- package/dist/runner/lint-text.js +20 -0
- package/dist/scoring/index.d.ts +16 -0
- package/dist/scoring/index.js +41 -0
- package/dist/suppressions/index.d.ts +23 -0
- package/dist/suppressions/index.js +86 -0
- package/dist/web/engine.meta.json +1 -0
- package/dist/web/engine.mjs +11029 -0
- package/dist/web/index.d.ts +39 -0
- package/dist/web/index.js +37 -0
- package/dist/web/node-crypto-shim.d.ts +9 -0
- package/dist/web/node-crypto-shim.js +24 -0
- package/dist/web/sha256.d.ts +11 -0
- package/dist/web/sha256.js +89 -0
- package/package.json +88 -4
- package/rulepack/rulepack.json +1496 -0
- package/rules/profiles/academico.yml +4 -0
- package/rules/profiles/chat.yml +4 -0
- package/rules/profiles/correo.yml +3 -0
- package/rules/profiles/general.yml +2 -0
- package/rules/profiles/marketing.yml +4 -0
- package/rules/profiles/readme.yml +5 -0
- package/rules/profiles/redes.yml +6 -0
- package/rules/profiles/tecnico.yml +4 -0
- package/rules/situaciones.yml +27 -0
- package/schemas/rule.schema.json +90 -0
package/dist/cli/main.js
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { Command, CommanderError } from "commander";
|
|
5
|
+
import fg from "fast-glob";
|
|
6
|
+
import { explainConfig, loadConfig } from "../config/index.js";
|
|
7
|
+
import { loadSituaciones, overridesDeSituaciones, situacionDe } from "../config/situaciones.js";
|
|
8
|
+
import { createBaseline, readBaseline, updateBaseline, writeBaseline } from "../baseline/index.js";
|
|
9
|
+
import { render } from "../reporters/index.js";
|
|
10
|
+
import { scanProject, lintDocumentText, evaluatePolicy } from "../runner/index.js";
|
|
11
|
+
import { loadRulePack, toolVersion } from "../api/index.js";
|
|
12
|
+
import { SCHEMA_VERSION } from "../contracts/index.js";
|
|
13
|
+
/** Códigos de salida: 0 OK, 1 la política falla, 2 error de uso o configuración. */
|
|
14
|
+
/** Nombre por defecto de la baseline. El viejo se sigue leyendo si es el que hay en el proyecto. */
|
|
15
|
+
const BASELINE_DEFECTO = "textoneitor-baseline.json";
|
|
16
|
+
const BASELINE_ANTERIOR = "ia-linter-baseline.json";
|
|
17
|
+
const EXIT_FAIL = 1;
|
|
18
|
+
const EXIT_USAGE = 2;
|
|
19
|
+
function die(msg) {
|
|
20
|
+
process.stderr.write(`textoneitor: ${msg}\n`);
|
|
21
|
+
process.exit(EXIT_USAGE);
|
|
22
|
+
}
|
|
23
|
+
function context(g) {
|
|
24
|
+
const cwd = path.resolve(g.cwd ?? process.cwd());
|
|
25
|
+
const loaded = loadConfig({ cwd, file: g.config });
|
|
26
|
+
if (g.config && !fs.existsSync(path.resolve(cwd, g.config)))
|
|
27
|
+
die(`no existe el archivo de configuración ${g.config}`);
|
|
28
|
+
if (loaded.issues.length) {
|
|
29
|
+
die(`configuración inválida (${loaded.file}):\n` + loaded.issues.map((i) => ` ${i.path || "(raíz)"}: ${i.message}`).join("\n"));
|
|
30
|
+
}
|
|
31
|
+
let pack;
|
|
32
|
+
try {
|
|
33
|
+
pack = loadRulePack(g.rulepack);
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
die(e.message);
|
|
37
|
+
}
|
|
38
|
+
// Un id mal escrito en `rules` u `overrides` no hace nada: se avisa en vez de callarlo (config validate lo trata como error).
|
|
39
|
+
const known = new Set(pack.rules.flatMap((r) => [r.id, `${r.category}/*`]));
|
|
40
|
+
const unknown = [
|
|
41
|
+
...Object.keys(loaded.config.rules).filter((k) => !known.has(k)).map((k) => `rules.${k}`),
|
|
42
|
+
...loaded.config.overrides.flatMap((o, i) => Object.keys(o.rules ?? {}).filter((k) => !known.has(k)).map((k) => `overrides[${i}].rules.${k}`)),
|
|
43
|
+
];
|
|
44
|
+
for (const u of unknown)
|
|
45
|
+
process.stderr.write(`textoneitor: aviso: ${u} no es ninguna regla ni categoría; se ignora\n`);
|
|
46
|
+
return { config: loaded.config, root: loaded.root, pack, toolVersion: toolVersion(), configFile: loaded.file, cwd };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Las rutas de la línea de órdenes son relativas al directorio de trabajo, no a la raíz del proyecto
|
|
50
|
+
* (la carpeta del textoneitor.yml). Las que existen se pasan absolutas; los globs se anclan al directorio de trabajo.
|
|
51
|
+
*/
|
|
52
|
+
function rutasDesde(cwd, root, rutas) {
|
|
53
|
+
if (path.resolve(cwd) === path.resolve(root))
|
|
54
|
+
return rutas;
|
|
55
|
+
const prefijo = fg.convertPathToPattern(path.relative(root, cwd).replace(/\\/g, "/"));
|
|
56
|
+
return rutas.map((r) => (fs.existsSync(path.resolve(cwd, r)) ? path.resolve(cwd, r) : `${prefijo}/${r.replace(/\\/g, "/")}`));
|
|
57
|
+
}
|
|
58
|
+
/** Hasta cinco rutas, para los avisos de stderr. */
|
|
59
|
+
function lista(rutas) {
|
|
60
|
+
return `${rutas.slice(0, 5).join(", ")}${rutas.length > 5 ? ", …" : ""}`;
|
|
61
|
+
}
|
|
62
|
+
function readStdin() {
|
|
63
|
+
return fs.readFileSync(0, "utf8");
|
|
64
|
+
}
|
|
65
|
+
const program = new Command();
|
|
66
|
+
// Los errores de uso que detecta commander (opción o comando desconocido, falta un argumento) salen con 2, no con su 1
|
|
67
|
+
// por defecto, que se confundiría con «la política falla». Va antes de declarar subcomandos para que lo hereden.
|
|
68
|
+
program.exitOverride();
|
|
69
|
+
program
|
|
70
|
+
.name("textoneitor")
|
|
71
|
+
.description("Revisor de textos en español: marca lo que suena a máquina y explica por qué. Mide patrones editoriales, no autoría.")
|
|
72
|
+
.version(toolVersion())
|
|
73
|
+
.option("-c, --config <archivo>", "archivo de configuración (por defecto se busca textoneitor.yml hacia arriba)")
|
|
74
|
+
.option("--cwd <dir>", "directorio de trabajo")
|
|
75
|
+
.option("--rulepack <archivo>", "Rule Pack alternativo (JSON compilado)");
|
|
76
|
+
program
|
|
77
|
+
.command("lint")
|
|
78
|
+
.description("analiza archivos, directorios o globs")
|
|
79
|
+
.argument("[rutas...]", "archivos, directorios o globs (por defecto, el proyecto)")
|
|
80
|
+
.option("-f, --format <reporter>", "terminal | json | sarif | revision")
|
|
81
|
+
.option("-o, --output <archivo>", "escribe el informe en un archivo")
|
|
82
|
+
.option("--stdin", "lee el texto de la entrada estándar")
|
|
83
|
+
.option("--stdin-filename <nombre>", "nombre lógico para --stdin (decide formato y overrides)")
|
|
84
|
+
.option("--fail-on <nivel>", "never | info | warning | error")
|
|
85
|
+
.option("--max-index <n>", "falla si el índice de algún archivo supera n")
|
|
86
|
+
.option("--profile <perfil>", "general | tecnico | academico | marketing | chat | correo | readme | redes | auto (por la ruta, según situaciones.yml)")
|
|
87
|
+
.option("--baseline <archivo>", "baseline a aplicar")
|
|
88
|
+
.option("--no-baseline", "ignora la baseline configurada")
|
|
89
|
+
.option("--no-cache", "no usa la caché")
|
|
90
|
+
.option("--no-color", "sin color")
|
|
91
|
+
.option("-v, --verbose", "muestra snippets, contribuyentes y archivos sin hallazgos")
|
|
92
|
+
.action((rutas, o) => {
|
|
93
|
+
const ctx = context(program.opts());
|
|
94
|
+
if (o.failOn) {
|
|
95
|
+
if (!["never", "info", "warning", "error"].includes(o.failOn))
|
|
96
|
+
die("--fail-on debe ser never, info, warning o error");
|
|
97
|
+
ctx.config.fail_on = o.failOn;
|
|
98
|
+
}
|
|
99
|
+
if (o.maxIndex !== undefined) {
|
|
100
|
+
const n = Number(o.maxIndex);
|
|
101
|
+
if (!Number.isFinite(n) || n < 0 || n > 100)
|
|
102
|
+
die("--max-index debe estar entre 0 y 100");
|
|
103
|
+
ctx.config.max_index = n;
|
|
104
|
+
}
|
|
105
|
+
// `auto`: el perfil sale de la ruta según rules/situaciones.yml. Los overrides del proyecto siguen mandando.
|
|
106
|
+
let sinSituacion = false;
|
|
107
|
+
let situaciones = null;
|
|
108
|
+
if (o.profile === "auto") {
|
|
109
|
+
try {
|
|
110
|
+
situaciones = loadSituaciones();
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
die(e.message);
|
|
114
|
+
}
|
|
115
|
+
ctx.config.overrides = [...overridesDeSituaciones(situaciones), ...ctx.config.overrides];
|
|
116
|
+
if (o.stdin) {
|
|
117
|
+
if (!o.stdinFilename)
|
|
118
|
+
die("--profile auto con --stdin necesita --stdin-filename: la ruta decide la situación");
|
|
119
|
+
sinSituacion = situacionDe(o.stdinFilename, situaciones) === null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
else if (o.profile) {
|
|
123
|
+
if (!["general", "tecnico", "academico", "marketing", "chat", "correo", "readme", "redes"].includes(o.profile))
|
|
124
|
+
die("--profile inválido");
|
|
125
|
+
ctx.config.profile = o.profile;
|
|
126
|
+
}
|
|
127
|
+
const reporter = (o.format ?? ctx.config.reporter);
|
|
128
|
+
if (!["terminal", "json", "sarif", "revision"].includes(reporter))
|
|
129
|
+
die("--format debe ser terminal, json, sarif o revision");
|
|
130
|
+
let result;
|
|
131
|
+
if (o.stdin) {
|
|
132
|
+
if (rutas.length)
|
|
133
|
+
process.stderr.write(`textoneitor: aviso: con --stdin se analiza la entrada estándar y se ignoran las rutas (${rutas.join(", ")})\n`);
|
|
134
|
+
if (sinSituacion)
|
|
135
|
+
process.stderr.write(`textoneitor: ${o.stdinFilename} no corresponde a ninguna situación de situaciones.yml; con --profile auto no se analiza\n`);
|
|
136
|
+
const files = sinSituacion ? [] : [lintDocumentText(readStdin(), ctx, { relPath: o.stdinFilename, format: o.stdinFilename ? undefined : "text" })];
|
|
137
|
+
result = {
|
|
138
|
+
schema_version: SCHEMA_VERSION,
|
|
139
|
+
tool: { name: "textoneitor", version: ctx.toolVersion, rulepack: ctx.pack.version },
|
|
140
|
+
files,
|
|
141
|
+
policy: evaluatePolicy(files, ctx.config),
|
|
142
|
+
durationMs: 0,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
const baseline = o.baseline === false ? null : typeof o.baseline === "string" ? o.baseline : undefined;
|
|
147
|
+
const ilegibles = [];
|
|
148
|
+
result = scanProject(ctx, { targets: rutasDesde(ctx.cwd, ctx.root, rutas), noCache: o.cache === false, baseline, onUnreadable: (p) => ilegibles.push(p) });
|
|
149
|
+
// Si las rutas existen pero `exclude` o .gitignore las dejan fuera (pre-commit con un CHANGELOG), no hay nada que analizar
|
|
150
|
+
// y no es un error. Solo es un error de uso que ninguna ruta exista ni coincida con nada.
|
|
151
|
+
if (rutas.length && result.files.length === 0 && !rutas.some((r) => fs.existsSync(path.resolve(ctx.cwd, r)))) {
|
|
152
|
+
die(`ninguna ruta coincide: ${rutas.join(", ")}`);
|
|
153
|
+
}
|
|
154
|
+
// Lo que no se analiza se dice, por stderr y sin cambiar la salida ni el informe.
|
|
155
|
+
if (ilegibles.length) {
|
|
156
|
+
process.stderr.write(`textoneitor: ${ilegibles.length} archivo(s) sin analizar porque no son texto en UTF-8 (${lista(ilegibles)})\n`);
|
|
157
|
+
}
|
|
158
|
+
const analizados = new Set(result.files.map((f) => f.path));
|
|
159
|
+
const excluidos = rutas
|
|
160
|
+
.filter((r) => {
|
|
161
|
+
const abs = path.resolve(ctx.cwd, r);
|
|
162
|
+
return fs.existsSync(abs) && fs.statSync(abs).isFile();
|
|
163
|
+
})
|
|
164
|
+
.map((r) => path.relative(ctx.root, path.resolve(ctx.cwd, r)).replace(/\\/g, "/"))
|
|
165
|
+
.filter((rel) => !analizados.has(rel) && !ilegibles.includes(rel));
|
|
166
|
+
if (excluidos.length) {
|
|
167
|
+
process.stderr.write(`textoneitor: ${excluidos.length} archivo(s) sin analizar porque \`exclude\` o .gitignore los dejan fuera (${lista(excluidos)})\n`);
|
|
168
|
+
}
|
|
169
|
+
// Con `auto`, igual que con --stdin: lo que no corresponde a ninguna situación no se analiza.
|
|
170
|
+
if (situaciones) {
|
|
171
|
+
const sit = situaciones;
|
|
172
|
+
const fuera = result.files.filter((f) => situacionDe(f.path, sit) === null);
|
|
173
|
+
if (fuera.length) {
|
|
174
|
+
process.stderr.write(`textoneitor: ${fuera.length} archivo(s) sin situación en situaciones.yml; con --profile auto no se analizan (${fuera.slice(0, 5).map((f) => f.path).join(", ")}${fuera.length > 5 ? ", …" : ""})\n`);
|
|
175
|
+
const files = result.files.filter((f) => !fuera.includes(f));
|
|
176
|
+
result = { ...result, files, policy: evaluatePolicy(files, ctx.config) };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const color = o.color !== false && reporter === "terminal" && !o.output && process.stdout.isTTY === true && !process.env.NO_COLOR;
|
|
181
|
+
const out = render(reporter, result, ctx.pack.rules, { color, verbose: o.verbose, uriBase: pathToFileUri(ctx.root) });
|
|
182
|
+
if (o.output)
|
|
183
|
+
fs.writeFileSync(path.resolve(o.output), out, "utf8");
|
|
184
|
+
else
|
|
185
|
+
process.stdout.write(out);
|
|
186
|
+
process.exitCode = result.policy.ok ? 0 : EXIT_FAIL;
|
|
187
|
+
});
|
|
188
|
+
const rules = program.command("rules").description("consulta las reglas del Rule Pack");
|
|
189
|
+
rules
|
|
190
|
+
.command("list")
|
|
191
|
+
.option("--json", "salida JSON")
|
|
192
|
+
.option("--status <estado>", "filtra por estado")
|
|
193
|
+
.action((o) => {
|
|
194
|
+
const ctx = context(program.opts());
|
|
195
|
+
const list = ctx.pack.rules.filter((r) => !o.status || r.status === o.status);
|
|
196
|
+
if (o.json) {
|
|
197
|
+
process.stdout.write(JSON.stringify(list.map((r) => ({ id: r.id, status: r.status, category: r.category, detector: r.detector, default_level: r.default_level, title: r.title })), null, 2) + "\n");
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const w = Math.max(...list.map((r) => r.id.length));
|
|
201
|
+
for (const r of list)
|
|
202
|
+
process.stdout.write(`${r.id.padEnd(w)} ${r.status.padEnd(10)} ${r.default_level.padEnd(8)} ${r.title}\n`);
|
|
203
|
+
process.stdout.write(`\n${list.length} reglas (Rule Pack ${ctx.pack.version})\n`);
|
|
204
|
+
});
|
|
205
|
+
rules
|
|
206
|
+
.command("explain")
|
|
207
|
+
.argument("<id>", "identificador de la regla")
|
|
208
|
+
.option("--json", "salida JSON")
|
|
209
|
+
.action((id, o) => {
|
|
210
|
+
const ctx = context(program.opts());
|
|
211
|
+
const r = ctx.pack.rules.find((x) => x.id === id);
|
|
212
|
+
if (!r)
|
|
213
|
+
die(`regla desconocida: ${id}`);
|
|
214
|
+
if (o.json) {
|
|
215
|
+
process.stdout.write(JSON.stringify(r, null, 2) + "\n");
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
process.stdout.write([
|
|
219
|
+
`${r.id} (rev ${r.revision}, ${r.status})`,
|
|
220
|
+
r.title,
|
|
221
|
+
"",
|
|
222
|
+
r.summary,
|
|
223
|
+
"",
|
|
224
|
+
r.explanation,
|
|
225
|
+
"",
|
|
226
|
+
`Orientación: ${r.rewrite_guidance}`,
|
|
227
|
+
"",
|
|
228
|
+
`Categoría: ${r.category} · Detector: ${r.detector} · Nivel: ${r.default_level} · Peso: ${r.score.weight} (cap ${r.score.cap})`,
|
|
229
|
+
Object.keys(r.profiles).length ? `Perfiles: ${Object.entries(r.profiles).map(([k, v]) => `${k}=${v}`).join(", ")}` : "",
|
|
230
|
+
"",
|
|
231
|
+
].join("\n"));
|
|
232
|
+
});
|
|
233
|
+
const config = program.command("config").description("valida y explica la configuración");
|
|
234
|
+
/** `-c` apunta a un archivo que no existe: se dice así, no como «YAML inválido: ENOENT». */
|
|
235
|
+
function exigirConfig(g) {
|
|
236
|
+
if (g.config && !fs.existsSync(path.resolve(g.cwd ?? process.cwd(), g.config)))
|
|
237
|
+
die(`no existe el archivo de configuración ${g.config}`);
|
|
238
|
+
}
|
|
239
|
+
config.command("validate").action(() => {
|
|
240
|
+
const g = program.opts();
|
|
241
|
+
exigirConfig(g);
|
|
242
|
+
const loaded = loadConfig({ cwd: path.resolve(g.cwd ?? process.cwd()), file: g.config });
|
|
243
|
+
if (!loaded.file) {
|
|
244
|
+
process.stdout.write("Sin archivo de configuración: se usan los valores internos.\n");
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const pack = loadRulePack(g.rulepack);
|
|
248
|
+
const known = new Set(pack.rules.map((r) => r.id));
|
|
249
|
+
const cats = new Set(pack.rules.map((r) => `${r.category}/*`));
|
|
250
|
+
const unknown = [];
|
|
251
|
+
const check = (m, where) => {
|
|
252
|
+
for (const k of Object.keys(m ?? {}))
|
|
253
|
+
if (!known.has(k) && !cats.has(k))
|
|
254
|
+
unknown.push(`${where}.${k}`);
|
|
255
|
+
};
|
|
256
|
+
check(loaded.config.rules, "rules");
|
|
257
|
+
loaded.config.overrides.forEach((o, i) => check(o.rules, `overrides[${i}].rules`));
|
|
258
|
+
for (const i of loaded.issues)
|
|
259
|
+
process.stdout.write(`✘ ${i.path || "(raíz)"}: ${i.message}\n`);
|
|
260
|
+
for (const u of unknown)
|
|
261
|
+
process.stdout.write(`✘ ${u}: regla o categoría desconocida\n`);
|
|
262
|
+
if (loaded.issues.length || unknown.length) {
|
|
263
|
+
process.exitCode = EXIT_USAGE;
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
process.stdout.write(`✔ ${loaded.file} es válida\n`);
|
|
267
|
+
});
|
|
268
|
+
config
|
|
269
|
+
.command("explain")
|
|
270
|
+
.argument("[archivo]", "archivo para el que se resuelve la configuración efectiva")
|
|
271
|
+
.option("--json", "salida JSON")
|
|
272
|
+
.action((archivo, o) => {
|
|
273
|
+
const g = program.opts();
|
|
274
|
+
exigirConfig(g);
|
|
275
|
+
const cwd = path.resolve(g.cwd ?? process.cwd());
|
|
276
|
+
const loaded = loadConfig({ cwd, file: g.config });
|
|
277
|
+
if (loaded.issues.length)
|
|
278
|
+
die("configuración inválida; ejecuta `config validate`");
|
|
279
|
+
const pack = loadRulePack(g.rulepack);
|
|
280
|
+
const rel = archivo ? path.relative(loaded.root, path.resolve(cwd, archivo)).replace(/\\/g, "/") : null;
|
|
281
|
+
const ex = explainConfig(loaded, pack.rules, rel);
|
|
282
|
+
if (o.json) {
|
|
283
|
+
process.stdout.write(JSON.stringify(ex, null, 2) + "\n");
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
const c = ex.config;
|
|
287
|
+
process.stdout.write([
|
|
288
|
+
`Archivo de configuración: ${ex.file ?? "(ninguno; valores internos)"}`,
|
|
289
|
+
`Raíz del proyecto: ${ex.root}`,
|
|
290
|
+
`Archivo analizado: ${rel ?? "(ninguno)"}`,
|
|
291
|
+
`Perfil: ${c.profile} · Registro: ${c.register} · fail_on: ${c.fail_on} · max_index: ${c.max_index ?? "—"}`,
|
|
292
|
+
`Baseline: ${c.baseline.path ?? "—"} · Caché: ${c.cache.enabled ? c.cache.dir : "desactivada"} · Reporter: ${c.reporter}`,
|
|
293
|
+
"",
|
|
294
|
+
"Reglas (nivel efectivo ← origen):",
|
|
295
|
+
...ex.effective.map((e) => ` ${e.rule.padEnd(40)} ${e.level.padEnd(8)} ← ${e.source}: ${e.detail}`),
|
|
296
|
+
"",
|
|
297
|
+
].join("\n"));
|
|
298
|
+
});
|
|
299
|
+
const baseline = program.command("baseline").description("gestiona la baseline de hallazgos existentes");
|
|
300
|
+
baseline
|
|
301
|
+
.command("create")
|
|
302
|
+
.argument("[rutas...]")
|
|
303
|
+
.option("-o, --output <archivo>", "ruta de la baseline")
|
|
304
|
+
.option("--reason <texto>", "motivo que se guarda en cada entrada")
|
|
305
|
+
.action((rutas, o) => {
|
|
306
|
+
const ctx = context(program.opts());
|
|
307
|
+
const out = o.output ?? ctx.config.baseline.path ?? BASELINE_DEFECTO;
|
|
308
|
+
if (ctx.config.baseline.require_reason && !o.reason)
|
|
309
|
+
die("la configuración exige --reason para crear la baseline");
|
|
310
|
+
const result = scanProject(ctx, { targets: rutasDesde(ctx.cwd, ctx.root, rutas), baseline: null, noCache: true });
|
|
311
|
+
const b = createBaseline(result.files, o.reason);
|
|
312
|
+
writeBaseline(path.resolve(ctx.root, out), b);
|
|
313
|
+
process.stdout.write(`Baseline creada: ${out} (${b.entries.length} entradas)\n`);
|
|
314
|
+
});
|
|
315
|
+
baseline
|
|
316
|
+
.command("update")
|
|
317
|
+
.argument("[rutas...]")
|
|
318
|
+
.option("-o, --output <archivo>", "ruta de la baseline")
|
|
319
|
+
.option("--add-new", "añade también los hallazgos nuevos")
|
|
320
|
+
.option("--reason <texto>", "motivo para las entradas nuevas")
|
|
321
|
+
.action((rutas, o) => {
|
|
322
|
+
const ctx = context(program.opts());
|
|
323
|
+
// Si no se dice cuál y la del nombre nuevo no está, se usa la del nombre viejo.
|
|
324
|
+
const porDefecto = !fs.existsSync(path.resolve(ctx.root, BASELINE_DEFECTO)) && fs.existsSync(path.resolve(ctx.root, BASELINE_ANTERIOR))
|
|
325
|
+
? BASELINE_ANTERIOR
|
|
326
|
+
: BASELINE_DEFECTO;
|
|
327
|
+
const out = o.output ?? ctx.config.baseline.path ?? porDefecto;
|
|
328
|
+
const abs = path.resolve(ctx.root, out);
|
|
329
|
+
if (!fs.existsSync(abs))
|
|
330
|
+
die(`no existe la baseline ${out}; usa \`baseline create\``);
|
|
331
|
+
if (o.addNew && ctx.config.baseline.require_reason && !o.reason)
|
|
332
|
+
die("la configuración exige --reason para añadir entradas");
|
|
333
|
+
const existing = readBaseline(abs);
|
|
334
|
+
const result = scanProject(ctx, { targets: rutasDesde(ctx.cwd, ctx.root, rutas), baseline: null, noCache: true });
|
|
335
|
+
const b = updateBaseline(existing, result.files, { addNew: Boolean(o.addNew), reason: o.reason });
|
|
336
|
+
writeBaseline(abs, b);
|
|
337
|
+
process.stdout.write(`Baseline actualizada: ${out} (${existing.entries.length} → ${b.entries.length} entradas)\n`);
|
|
338
|
+
});
|
|
339
|
+
program
|
|
340
|
+
.command("benchmark")
|
|
341
|
+
.description("ejecuta el benchmark reproducible sobre un corpus con manifiestos")
|
|
342
|
+
.command("run")
|
|
343
|
+
.requiredOption("--corpus <dir>", "directorio raíz del corpus")
|
|
344
|
+
.requiredOption("--partition <nombre>", "development | holdout | challenge")
|
|
345
|
+
.option("--profile <perfil>", "perfil con el que evaluar el corpus (queda registrado en el informe)")
|
|
346
|
+
.option("--register <registro>", "evalúa solo las muestras de ese registro del manifiesto")
|
|
347
|
+
.option("--annotations <archivo>", "adjudicaciones de hallazgos; sin esta opción se usa benchmark/annotations/<partición>.yml")
|
|
348
|
+
.option("-o, --output <archivo>", "informe JSON")
|
|
349
|
+
.action(async (o) => {
|
|
350
|
+
if (o.profile && !["general", "tecnico", "academico", "marketing", "chat", "correo", "readme", "redes"].includes(o.profile))
|
|
351
|
+
die("--profile inválido");
|
|
352
|
+
const base = context(program.opts());
|
|
353
|
+
const ctx = o.profile ? { ...base, config: { ...base.config, profile: o.profile } } : base;
|
|
354
|
+
const { runBenchmark } = await import("./benchmark.js");
|
|
355
|
+
const report = runBenchmark(ctx, path.resolve(o.corpus), o.partition, {
|
|
356
|
+
...(o.register ? { register: String(o.register) } : {}),
|
|
357
|
+
...(o.annotations ? { annotations: path.resolve(String(o.annotations)) } : {}),
|
|
358
|
+
});
|
|
359
|
+
const json = JSON.stringify(report, null, 2) + "\n";
|
|
360
|
+
if (o.output) {
|
|
361
|
+
fs.mkdirSync(path.dirname(path.resolve(o.output)), { recursive: true });
|
|
362
|
+
fs.writeFileSync(path.resolve(o.output), json, "utf8");
|
|
363
|
+
process.stdout.write(`Informe: ${o.output}\n`);
|
|
364
|
+
}
|
|
365
|
+
else
|
|
366
|
+
process.stdout.write(json);
|
|
367
|
+
});
|
|
368
|
+
function pathToFileUri(p) {
|
|
369
|
+
const s = p.replace(/\\/g, "/");
|
|
370
|
+
return (s.startsWith("/") ? `file://${encodeURI(s)}` : `file:///${encodeURI(s)}`) + "/";
|
|
371
|
+
}
|
|
372
|
+
program.parseAsync(process.argv).catch((e) => {
|
|
373
|
+
// commander ya ha escrito su mensaje; --help y --version salen con 0.
|
|
374
|
+
if (e instanceof CommanderError)
|
|
375
|
+
process.exit(e.exitCode === 0 ? 0 : EXIT_USAGE);
|
|
376
|
+
die(e.message);
|
|
377
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuración sin disco: valores por defecto, validación, mezcla y resolución de niveles.
|
|
3
|
+
*
|
|
4
|
+
* Separado de `index.ts` porque leer `textoneitor.yml` necesita `node:fs`, y esta parte tiene
|
|
5
|
+
* que poder ejecutarse también en el navegador (`src/web/index.ts`).
|
|
6
|
+
*/
|
|
7
|
+
import type { Config, Level, ProfileName, Register, CompiledRule } from "../contracts/index.js";
|
|
8
|
+
/**
|
|
9
|
+
* Se busca en este orden. Los cuatro últimos son el nombre viejo del paquete y se
|
|
10
|
+
* mantienen para que un proyecto que ya tenga su ia-linter.yml siga funcionando.
|
|
11
|
+
*/
|
|
12
|
+
export declare const CONFIG_FILENAMES: string[];
|
|
13
|
+
export declare const PROFILES: ProfileName[];
|
|
14
|
+
/** Valores internos (nivel 1 de precedencia). */
|
|
15
|
+
export declare function defaultConfig(): Config;
|
|
16
|
+
export interface ConfigIssue {
|
|
17
|
+
path: string;
|
|
18
|
+
message: string;
|
|
19
|
+
}
|
|
20
|
+
export interface LoadedConfig {
|
|
21
|
+
config: Config;
|
|
22
|
+
/** Ruta del archivo de configuración o null si se usan solo valores internos. */
|
|
23
|
+
file: string | null;
|
|
24
|
+
/** Directorio raíz del proyecto (donde está la configuración o el cwd). */
|
|
25
|
+
root: string;
|
|
26
|
+
issues: ConfigIssue[];
|
|
27
|
+
}
|
|
28
|
+
/** Valida un objeto crudo y devuelve los problemas. No lanza. */
|
|
29
|
+
export declare function validateConfigObject(raw: unknown): ConfigIssue[];
|
|
30
|
+
/** Fusiona un objeto crudo validado sobre la configuración base. */
|
|
31
|
+
export declare function mergeConfig(base: Config, raw: Record<string, unknown>): Config;
|
|
32
|
+
export type LevelSource = "internal" | "profile" | "register" | "project" | "override" | "rule" | "inline";
|
|
33
|
+
export interface EffectiveRule {
|
|
34
|
+
rule: string;
|
|
35
|
+
level: Level;
|
|
36
|
+
source: LevelSource;
|
|
37
|
+
detail: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Registros que silencian categorías o reglas por defecto (nivel 3 de precedencia).
|
|
41
|
+
* Se mantiene deliberadamente pequeño: solo lo que la evidencia del benchmark justifica.
|
|
42
|
+
*/
|
|
43
|
+
export declare const REGISTER_ADJUSTMENTS: Partial<Record<Register, Record<string, Level>>>;
|
|
44
|
+
/**
|
|
45
|
+
* Resuelve el nivel efectivo de cada regla para un archivo concreto.
|
|
46
|
+
* Precedencia: internos < perfil < registro < proyecto < override por ruta < regla concreta.
|
|
47
|
+
* La supresión inline (nivel 7) se aplica en el runner sobre los hallazgos.
|
|
48
|
+
*/
|
|
49
|
+
export declare function resolveEffectiveRules(config: Config, rules: CompiledRule[], relPath: string | null): EffectiveRule[];
|
|
50
|
+
export declare function explainConfig(loaded: LoadedConfig, rules: CompiledRule[], relPath: string | null): {
|
|
51
|
+
file: string | null;
|
|
52
|
+
root: string;
|
|
53
|
+
config: Config;
|
|
54
|
+
effective: EffectiveRule[];
|
|
55
|
+
};
|