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
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { SCHEMA_VERSION } from "../contracts/index.js";
|
|
2
|
+
import { matchesAny } from "./glob.js";
|
|
3
|
+
/**
|
|
4
|
+
* Se busca en este orden. Los cuatro últimos son el nombre viejo del paquete y se
|
|
5
|
+
* mantienen para que un proyecto que ya tenga su ia-linter.yml siga funcionando.
|
|
6
|
+
*/
|
|
7
|
+
export const CONFIG_FILENAMES = [
|
|
8
|
+
"textoneitor.yml",
|
|
9
|
+
"textoneitor.yaml",
|
|
10
|
+
".textoneitor.yml",
|
|
11
|
+
".textoneitor.yaml",
|
|
12
|
+
"ia-linter.yml",
|
|
13
|
+
"ia-linter.yaml",
|
|
14
|
+
".ia-linter.yml",
|
|
15
|
+
".ia-linter.yaml",
|
|
16
|
+
];
|
|
17
|
+
const LEVELS = ["off", "info", "warning", "error"];
|
|
18
|
+
export const PROFILES = ["general", "tecnico", "academico", "marketing", "chat", "correo", "readme", "redes"];
|
|
19
|
+
const REGISTERS = ["general", "tecnico", "academico", "marketing", "literario", "periodistico", "institucional"];
|
|
20
|
+
/** Valores internos (nivel 1 de precedencia). */
|
|
21
|
+
export function defaultConfig() {
|
|
22
|
+
return {
|
|
23
|
+
schema_version: SCHEMA_VERSION,
|
|
24
|
+
profile: "general",
|
|
25
|
+
register: "general",
|
|
26
|
+
include: ["**/*.md", "**/*.markdown", "**/*.txt"],
|
|
27
|
+
exclude: ["**/node_modules/**", "**/.git/**", "**/dist/**", "**/CHANGELOG.md", "**/LICENSE*"],
|
|
28
|
+
respect_gitignore: true,
|
|
29
|
+
rules: {},
|
|
30
|
+
overrides: [],
|
|
31
|
+
baseline: { path: null, require_reason: false },
|
|
32
|
+
fail_on: "warning",
|
|
33
|
+
max_index: null,
|
|
34
|
+
privacy: { snippets: true },
|
|
35
|
+
reporter: "terminal",
|
|
36
|
+
cache: { enabled: true, dir: ".textoneitor-cache" },
|
|
37
|
+
min_words_for_index: 150,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** Valida un objeto crudo y devuelve los problemas. No lanza. */
|
|
41
|
+
export function validateConfigObject(raw) {
|
|
42
|
+
const issues = [];
|
|
43
|
+
if (raw === null || raw === undefined)
|
|
44
|
+
return issues;
|
|
45
|
+
if (typeof raw !== "object" || Array.isArray(raw))
|
|
46
|
+
return [{ path: "", message: "la configuración debe ser un objeto" }];
|
|
47
|
+
const o = raw;
|
|
48
|
+
const known = new Set([
|
|
49
|
+
"schema_version", "profile", "register", "include", "exclude", "respect_gitignore", "rules", "overrides",
|
|
50
|
+
"baseline", "fail_on", "max_index", "privacy", "reporter", "cache", "min_words_for_index",
|
|
51
|
+
]);
|
|
52
|
+
for (const k of Object.keys(o))
|
|
53
|
+
if (!known.has(k))
|
|
54
|
+
issues.push({ path: k, message: "clave desconocida" });
|
|
55
|
+
if (o.schema_version !== undefined && o.schema_version !== SCHEMA_VERSION)
|
|
56
|
+
issues.push({ path: "schema_version", message: `debe ser ${SCHEMA_VERSION}` });
|
|
57
|
+
if (o.profile !== undefined && !PROFILES.includes(o.profile))
|
|
58
|
+
issues.push({ path: "profile", message: `debe ser uno de: ${PROFILES.join(", ")}` });
|
|
59
|
+
if (o.register !== undefined && !REGISTERS.includes(o.register))
|
|
60
|
+
issues.push({ path: "register", message: `debe ser uno de: ${REGISTERS.join(", ")}` });
|
|
61
|
+
for (const k of ["include", "exclude"]) {
|
|
62
|
+
if (o[k] !== undefined && (!Array.isArray(o[k]) || !o[k].every((x) => typeof x === "string")))
|
|
63
|
+
issues.push({ path: k, message: "debe ser una lista de patrones glob" });
|
|
64
|
+
}
|
|
65
|
+
if (o.respect_gitignore !== undefined && typeof o.respect_gitignore !== "boolean")
|
|
66
|
+
issues.push({ path: "respect_gitignore", message: "debe ser booleano" });
|
|
67
|
+
if (o.rules !== undefined)
|
|
68
|
+
issues.push(...validateRulesMap(o.rules, "rules"));
|
|
69
|
+
if (o.overrides !== undefined) {
|
|
70
|
+
if (!Array.isArray(o.overrides))
|
|
71
|
+
issues.push({ path: "overrides", message: "debe ser una lista" });
|
|
72
|
+
else
|
|
73
|
+
o.overrides.forEach((ov, i) => {
|
|
74
|
+
const p = `overrides[${i}]`;
|
|
75
|
+
if (typeof ov !== "object" || ov === null)
|
|
76
|
+
return issues.push({ path: p, message: "debe ser un objeto" });
|
|
77
|
+
const r = ov;
|
|
78
|
+
if (!Array.isArray(r.files) || !r.files.every((x) => typeof x === "string"))
|
|
79
|
+
issues.push({ path: `${p}.files`, message: "debe ser una lista de patrones glob" });
|
|
80
|
+
if (r.rules !== undefined)
|
|
81
|
+
issues.push(...validateRulesMap(r.rules, `${p}.rules`));
|
|
82
|
+
if (r.profile !== undefined && !PROFILES.includes(r.profile))
|
|
83
|
+
issues.push({ path: `${p}.profile`, message: `debe ser uno de: ${PROFILES.join(", ")}` });
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
if (o.baseline !== undefined) {
|
|
87
|
+
if (typeof o.baseline !== "object" || o.baseline === null)
|
|
88
|
+
issues.push({ path: "baseline", message: "debe ser un objeto" });
|
|
89
|
+
else {
|
|
90
|
+
const b = o.baseline;
|
|
91
|
+
if (b.path !== undefined && b.path !== null && typeof b.path !== "string")
|
|
92
|
+
issues.push({ path: "baseline.path", message: "debe ser una ruta o null" });
|
|
93
|
+
if (b.require_reason !== undefined && typeof b.require_reason !== "boolean")
|
|
94
|
+
issues.push({ path: "baseline.require_reason", message: "debe ser booleano" });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (o.fail_on !== undefined && o.fail_on !== "never" && !LEVELS.includes(o.fail_on))
|
|
98
|
+
issues.push({ path: "fail_on", message: "debe ser never, info, warning o error" });
|
|
99
|
+
if (o.max_index !== undefined && o.max_index !== null && (typeof o.max_index !== "number" || o.max_index < 0 || o.max_index > 100))
|
|
100
|
+
issues.push({ path: "max_index", message: "debe ser un número entre 0 y 100 o null" });
|
|
101
|
+
if (o.privacy !== undefined) {
|
|
102
|
+
const p = o.privacy;
|
|
103
|
+
if (typeof p !== "object" || p === null || (p.snippets !== undefined && typeof p.snippets !== "boolean"))
|
|
104
|
+
issues.push({ path: "privacy.snippets", message: "debe ser booleano" });
|
|
105
|
+
}
|
|
106
|
+
if (o.reporter !== undefined && !["terminal", "json", "sarif", "revision"].includes(o.reporter))
|
|
107
|
+
issues.push({ path: "reporter", message: "debe ser terminal, json, sarif o revision" });
|
|
108
|
+
if (o.cache !== undefined) {
|
|
109
|
+
const c = o.cache;
|
|
110
|
+
if (typeof c !== "object" || c === null)
|
|
111
|
+
issues.push({ path: "cache", message: "debe ser un objeto" });
|
|
112
|
+
else {
|
|
113
|
+
if (c.enabled !== undefined && typeof c.enabled !== "boolean")
|
|
114
|
+
issues.push({ path: "cache.enabled", message: "debe ser booleano" });
|
|
115
|
+
if (c.dir !== undefined && typeof c.dir !== "string")
|
|
116
|
+
issues.push({ path: "cache.dir", message: "debe ser una ruta" });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (o.min_words_for_index !== undefined && (typeof o.min_words_for_index !== "number" || o.min_words_for_index < 0))
|
|
120
|
+
issues.push({ path: "min_words_for_index", message: "debe ser un número >= 0" });
|
|
121
|
+
return issues;
|
|
122
|
+
}
|
|
123
|
+
function validateRulesMap(v, p) {
|
|
124
|
+
if (typeof v !== "object" || v === null || Array.isArray(v))
|
|
125
|
+
return [{ path: p, message: "debe ser un mapa id -> nivel" }];
|
|
126
|
+
const out = [];
|
|
127
|
+
for (const [k, lv] of Object.entries(v)) {
|
|
128
|
+
if (!LEVELS.includes(lv))
|
|
129
|
+
out.push({ path: `${p}.${k}`, message: "nivel inválido (off, info, warning, error)" });
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
/** Fusiona un objeto crudo validado sobre la configuración base. */
|
|
134
|
+
export function mergeConfig(base, raw) {
|
|
135
|
+
const c = { ...base, rules: { ...base.rules }, overrides: [...base.overrides] };
|
|
136
|
+
if (raw.profile !== undefined)
|
|
137
|
+
c.profile = raw.profile;
|
|
138
|
+
if (raw.register !== undefined)
|
|
139
|
+
c.register = raw.register;
|
|
140
|
+
if (raw.include !== undefined)
|
|
141
|
+
c.include = raw.include;
|
|
142
|
+
if (raw.exclude !== undefined)
|
|
143
|
+
c.exclude = raw.exclude;
|
|
144
|
+
if (raw.respect_gitignore !== undefined)
|
|
145
|
+
c.respect_gitignore = raw.respect_gitignore;
|
|
146
|
+
if (raw.rules !== undefined)
|
|
147
|
+
Object.assign(c.rules, raw.rules);
|
|
148
|
+
if (raw.overrides !== undefined)
|
|
149
|
+
c.overrides = raw.overrides;
|
|
150
|
+
if (raw.baseline !== undefined)
|
|
151
|
+
c.baseline = { ...c.baseline, ...raw.baseline };
|
|
152
|
+
if (raw.fail_on !== undefined)
|
|
153
|
+
c.fail_on = raw.fail_on;
|
|
154
|
+
if (raw.max_index !== undefined)
|
|
155
|
+
c.max_index = raw.max_index;
|
|
156
|
+
if (raw.privacy !== undefined)
|
|
157
|
+
c.privacy = { ...c.privacy, ...raw.privacy };
|
|
158
|
+
if (raw.reporter !== undefined)
|
|
159
|
+
c.reporter = raw.reporter;
|
|
160
|
+
if (raw.cache !== undefined)
|
|
161
|
+
c.cache = { ...c.cache, ...raw.cache };
|
|
162
|
+
if (raw.min_words_for_index !== undefined)
|
|
163
|
+
c.min_words_for_index = raw.min_words_for_index;
|
|
164
|
+
return c;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Registros que silencian categorías o reglas por defecto (nivel 3 de precedencia).
|
|
168
|
+
* Se mantiene deliberadamente pequeño: solo lo que la evidencia del benchmark justifica.
|
|
169
|
+
*/
|
|
170
|
+
export const REGISTER_ADJUSTMENTS = {
|
|
171
|
+
literario: { "repeticion/anafora": "off", "retorica/pregunta-retorica-apertura": "off", "retorica/triada": "off", "densidad/exclamaciones": "off" },
|
|
172
|
+
periodistico: { "estructura/encabezado-dos-puntos": "off" },
|
|
173
|
+
institucional: { "densidad/conectores": "info", "estructura/enumeracion-ordinal": "off" },
|
|
174
|
+
tecnico: {},
|
|
175
|
+
academico: {},
|
|
176
|
+
marketing: {},
|
|
177
|
+
general: {},
|
|
178
|
+
};
|
|
179
|
+
/**
|
|
180
|
+
* Resuelve el nivel efectivo de cada regla para un archivo concreto.
|
|
181
|
+
* Precedencia: internos < perfil < registro < proyecto < override por ruta < regla concreta.
|
|
182
|
+
* La supresión inline (nivel 7) se aplica en el runner sobre los hallazgos.
|
|
183
|
+
*/
|
|
184
|
+
export function resolveEffectiveRules(config, rules, relPath) {
|
|
185
|
+
const out = [];
|
|
186
|
+
const matchingOverrides = relPath ? config.overrides.filter((o) => matchesAny(relPath, o.files)) : [];
|
|
187
|
+
// Perfil efectivo: un override puede cambiarlo.
|
|
188
|
+
let profile = config.profile;
|
|
189
|
+
for (const ov of matchingOverrides)
|
|
190
|
+
if (ov.profile)
|
|
191
|
+
profile = ov.profile;
|
|
192
|
+
const registerAdj = REGISTER_ADJUSTMENTS[config.register] ?? {};
|
|
193
|
+
for (const r of rules) {
|
|
194
|
+
let level = r.status === "deprecated" ? "off" : r.default_level;
|
|
195
|
+
let source = "internal";
|
|
196
|
+
let detail = `nivel por defecto de la regla (${r.status})`;
|
|
197
|
+
const p = r.profiles[profile];
|
|
198
|
+
if (p !== undefined) {
|
|
199
|
+
level = p;
|
|
200
|
+
source = "profile";
|
|
201
|
+
detail = `perfil ${profile}`;
|
|
202
|
+
}
|
|
203
|
+
const ra = registerAdj[r.id];
|
|
204
|
+
if (ra !== undefined) {
|
|
205
|
+
level = ra;
|
|
206
|
+
source = "register";
|
|
207
|
+
detail = `registro ${config.register}`;
|
|
208
|
+
}
|
|
209
|
+
// Proyecto: `rules` admite id exacto o categoría "categoria/*".
|
|
210
|
+
const cat = `${r.category}/*`;
|
|
211
|
+
if (config.rules[cat] !== undefined) {
|
|
212
|
+
level = config.rules[cat];
|
|
213
|
+
source = "project";
|
|
214
|
+
detail = `rules["${cat}"]`;
|
|
215
|
+
}
|
|
216
|
+
if (config.rules[r.id] !== undefined) {
|
|
217
|
+
level = config.rules[r.id];
|
|
218
|
+
source = "project";
|
|
219
|
+
detail = `rules["${r.id}"]`;
|
|
220
|
+
}
|
|
221
|
+
// Override por ruta (categoría) y, con mayor precedencia, la regla concreta dentro del override.
|
|
222
|
+
for (const ov of matchingOverrides) {
|
|
223
|
+
const lvCat = ov.rules?.[cat];
|
|
224
|
+
if (lvCat !== undefined) {
|
|
225
|
+
level = lvCat;
|
|
226
|
+
source = "override";
|
|
227
|
+
detail = `override files=[${ov.files.join(", ")}] rules["${cat}"]`;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
for (const ov of matchingOverrides) {
|
|
231
|
+
const lvId = ov.rules?.[r.id];
|
|
232
|
+
if (lvId !== undefined) {
|
|
233
|
+
level = lvId;
|
|
234
|
+
source = "rule";
|
|
235
|
+
detail = `override files=[${ov.files.join(", ")}] rules["${r.id}"]`;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
out.push({ rule: r.id, level, source, detail });
|
|
239
|
+
}
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
export function explainConfig(loaded, rules, relPath) {
|
|
243
|
+
return { file: loaded.file, root: loaded.root, config: loaded.config, effective: resolveEffectiveRules(loaded.config, rules, relPath) };
|
|
244
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Conversión mínima de glob a RegExp: `**`, `*`, `?`, `{a,b}`, clases `[...]`. Las rutas se comparan con barras `/`. */
|
|
2
|
+
const cache = new Map();
|
|
3
|
+
export function globToRegExp(glob) {
|
|
4
|
+
const hit = cache.get(glob);
|
|
5
|
+
if (hit)
|
|
6
|
+
return hit;
|
|
7
|
+
let re = "";
|
|
8
|
+
let i = 0;
|
|
9
|
+
let g = glob.replace(/\\/g, "/");
|
|
10
|
+
if (g.startsWith("./"))
|
|
11
|
+
g = g.slice(2);
|
|
12
|
+
while (i < g.length) {
|
|
13
|
+
const c = g[i];
|
|
14
|
+
if (c === "*") {
|
|
15
|
+
if (g[i + 1] === "*") {
|
|
16
|
+
// `**/` o `**`
|
|
17
|
+
if (g[i + 2] === "/") {
|
|
18
|
+
re += "(?:.*/)?";
|
|
19
|
+
i += 3;
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
re += ".*";
|
|
23
|
+
i += 2;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
re += "[^/]*";
|
|
28
|
+
i++;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
else if (c === "?") {
|
|
32
|
+
re += "[^/]";
|
|
33
|
+
i++;
|
|
34
|
+
}
|
|
35
|
+
else if (c === "{") {
|
|
36
|
+
const end = g.indexOf("}", i);
|
|
37
|
+
if (end === -1) {
|
|
38
|
+
re += "\\{";
|
|
39
|
+
i++;
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
const alts = g.slice(i + 1, end).split(",").map((a) => globToRegExp(a).source.slice(1, -1));
|
|
43
|
+
re += `(?:${alts.join("|")})`;
|
|
44
|
+
i = end + 1;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
else if (c === "[") {
|
|
48
|
+
const end = g.indexOf("]", i);
|
|
49
|
+
if (end === -1) {
|
|
50
|
+
re += "\\[";
|
|
51
|
+
i++;
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
re += g.slice(i, end + 1);
|
|
55
|
+
i = end + 1;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
re += /[.+^$()|\\]/.test(c) ? `\\${c}` : c;
|
|
60
|
+
i++;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// Un patrón sin `/` se aplica a cualquier profundidad (como .gitignore).
|
|
64
|
+
const anchored = g.includes("/") ? `^${re}$` : `^(?:.*/)?${re}$`;
|
|
65
|
+
const out = new RegExp(anchored);
|
|
66
|
+
cache.set(glob, out);
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
export function matchesAny(relPath, globs) {
|
|
70
|
+
const p = relPath.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
71
|
+
return globs.some((g) => globToRegExp(g).test(p));
|
|
72
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { LoadedConfig } from "./core.js";
|
|
2
|
+
export * from "./core.js";
|
|
3
|
+
/** Busca el archivo de configuración hacia arriba desde `start`. */
|
|
4
|
+
export declare function findConfigFile(start: string): string | null;
|
|
5
|
+
export declare function loadConfig(opts?: {
|
|
6
|
+
cwd?: string;
|
|
7
|
+
file?: string | null;
|
|
8
|
+
}): LoadedConfig;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parse as parseYaml } from "yaml";
|
|
4
|
+
import { CONFIG_FILENAMES, defaultConfig, mergeConfig, validateConfigObject } from "./core.js";
|
|
5
|
+
export * from "./core.js";
|
|
6
|
+
/** Busca el archivo de configuración hacia arriba desde `start`. */
|
|
7
|
+
export function findConfigFile(start) {
|
|
8
|
+
let dir = path.resolve(start);
|
|
9
|
+
for (;;) {
|
|
10
|
+
for (const name of CONFIG_FILENAMES) {
|
|
11
|
+
const p = path.join(dir, name);
|
|
12
|
+
if (fs.existsSync(p))
|
|
13
|
+
return p;
|
|
14
|
+
}
|
|
15
|
+
const parent = path.dirname(dir);
|
|
16
|
+
if (parent === dir)
|
|
17
|
+
return null;
|
|
18
|
+
dir = parent;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function loadConfig(opts = {}) {
|
|
22
|
+
const cwd = path.resolve(opts.cwd ?? process.cwd());
|
|
23
|
+
const file = opts.file === undefined ? findConfigFile(cwd) : opts.file;
|
|
24
|
+
const base = defaultConfig();
|
|
25
|
+
if (!file)
|
|
26
|
+
return { config: base, file: null, root: cwd, issues: [] };
|
|
27
|
+
const abs = path.resolve(cwd, file);
|
|
28
|
+
let raw;
|
|
29
|
+
try {
|
|
30
|
+
raw = parseYaml(fs.readFileSync(abs, "utf8"));
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
return { config: base, file: abs, root: path.dirname(abs), issues: [{ path: "", message: `YAML inválido: ${e.message}` }] };
|
|
34
|
+
}
|
|
35
|
+
const issues = validateConfigObject(raw);
|
|
36
|
+
const config = issues.length === 0 && raw && typeof raw === "object" ? mergeConfig(base, raw) : base;
|
|
37
|
+
return { config, file: abs, root: path.dirname(abs), issues };
|
|
38
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { PathOverride, ProfileName } from "../contracts/index.js";
|
|
2
|
+
/** Una situación de escritura: su perfil, su viñeta en la guía y los archivos de texto que le corresponden. */
|
|
3
|
+
export interface Situacion {
|
|
4
|
+
id: string;
|
|
5
|
+
perfil: ProfileName;
|
|
6
|
+
guia: string;
|
|
7
|
+
archivos: string[];
|
|
8
|
+
}
|
|
9
|
+
/** Lee `rules/situaciones.yml` del paquete (o el archivo indicado) y lo valida. */
|
|
10
|
+
export declare function loadSituaciones(file?: string): Situacion[];
|
|
11
|
+
/** La primera situación cuyos archivos coinciden con la ruta, o null. */
|
|
12
|
+
export declare function situacionDe(relPath: string, situaciones: Situacion[]): Situacion | null;
|
|
13
|
+
/**
|
|
14
|
+
* `--profile auto` como overrides de perfil por ruta, en orden inverso para que gane la primera situación que coincide
|
|
15
|
+
* (en los overrides gana el último). Van delante de los del proyecto, que así siguen mandando.
|
|
16
|
+
*/
|
|
17
|
+
export declare function overridesDeSituaciones(situaciones: Situacion[]): PathOverride[];
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parse as parseYaml } from "yaml";
|
|
4
|
+
import { rulesDir } from "../paths.js";
|
|
5
|
+
import { matchesAny } from "./glob.js";
|
|
6
|
+
import { PROFILES } from "./index.js";
|
|
7
|
+
/** Lee `rules/situaciones.yml` del paquete (o el archivo indicado) y lo valida. */
|
|
8
|
+
export function loadSituaciones(file = path.join(rulesDir(), "situaciones.yml")) {
|
|
9
|
+
if (!fs.existsSync(file))
|
|
10
|
+
throw new Error(`no existe ${file}`);
|
|
11
|
+
const raw = parseYaml(fs.readFileSync(file, "utf8"));
|
|
12
|
+
if (raw?.schema_version !== 1 || !Array.isArray(raw.situaciones))
|
|
13
|
+
throw new Error(`${file}: hace falta schema_version: 1 y una lista situaciones`);
|
|
14
|
+
const vistos = new Set();
|
|
15
|
+
return raw.situaciones.map((s, i) => {
|
|
16
|
+
const donde = `${file}: situaciones[${i}]`;
|
|
17
|
+
if (typeof s.id !== "string" || !s.id)
|
|
18
|
+
throw new Error(`${donde}: falta id`);
|
|
19
|
+
if (vistos.has(s.id))
|
|
20
|
+
throw new Error(`${donde}: id repetido ${s.id}`);
|
|
21
|
+
vistos.add(s.id);
|
|
22
|
+
if (!PROFILES.includes(s.perfil))
|
|
23
|
+
throw new Error(`${donde}: perfil desconocido ${String(s.perfil)}`);
|
|
24
|
+
if (typeof s.guia !== "string" || !s.guia)
|
|
25
|
+
throw new Error(`${donde}: falta guia`);
|
|
26
|
+
const archivos = s.archivos ?? [];
|
|
27
|
+
if (!Array.isArray(archivos) || archivos.some((a) => typeof a !== "string"))
|
|
28
|
+
throw new Error(`${donde}: archivos tiene que ser una lista de globs`);
|
|
29
|
+
return { id: s.id, perfil: s.perfil, guia: s.guia, archivos: archivos };
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** La primera situación cuyos archivos coinciden con la ruta, o null. */
|
|
33
|
+
export function situacionDe(relPath, situaciones) {
|
|
34
|
+
const p = relPath.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
35
|
+
return situaciones.find((s) => s.archivos.length && matchesAny(p, s.archivos)) ?? null;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* `--profile auto` como overrides de perfil por ruta, en orden inverso para que gane la primera situación que coincide
|
|
39
|
+
* (en los overrides gana el último). Van delante de los del proyecto, que así siguen mandando.
|
|
40
|
+
*/
|
|
41
|
+
export function overridesDeSituaciones(situaciones) {
|
|
42
|
+
return situaciones.filter((s) => s.archivos.length).map((s) => ({ files: s.archivos, profile: s.perfil })).reverse();
|
|
43
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contratos públicos del linter. Todo formato JSON externo lleva `schema_version`.
|
|
3
|
+
*/
|
|
4
|
+
export declare const SCHEMA_VERSION: 1;
|
|
5
|
+
export type Level = "off" | "info" | "warning" | "error";
|
|
6
|
+
export type RuleStatus = "draft" | "candidate" | "stable" | "deprecated";
|
|
7
|
+
export type RuleCategory = "lexico" | "estructura" | "repeticion" | "densidad" | "retorica" | "formato";
|
|
8
|
+
export type DetectorKind = "regex" | "lexicon" | "sequence" | "density" | "repetition" | "structure" | "cooccurrence";
|
|
9
|
+
export type RuleScope = "sentence" | "paragraph" | "document" | "block";
|
|
10
|
+
export type ProfileName = "general" | "tecnico" | "academico" | "marketing" | "chat" | "correo" | "readme" | "redes";
|
|
11
|
+
export type Register = "general" | "tecnico" | "academico" | "marketing" | "literario" | "periodistico" | "institucional";
|
|
12
|
+
/** Posición: offset 0-based en el texto original (unidades UTF-16) y línea/columna 1-based (columna en code points). */
|
|
13
|
+
export interface Position {
|
|
14
|
+
offset: number;
|
|
15
|
+
line: number;
|
|
16
|
+
column: number;
|
|
17
|
+
}
|
|
18
|
+
export interface SourceRange {
|
|
19
|
+
start: Position;
|
|
20
|
+
end: Position;
|
|
21
|
+
}
|
|
22
|
+
export interface RuleExample {
|
|
23
|
+
text: string;
|
|
24
|
+
/** Número de hallazgos esperados. */
|
|
25
|
+
expect: number;
|
|
26
|
+
note?: string;
|
|
27
|
+
}
|
|
28
|
+
/** Definición de regla tal y como se escribe en YAML (autoría). */
|
|
29
|
+
export interface RuleDefinition {
|
|
30
|
+
schema_version: number;
|
|
31
|
+
id: string;
|
|
32
|
+
revision: number;
|
|
33
|
+
status: RuleStatus;
|
|
34
|
+
title: string;
|
|
35
|
+
summary: string;
|
|
36
|
+
category: RuleCategory;
|
|
37
|
+
scope: RuleScope;
|
|
38
|
+
detector: DetectorKind;
|
|
39
|
+
conditions: Record<string, unknown>;
|
|
40
|
+
exceptions?: Record<string, unknown>;
|
|
41
|
+
default_level: Level;
|
|
42
|
+
score: {
|
|
43
|
+
weight: number;
|
|
44
|
+
cap: number;
|
|
45
|
+
};
|
|
46
|
+
message: string;
|
|
47
|
+
explanation: string;
|
|
48
|
+
rewrite_guidance: string;
|
|
49
|
+
examples: {
|
|
50
|
+
positive: RuleExample[];
|
|
51
|
+
negative: RuleExample[];
|
|
52
|
+
};
|
|
53
|
+
provenance: {
|
|
54
|
+
evidence: string;
|
|
55
|
+
known_false_positives: string[];
|
|
56
|
+
reviewed_by: string[];
|
|
57
|
+
};
|
|
58
|
+
profiles?: Partial<Record<ProfileName, Level>>;
|
|
59
|
+
}
|
|
60
|
+
/** Regla compilada: lo único que interpreta el runtime. */
|
|
61
|
+
export interface CompiledRule {
|
|
62
|
+
id: string;
|
|
63
|
+
revision: number;
|
|
64
|
+
status: RuleStatus;
|
|
65
|
+
title: string;
|
|
66
|
+
summary: string;
|
|
67
|
+
category: RuleCategory;
|
|
68
|
+
scope: RuleScope;
|
|
69
|
+
detector: DetectorKind;
|
|
70
|
+
/** Parámetros del detector ya resueltos (léxicos expandidos, regex validadas). */
|
|
71
|
+
params: Record<string, unknown>;
|
|
72
|
+
exceptions: {
|
|
73
|
+
patterns?: string[];
|
|
74
|
+
lexicon?: string[];
|
|
75
|
+
};
|
|
76
|
+
default_level: Level;
|
|
77
|
+
score: {
|
|
78
|
+
weight: number;
|
|
79
|
+
cap: number;
|
|
80
|
+
};
|
|
81
|
+
message: string;
|
|
82
|
+
explanation: string;
|
|
83
|
+
rewrite_guidance: string;
|
|
84
|
+
profiles: Partial<Record<ProfileName, Level>>;
|
|
85
|
+
}
|
|
86
|
+
export interface RulePack {
|
|
87
|
+
schema_version: number;
|
|
88
|
+
name: string;
|
|
89
|
+
version: string;
|
|
90
|
+
generated_at: string;
|
|
91
|
+
rules: CompiledRule[];
|
|
92
|
+
}
|
|
93
|
+
export type BlockKind = "paragraph" | "heading" | "list_item" | "blockquote" | "table_cell" | "plain";
|
|
94
|
+
/** Bloque de texto elegible para análisis, con su posición en el original. */
|
|
95
|
+
export interface TextBlock {
|
|
96
|
+
kind: BlockKind;
|
|
97
|
+
/** Texto del bloque sin marcado. */
|
|
98
|
+
text: string;
|
|
99
|
+
/** Mapa: índice en `text` -> offset en el texto original. Longitud = text.length + 1. */
|
|
100
|
+
map: Int32Array;
|
|
101
|
+
depth: number;
|
|
102
|
+
/** El bloque empieza con texto en negrita (patrón «- **Título:** texto»). */
|
|
103
|
+
startsWithStrong?: boolean;
|
|
104
|
+
}
|
|
105
|
+
export interface Sentence {
|
|
106
|
+
blockIndex: number;
|
|
107
|
+
/** Rango dentro de `block.text`. */
|
|
108
|
+
start: number;
|
|
109
|
+
end: number;
|
|
110
|
+
text: string;
|
|
111
|
+
}
|
|
112
|
+
export interface Token {
|
|
113
|
+
blockIndex: number;
|
|
114
|
+
start: number;
|
|
115
|
+
end: number;
|
|
116
|
+
text: string;
|
|
117
|
+
lower: string;
|
|
118
|
+
/** Palabra alfabética (no número ni símbolo). */
|
|
119
|
+
isWord: boolean;
|
|
120
|
+
}
|
|
121
|
+
export interface Document {
|
|
122
|
+
path: string | null;
|
|
123
|
+
format: "text" | "markdown";
|
|
124
|
+
/** Texto original tal y como se leyó (con BOM y CRLF si los había). */
|
|
125
|
+
original: string;
|
|
126
|
+
lineStarts: number[];
|
|
127
|
+
blocks: TextBlock[];
|
|
128
|
+
sentences: Sentence[];
|
|
129
|
+
tokens: Token[];
|
|
130
|
+
/** Palabras elegibles (tokens alfabéticos de bloques analizados). */
|
|
131
|
+
eligibleWords: number;
|
|
132
|
+
/** Rangos [inicio, fin) del original ocupados por código en Markdown (bloques e inline). Las directivas de supresión escritas ahí son ejemplos, no directivas. */
|
|
133
|
+
codeRanges?: [number, number][];
|
|
134
|
+
}
|
|
135
|
+
export interface Finding {
|
|
136
|
+
rule: string;
|
|
137
|
+
revision: number;
|
|
138
|
+
level: Exclude<Level, "off">;
|
|
139
|
+
category: RuleCategory;
|
|
140
|
+
message: string;
|
|
141
|
+
range: SourceRange;
|
|
142
|
+
snippet: string;
|
|
143
|
+
/** Huella estable para baseline y deduplicación. */
|
|
144
|
+
fingerprint: string;
|
|
145
|
+
suppressed?: {
|
|
146
|
+
by: "inline" | "baseline";
|
|
147
|
+
reason?: string;
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
export interface ScoreContributor {
|
|
151
|
+
rule: string;
|
|
152
|
+
findings: number;
|
|
153
|
+
contribution: number;
|
|
154
|
+
}
|
|
155
|
+
export interface ScoreResult {
|
|
156
|
+
/** Índice de patrones editoriales 0-100. `null` si el texto no tiene suficientes palabras. */
|
|
157
|
+
index: number | null;
|
|
158
|
+
eligibleWords: number;
|
|
159
|
+
minWords: number;
|
|
160
|
+
contributors: ScoreContributor[];
|
|
161
|
+
}
|
|
162
|
+
export interface FileResult {
|
|
163
|
+
path: string;
|
|
164
|
+
format: "text" | "markdown";
|
|
165
|
+
findings: Finding[];
|
|
166
|
+
score: ScoreResult;
|
|
167
|
+
durationMs: number;
|
|
168
|
+
fromCache?: boolean;
|
|
169
|
+
}
|
|
170
|
+
export interface PolicyResult {
|
|
171
|
+
ok: boolean;
|
|
172
|
+
failOn: Level | "never";
|
|
173
|
+
maxIndex: number | null;
|
|
174
|
+
reasons: string[];
|
|
175
|
+
counts: {
|
|
176
|
+
error: number;
|
|
177
|
+
warning: number;
|
|
178
|
+
info: number;
|
|
179
|
+
suppressed: number;
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
export interface ScanResult {
|
|
183
|
+
schema_version: number;
|
|
184
|
+
tool: {
|
|
185
|
+
name: string;
|
|
186
|
+
version: string;
|
|
187
|
+
rulepack: string;
|
|
188
|
+
};
|
|
189
|
+
files: FileResult[];
|
|
190
|
+
policy: PolicyResult;
|
|
191
|
+
baseline?: {
|
|
192
|
+
path: string;
|
|
193
|
+
matched: number;
|
|
194
|
+
stale: number;
|
|
195
|
+
};
|
|
196
|
+
durationMs: number;
|
|
197
|
+
}
|
|
198
|
+
export interface BaselineEntry {
|
|
199
|
+
rule: string;
|
|
200
|
+
path: string;
|
|
201
|
+
fingerprint: string;
|
|
202
|
+
reason?: string;
|
|
203
|
+
}
|
|
204
|
+
export interface BaselineFile {
|
|
205
|
+
schema_version: number;
|
|
206
|
+
created: string;
|
|
207
|
+
entries: BaselineEntry[];
|
|
208
|
+
}
|
|
209
|
+
export interface PathOverride {
|
|
210
|
+
files: string[];
|
|
211
|
+
rules?: Record<string, Level>;
|
|
212
|
+
profile?: ProfileName;
|
|
213
|
+
}
|
|
214
|
+
export interface Config {
|
|
215
|
+
schema_version: number;
|
|
216
|
+
profile: ProfileName;
|
|
217
|
+
register: Register;
|
|
218
|
+
include: string[];
|
|
219
|
+
exclude: string[];
|
|
220
|
+
respect_gitignore: boolean;
|
|
221
|
+
rules: Record<string, Level>;
|
|
222
|
+
overrides: PathOverride[];
|
|
223
|
+
baseline: {
|
|
224
|
+
path: string | null;
|
|
225
|
+
require_reason: boolean;
|
|
226
|
+
};
|
|
227
|
+
fail_on: Level | "never";
|
|
228
|
+
max_index: number | null;
|
|
229
|
+
privacy: {
|
|
230
|
+
snippets: boolean;
|
|
231
|
+
};
|
|
232
|
+
reporter: "terminal" | "json" | "sarif" | "revision";
|
|
233
|
+
cache: {
|
|
234
|
+
enabled: boolean;
|
|
235
|
+
dir: string;
|
|
236
|
+
};
|
|
237
|
+
min_words_for_index: number;
|
|
238
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Document, TextBlock } from "../contracts/index.js";
|
|
2
|
+
export { normalizeText, computeLineStarts, offsetToLineColumn, snippetOf } from "./text.js";
|
|
3
|
+
export { splitSentences, tokenizeBlock } from "./tokenize.js";
|
|
4
|
+
/** Bloques de texto plano: párrafos separados por líneas en blanco. */
|
|
5
|
+
export declare function plainTextBlocks(text: string): TextBlock[];
|
|
6
|
+
export declare function detectFormat(path: string | null | undefined): "text" | "markdown";
|
|
7
|
+
export declare function buildDocument(original: string, opts: {
|
|
8
|
+
path?: string | null;
|
|
9
|
+
format?: "text" | "markdown";
|
|
10
|
+
}): Document;
|