Elffuss BraidHub

utopia-ia/elffuss-code public

main · 9.5 KiBRawPermalink
1// Lenguajes de VS Code (contributes.languages + language-configuration.json)
2// → registro de Monaco y su configuración (comentarios, corchetes, sangría…).
3
4// ¿Repite algo que ya se repite? (a+)+, (a*)*, (x|y+){2,}… es la forma clásica
5// del retroceso catastrófico: con la línea adecuada, la expresión no termina y
6// congela la pestaña. Estas expresiones las ejecuta Monaco en el hilo de la
7// página, así que una así se descarta entera. No caza todo (las alternativas
8// que se solapan, como (a|a)*, o muchos .* seguidos), pero sí lo más común.
9export function nestedRepetition(src) {
10 const pila = [{ rep: false }]; // por grupo abierto: ¿dentro hay algo que se repite?
11 let ultimo = null; // lo que cuantificaría un cuantificador: { rep }
12 for (let i = 0; i < src.length; i++) {
13 const c = src[i];
14 if (c === '\\') { i++; ultimo = { rep: false }; continue; }
15 if (c === '[') {
16 let j = i + 1;
17 if (src[j] === '^') j++;
18 if (src[j] === ']') j++;
19 for (; j < src.length && src[j] !== ']'; j++) if (src[j] === '\\') j++;
20 i = j; ultimo = { rep: false }; continue;
21 }
22 if (c === '(') {
23 pila.push({ rep: false });
24 const m = /^\(\?(?:[:=!]|<[=!]|<[^>]*>)/.exec(src.slice(i, i + 64));
25 if (m) i += m[0].length - 1;
26 ultimo = null; continue;
27 }
28 if (c === ')') {
29 const g = pila.length > 1 ? pila.pop() : { rep: false };
30 if (g.rep) pila[pila.length - 1].rep = true;
31 ultimo = { rep: g.rep }; continue;
32 }
33 if (c === '|') { ultimo = null; continue; }
34 let max = null;
35 if (c === '*' || c === '+') max = Infinity;
36 else if (c === '?') max = 1;
37 else if (c === '{') {
38 const m = /^\{(\d+)(,(\d*))?\}/.exec(src.slice(i, i + 32));
39 if (m) { max = !m[2] ? +m[1] : m[3] === '' ? Infinity : +m[3]; i += m[0].length - 1; }
40 }
41 if (max === null) { ultimo = { rep: false }; continue; }
42 if (src[i + 1] === '?') i++; // perezoso: igual de caro
43 if (ultimo) {
44 if (max > 1 && ultimo.rep) return true;
45 if (max > 1 || ultimo.rep) pila[pila.length - 1].rep = true;
46 }
47 ultimo = null;
48 }
49 return false;
50}
51
52// Expresión de VS Code (cadena o { pattern, flags }) → RegExp. Las que no
53// compilan en JavaScript se descartan, como hace VS Code, y también las de
54// repetición anidada (ver arriba).
55function re(v) {
56 try {
57 const [src, flags] = typeof v === 'string' ? [v, ''] : v && typeof v.pattern === 'string' ? [v.pattern, String(v.flags || '').replace(/[^dgimsuy]/g, '')] : [null];
58 if (src == null || nestedRepetition(src)) return undefined;
59 return new RegExp(src, flags);
60 } catch { /* inválida */ }
61 return undefined;
62}
63
64// Todas las expresiones de un language-configuration.json que se descartarían
65// por peligrosas (para avisar al instalar).
66export function unsafeConfigRegexes(j) {
67 if (!j || typeof j !== 'object') return [];
68 const fuente = v => (typeof v === 'string' ? v : typeof v?.pattern === 'string' ? v.pattern : null);
69 const todas = [j.wordPattern, j.indentationRules?.increaseIndentPattern, j.indentationRules?.decreaseIndentPattern,
70 j.indentationRules?.indentNextLinePattern, j.indentationRules?.unIndentedLinePattern, j.folding?.markers?.start, j.folding?.markers?.end,
71 ...(Array.isArray(j.onEnterRules) ? j.onEnterRules.flatMap(r => [r?.beforeText, r?.afterText, r?.previousLineText]) : [])];
72 return todas.map(fuente).filter(s => s != null && nestedRepetition(s));
73}
74const par = p => (Array.isArray(p) && p.length === 2 && p.every(x => typeof x === 'string') ? { open: p[0], close: p[1] }
75 : p && typeof p.open === 'string' && typeof p.close === 'string' ? { open: p.open, close: p.close, ...(Array.isArray(p.notIn) && { notIn: p.notIn.filter(x => typeof x === 'string') }) }
76 : null);
77const corchetes = l => (Array.isArray(l) ? l.filter(p => Array.isArray(p) && p.length === 2 && p.every(x => typeof x === 'string')) : undefined);
78
79// language-configuration.json → LanguageConfiguration de Monaco.
80export function toLanguageConfiguration(j, monaco) {
81 if (!j || typeof j !== 'object') return {};
82 const out = {};
83 if (j.comments && typeof j.comments === 'object') {
84 const c = {};
85 if (typeof j.comments.lineComment === 'string') c.lineComment = j.comments.lineComment;
86 if (corchetes([j.comments.blockComment])?.length) c.blockComment = j.comments.blockComment;
87 out.comments = c;
88 }
89 if (corchetes(j.brackets)) out.brackets = corchetes(j.brackets);
90 if (corchetes(j.colorizedBracketPairs)) out.colorizedBracketPairs = corchetes(j.colorizedBracketPairs);
91 if (Array.isArray(j.autoClosingPairs)) out.autoClosingPairs = j.autoClosingPairs.map(par).filter(Boolean);
92 if (Array.isArray(j.surroundingPairs)) out.surroundingPairs = j.surroundingPairs.map(par).filter(Boolean).map(({ open, close }) => ({ open, close }));
93 if (typeof j.autoCloseBefore === 'string') out.autoCloseBefore = j.autoCloseBefore;
94 const wp = re(j.wordPattern);
95 if (wp) out.wordPattern = wp;
96 if (j.indentationRules && typeof j.indentationRules === 'object') {
97 const ir = j.indentationRules;
98 const inc = re(ir.increaseIndentPattern), dec = re(ir.decreaseIndentPattern);
99 if (inc && dec) {
100 out.indentationRules = { increaseIndentPattern: inc, decreaseIndentPattern: dec };
101 const nl = re(ir.indentNextLinePattern), un = re(ir.unIndentedLinePattern);
102 if (nl) out.indentationRules.indentNextLinePattern = nl;
103 if (un) out.indentationRules.unIndentedLinePattern = un;
104 }
105 }
106 if (j.folding && typeof j.folding === 'object') {
107 const f = {};
108 if (typeof j.folding.offSide === 'boolean') f.offSide = j.folding.offSide;
109 const s = re(j.folding.markers?.start), e = re(j.folding.markers?.end);
110 if (s && e) f.markers = { start: s, end: e };
111 out.folding = f;
112 }
113 if (Array.isArray(j.onEnterRules) && monaco) {
114 const IA = monaco.languages.IndentAction;
115 const acciones = { none: IA.None, indent: IA.Indent, indentOutdent: IA.IndentOutdent, outdent: IA.Outdent };
116 out.onEnterRules = j.onEnterRules.map(r => {
117 const beforeText = re(r?.beforeText);
118 const indentAction = acciones[r?.action?.indent];
119 if (!beforeText || indentAction === undefined) return null;
120 const regla = { beforeText, action: { indentAction } };
121 const at = re(r.afterText), pl = re(r.previousLineText);
122 if (at) regla.afterText = at;
123 if (pl) regla.previousLineText = pl;
124 if (typeof r.action.appendText === 'string') regla.action.appendText = r.action.appendText;
125 if (Number.isInteger(r.action.removeText)) regla.action.removeText = r.action.removeText;
126 return regla;
127 }).filter(Boolean);
128 }
129 return out;
130}
131
132// Glob de VS Code (filenamePatterns) → RegExp: **, *, ?, {a,b}.
133export function globToRegExp(glob) {
134 let out = '';
135 for (let i = 0; i < glob.length; i++) {
136 const c = glob[i];
137 if (c === '*' && glob[i + 1] === '*') { out += glob[i + 2] === '/' ? '(?:.*/)?' : '.*'; i += glob[i + 2] === '/' ? 2 : 1; }
138 else if (c === '*') out += '[^/]*';
139 else if (c === '?') out += '[^/]';
140 else if (c === '{') { const e = glob.indexOf('}', i); if (e < 0) { out += '\\{'; continue; } out += '(?:' + glob.slice(i + 1, e).split(',').map(x => x.replace(/[.+^$()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')).join('|') + ')'; i = e; }
141 else out += c.replace(/[.+^$()|[\]\\]/g, '\\$&');
142 }
143 return new RegExp('^' + out + '$', 'i');
144}
145
146// Lenguaje para una ruta según las contribuciones activas (las últimas
147// instaladas mandan). Como VS Code: nombre exacto, luego patrones y luego la
148// extensión más larga. La primera línea va aparte (firstLineCandidates): solo
149// cuenta si nadie, ni las extensiones ni lo de serie, reclama el fichero.
150export function matchLanguage(contribs, path) {
151 const base = String(path).split('/').pop();
152 const low = base.toLowerCase();
153 for (let i = contribs.length - 1; i >= 0; i--) if ((contribs[i].filenames || []).some(f => f === base)) return contribs[i].id;
154 for (let i = contribs.length - 1; i >= 0; i--) {
155 for (const g of contribs[i].filenamePatterns || []) {
156 try { if (globToRegExp(g).test(g.includes('/') ? path : base)) return contribs[i].id; } catch { /* patrón roto */ }
157 }
158 }
159 let mejor = null, largo = 0;
160 for (let i = contribs.length - 1; i >= 0; i--) {
161 for (const e of contribs[i].extensions || []) {
162 const el = String(e).toLowerCase();
163 if (el && el.length > largo && low.endsWith(el)) { mejor = contribs[i].id; largo = el.length; }
164 }
165 }
166 return mejor;
167}
168
169// firstLine de las contribuciones, en orden (la última instalada primero):
170// anclada al principio como en VS Code y sin las de repetición anidada.
171export const FIRST_LINE_MAX = 200; // caracteres de la primera línea que se miran
172export function firstLineCandidates(contribs) {
173 const out = [];
174 for (let i = contribs.length - 1; i >= 0; i--) {
175 const fl = contribs[i].firstLine;
176 if (typeof fl !== 'string' || !fl || nestedRepetition(fl)) continue;
177 const src = fl.startsWith('^') ? fl : '^' + fl;
178 try { new RegExp(src); out.push({ id: contribs[i].id, src }); } catch { /* inválida */ }
179 }
180 return out;
181}
182// Corre las expresiones de verdad: en la página va dentro de un Worker con
183// tiempo tope (firstline-worker.js), porque una expresión de un paquete puede
184// no terminar nunca.
185export function matchFirstLine(candidates, line) {
186 const l = String(line ?? '').replace(/^/, '').slice(0, FIRST_LINE_MAX);
187 if (!l) return null;
188 for (const c of candidates) {
189 try { if (new RegExp(c.src).test(l)) return c.id; } catch { /* inválida */ }
190 }
191 return null;
192}