| 1 | // Gramáticas TextMate de las extensiones, con el mismo motor que VS Code: |
| 2 | // vscode-textmate + Oniguruma (WebAssembly). El motor va en el repositorio |
| 3 | // (vendor/, el release/main.js de cada paquete sin cambios) y el WebAssembly se |
| 4 | // baja del CDN con comprobación de integridad. Todo SOLO cuando un fichero |
| 5 | // necesita la primera gramática; sin extensiones de lenguaje no se carga nada. |
| 6 | // |
| 7 | // Los tokens van a Monaco en binario (tokenizeEncoded), igual que en VS Code: |
| 8 | // cada token lleva el índice de su color en el mapa de colores de TextMate, y |
| 9 | // el tema de Monaco se define con ese mismo mapa delante (encodedTokensColors), |
| 10 | // así los dos mapas coinciden índice a índice. Resultado: los colores exactos |
| 11 | // del tema (incluidos los selectores con contexto), cursivas/negritas, y el |
| 12 | // tipo de token (comentario/cadena) que Monaco usa para el autocierre. |
| 13 | import { NOMBRES_PROTO } from './formats.js'; |
| 14 | |
| 15 | const TM_URL = './vendor/vscode-textmate@9.3.2/main.js'; |
| 16 | const ONIG_URL = './vendor/vscode-oniguruma@2.0.1/main.js'; |
| 17 | const WASM_URL = 'https://cdn.jsdelivr.net/npm/vscode-oniguruma@2.0.1/release/onig.wasm'; |
| 18 | const WASM_SRI = 'sha384-bmaXom6bK+vfssb0IcRH2lE1asksQiEsK/WnxAcnHDB3Cx8v3KxZ7BthuGq1DU8v'; |
| 19 | const LIMITE_MS = 500; // por línea, como VS Code: una gramática mala no congela la pestaña |
| 20 | const TIPOS = { other: 0, comment: 1, string: 2, regex: 3 }; |
| 21 | |
| 22 | // ── gramáticas seguras para el motor ───────────────────────────────────────── |
| 23 | // vscode-textmate busca las reglas en objetos normales: `repository[nombre]` y, |
| 24 | // para otra gramática, `_includedGrammars[ámbito]`. Con un nombre como |
| 25 | // «__proto__» o «constructor» la búsqueda acaba en Object.prototype (o en |
| 26 | // Object) y el motor le escribe `.id`: toda la página queda contaminada y las |
| 27 | // gramáticas que se compilan después dejan de pintar. Así que, al instalar y |
| 28 | // al cargar de la base: |
| 29 | // · las claves de repository con nombre de Object.prototype se renombran, y |
| 30 | // los include que las citan también: lo legítimo sigue funcionando y una |
| 31 | // búsqueda ya no puede salir del propio objeto; |
| 32 | // · fuera los include a una gramática con ese nombre (los ámbitos de verdad |
| 33 | // llevan punto: source.x); |
| 34 | // · fuera toda clave «__proto__» (al clonar, el motor la convertiría en el |
| 35 | // prototipo del objeto) y el `id` de las reglas (es la marca que pone el |
| 36 | // motor al compilar). |
| 37 | const RENOMBRE = '$elffuss-safe:'; |
| 38 | const nombreSeguro = k => (NOMBRES_PROTO.has(k) ? RENOMBRE + k : k); |
| 39 | const CAPTURAS = new Set(['captures', 'beginCaptures', 'endCaptures', 'whileCaptures']); |
| 40 | |
| 41 | function includeSeguro(inc) { |
| 42 | if (inc === '$self' || inc === '$base') return inc; |
| 43 | const i = inc.indexOf('#'); |
| 44 | const ambito = i < 0 ? inc : inc.slice(0, i); |
| 45 | if (i !== 0 && NOMBRES_PROTO.has(ambito)) return null; |
| 46 | return i < 0 ? inc : ambito + '#' + nombreSeguro(inc.slice(i + 1)); |
| 47 | } |
| 48 | // Copia sin claves «__proto__» (datos que no son reglas: fileTypes, comment…). |
| 49 | function copiaPlana(v) { |
| 50 | if (Array.isArray(v)) return v.map(copiaPlana); |
| 51 | if (!v || typeof v !== 'object') return v; |
| 52 | const o = {}; |
| 53 | for (const [k, x] of Object.entries(v)) if (k !== '__proto__') o[k] = copiaPlana(x); |
| 54 | return o; |
| 55 | } |
| 56 | function mapaDeReglas(m, renombrar) { |
| 57 | if (!m || typeof m !== 'object' || Array.isArray(m)) return undefined; |
| 58 | const o = {}; |
| 59 | for (const [k, r] of Object.entries(m)) { |
| 60 | if (k === '__proto__' && !renombrar) continue; |
| 61 | const limpia = regla(r); |
| 62 | if (limpia) o[renombrar ? nombreSeguro(k) : k] = limpia; |
| 63 | } |
| 64 | return o; |
| 65 | } |
| 66 | function regla(r) { |
| 67 | if (!r || typeof r !== 'object' || Array.isArray(r)) return null; |
| 68 | const o = {}; |
| 69 | for (const [k, v] of Object.entries(r)) { |
| 70 | if (k === '__proto__' || k === 'id') continue; |
| 71 | if (k === 'include') { |
| 72 | if (typeof v !== 'string') return null; |
| 73 | const inc = includeSeguro(v); |
| 74 | if (inc == null) return null; // la regla entera fuera, como un include que no existe |
| 75 | o.include = inc; |
| 76 | } else if (k === 'patterns') o.patterns = Array.isArray(v) ? v.map(regla).filter(Boolean) : undefined; |
| 77 | else if (k === 'repository') o.repository = mapaDeReglas(v, true); |
| 78 | else if (CAPTURAS.has(k)) o[k] = mapaDeReglas(v, false); |
| 79 | else if (k === 'injections') o.injections = mapaDeReglas(v, false); |
| 80 | else o[k] = copiaPlana(v); |
| 81 | } |
| 82 | return o; |
| 83 | } |
| 84 | export function sanitizeGrammar(g) { |
| 85 | const o = regla(g); |
| 86 | if (!o) throw new Error('no parece una gramática TextMate'); |
| 87 | return o; |
| 88 | } |
| 89 | // Un ámbito que el motor usará de clave (scopeName de una gramática). |
| 90 | export const ambitoValido = s => typeof s === 'string' && !!s.trim() && !NOMBRES_PROTO.has(s); |
| 91 | |
| 92 | let motor = null; |
| 93 | export function loadEngine() { |
| 94 | if (!motor) { |
| 95 | motor = (async () => { |
| 96 | const [tmMod, onigMod] = await Promise.all([import(TM_URL), import(ONIG_URL)]); |
| 97 | const tm = tmMod.default?.Registry ? tmMod.default : tmMod; |
| 98 | const onig = onigMod.default?.loadWASM ? onigMod.default : onigMod; |
| 99 | const res = await fetch(WASM_URL, { integrity: WASM_SRI, credentials: 'omit' }); |
| 100 | if (!res.ok) throw new Error('onig.wasm: ' + res.status); |
| 101 | await onig.loadWASM(await res.arrayBuffer()); |
| 102 | return { tm, onig }; |
| 103 | })(); |
| 104 | motor.catch(() => { motor = null; }); |
| 105 | } |
| 106 | return motor; |
| 107 | } |
| 108 | |
| 109 | // Lenguajes de serie de Monaco (Monarch): su definición tiene un `loader`. |
| 110 | const defDeSerie = (monaco, lang) => monaco.languages.getLanguages().find(l => l.id === lang); |
| 111 | export function canOverride(monaco, lang) { return typeof defDeSerie(monaco, lang)?.loader === 'function'; } |
| 112 | async function cargaDeSerie(monaco, lang) { |
| 113 | try { return await defDeSerie(monaco, lang)?.loader?.(); } catch { return null; } |
| 114 | } |
| 115 | |
| 116 | export class Grammars { |
| 117 | // builtin: lenguajes que ya tenía Monaco antes de las extensiones. |
| 118 | constructor(monaco, { loadFile, onActivate, builtin }) { |
| 119 | Object.assign(this, { monaco, loadFile, onActivate, builtin }); |
| 120 | this.gen = 0; |
| 121 | this.providers = new Map(); // lenguaje → { ready, disposable } |
| 122 | this.registry = null; |
| 123 | this.rawTheme = null; |
| 124 | this._ready = null; |
| 125 | this.restaurando = Promise.resolve(); |
| 126 | this.configure([]); |
| 127 | } |
| 128 | |
| 129 | get active() { return !!this.registry; } |
| 130 | hasGrammarFor(lang) { return this.byLanguage.has(lang); } |
| 131 | |
| 132 | // Gramáticas activas, en orden (la última instalada gana). Las de un |
| 133 | // lenguaje de serie sin Monarch (JSON, por ejemplo) no se aplican: al |
| 134 | // quitarlas no habría forma de devolverle su coloreado. |
| 135 | configure(contribs) { |
| 136 | this.gen++; |
| 137 | this.disposeProviders(); |
| 138 | this.registry = null; |
| 139 | this._ready = null; |
| 140 | this.byLanguage = new Map(); |
| 141 | this.byScope = new Map(); |
| 142 | this.injections = new Map(); |
| 143 | this.skipped = []; |
| 144 | for (const c of contribs) { |
| 145 | if (!ambitoValido(c.scopeName)) continue; |
| 146 | this.byScope.set(c.scopeName, c); |
| 147 | for (const destino of c.injectTo || []) { |
| 148 | if (!this.injections.has(destino)) this.injections.set(destino, []); |
| 149 | this.injections.get(destino).push(c.scopeName); |
| 150 | } |
| 151 | if (!c.language) continue; |
| 152 | if (this.builtin.has(c.language) && !canOverride(this.monaco, c.language)) { this.skipped.push(c); continue; } |
| 153 | this.byLanguage.set(c.language, c); |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | ensure() { |
| 158 | if (this._ready) return this._ready; |
| 159 | const gen = this.gen; |
| 160 | this._ready = (async () => { |
| 161 | const { tm, onig } = await loadEngine(); |
| 162 | if (gen !== this.gen) return this.ensure(); // se reconfiguró mientras bajaba |
| 163 | this.tm = tm; |
| 164 | this.registry = new tm.Registry({ |
| 165 | onigLib: Promise.resolve({ createOnigScanner: p => onig.createOnigScanner(p), createOnigString: s => onig.createOnigString(s) }), |
| 166 | loadGrammar: async scope => { |
| 167 | const c = this.byScope.get(scope); |
| 168 | if (!c) return null; |
| 169 | // también aquí: lo guardado antes de sanearse al instalar |
| 170 | try { const g = await this.loadFile(c.key); if (!g) return null; const s = sanitizeGrammar(g); s.scopeName = scope; return s; } catch { return null; } |
| 171 | }, |
| 172 | getInjections: scope => this.injections.get(scope), |
| 173 | }); |
| 174 | if (this.rawTheme) this.registry.setTheme(this.rawTheme); |
| 175 | await this.onActivate?.(); |
| 176 | })().catch(e => { |
| 177 | if (gen === this.gen) { this._ready = null; this.registry = null; } // se reintenta en el próximo fichero |
| 178 | throw e; |
| 179 | }); |
| 180 | return this._ready; |
| 181 | } |
| 182 | |
| 183 | // Tema TextMate actual → mapa de colores para encodedTokensColors (null si |
| 184 | // el motor aún no está activo: entonces no hay tokens TextMate que pintar). |
| 185 | setTheme(rawTheme) { |
| 186 | this.rawTheme = rawTheme; // ya sin ámbitos peligrosos: toTextMateTheme (themes.js) |
| 187 | if (!this.registry) return null; |
| 188 | this.registry.setTheme(rawTheme); |
| 189 | return this.registry.getColorMap().slice(1); |
| 190 | } |
| 191 | |
| 192 | prepare(lang) { |
| 193 | const c = this.byLanguage.get(lang); |
| 194 | if (!c) return Promise.resolve(false); |
| 195 | const hecho = this.providers.get(lang); |
| 196 | if (hecho) return hecho.ready; |
| 197 | const entry = { disposable: null, ready: null }; |
| 198 | this.providers.set(lang, entry); |
| 199 | const vivo = () => this.providers.get(lang) === entry; |
| 200 | entry.ready = (async () => { |
| 201 | await this.ensure(); |
| 202 | if (!vivo() || !this.registry) return false; // reconfigurado mientras tanto |
| 203 | const m = this.monaco; |
| 204 | const enc = m.languages.getEncodedLanguageId(lang); |
| 205 | const embeddedLanguages = {}; |
| 206 | for (const [scope, l] of Object.entries(c.embeddedLanguages || {})) { |
| 207 | const id = m.languages.getEncodedLanguageId(l); |
| 208 | if (id) embeddedLanguages[scope] = id; |
| 209 | } |
| 210 | const tokenTypes = {}; |
| 211 | for (const [sel, t] of Object.entries(c.tokenTypes || {})) if (t in TIPOS) tokenTypes[sel] = TIPOS[t]; |
| 212 | const grammar = await this.registry.loadGrammarWithConfiguration(c.scopeName, enc, { |
| 213 | embeddedLanguages, tokenTypes, |
| 214 | balancedBracketSelectors: c.balancedBracketScopes ?? ['*'], |
| 215 | unbalancedBracketSelectors: c.unbalancedBracketScopes ?? [], |
| 216 | }); |
| 217 | if (!grammar) throw new Error('no se pudo cargar ' + c.scopeName); |
| 218 | if (!vivo()) return false; |
| 219 | // un lenguaje de serie carga su Monarch en diferido: que termine ANTES |
| 220 | // de registrar el nuestro, o el suyo llegaría después y ganaría |
| 221 | if (this.builtin.has(lang)) { await cargaDeSerie(m, lang); await this.restaurando; await new Promise(r => setTimeout(r, 0)); } |
| 222 | if (!vivo()) return false; |
| 223 | entry.disposable = m.languages.setTokensProvider(lang, proveedor(grammar, this.tm.INITIAL, enc, lang)); |
| 224 | return true; |
| 225 | })().catch(e => { console.warn('[elffuss-ext] gramática de ' + lang + ':', e?.message || e); return false; }); |
| 226 | return entry.ready; |
| 227 | } |
| 228 | |
| 229 | // Fuera los proveedores; a los lenguajes de serie se les devuelve su Monarch. |
| 230 | disposeProviders() { |
| 231 | const pendientes = []; |
| 232 | for (const [lang, e] of this.providers) { |
| 233 | if (!e.disposable) continue; |
| 234 | e.disposable.dispose(); |
| 235 | if (this.builtin?.has(lang)) { |
| 236 | pendientes.push(cargaDeSerie(this.monaco, lang).then(mod => { |
| 237 | if (mod?.language && !this.providers.get(lang)?.disposable) this.monaco.languages.setMonarchTokensProvider(lang, mod.language); |
| 238 | })); |
| 239 | } |
| 240 | } |
| 241 | this.providers = new Map(); |
| 242 | this.restaurando = Promise.all(pendientes); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | function proveedor(grammar, INITIAL, enc, lang) { |
| 247 | // metadatos de un token «normal»: color 1 (primer plano por defecto) y 2 (fondo) |
| 248 | const normal = (enc | (1 << 15) | (2 << 24)) >>> 0; |
| 249 | let avisado = false; |
| 250 | const fallo = e => { if (!avisado) { avisado = true; console.warn('[elffuss-ext] la gramática de ' + lang + ' falló:', e?.message || e); } }; |
| 251 | return { |
| 252 | getInitialState: () => INITIAL, |
| 253 | tokenizeEncoded(line, state) { |
| 254 | try { |
| 255 | const r = grammar.tokenizeLine2(line, state, LIMITE_MS); |
| 256 | // si se pasó del tiempo, el estado de la línea no es fiable: la |
| 257 | // siguiente arranca desde el de esta, como hace VS Code |
| 258 | return { tokens: r.tokens, endState: r.stoppedEarly ? state : r.ruleStack }; |
| 259 | } catch (e) { fallo(e); return { tokens: new Uint32Array([0, normal]), endState: state }; } |
| 260 | }, |
| 261 | // versión con nombres de ámbito (monaco.editor.tokenize, inspección) |
| 262 | tokenize(line, state) { |
| 263 | try { |
| 264 | const r = grammar.tokenizeLine(line, state, LIMITE_MS); |
| 265 | return { tokens: r.tokens.map(t => ({ startIndex: t.startIndex, scopes: t.scopes[t.scopes.length - 1] })), endState: r.stoppedEarly ? state : r.ruleStack }; |
| 266 | } catch (e) { fallo(e); return { tokens: [{ startIndex: 0, scopes: '' }], endState: state }; } |
| 267 | }, |
| 268 | }; |
| 269 | } |