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,70 @@
|
|
|
1
|
+
import { computeLineStarts, normalizeText } from "./text.js";
|
|
2
|
+
import { splitSentences, tokenizeBlock } from "./tokenize.js";
|
|
3
|
+
import { markdownBlocks } from "../markdown/index.js";
|
|
4
|
+
export { normalizeText, computeLineStarts, offsetToLineColumn, snippetOf } from "./text.js";
|
|
5
|
+
export { splitSentences, tokenizeBlock } from "./tokenize.js";
|
|
6
|
+
/** Bloques de texto plano: párrafos separados por líneas en blanco. */
|
|
7
|
+
export function plainTextBlocks(text) {
|
|
8
|
+
const blocks = [];
|
|
9
|
+
const re = /(?:[^\n]|\n(?![ \t]*\n))+/g;
|
|
10
|
+
let m;
|
|
11
|
+
while ((m = re.exec(text)) !== null) {
|
|
12
|
+
const raw = m[0];
|
|
13
|
+
const lead = raw.length - raw.trimStart().length;
|
|
14
|
+
const body = raw.trim();
|
|
15
|
+
if (!body)
|
|
16
|
+
continue;
|
|
17
|
+
const start = m.index + lead;
|
|
18
|
+
const map = new Int32Array(body.length + 1);
|
|
19
|
+
for (let i = 0; i <= body.length; i++)
|
|
20
|
+
map[i] = start + i;
|
|
21
|
+
blocks.push({ kind: "plain", text: body, map, depth: 0 });
|
|
22
|
+
}
|
|
23
|
+
return blocks;
|
|
24
|
+
}
|
|
25
|
+
export function detectFormat(path) {
|
|
26
|
+
if (!path)
|
|
27
|
+
return "text";
|
|
28
|
+
return /\.(md|markdown|mdown|mkd)$/i.test(path) ? "markdown" : "text";
|
|
29
|
+
}
|
|
30
|
+
export function buildDocument(original, opts) {
|
|
31
|
+
const format = opts.format ?? detectFormat(opts.path);
|
|
32
|
+
const norm = normalizeText(original);
|
|
33
|
+
const codeRanges = [];
|
|
34
|
+
const blocks = format === "markdown" ? markdownBlocks(norm.text, codeRanges) : plainTextBlocks(norm.text);
|
|
35
|
+
if (norm.hadBom || norm.hadCr) {
|
|
36
|
+
for (const b of blocks) {
|
|
37
|
+
for (let i = 0; i < b.map.length; i++)
|
|
38
|
+
b.map[i] = norm.toOriginal(b.map[i]);
|
|
39
|
+
}
|
|
40
|
+
for (const r of codeRanges) {
|
|
41
|
+
r[0] = norm.toOriginal(r[0]);
|
|
42
|
+
r[1] = norm.toOriginal(r[1]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const sentences = [];
|
|
46
|
+
const tokens = [];
|
|
47
|
+
let eligibleWords = 0;
|
|
48
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
49
|
+
const b = blocks[i];
|
|
50
|
+
// Sin `push(...x)`: un bloque de más de cien mil tokens (un .txt grande sin líneas en blanco) desborda la pila.
|
|
51
|
+
for (const s of splitSentences(b, i))
|
|
52
|
+
sentences.push(s);
|
|
53
|
+
for (const tk of tokenizeBlock(b, i)) {
|
|
54
|
+
if (tk.isWord)
|
|
55
|
+
eligibleWords++;
|
|
56
|
+
tokens.push(tk);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
path: opts.path ?? null,
|
|
61
|
+
format,
|
|
62
|
+
original,
|
|
63
|
+
lineStarts: computeLineStarts(original),
|
|
64
|
+
blocks,
|
|
65
|
+
sentences,
|
|
66
|
+
tokens,
|
|
67
|
+
eligibleWords,
|
|
68
|
+
...(codeRanges.length ? { codeRanges } : {}),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Normalización de texto y utilidades de posiciones. */
|
|
2
|
+
export interface NormalizedText {
|
|
3
|
+
original: string;
|
|
4
|
+
/** Texto sin BOM y con CRLF/CR convertidos a LF. */
|
|
5
|
+
text: string;
|
|
6
|
+
/** Offset en `text` -> offset en `original`. */
|
|
7
|
+
toOriginal(offset: number): number;
|
|
8
|
+
hadBom: boolean;
|
|
9
|
+
hadCr: boolean;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Elimina BOM y convierte CRLF/CR a LF conservando la correspondencia de offsets.
|
|
13
|
+
*/
|
|
14
|
+
export declare function normalizeText(original: string): NormalizedText;
|
|
15
|
+
export declare function computeLineStarts(text: string): number[];
|
|
16
|
+
/** Línea y columna 1-based para un offset. La columna se cuenta en code points (no en unidades UTF-16). */
|
|
17
|
+
export declare function offsetToLineColumn(text: string, lineStarts: number[], offset: number): {
|
|
18
|
+
line: number;
|
|
19
|
+
column: number;
|
|
20
|
+
};
|
|
21
|
+
/** Recorta un fragmento para snippets sin partir pares subrogados. */
|
|
22
|
+
export declare function snippetOf(text: string, start: number, end: number, max?: number): string;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/** Normalización de texto y utilidades de posiciones. */
|
|
2
|
+
/**
|
|
3
|
+
* Elimina BOM y convierte CRLF/CR a LF conservando la correspondencia de offsets.
|
|
4
|
+
*/
|
|
5
|
+
export function normalizeText(original) {
|
|
6
|
+
const hadBom = original.charCodeAt(0) === 0xfeff;
|
|
7
|
+
const src = hadBom ? original.slice(1) : original;
|
|
8
|
+
const bomShift = hadBom ? 1 : 0;
|
|
9
|
+
if (!src.includes("\r")) {
|
|
10
|
+
return { original, text: src, hadBom, hadCr: false, toOriginal: (o) => o + bomShift };
|
|
11
|
+
}
|
|
12
|
+
let out = "";
|
|
13
|
+
let last = 0;
|
|
14
|
+
// Posiciones (en `out`) a partir de las cuales el desplazamiento aumenta en 1.
|
|
15
|
+
const shifts = [];
|
|
16
|
+
for (let i = 0; i < src.length; i++) {
|
|
17
|
+
if (src.charCodeAt(i) === 13) {
|
|
18
|
+
out += src.slice(last, i);
|
|
19
|
+
if (src.charCodeAt(i + 1) === 10) {
|
|
20
|
+
// CRLF -> LF: se elimina el CR; desplazamiento +1 a partir de aquí.
|
|
21
|
+
shifts.push(out.length);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
// CR solitario -> LF: mismo tamaño.
|
|
25
|
+
out += "\n";
|
|
26
|
+
}
|
|
27
|
+
last = i + 1;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
out += src.slice(last);
|
|
31
|
+
const toOriginal = (o) => {
|
|
32
|
+
let lo = 0;
|
|
33
|
+
let hi = shifts.length;
|
|
34
|
+
while (lo < hi) {
|
|
35
|
+
const mid = (lo + hi) >> 1;
|
|
36
|
+
if (shifts[mid] <= o)
|
|
37
|
+
lo = mid + 1;
|
|
38
|
+
else
|
|
39
|
+
hi = mid;
|
|
40
|
+
}
|
|
41
|
+
return o + lo + bomShift;
|
|
42
|
+
};
|
|
43
|
+
return { original, text: out, hadBom, hadCr: true, toOriginal };
|
|
44
|
+
}
|
|
45
|
+
export function computeLineStarts(text) {
|
|
46
|
+
const starts = [0];
|
|
47
|
+
for (let i = 0; i < text.length; i++) {
|
|
48
|
+
const c = text.charCodeAt(i);
|
|
49
|
+
// LF, y también CR solitario (finales de línea de Mac clásico), igual que hace normalizeText.
|
|
50
|
+
if (c === 10 || (c === 13 && text.charCodeAt(i + 1) !== 10))
|
|
51
|
+
starts.push(i + 1);
|
|
52
|
+
}
|
|
53
|
+
return starts;
|
|
54
|
+
}
|
|
55
|
+
/** Línea y columna 1-based para un offset. La columna se cuenta en code points (no en unidades UTF-16). */
|
|
56
|
+
export function offsetToLineColumn(text, lineStarts, offset) {
|
|
57
|
+
let lo = 0;
|
|
58
|
+
let hi = lineStarts.length - 1;
|
|
59
|
+
while (lo < hi) {
|
|
60
|
+
const mid = (lo + hi + 1) >> 1;
|
|
61
|
+
if (lineStarts[mid] <= offset)
|
|
62
|
+
lo = mid;
|
|
63
|
+
else
|
|
64
|
+
hi = mid - 1;
|
|
65
|
+
}
|
|
66
|
+
const lineStart = lineStarts[lo];
|
|
67
|
+
let column = 1;
|
|
68
|
+
for (let i = lineStart; i < offset; i++) {
|
|
69
|
+
const c = text.charCodeAt(i);
|
|
70
|
+
if (c >= 0xdc00 && c <= 0xdfff)
|
|
71
|
+
continue; // unidad baja de par subrogado
|
|
72
|
+
if (c === 13)
|
|
73
|
+
continue; // CR de un CRLF no cuenta como columna
|
|
74
|
+
if (c === 0xfeff && i === 0)
|
|
75
|
+
continue; // el BOM no es una columna visible
|
|
76
|
+
column++;
|
|
77
|
+
}
|
|
78
|
+
return { line: lo + 1, column };
|
|
79
|
+
}
|
|
80
|
+
/** Recorta un fragmento para snippets sin partir pares subrogados. */
|
|
81
|
+
export function snippetOf(text, start, end, max = 120) {
|
|
82
|
+
let s = text.slice(start, end).replace(/\s+/g, " ").trim();
|
|
83
|
+
if (s.length > max) {
|
|
84
|
+
let cut = max;
|
|
85
|
+
const c = s.charCodeAt(cut - 1);
|
|
86
|
+
if (c >= 0xd800 && c <= 0xdbff)
|
|
87
|
+
cut--;
|
|
88
|
+
s = s.slice(0, cut) + "…";
|
|
89
|
+
}
|
|
90
|
+
return s;
|
|
91
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Sentence, TextBlock, Token } from "../contracts/index.js";
|
|
2
|
+
export declare function tokenizeBlock(block: TextBlock, blockIndex: number): Token[];
|
|
3
|
+
/** Divide un bloque en frases. Un encabezado o elemento de lista sin puntuación es una única frase. */
|
|
4
|
+
export declare function splitSentences(block: TextBlock, blockIndex: number): Sentence[];
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const WORD_RE = /[\p{L}\p{M}\p{N}]+(?:['’\-·][\p{L}\p{M}\p{N}]+)*/gu;
|
|
2
|
+
const SENT_END = /[.!?…]+["»”')\]]*|\n/g;
|
|
3
|
+
const ABBREV = new Set([
|
|
4
|
+
"sr", "sra", "srta", "dr", "dra", "etc", "p", "pp", "pág", "págs", "ej", "núm", "ud", "uds", "vs",
|
|
5
|
+
"art", "cap", "fig", "vol", "aprox", "tel", "av", "avda", "sto", "sta", "d", "dña", "prof", "ing", "lic",
|
|
6
|
+
]);
|
|
7
|
+
export function tokenizeBlock(block, blockIndex) {
|
|
8
|
+
const tokens = [];
|
|
9
|
+
const re = new RegExp(WORD_RE.source, WORD_RE.flags);
|
|
10
|
+
let m;
|
|
11
|
+
while ((m = re.exec(block.text)) !== null) {
|
|
12
|
+
const text = m[0];
|
|
13
|
+
const isWord = /\p{L}/u.test(text);
|
|
14
|
+
tokens.push({ blockIndex, start: m.index, end: m.index + text.length, text, lower: text.toLowerCase(), isWord });
|
|
15
|
+
}
|
|
16
|
+
return tokens;
|
|
17
|
+
}
|
|
18
|
+
/** Divide un bloque en frases. Un encabezado o elemento de lista sin puntuación es una única frase. */
|
|
19
|
+
export function splitSentences(block, blockIndex) {
|
|
20
|
+
const text = block.text;
|
|
21
|
+
const out = [];
|
|
22
|
+
let start = 0;
|
|
23
|
+
const re = new RegExp(SENT_END.source, SENT_END.flags);
|
|
24
|
+
let m;
|
|
25
|
+
while ((m = re.exec(text)) !== null) {
|
|
26
|
+
const end = m.index + m[0].length;
|
|
27
|
+
if (m[0] === "\n") {
|
|
28
|
+
// Un salto de línea dentro de un párrafo envuelto a mano (correo, README a 72-80 columnas) no cierra la frase:
|
|
29
|
+
// si la línea siguiente sigue en minúscula, es la misma frase. Sin esto el ritmo mide líneas y no frases.
|
|
30
|
+
if (/^[ \t]*\p{Ll}/u.test(text.slice(end, end + 8)))
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
const before = text.slice(Math.max(start, m.index - 8), m.index);
|
|
35
|
+
const wordBefore = /(\p{L}+)$/u.exec(before)?.[1]?.toLowerCase();
|
|
36
|
+
const next = text.charAt(end);
|
|
37
|
+
if (m[0] === "." && wordBefore && ABBREV.has(wordBefore))
|
|
38
|
+
continue;
|
|
39
|
+
if (m[0] === "." && /\p{N}/u.test(next))
|
|
40
|
+
continue;
|
|
41
|
+
if (m[0] === "." && wordBefore && wordBefore.length === 1 && /\p{Lu}/u.test(before.slice(-1)))
|
|
42
|
+
continue; // iniciales
|
|
43
|
+
if (next !== "" && !/\s/.test(next))
|
|
44
|
+
continue; // "v1.0", "www.x"
|
|
45
|
+
}
|
|
46
|
+
push(start, end);
|
|
47
|
+
start = end;
|
|
48
|
+
}
|
|
49
|
+
push(start, text.length);
|
|
50
|
+
return out;
|
|
51
|
+
function push(s, e) {
|
|
52
|
+
const t = text.slice(s, e);
|
|
53
|
+
const ns = s + (t.length - t.trimStart().length);
|
|
54
|
+
const ne = e - (t.length - t.trimEnd().length);
|
|
55
|
+
if (ne <= ns)
|
|
56
|
+
return;
|
|
57
|
+
out.push({ blockIndex, start: ns, end: ne, text: text.slice(ns, ne) });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { TextBlock } from "../contracts/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Extrae bloques elegibles de un Markdown mediante AST.
|
|
4
|
+
* Excluidos: código (bloque e inline), front matter, URLs y destinos de enlaces, comentarios y HTML, definiciones.
|
|
5
|
+
* Analizados: párrafos, encabezados, elementos de lista, citas, celdas de tabla y texto visible de enlaces.
|
|
6
|
+
*/
|
|
7
|
+
export declare function markdownBlocks(text: string, codeRanges?: [number, number][]): TextBlock[];
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { fromMarkdown } from "mdast-util-from-markdown";
|
|
2
|
+
import { frontmatter } from "micromark-extension-frontmatter";
|
|
3
|
+
import { frontmatterFromMarkdown } from "mdast-util-frontmatter";
|
|
4
|
+
import { gfm } from "micromark-extension-gfm";
|
|
5
|
+
import { gfmFromMarkdown } from "mdast-util-gfm";
|
|
6
|
+
/**
|
|
7
|
+
* Extrae bloques elegibles de un Markdown mediante AST.
|
|
8
|
+
* Excluidos: código (bloque e inline), front matter, URLs y destinos de enlaces, comentarios y HTML, definiciones.
|
|
9
|
+
* Analizados: párrafos, encabezados, elementos de lista, citas, celdas de tabla y texto visible de enlaces.
|
|
10
|
+
*/
|
|
11
|
+
export function markdownBlocks(text, codeRanges) {
|
|
12
|
+
const tree = fromMarkdown(text, {
|
|
13
|
+
extensions: [frontmatter(["yaml", "toml"]), gfm()],
|
|
14
|
+
mdastExtensions: [frontmatterFromMarkdown(["yaml", "toml"]), gfmFromMarkdown()],
|
|
15
|
+
});
|
|
16
|
+
const blocks = [];
|
|
17
|
+
walk(tree, 0);
|
|
18
|
+
return blocks;
|
|
19
|
+
function codeRange(node) {
|
|
20
|
+
const s = node.position?.start.offset;
|
|
21
|
+
const e = node.position?.end.offset;
|
|
22
|
+
if (codeRanges && s !== undefined && e !== undefined)
|
|
23
|
+
codeRanges.push([s, e]);
|
|
24
|
+
}
|
|
25
|
+
function walk(node, depth) {
|
|
26
|
+
if (node.type === "code")
|
|
27
|
+
codeRange(node);
|
|
28
|
+
switch (node.type) {
|
|
29
|
+
case "root":
|
|
30
|
+
for (const c of node.children)
|
|
31
|
+
walk(c, depth);
|
|
32
|
+
return;
|
|
33
|
+
case "paragraph":
|
|
34
|
+
emit("paragraph", node, depth);
|
|
35
|
+
return;
|
|
36
|
+
case "heading":
|
|
37
|
+
emit("heading", node, node.depth);
|
|
38
|
+
return;
|
|
39
|
+
case "blockquote":
|
|
40
|
+
for (const c of node.children) {
|
|
41
|
+
if (c.type === "paragraph")
|
|
42
|
+
emit("blockquote", c, depth + 1);
|
|
43
|
+
else
|
|
44
|
+
walk(c, depth + 1);
|
|
45
|
+
}
|
|
46
|
+
return;
|
|
47
|
+
case "list":
|
|
48
|
+
for (const c of node.children)
|
|
49
|
+
walk(c, depth + 1);
|
|
50
|
+
return;
|
|
51
|
+
case "listItem":
|
|
52
|
+
for (const c of node.children) {
|
|
53
|
+
if (c.type === "paragraph")
|
|
54
|
+
emit("list_item", c, depth);
|
|
55
|
+
else
|
|
56
|
+
walk(c, depth);
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
case "table":
|
|
60
|
+
for (const row of node.children)
|
|
61
|
+
for (const cell of row.children)
|
|
62
|
+
emit("table_cell", cell, depth);
|
|
63
|
+
return;
|
|
64
|
+
case "footnoteDefinition":
|
|
65
|
+
for (const c of node.children)
|
|
66
|
+
walk(c, depth);
|
|
67
|
+
return;
|
|
68
|
+
default:
|
|
69
|
+
// code, html, yaml, toml, definition, thematicBreak: excluidos.
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function emit(kind, node, depth) {
|
|
74
|
+
const parts = [];
|
|
75
|
+
collect(node, parts);
|
|
76
|
+
let out = "";
|
|
77
|
+
const map = [];
|
|
78
|
+
for (const p of parts) {
|
|
79
|
+
out += p.text;
|
|
80
|
+
for (const o of p.offsets)
|
|
81
|
+
map.push(o);
|
|
82
|
+
}
|
|
83
|
+
let s = 0;
|
|
84
|
+
let e = out.length;
|
|
85
|
+
while (s < e && /\s/.test(out[s]))
|
|
86
|
+
s++;
|
|
87
|
+
while (e > s && /\s/.test(out[e - 1]))
|
|
88
|
+
e--;
|
|
89
|
+
if (e <= s)
|
|
90
|
+
return;
|
|
91
|
+
const body = out.slice(s, e);
|
|
92
|
+
const m = new Int32Array(body.length + 1);
|
|
93
|
+
for (let i = 0; i < body.length; i++)
|
|
94
|
+
m[i] = map[s + i];
|
|
95
|
+
m[body.length] = map[e - 1] + 1;
|
|
96
|
+
const first = node.children[0];
|
|
97
|
+
const startsWithStrong = first?.type === "strong";
|
|
98
|
+
blocks.push({ kind, text: body, map: m, depth, startsWithStrong });
|
|
99
|
+
}
|
|
100
|
+
function collect(node, parts) {
|
|
101
|
+
switch (node.type) {
|
|
102
|
+
case "text": {
|
|
103
|
+
const start = node.position?.start.offset ?? 0;
|
|
104
|
+
const end = node.position?.end.offset ?? start;
|
|
105
|
+
const raw = text.slice(start, end);
|
|
106
|
+
if (raw === node.value) {
|
|
107
|
+
parts.push({ text: node.value, offsets: range(start, end) });
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
// Entidades o escapes: alineación aproximada y acotada dentro del nodo.
|
|
111
|
+
parts.push({ text: node.value, offsets: approx(node.value, raw, start) });
|
|
112
|
+
}
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
case "inlineCode":
|
|
116
|
+
codeRange(node);
|
|
117
|
+
parts.push({ text: " ", offsets: [node.position?.start.offset ?? 0] });
|
|
118
|
+
return;
|
|
119
|
+
case "html":
|
|
120
|
+
case "image":
|
|
121
|
+
case "imageReference":
|
|
122
|
+
case "footnoteReference":
|
|
123
|
+
case "break": {
|
|
124
|
+
const o = node.position?.start.offset ?? 0;
|
|
125
|
+
parts.push({ text: " ", offsets: [o] });
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
case "link":
|
|
129
|
+
case "linkReference":
|
|
130
|
+
case "emphasis":
|
|
131
|
+
case "strong":
|
|
132
|
+
case "delete":
|
|
133
|
+
for (const c of node.children)
|
|
134
|
+
collect(c, parts);
|
|
135
|
+
return;
|
|
136
|
+
default:
|
|
137
|
+
if ("children" in node)
|
|
138
|
+
for (const c of node.children)
|
|
139
|
+
collect(c, parts);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function range(a, b) {
|
|
145
|
+
const r = new Array(b - a);
|
|
146
|
+
for (let i = a; i < b; i++)
|
|
147
|
+
r[i - a] = i;
|
|
148
|
+
return r;
|
|
149
|
+
}
|
|
150
|
+
/** Alinea `value` (decodificado) con `raw` (crudo) de forma monótona; cada carácter apunta a una posición válida dentro de raw. */
|
|
151
|
+
function approx(value, raw, start) {
|
|
152
|
+
const offs = [];
|
|
153
|
+
let j = 0;
|
|
154
|
+
for (let i = 0; i < value.length; i++) {
|
|
155
|
+
const v = value[i];
|
|
156
|
+
// Escape "\x" en raw que produce "x" en value.
|
|
157
|
+
if (raw[j] === "\\" && raw[j + 1] === v && v !== "\\")
|
|
158
|
+
j++;
|
|
159
|
+
// Entidad HTML en raw (&) que produce un carácter distinto en value.
|
|
160
|
+
if (raw[j] === "&") {
|
|
161
|
+
const semi = raw.indexOf(";", j);
|
|
162
|
+
if (semi > j && semi - j <= 12 && !value.startsWith(raw.slice(j, semi + 1), i)) {
|
|
163
|
+
offs.push(start + j);
|
|
164
|
+
j = semi + 1;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (j < raw.length && raw[j] === v) {
|
|
169
|
+
offs.push(start + j);
|
|
170
|
+
j++;
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
offs.push(start + Math.min(j, raw.length - 1));
|
|
174
|
+
j++;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return offs;
|
|
178
|
+
}
|
package/dist/paths.d.ts
ADDED
package/dist/paths.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
/** Raíz del paquete (packages/linter), tanto desde src/ (tests) como desde dist/. */
|
|
4
|
+
export function packageRoot() {
|
|
5
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
6
|
+
// src/paths.ts o dist/paths.js -> un nivel arriba.
|
|
7
|
+
return path.resolve(here, "..");
|
|
8
|
+
}
|
|
9
|
+
export function rulesDir() {
|
|
10
|
+
return path.join(packageRoot(), "rules");
|
|
11
|
+
}
|
|
12
|
+
export function rulepackPath() {
|
|
13
|
+
return path.join(packageRoot(), "rulepack", "rulepack.json");
|
|
14
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { CompiledRule, ScanResult } from "../contracts/index.js";
|
|
2
|
+
export type ReporterName = "terminal" | "json" | "sarif" | "revision";
|
|
3
|
+
/** JSON determinista: mismas claves, mismo orden, sin tiempos. */
|
|
4
|
+
export declare function reportJson(result: ScanResult, opts?: {
|
|
5
|
+
pretty?: boolean;
|
|
6
|
+
includeTimings?: boolean;
|
|
7
|
+
}): string;
|
|
8
|
+
export declare function reportTerminal(result: ScanResult, opts?: {
|
|
9
|
+
color?: boolean;
|
|
10
|
+
verbose?: boolean;
|
|
11
|
+
}): string;
|
|
12
|
+
export declare function reportSarif(result: ScanResult, rules: CompiledRule[], opts?: {
|
|
13
|
+
uriBase?: string;
|
|
14
|
+
}): string;
|
|
15
|
+
/**
|
|
16
|
+
* Orientación para quien vaya a reescribir el texto (el asistente, desde los hooks o /revisar). Es orientación y no una
|
|
17
|
+
* lista de órdenes: quien reescribe decide qué hallazgos acepta, cuáles ignora y cómo los adapta al contexto.
|
|
18
|
+
* Agrupa por regla para no repetir la orientación en cada hallazgo: qué busca la regla, la orientación (`rewrite_guidance`)
|
|
19
|
+
* y dónde está cada caso. Texto plano, sin color y determinista. Sin --verbose lleva error y warning; con --verbose
|
|
20
|
+
* también los info. Los suprimidos no salen nunca.
|
|
21
|
+
*/
|
|
22
|
+
export declare function reportRevision(result: ScanResult, rules: CompiledRule[], opts?: {
|
|
23
|
+
verbose?: boolean;
|
|
24
|
+
}): string;
|
|
25
|
+
export declare function render(name: ReporterName, result: ScanResult, rules: CompiledRule[], opts?: {
|
|
26
|
+
color?: boolean;
|
|
27
|
+
verbose?: boolean;
|
|
28
|
+
uriBase?: string;
|
|
29
|
+
}): string;
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/* ---------------- JSON ---------------- */
|
|
2
|
+
/** JSON determinista: mismas claves, mismo orden, sin tiempos. */
|
|
3
|
+
export function reportJson(result, opts = {}) {
|
|
4
|
+
const clean = {
|
|
5
|
+
...result,
|
|
6
|
+
durationMs: opts.includeTimings ? result.durationMs : 0,
|
|
7
|
+
files: result.files.map((f) => {
|
|
8
|
+
const { fromCache: _fc, ...rest } = f;
|
|
9
|
+
return { ...rest, durationMs: opts.includeTimings ? f.durationMs : 0 };
|
|
10
|
+
}),
|
|
11
|
+
};
|
|
12
|
+
return JSON.stringify(clean, null, opts.pretty === false ? undefined : 2) + "\n";
|
|
13
|
+
}
|
|
14
|
+
/* ---------------- Terminal ---------------- */
|
|
15
|
+
const COLORS = {
|
|
16
|
+
reset: "\x1b[0m",
|
|
17
|
+
dim: "\x1b[2m",
|
|
18
|
+
bold: "\x1b[1m",
|
|
19
|
+
red: "\x1b[31m",
|
|
20
|
+
yellow: "\x1b[33m",
|
|
21
|
+
cyan: "\x1b[36m",
|
|
22
|
+
green: "\x1b[32m",
|
|
23
|
+
};
|
|
24
|
+
export function reportTerminal(result, opts = {}) {
|
|
25
|
+
const c = (code, s) => (opts.color ? `${COLORS[code]}${s}${COLORS.reset}` : s);
|
|
26
|
+
const lines = [];
|
|
27
|
+
const levelTag = (f) => f.level === "error" ? c("red", "error ") : f.level === "warning" ? c("yellow", "warning") : c("cyan", "info ");
|
|
28
|
+
for (const file of result.files) {
|
|
29
|
+
const active = file.findings.filter((f) => !f.suppressed);
|
|
30
|
+
const suppressed = file.findings.length - active.length;
|
|
31
|
+
if (active.length === 0 && !opts.verbose)
|
|
32
|
+
continue;
|
|
33
|
+
const idx = file.score.index === null ? c("dim", `índice: n/d (${file.score.eligibleWords} palabras, mínimo ${file.score.minWords})`) : `índice ${c("bold", String(file.score.index))}/100`;
|
|
34
|
+
lines.push(`${c("bold", file.path)} ${idx}${suppressed ? c("dim", ` (${suppressed} suprimidos)`) : ""}`);
|
|
35
|
+
for (const f of active) {
|
|
36
|
+
const pos = `${f.range.start.line}:${f.range.start.column}`;
|
|
37
|
+
lines.push(` ${pos.padEnd(8)} ${levelTag(f)} ${f.message} ${c("dim", f.rule)}`);
|
|
38
|
+
if (f.snippet && opts.verbose)
|
|
39
|
+
lines.push(` ${c("dim", `«${f.snippet}»`)}`);
|
|
40
|
+
}
|
|
41
|
+
if (file.score.contributors.length && opts.verbose) {
|
|
42
|
+
lines.push(` ${c("dim", "contribuyentes: " + file.score.contributors.slice(0, 5).map((x) => `${x.rule} (${x.findings})`).join(", "))}`);
|
|
43
|
+
}
|
|
44
|
+
lines.push("");
|
|
45
|
+
}
|
|
46
|
+
const { counts } = result.policy;
|
|
47
|
+
const total = counts.error + counts.warning + counts.info;
|
|
48
|
+
const summary = `${result.files.length} archivo(s), ${total} hallazgo(s): ${counts.error} error, ${counts.warning} warning, ${counts.info} info` + (counts.suppressed ? `, ${counts.suppressed} suprimido(s)` : "");
|
|
49
|
+
lines.push(summary);
|
|
50
|
+
if (result.baseline)
|
|
51
|
+
lines.push(c("dim", `baseline ${result.baseline.path}: ${result.baseline.matched} coincidencias, ${result.baseline.stale} obsoletas`));
|
|
52
|
+
if (result.policy.ok)
|
|
53
|
+
lines.push(c("green", "OK") + c("dim", ` (fail_on: ${result.policy.failOn})`));
|
|
54
|
+
else {
|
|
55
|
+
lines.push(c("red", "FALLO"));
|
|
56
|
+
for (const r of result.policy.reasons)
|
|
57
|
+
lines.push(` - ${r}`);
|
|
58
|
+
}
|
|
59
|
+
return lines.join("\n") + "\n";
|
|
60
|
+
}
|
|
61
|
+
/* ---------------- SARIF 2.1.0 ---------------- */
|
|
62
|
+
export function reportSarif(result, rules, opts = {}) {
|
|
63
|
+
const used = new Set(result.files.flatMap((f) => f.findings.map((x) => x.rule)));
|
|
64
|
+
const ruleList = rules.filter((r) => used.has(r.id)).sort((a, b) => a.id.localeCompare(b.id, "en"));
|
|
65
|
+
const ruleIndex = new Map(ruleList.map((r, i) => [r.id, i]));
|
|
66
|
+
const sarif = {
|
|
67
|
+
$schema: "https://json.schemastore.org/sarif-2.1.0.json",
|
|
68
|
+
version: "2.1.0",
|
|
69
|
+
runs: [
|
|
70
|
+
{
|
|
71
|
+
tool: {
|
|
72
|
+
driver: {
|
|
73
|
+
name: result.tool.name,
|
|
74
|
+
version: result.tool.version,
|
|
75
|
+
informationUri: "https://github.com/Josulo72/textoneitor",
|
|
76
|
+
rules: ruleList.map((r) => ({
|
|
77
|
+
id: r.id,
|
|
78
|
+
name: r.title,
|
|
79
|
+
shortDescription: { text: r.summary },
|
|
80
|
+
fullDescription: { text: r.explanation },
|
|
81
|
+
help: { text: r.rewrite_guidance },
|
|
82
|
+
defaultConfiguration: { level: sarifLevel(r.default_level) },
|
|
83
|
+
properties: { category: r.category, status: r.status, revision: r.revision },
|
|
84
|
+
})),
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
originalUriBaseIds: { PROJECTROOT: { uri: opts.uriBase ?? "file:///" } },
|
|
88
|
+
results: result.files.flatMap((f) => f.findings.map((x) => ({
|
|
89
|
+
ruleId: x.rule,
|
|
90
|
+
ruleIndex: ruleIndex.get(x.rule) ?? -1,
|
|
91
|
+
level: sarifLevel(x.level),
|
|
92
|
+
message: { text: x.message },
|
|
93
|
+
locations: [
|
|
94
|
+
{
|
|
95
|
+
physicalLocation: {
|
|
96
|
+
// SARIF pide una referencia URI válida: espacios, «ñ» o «<texto>» van codificados por segmento.
|
|
97
|
+
artifactLocation: { uri: f.path.replace(/\\/g, "/").split("/").map(encodeURIComponent).join("/"), uriBaseId: "PROJECTROOT" },
|
|
98
|
+
region: {
|
|
99
|
+
startLine: x.range.start.line,
|
|
100
|
+
startColumn: x.range.start.column,
|
|
101
|
+
endLine: x.range.end.line,
|
|
102
|
+
endColumn: x.range.end.column,
|
|
103
|
+
...(x.snippet ? { snippet: { text: x.snippet } } : {}),
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
],
|
|
108
|
+
partialFingerprints: { "textoneitor/v1": x.fingerprint },
|
|
109
|
+
...(x.suppressed ? { suppressions: [{ kind: x.suppressed.by === "inline" ? "inSource" : "external", ...(x.suppressed.reason ? { justification: x.suppressed.reason } : {}) }] } : {}),
|
|
110
|
+
}))),
|
|
111
|
+
properties: {
|
|
112
|
+
policy: result.policy,
|
|
113
|
+
scores: Object.fromEntries(result.files.map((f) => [f.path, f.score.index])),
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
],
|
|
117
|
+
};
|
|
118
|
+
return JSON.stringify(sarif, null, 2) + "\n";
|
|
119
|
+
}
|
|
120
|
+
function sarifLevel(l) {
|
|
121
|
+
return l === "error" ? "error" : l === "warning" ? "warning" : l === "info" ? "note" : "none";
|
|
122
|
+
}
|
|
123
|
+
/* ---------------- Revisión ---------------- */
|
|
124
|
+
/**
|
|
125
|
+
* Orientación para quien vaya a reescribir el texto (el asistente, desde los hooks o /revisar). Es orientación y no una
|
|
126
|
+
* lista de órdenes: quien reescribe decide qué hallazgos acepta, cuáles ignora y cómo los adapta al contexto.
|
|
127
|
+
* Agrupa por regla para no repetir la orientación en cada hallazgo: qué busca la regla, la orientación (`rewrite_guidance`)
|
|
128
|
+
* y dónde está cada caso. Texto plano, sin color y determinista. Sin --verbose lleva error y warning; con --verbose
|
|
129
|
+
* también los info. Los suprimidos no salen nunca.
|
|
130
|
+
*/
|
|
131
|
+
export function reportRevision(result, rules, opts = {}) {
|
|
132
|
+
const byId = new Map(rules.map((r) => [r.id, r]));
|
|
133
|
+
const out = [];
|
|
134
|
+
const cabecera = [
|
|
135
|
+
"Orientación para revisar el texto. Cada hallazgo es una señal, no una orden: acéptalo, ignóralo o reinterprétalo según el contexto.",
|
|
136
|
+
"",
|
|
137
|
+
];
|
|
138
|
+
for (const file of result.files) {
|
|
139
|
+
const active = file.findings.filter((f) => !f.suppressed && (opts.verbose || f.level !== "info"));
|
|
140
|
+
if (!active.length)
|
|
141
|
+
continue;
|
|
142
|
+
const idx = file.score.index === null ? "sin índice (texto corto)" : `índice ${file.score.index}/100`;
|
|
143
|
+
out.push(`${file.path} (${idx})`, "");
|
|
144
|
+
const groups = new Map();
|
|
145
|
+
for (const f of active) {
|
|
146
|
+
const g = groups.get(f.rule);
|
|
147
|
+
if (g)
|
|
148
|
+
g.push(f);
|
|
149
|
+
else
|
|
150
|
+
groups.set(f.rule, [f]);
|
|
151
|
+
}
|
|
152
|
+
for (const [id, fs] of groups) {
|
|
153
|
+
const r = byId.get(id);
|
|
154
|
+
out.push(`${id}${r ? `: ${r.title}` : ""}`);
|
|
155
|
+
if (r)
|
|
156
|
+
out.push(` Qué busca: ${r.summary}`, ` Orientación: ${r.rewrite_guidance}`);
|
|
157
|
+
// Las reglas que miden la estructura del texto entero (longitud de frase) no señalan un sitio: su «fragmento» es solo el principio.
|
|
158
|
+
const wholeText = r?.scope === "document" && r.detector === "structure";
|
|
159
|
+
for (const f of fs) {
|
|
160
|
+
const pos = `${f.range.start.line}:${f.range.start.column}`;
|
|
161
|
+
const where = wholeText ? " Afecta a todo el texto." : f.snippet ? ` Fragmento: "${f.snippet.replace(/\s+/g, " ")}"` : "";
|
|
162
|
+
out.push(` - ${wholeText ? "" : `${pos} `}${f.message}${where}`);
|
|
163
|
+
}
|
|
164
|
+
out.push("");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (!out.length)
|
|
168
|
+
return "Nada que revisar.\n";
|
|
169
|
+
return [...cabecera, ...out].join("\n");
|
|
170
|
+
}
|
|
171
|
+
export function render(name, result, rules, opts = {}) {
|
|
172
|
+
switch (name) {
|
|
173
|
+
case "json":
|
|
174
|
+
return reportJson(result);
|
|
175
|
+
case "sarif":
|
|
176
|
+
return reportSarif(result, rules, { uriBase: opts.uriBase });
|
|
177
|
+
case "revision":
|
|
178
|
+
return reportRevision(result, rules, { verbose: opts.verbose });
|
|
179
|
+
default:
|
|
180
|
+
return reportTerminal(result, { color: opts.color, verbose: opts.verbose });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|