textoneitor 0.0.0-stage → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +29861 -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 +357 -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 +68 -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 +636 -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 +16 -0
- package/dist/runner/index.js +171 -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 +11018 -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,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
|
+
};
|
|
@@ -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
|
+
}
|