utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | 6f0e1e16a05fbc0858952cc048ca364d38a5d058941b78366852f2ee49658d20 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-10 15:09 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 14:16 +02:00 |
| Parents | 15afc5e2bb8b |
5 files changed
added web/js/ext/grammars.js +194 −0
| @@ -0,0 +1,194 @@ | ||
| 1 | +// Gramáticas TextMate de las extensiones, con el mismo motor que VS Code: | |
| 2 | +// vscode-textmate + Oniguruma (WebAssembly). Se bajan del CDN SOLO cuando un | |
| 3 | +// fichero necesita la primera gramática; sin extensiones de lenguaje no se | |
| 4 | +// carga nada. | |
| 5 | +// | |
| 6 | +// Los tokens van a Monaco en binario (tokenizeEncoded), igual que en VS Code: | |
| 7 | +// cada token lleva el índice de su color en el mapa de colores de TextMate, y | |
| 8 | +// el tema de Monaco se define con ese mismo mapa delante (encodedTokensColors), | |
| 9 | +// así los dos mapas coinciden índice a índice. Resultado: los colores exactos | |
| 10 | +// del tema (incluidos los selectores con contexto), cursivas/negritas, y el | |
| 11 | +// tipo de token (comentario/cadena) que Monaco usa para el autocierre. | |
| 12 | +const TM_URL = 'https://cdn.jsdelivr.net/npm/vscode-textmate@9.3.2/+esm'; | |
| 13 | +const ONIG_URL = 'https://cdn.jsdelivr.net/npm/vscode-oniguruma@2.0.1/+esm'; | |
| 14 | +const WASM_URL = 'https://cdn.jsdelivr.net/npm/vscode-oniguruma@2.0.1/release/onig.wasm'; | |
| 15 | +const WASM_SRI = 'sha384-bmaXom6bK+vfssb0IcRH2lE1asksQiEsK/WnxAcnHDB3Cx8v3KxZ7BthuGq1DU8v'; | |
| 16 | +const LIMITE_MS = 500; // por línea, como VS Code: una gramática mala no congela la pestaña | |
| 17 | +const TIPOS = { other: 0, comment: 1, string: 2, regex: 3 }; | |
| 18 | + | |
| 19 | +let motor = null; | |
| 20 | +export function loadEngine() { | |
| 21 | + if (!motor) { | |
| 22 | + motor = (async () => { | |
| 23 | + const [tmMod, onigMod] = await Promise.all([import(TM_URL), import(ONIG_URL)]); | |
| 24 | + const tm = tmMod.default?.Registry ? tmMod.default : tmMod; | |
| 25 | + const onig = onigMod.default?.loadWASM ? onigMod.default : onigMod; | |
| 26 | + const res = await fetch(WASM_URL, { integrity: WASM_SRI, credentials: 'omit' }); | |
| 27 | + if (!res.ok) throw new Error('onig.wasm: ' + res.status); | |
| 28 | + await onig.loadWASM(await res.arrayBuffer()); | |
| 29 | + return { tm, onig }; | |
| 30 | + })(); | |
| 31 | + motor.catch(() => { motor = null; }); | |
| 32 | + } | |
| 33 | + return motor; | |
| 34 | +} | |
| 35 | + | |
| 36 | +// Lenguajes de serie de Monaco (Monarch): su definición tiene un `loader`. | |
| 37 | +const defDeSerie = (monaco, lang) => monaco.languages.getLanguages().find(l => l.id === lang); | |
| 38 | +export function canOverride(monaco, lang) { return typeof defDeSerie(monaco, lang)?.loader === 'function'; } | |
| 39 | +async function cargaDeSerie(monaco, lang) { | |
| 40 | + try { return await defDeSerie(monaco, lang)?.loader?.(); } catch { return null; } | |
| 41 | +} | |
| 42 | + | |
| 43 | +export class Grammars { | |
| 44 | + // builtin: lenguajes que ya tenía Monaco antes de las extensiones. | |
| 45 | + constructor(monaco, { loadFile, onActivate, builtin }) { | |
| 46 | + Object.assign(this, { monaco, loadFile, onActivate, builtin }); | |
| 47 | + this.gen = 0; | |
| 48 | + this.providers = new Map(); // lenguaje → { ready, disposable } | |
| 49 | + this.registry = null; | |
| 50 | + this.rawTheme = null; | |
| 51 | + this._ready = null; | |
| 52 | + this.restaurando = Promise.resolve(); | |
| 53 | + this.configure([]); | |
| 54 | + } | |
| 55 | + | |
| 56 | + get active() { return !!this.registry; } | |
| 57 | + hasGrammarFor(lang) { return this.byLanguage.has(lang); } | |
| 58 | + | |
| 59 | + // Gramáticas activas, en orden (la última instalada gana). Las de un | |
| 60 | + // lenguaje de serie sin Monarch (JSON, por ejemplo) no se aplican: al | |
| 61 | + // quitarlas no habría forma de devolverle su coloreado. | |
| 62 | + configure(contribs) { | |
| 63 | + this.gen++; | |
| 64 | + this.disposeProviders(); | |
| 65 | + this.registry = null; | |
| 66 | + this._ready = null; | |
| 67 | + this.byLanguage = new Map(); | |
| 68 | + this.byScope = new Map(); | |
| 69 | + this.injections = new Map(); | |
| 70 | + this.skipped = []; | |
| 71 | + for (const c of contribs) { | |
| 72 | + this.byScope.set(c.scopeName, c); | |
| 73 | + for (const destino of c.injectTo || []) { | |
| 74 | + if (!this.injections.has(destino)) this.injections.set(destino, []); | |
| 75 | + this.injections.get(destino).push(c.scopeName); | |
| 76 | + } | |
| 77 | + if (!c.language) continue; | |
| 78 | + if (this.builtin.has(c.language) && !canOverride(this.monaco, c.language)) { this.skipped.push(c); continue; } | |
| 79 | + this.byLanguage.set(c.language, c); | |
| 80 | + } | |
| 81 | + } | |
| 82 | + | |
| 83 | + ensure() { | |
| 84 | + if (this._ready) return this._ready; | |
| 85 | + const gen = this.gen; | |
| 86 | + this._ready = (async () => { | |
| 87 | + const { tm, onig } = await loadEngine(); | |
| 88 | + if (gen !== this.gen) return this.ensure(); // se reconfiguró mientras bajaba | |
| 89 | + this.tm = tm; | |
| 90 | + this.registry = new tm.Registry({ | |
| 91 | + onigLib: Promise.resolve({ createOnigScanner: p => onig.createOnigScanner(p), createOnigString: s => onig.createOnigString(s) }), | |
| 92 | + loadGrammar: async scope => { | |
| 93 | + const c = this.byScope.get(scope); | |
| 94 | + if (!c) return null; | |
| 95 | + try { const g = await this.loadFile(c.key); if (g) g.scopeName = scope; return g || null; } catch { return null; } | |
| 96 | + }, | |
| 97 | + getInjections: scope => this.injections.get(scope), | |
| 98 | + }); | |
| 99 | + if (this.rawTheme) this.registry.setTheme(this.rawTheme); | |
| 100 | + await this.onActivate?.(); | |
| 101 | + })().catch(e => { | |
| 102 | + if (gen === this.gen) { this._ready = null; this.registry = null; } // se reintenta en el próximo fichero | |
| 103 | + throw e; | |
| 104 | + }); | |
| 105 | + return this._ready; | |
| 106 | + } | |
| 107 | + | |
| 108 | + // Tema TextMate actual → mapa de colores para encodedTokensColors (null si | |
| 109 | + // el motor aún no está activo: entonces no hay tokens TextMate que pintar). | |
| 110 | + setTheme(rawTheme) { | |
| 111 | + this.rawTheme = rawTheme; | |
| 112 | + if (!this.registry) return null; | |
| 113 | + this.registry.setTheme(rawTheme); | |
| 114 | + return this.registry.getColorMap().slice(1); | |
| 115 | + } | |
| 116 | + | |
| 117 | + prepare(lang) { | |
| 118 | + const c = this.byLanguage.get(lang); | |
| 119 | + if (!c) return Promise.resolve(false); | |
| 120 | + const hecho = this.providers.get(lang); | |
| 121 | + if (hecho) return hecho.ready; | |
| 122 | + const entry = { disposable: null, ready: null }; | |
| 123 | + this.providers.set(lang, entry); | |
| 124 | + const vivo = () => this.providers.get(lang) === entry; | |
| 125 | + entry.ready = (async () => { | |
| 126 | + await this.ensure(); | |
| 127 | + if (!vivo() || !this.registry) return false; // reconfigurado mientras tanto | |
| 128 | + const m = this.monaco; | |
| 129 | + const enc = m.languages.getEncodedLanguageId(lang); | |
| 130 | + const embeddedLanguages = {}; | |
| 131 | + for (const [scope, l] of Object.entries(c.embeddedLanguages || {})) { | |
| 132 | + const id = m.languages.getEncodedLanguageId(l); | |
| 133 | + if (id) embeddedLanguages[scope] = id; | |
| 134 | + } | |
| 135 | + const tokenTypes = {}; | |
| 136 | + for (const [sel, t] of Object.entries(c.tokenTypes || {})) if (t in TIPOS) tokenTypes[sel] = TIPOS[t]; | |
| 137 | + const grammar = await this.registry.loadGrammarWithConfiguration(c.scopeName, enc, { | |
| 138 | + embeddedLanguages, tokenTypes, | |
| 139 | + balancedBracketSelectors: c.balancedBracketScopes ?? ['*'], | |
| 140 | + unbalancedBracketSelectors: c.unbalancedBracketScopes ?? [], | |
| 141 | + }); | |
| 142 | + if (!grammar) throw new Error('no se pudo cargar ' + c.scopeName); | |
| 143 | + if (!vivo()) return false; | |
| 144 | + // un lenguaje de serie carga su Monarch en diferido: que termine ANTES | |
| 145 | + // de registrar el nuestro, o el suyo llegaría después y ganaría | |
| 146 | + if (this.builtin.has(lang)) { await cargaDeSerie(m, lang); await this.restaurando; await new Promise(r => setTimeout(r, 0)); } | |
| 147 | + if (!vivo()) return false; | |
| 148 | + entry.disposable = m.languages.setTokensProvider(lang, proveedor(grammar, this.tm.INITIAL, enc, lang)); | |
| 149 | + return true; | |
| 150 | + })().catch(e => { console.warn('[elffuss-ext] gramática de ' + lang + ':', e?.message || e); return false; }); | |
| 151 | + return entry.ready; | |
| 152 | + } | |
| 153 | + | |
| 154 | + // Fuera los proveedores; a los lenguajes de serie se les devuelve su Monarch. | |
| 155 | + disposeProviders() { | |
| 156 | + const pendientes = []; | |
| 157 | + for (const [lang, e] of this.providers) { | |
| 158 | + if (!e.disposable) continue; | |
| 159 | + e.disposable.dispose(); | |
| 160 | + if (this.builtin?.has(lang)) { | |
| 161 | + pendientes.push(cargaDeSerie(this.monaco, lang).then(mod => { | |
| 162 | + if (mod?.language && !this.providers.get(lang)?.disposable) this.monaco.languages.setMonarchTokensProvider(lang, mod.language); | |
| 163 | + })); | |
| 164 | + } | |
| 165 | + } | |
| 166 | + this.providers = new Map(); | |
| 167 | + this.restaurando = Promise.all(pendientes); | |
| 168 | + } | |
| 169 | +} | |
| 170 | + | |
| 171 | +function proveedor(grammar, INITIAL, enc, lang) { | |
| 172 | + // metadatos de un token «normal»: color 1 (primer plano por defecto) y 2 (fondo) | |
| 173 | + const normal = (enc | (1 << 15) | (2 << 24)) >>> 0; | |
| 174 | + let avisado = false; | |
| 175 | + const fallo = e => { if (!avisado) { avisado = true; console.warn('[elffuss-ext] la gramática de ' + lang + ' falló:', e?.message || e); } }; | |
| 176 | + return { | |
| 177 | + getInitialState: () => INITIAL, | |
| 178 | + tokenizeEncoded(line, state) { | |
| 179 | + try { | |
| 180 | + const r = grammar.tokenizeLine2(line, state, LIMITE_MS); | |
| 181 | + // si se pasó del tiempo, el estado de la línea no es fiable: la | |
| 182 | + // siguiente arranca desde el de esta, como hace VS Code | |
| 183 | + return { tokens: r.tokens, endState: r.stoppedEarly ? state : r.ruleStack }; | |
| 184 | + } catch (e) { fallo(e); return { tokens: new Uint32Array([0, normal]), endState: state }; } | |
| 185 | + }, | |
| 186 | + // versión con nombres de ámbito (monaco.editor.tokenize, inspección) | |
| 187 | + tokenize(line, state) { | |
| 188 | + try { | |
| 189 | + const r = grammar.tokenizeLine(line, state, LIMITE_MS); | |
| 190 | + return { tokens: r.tokens.map(t => ({ startIndex: t.startIndex, scopes: t.scopes[t.scopes.length - 1] })), endState: r.stoppedEarly ? state : r.ruleStack }; | |
| 191 | + } catch (e) { fallo(e); return { tokens: [{ startIndex: 0, scopes: '' }], endState: state }; } | |
| 192 | + }, | |
| 193 | + }; | |
| 194 | +} |
added web/js/ext/host.js +222 −0
| @@ -0,0 +1,222 @@ | ||
| 1 | +// Host de extensiones de VS Code — nivel 1: solo contribuciones declarativas | |
| 2 | +// (temas de color, gramáticas TextMate, snippets y configuración de lenguajes). | |
| 3 | +// NINGÚN JavaScript de una extensión se ejecuta aquí. | |
| 4 | +// | |
| 5 | +// ide.js lo carga solo si hay alguna extensión activa (o un tema elegido) y el | |
| 6 | +// panel lo carga al abrirse: sin extensiones, el arranque de Code no cambia. | |
| 7 | +// Cada cambio (instalar, activar, desactivar, desinstalar) deshace lo aplicado | |
| 8 | +// y lo vuelve a aplicar desde cero, de uno en uno: más simple y sin restos. | |
| 9 | +// Las gramáticas solo se rehacen si su lista cambia. | |
| 10 | +import * as store from './store.js'; | |
| 11 | +import { BASES, builtinTheme, toMonacoTheme, toTextMateTheme, chromeCss, themeIdFor } from './themes.js'; | |
| 12 | +import { registerSnippets } from './snippets.js'; | |
| 13 | +import { toLanguageConfiguration, matchLanguage } from './languages.js'; | |
| 14 | +import { Grammars } from './grammars.js'; | |
| 15 | +import { uiLang } from '../i18n.js'; | |
| 16 | + | |
| 17 | +export const THEME_PREF = 'elffusscode.theme'; | |
| 18 | +let instancia = null; | |
| 19 | + | |
| 20 | +export function init(monaco, opts = {}) { | |
| 21 | + instancia ??= crear(monaco, opts).catch(e => { instancia = null; throw e; }); | |
| 22 | + return instancia; | |
| 23 | +} | |
| 24 | + | |
| 25 | +async function crear(monaco, { onLanguagesChanged = () => {} } = {}) { | |
| 26 | + const paused = /[?&]noext\b/.test(location.search); | |
| 27 | + const builtin = new Set(monaco.languages.getLanguages().map(l => l.id)); | |
| 28 | + const registrados = new Set(); // lenguajes que registramos (Monaco no permite quitarlos) | |
| 29 | + const listeners = new Set(); | |
| 30 | + let exts = []; | |
| 31 | + let aplicado = []; // disposables de lo aplicado | |
| 32 | + let langContribs = []; | |
| 33 | + let themeIndex = new Map(); // id de tema → { key, label, uiTheme, ext, extName } | |
| 34 | + let pref = leePref(); | |
| 35 | + let actual = 'vs-dark', monacoId = 'vs-dark'; | |
| 36 | + let estilo = null; | |
| 37 | + let firmaGramaticas = '[]'; | |
| 38 | + let cola = Promise.resolve(); // los cambios se aplican de uno en uno | |
| 39 | + | |
| 40 | + const grammars = new Grammars(monaco, { | |
| 41 | + loadFile: store.getFile, | |
| 42 | + builtin, | |
| 43 | + // la primera gramática enciende el motor: el tema se redefine con el mapa | |
| 44 | + // de colores de TextMate antes de pintar ningún token | |
| 45 | + onActivate: () => aplicaTema(actual), | |
| 46 | + }); | |
| 47 | + | |
| 48 | + function leePref() { try { return localStorage.getItem(THEME_PREF) || 'vs-dark'; } catch { return 'vs-dark'; } } | |
| 49 | + function guardaPref(id) { | |
| 50 | + pref = id; | |
| 51 | + try { if (id === 'vs-dark') localStorage.removeItem(THEME_PREF); else localStorage.setItem(THEME_PREF, id); } catch { /* sin almacenamiento */ } | |
| 52 | + } | |
| 53 | + | |
| 54 | + function pintaCromo(tema, id) { | |
| 55 | + if (!estilo) { estilo = document.createElement('style'); estilo.id = 'ext-theme-chrome'; document.head.appendChild(estilo); } | |
| 56 | + estilo.textContent = id === 'vs-dark' ? '' : chromeCss(tema); | |
| 57 | + } | |
| 58 | + | |
| 59 | + let turnoTema = 0; | |
| 60 | + async function aplicaTema(id, { guardar = false } = {}) { | |
| 61 | + const turno = ++turnoTema; | |
| 62 | + let elegido = id, tema = null; | |
| 63 | + if (themeIndex.has(id)) { | |
| 64 | + tema = await store.getFile(themeIndex.get(id).key).catch(() => null); | |
| 65 | + if (!tema) elegido = 'vs-dark'; | |
| 66 | + } else if (!BASES.includes(id)) elegido = 'vs-dark'; | |
| 67 | + // flechas rápidas en el selector: solo cuenta la última petición | |
| 68 | + if (turno !== turnoTema) return actual; | |
| 69 | + tema ??= builtinTheme(elegido); | |
| 70 | + const encoded = grammars.setTheme(toTextMateTheme(tema)); | |
| 71 | + let mid = elegido; | |
| 72 | + if (!tema.builtin) monaco.editor.defineTheme(elegido, toMonacoTheme(tema, encoded)); | |
| 73 | + else if (encoded) { | |
| 74 | + mid = 'elffuss-tm-' + elegido; | |
| 75 | + monaco.editor.defineTheme(mid, { base: elegido, inherit: true, rules: [], colors: {}, encodedTokensColors: encoded }); | |
| 76 | + } | |
| 77 | + monaco.editor.setTheme(mid); | |
| 78 | + actual = elegido; | |
| 79 | + monacoId = mid; | |
| 80 | + pintaCromo(tema, elegido); | |
| 81 | + if (guardar) guardaPref(elegido); | |
| 82 | + return elegido; | |
| 83 | + } | |
| 84 | + | |
| 85 | + async function reaplica() { | |
| 86 | + for (const d of aplicado) { try { d.dispose(); } catch { /* ya fuera */ } } | |
| 87 | + aplicado = []; | |
| 88 | + const activas = paused ? [] : exts.filter(e => e.enabled); | |
| 89 | + | |
| 90 | + langContribs = []; | |
| 91 | + for (const e of activas) { | |
| 92 | + for (const l of e.languages || []) { | |
| 93 | + langContribs.push(l); | |
| 94 | + if (builtin.has(l.id)) continue; // los de serie conservan su configuración | |
| 95 | + if (!registrados.has(l.id)) { | |
| 96 | + monaco.languages.register({ id: l.id, extensions: l.extensions, filenames: l.filenames, filenamePatterns: l.filenamePatterns, firstLine: l.firstLine, aliases: l.aliases, mimetypes: l.mimetypes }); | |
| 97 | + registrados.add(l.id); | |
| 98 | + } | |
| 99 | + if (l.configKey) { | |
| 100 | + const conf = await store.getFile(l.configKey).catch(() => null); | |
| 101 | + if (conf) aplicado.push(monaco.languages.setLanguageConfiguration(l.id, toLanguageConfiguration(conf, monaco))); | |
| 102 | + } | |
| 103 | + } | |
| 104 | + } | |
| 105 | + | |
| 106 | + const porLang = new Map(); | |
| 107 | + for (const e of activas) { | |
| 108 | + for (const s of e.snippets || []) { | |
| 109 | + if (!porLang.has(s.language)) porLang.set(s.language, []); | |
| 110 | + porLang.get(s.language).push({ key: s.key, ext: e.displayName }); | |
| 111 | + } | |
| 112 | + } | |
| 113 | + for (const [lang, fuentes] of porLang) { | |
| 114 | + const cargar = async () => (await Promise.all(fuentes.map(async f => ((await store.getFile(f.key)) || []).map(s => ({ ...s, ext: f.ext }))))).flat(); | |
| 115 | + aplicado.push(registerSnippets(monaco, lang, cargar, s => s.ext)); | |
| 116 | + } | |
| 117 | + | |
| 118 | + // las gramáticas solo se rehacen si cambian: un tema nuevo no obliga a | |
| 119 | + // recompilarlas ni a repintar los ficheros con gramática | |
| 120 | + const gramaticas = activas.flatMap(e => (e.grammars || []).map(g => ({ ...g, ext: e.id }))); | |
| 121 | + const firma = JSON.stringify(gramaticas.map(g => [g.key, g.language, g.scopeName])); | |
| 122 | + if (firma !== firmaGramaticas) { firmaGramaticas = firma; grammars.configure(gramaticas); } | |
| 123 | + | |
| 124 | + themeIndex = new Map(); | |
| 125 | + for (const e of activas) for (const t of e.themes || []) themeIndex.set(t.themeId, { ...t, ext: e.id, extName: e.displayName }); | |
| 126 | + await aplicaTema(pref); | |
| 127 | + } | |
| 128 | + | |
| 129 | + const emit = () => { | |
| 130 | + for (const f of listeners) { try { f(); } catch { /* un oyente roto no para al resto */ } } | |
| 131 | + try { onLanguagesChanged(); } catch { /* — */ } | |
| 132 | + }; | |
| 133 | + function recarga() { | |
| 134 | + const r = cola.then(async () => { exts = await store.list(); await reaplica(); }); | |
| 135 | + cola = r.catch(() => {}); | |
| 136 | + return r.then(emit); | |
| 137 | + } | |
| 138 | + | |
| 139 | + // ── arranque ── | |
| 140 | + try { await store.reconcile(); } catch (e) { console.warn('[elffuss-ext] no pude ordenar las extensiones guardadas:', e?.message || e); } | |
| 141 | + exts = await store.list().catch(() => []); | |
| 142 | + await reaplica(); | |
| 143 | + | |
| 144 | + const quitaTemasDe = id => { if (themeIndex.get(pref)?.ext === id) guardaPref('vs-dark'); }; | |
| 145 | + | |
| 146 | + async function install(src, { onProgress, confirmLarge, signal } = {}) { | |
| 147 | + let bytes, sha256, verified = false, source = 'file', meta = null; | |
| 148 | + const ovsx = await import('./openvsx.js'); | |
| 149 | + if (src instanceof Blob) { | |
| 150 | + bytes = new Uint8Array(await src.arrayBuffer()); | |
| 151 | + sha256 = await ovsx.sha256Hex(bytes); | |
| 152 | + } else { | |
| 153 | + meta = await ovsx.metadata(src.namespace, src.name, src.version || '', { signal }); | |
| 154 | + ({ bytes, sha256, verified } = await ovsx.download(meta, { onProgress, confirmLarge, signal })); | |
| 155 | + source = 'open-vsx'; | |
| 156 | + } | |
| 157 | + const { readVsix } = await import('./vsix.js'); | |
| 158 | + const v = await readVsix(bytes, { lang: uiLang() }); | |
| 159 | + if (meta && v.id !== `${meta.namespace}.${meta.name}`.toLowerCase()) throw new Error(`el paquete dice ser ${v.id}, no ${meta.namespace}.${meta.name}`); | |
| 160 | + if (!v.themes.length && !v.grammars.length && !v.snippets.length && !v.languages.length) { | |
| 161 | + const e = new Error('nothing-applies'); e.code = 'nothing'; throw e; | |
| 162 | + } | |
| 163 | + const previo = exts.find(e => e.id === v.id); | |
| 164 | + const usados = new Set(exts.filter(e => e.id !== v.id).flatMap(e => (e.themes || []).map(t => t.themeId))); | |
| 165 | + const files = new Map(); | |
| 166 | + const k = p => store.fileKey(v.id, v.version, p); | |
| 167 | + const rec = { | |
| 168 | + id: v.id, publisher: v.publisher, name: v.name, version: v.version, | |
| 169 | + displayName: v.displayName, description: v.description.slice(0, 500), | |
| 170 | + license: (meta?.license || v.license || '').slice(0, 200), sha256, verified, source, size: bytes.length, | |
| 171 | + installedAt: previo?.installedAt || Date.now(), enabled: previo ? previo.enabled : true, | |
| 172 | + hasCode: v.analysis.hasCode, ignored: v.analysis.ignored, pack: v.analysis.pack, warnings: v.warnings.slice(0, 20), | |
| 173 | + themes: v.themes.map(t => { const key = k('theme/' + t.index); files.set(key, t.data); return { key, label: t.label, uiTheme: t.uiTheme, themeId: themeIdFor(v.id, t, t.index, usados) }; }), | |
| 174 | + grammars: v.grammars.map(g => { | |
| 175 | + const key = k(g.path); files.set(key, g.data); | |
| 176 | + return { key, scopeName: g.scopeName, language: g.language, embeddedLanguages: g.embeddedLanguages, tokenTypes: g.tokenTypes, injectTo: g.injectTo, balancedBracketScopes: g.balancedBracketScopes, unbalancedBracketScopes: g.unbalancedBracketScopes }; | |
| 177 | + }), | |
| 178 | + snippets: v.snippets.map(s => { const key = k(s.path); files.set(key, s.data); return { key, language: s.language, count: s.data.length }; }), | |
| 179 | + languages: v.languages.map(l => { | |
| 180 | + let configKey = null; | |
| 181 | + if (l.config) { configKey = k(l.configPath); files.set(configKey, l.config); } | |
| 182 | + return { id: l.id, aliases: l.aliases, extensions: l.extensions, filenames: l.filenames, filenamePatterns: l.filenamePatterns, firstLine: l.firstLine, mimetypes: l.mimetypes, configKey }; | |
| 183 | + }), | |
| 184 | + licenseKey: null, | |
| 185 | + }; | |
| 186 | + if (v.licenseText) { rec.licenseKey = k('LICENSE'); files.set(rec.licenseKey, v.licenseText); } | |
| 187 | + await store.put(rec, files); | |
| 188 | + await recarga(); | |
| 189 | + return rec; | |
| 190 | + } | |
| 191 | + | |
| 192 | + async function setEnabled(id, on) { | |
| 193 | + if (!on) quitaTemasDe(id); | |
| 194 | + await store.setEnabled(id, on); | |
| 195 | + await recarga(); | |
| 196 | + } | |
| 197 | + async function uninstall(id) { | |
| 198 | + quitaTemasDe(id); | |
| 199 | + await store.remove(id); | |
| 200 | + await recarga(); | |
| 201 | + } | |
| 202 | + | |
| 203 | + const nombresSerie = { 'vs-dark': 'builtinDark', vs: 'builtinLight', 'hc-black': 'builtinHc', 'hc-light': 'builtinHcLight' }; | |
| 204 | + return { | |
| 205 | + paused, | |
| 206 | + list: () => exts.map(e => ({ ...e })), | |
| 207 | + onChange(fn) { listeners.add(fn); return () => listeners.delete(fn); }, | |
| 208 | + install, setEnabled, uninstall, | |
| 209 | + licenseText: async id => { const e = exts.find(x => x.id === id); return e?.licenseKey ? (await store.getFile(e.licenseKey)) || '' : ''; }, | |
| 210 | + themes: () => [ | |
| 211 | + ...BASES.map(id => ({ id, builtin: true, labelKey: nombresSerie[id], uiTheme: id })), | |
| 212 | + ...[...themeIndex].map(([id, t]) => ({ id, label: t.label, uiTheme: t.uiTheme, ext: t.ext, extName: t.extName })), | |
| 213 | + ], | |
| 214 | + currentTheme: () => actual, | |
| 215 | + themeId: () => monacoId, | |
| 216 | + setTheme: id => aplicaTema(id, { guardar: true }), | |
| 217 | + previewTheme: id => aplicaTema(id), | |
| 218 | + languageForPath: (path, primeraLinea = null) => (paused ? null : matchLanguage(langContribs, path, primeraLinea)), | |
| 219 | + prepareLanguage: async lang => (paused || !grammars.hasGrammarFor(lang) ? false : grammars.prepare(lang)), | |
| 220 | + skippedGrammars: () => grammars.skipped.map(g => ({ ext: g.ext, language: g.language, scopeName: g.scopeName })), | |
| 221 | + }; | |
| 222 | +} |
added web/js/ext/openvsx.js +114 −0
| @@ -0,0 +1,114 @@ | ||
| 1 | +// Cliente de Open VSX (open-vsx.org, de la Eclipse Foundation). La API, los | |
| 2 | +// ficheros sueltos y los .vsix mandan Access-Control-Allow-Origin: *, así que | |
| 3 | +// el navegador habla con Open VSX directamente: sin proxy, y nada de tu | |
| 4 | +// proyecto sale nunca hacia allí — solo lo que buscas y lo que instalas. | |
| 5 | +// (El Marketplace de Microsoft no se usa: sus términos solo permiten sus | |
| 6 | +// productos.) | |
| 7 | + | |
| 8 | +export const BASE = 'https://open-vsx.org'; | |
| 9 | +const ORIGENES_ICONO = new Set(['https://open-vsx.org', 'https://openvsx.eclipsecontent.org']); | |
| 10 | +export const BIG = 25 * 1024 * 1024; // por encima, se pregunta antes de bajar | |
| 11 | +const MAX = 120 * 1024 * 1024; // tope duro de un .vsix | |
| 12 | + | |
| 13 | +class OpenVsxError extends Error { | |
| 14 | + constructor(msg, code) { super(msg); this.code = code; } | |
| 15 | +} | |
| 16 | + | |
| 17 | +async function getJson(url, signal) { | |
| 18 | + let res; | |
| 19 | + try { res = await fetch(url, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); } | |
| 20 | + catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); } | |
| 21 | + if (res.status === 429) throw new OpenVsxError('Open VSX está limitando peticiones', 'rate'); | |
| 22 | + if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, res.status === 404 ? 'notfound' : 'http'); | |
| 23 | + return res.json(); | |
| 24 | +} | |
| 25 | +// solo URLs de la propia API (las de ficheros redirigen después a su CDN) | |
| 26 | +function deOpenVsx(u) { | |
| 27 | + try { const x = new URL(u); return x.origin === BASE ? x.href : null; } catch { return null; } | |
| 28 | +} | |
| 29 | +const seg = s => encodeURIComponent(String(s)); | |
| 30 | + | |
| 31 | +const resumen = e => ({ | |
| 32 | + namespace: String(e.namespace || ''), name: String(e.name || ''), version: String(e.version || ''), | |
| 33 | + displayName: String(e.displayName || e.name || ''), description: String(e.description || ''), | |
| 34 | + downloadCount: Number(e.downloadCount) || 0, verified: !!e.verified, deprecated: !!e.deprecated, | |
| 35 | + icon: (() => { try { const u = new URL(e.files?.icon); return ORIGENES_ICONO.has(u.origin) ? u.href : null; } catch { return null; } })(), | |
| 36 | +}); | |
| 37 | + | |
| 38 | +export async function search(query, { category = '', offset = 0, size = 20, signal } = {}) { | |
| 39 | + const q = new URLSearchParams({ size: String(size), offset: String(offset) }); | |
| 40 | + if (query) q.set('query', query); | |
| 41 | + if (category) q.set('category', category); | |
| 42 | + if (query) q.set('sortBy', 'relevance'); | |
| 43 | + else { q.set('sortBy', 'downloadCount'); q.set('sortOrder', 'desc'); } | |
| 44 | + const j = await getJson(`${BASE}/api/-/search?${q}`, signal); | |
| 45 | + return { total: Number(j.totalSize) || 0, offset: Number(j.offset) || 0, items: (j.extensions || []).map(resumen) }; | |
| 46 | +} | |
| 47 | + | |
| 48 | +export async function metadata(namespace, name, version = '', { signal } = {}) { | |
| 49 | + const j = await getJson(`${BASE}/api/${seg(namespace)}/${seg(name)}${version ? '/' + seg(version) : ''}`, signal); | |
| 50 | + if (j.error) throw new OpenVsxError(String(j.error), 'notfound'); | |
| 51 | + return { | |
| 52 | + ...resumen(j), license: String(j.license || ''), categories: Array.isArray(j.categories) ? j.categories.map(String) : [], | |
| 53 | + files: Object.fromEntries(['download', 'sha256', 'manifest', 'license', 'readme'].map(k => [k, deOpenVsx(j.files?.[k])])), | |
| 54 | + homepage: String(j.homepage || ''), repository: String(j.repository || ''), | |
| 55 | + }; | |
| 56 | +} | |
| 57 | + | |
| 58 | +// package.json publicado: sirve para decir qué aplicaría sin bajar el .vsix. | |
| 59 | +export async function manifest(meta, { signal } = {}) { | |
| 60 | + if (!meta.files.manifest) throw new OpenVsxError('esta versión no publica su package.json', 'notfound'); | |
| 61 | + return getJson(meta.files.manifest, signal); | |
| 62 | +} | |
| 63 | + | |
| 64 | +export async function text(url, { signal, max = 200_000 } = {}) { | |
| 65 | + const u = deOpenVsx(url); | |
| 66 | + if (!u) throw new OpenVsxError('URL fuera de Open VSX', 'http'); | |
| 67 | + const res = await fetch(u, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); | |
| 68 | + if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, 'http'); | |
| 69 | + return (await res.text()).slice(0, max); | |
| 70 | +} | |
| 71 | + | |
| 72 | +export async function sha256Hex(bytes) { | |
| 73 | + const d = await crypto.subtle.digest('SHA-256', bytes); | |
| 74 | + return [...new Uint8Array(d)].map(b => b.toString(16).padStart(2, '0')).join(''); | |
| 75 | +} | |
| 76 | + | |
| 77 | +// Baja el .vsix y comprueba su SHA-256 contra la que publica Open VSX. | |
| 78 | +// `confirmLarge(mb)` decide si seguir con uno de más de 25 MB. | |
| 79 | +export async function download(meta, { onProgress = () => {}, confirmLarge = async () => false, signal } = {}) { | |
| 80 | + if (!meta.files.download) throw new OpenVsxError('esta versión no se puede descargar', 'notfound'); | |
| 81 | + const ctl = new AbortController(); | |
| 82 | + signal?.addEventListener('abort', () => ctl.abort(), { once: true }); | |
| 83 | + let res; | |
| 84 | + try { res = await fetch(meta.files.download, { signal: ctl.signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); } | |
| 85 | + catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); } | |
| 86 | + if (res.status === 429) throw new OpenVsxError('Open VSX está limitando peticiones', 'rate'); | |
| 87 | + if (!res.ok) throw new OpenVsxError(`descarga: ${res.status}`, 'http'); | |
| 88 | + const total = Number(res.headers.get('content-length')) || 0; | |
| 89 | + if (total > MAX) { ctl.abort(); throw new OpenVsxError(`demasiado grande (${(total / 1048576).toFixed(0)} MB)`, 'big'); } | |
| 90 | + if (total > BIG && !(await confirmLarge(Math.round(total / 1048576)))) { ctl.abort(); throw new OpenVsxError('cancelado', 'cancel'); } | |
| 91 | + const reader = res.body.getReader(); | |
| 92 | + const trozos = []; | |
| 93 | + let n = 0; | |
| 94 | + for (;;) { | |
| 95 | + const { done, value } = await reader.read(); | |
| 96 | + if (done) break; | |
| 97 | + n += value.length; | |
| 98 | + if (n > MAX) { ctl.abort(); throw new OpenVsxError('demasiado grande', 'big'); } | |
| 99 | + trozos.push(value); | |
| 100 | + onProgress(n, total); | |
| 101 | + } | |
| 102 | + const bytes = new Uint8Array(n); | |
| 103 | + let o = 0; | |
| 104 | + for (const t of trozos) { bytes.set(t, o); o += t.length; } | |
| 105 | + const sha = await sha256Hex(bytes); | |
| 106 | + let publicada = null; | |
| 107 | + if (meta.files.sha256) { | |
| 108 | + try { publicada = (await text(meta.files.sha256, { signal: ctl.signal, max: 200 })).trim().split(/\s+/)[0].toLowerCase(); } | |
| 109 | + catch { publicada = null; } | |
| 110 | + if (!/^[0-9a-f]{64}$/.test(publicada || '')) publicada = null; // no es una suma: como si no la publicara | |
| 111 | + } | |
| 112 | + if (publicada && publicada !== sha) throw new OpenVsxError('la suma SHA-256 no coincide con la publicada', 'sha'); | |
| 113 | + return { bytes, sha256: sha, verified: !!publicada }; | |
| 114 | +} |
added web/js/ext/store.js +121 −0
| @@ -0,0 +1,121 @@ | ||
| 1 | +// Extensiones instaladas, en su PROPIA base IndexedDB (elffuss-code-ext): así | |
| 2 | +// db.js no sube de versión y otra pestaña abierta con la versión vieja no | |
| 3 | +// bloquea la actualización. Nada de OPFS: con ?test-opfs la raíz de OPFS ES el | |
| 4 | +// proyecto, y los ficheros de las extensiones aparecerían en el árbol y para | |
| 5 | +// el agente. | |
| 6 | +// | |
| 7 | +// ext id → registro (versión, sha256, licencia, activa, contribuciones…) | |
| 8 | +// files "id@versión/ruta" → contenido ya parseado (tema, gramática…) | |
| 9 | +// meta marcas internas | |
| 10 | +// | |
| 11 | +// La lista [{id, version, enabled}] se refleja en kv «extensions» de la base | |
| 12 | +// principal, que es lo que ven el inventario y la copia del espacio de trabajo. | |
| 13 | +import * as maindb from '../db.js'; | |
| 14 | + | |
| 15 | +const NAME = 'elffuss-code-ext', VERSION = 1; | |
| 16 | +const MIRROR = 'extensions'; | |
| 17 | +let dbp = null; | |
| 18 | + | |
| 19 | +function open() { | |
| 20 | + dbp ??= new Promise((resolve, reject) => { | |
| 21 | + const req = indexedDB.open(NAME, VERSION); | |
| 22 | + req.onupgradeneeded = () => { | |
| 23 | + for (const s of ['ext', 'files', 'meta']) if (!req.result.objectStoreNames.contains(s)) req.result.createObjectStore(s); | |
| 24 | + }; | |
| 25 | + req.onsuccess = () => { | |
| 26 | + const db = req.result; | |
| 27 | + db.onversionchange = () => { db.close(); dbp = null; }; // no bloquear una versión futura | |
| 28 | + resolve(db); | |
| 29 | + }; | |
| 30 | + req.onerror = () => { dbp = null; reject(req.error); }; | |
| 31 | + req.onblocked = () => { dbp = null; reject(new Error('base de extensiones bloqueada por otra pestaña')); }; | |
| 32 | + }); | |
| 33 | + return dbp; | |
| 34 | +} | |
| 35 | +const done = req => new Promise((res, rej) => { req.onsuccess = () => res(req.result); req.onerror = () => rej(req.error); }); | |
| 36 | +const txDone = tx => new Promise((res, rej) => { tx.oncomplete = () => res(); tx.onerror = () => rej(tx.error); tx.onabort = () => rej(tx.error || new Error('transacción abortada')); }); | |
| 37 | + | |
| 38 | +export const fileKey = (id, version, path) => `${id}@${version}/${path}`; | |
| 39 | + | |
| 40 | +export async function list() { | |
| 41 | + const db = await open(); | |
| 42 | + const recs = await done(db.transaction('ext').objectStore('ext').getAll()); | |
| 43 | + return recs.sort((a, b) => (a.installedAt || 0) - (b.installedAt || 0)); | |
| 44 | +} | |
| 45 | +export async function get(id) { return done((await open()).transaction('ext').objectStore('ext').get(id)); } | |
| 46 | +export async function getFile(key) { return done((await open()).transaction('files').objectStore('files').get(key)); } | |
| 47 | + | |
| 48 | +// Instala/reemplaza en UNA transacción: registro + ficheros nuevos, y fuera | |
| 49 | +// los de la versión anterior. | |
| 50 | +export async function put(rec, files) { | |
| 51 | + const db = await open(); | |
| 52 | + const tx = db.transaction(['ext', 'files'], 'readwrite'); | |
| 53 | + const prev = await done(tx.objectStore('ext').get(rec.id)); | |
| 54 | + if (prev && prev.version !== rec.version) tx.objectStore('files').delete(rango(`${prev.id}@${prev.version}/`)); | |
| 55 | + for (const [k, v] of files) tx.objectStore('files').put(v, k); | |
| 56 | + tx.objectStore('ext').put(rec, rec.id); | |
| 57 | + await txDone(tx); | |
| 58 | + await writeMirror(); | |
| 59 | +} | |
| 60 | + | |
| 61 | +const rango = prefijo => IDBKeyRange.bound(prefijo, prefijo + ''); | |
| 62 | + | |
| 63 | +export async function remove(id) { | |
| 64 | + const db = await open(); | |
| 65 | + const tx = db.transaction(['ext', 'files'], 'readwrite'); | |
| 66 | + tx.objectStore('files').delete(rango(`${id}@`)); | |
| 67 | + tx.objectStore('ext').delete(id); | |
| 68 | + await txDone(tx); | |
| 69 | + await writeMirror(); | |
| 70 | +} | |
| 71 | + | |
| 72 | +export async function setEnabled(id, enabled) { | |
| 73 | + const db = await open(); | |
| 74 | + const tx = db.transaction('ext', 'readwrite'); | |
| 75 | + const rec = await done(tx.objectStore('ext').get(id)); | |
| 76 | + if (!rec) throw new Error('no instalada: ' + id); | |
| 77 | + rec.enabled = !!enabled; | |
| 78 | + tx.objectStore('ext').put(rec, id); | |
| 79 | + await txDone(tx); | |
| 80 | + await writeMirror(); | |
| 81 | + return rec; | |
| 82 | +} | |
| 83 | + | |
| 84 | +async function writeMirror() { | |
| 85 | + const recs = await list(); | |
| 86 | + await maindb.set('kv', MIRROR, recs.map(r => ({ id: r.id, version: r.version, enabled: !!r.enabled }))); | |
| 87 | + const db = await open(); | |
| 88 | + const tx = db.transaction('meta', 'readwrite'); | |
| 89 | + tx.objectStore('meta').put(true, 'mirrored'); | |
| 90 | + await txDone(tx); | |
| 91 | +} | |
| 92 | + | |
| 93 | +// Al arrancar: la lista de kv «extensions» manda. Si alguien la borró (copia | |
| 94 | +// del espacio de trabajo → «borrar»), se borran también las extensiones; si | |
| 95 | +// nunca llegó a escribirse, se escribe ahora. Y fuera los ficheros huérfanos | |
| 96 | +// (de versiones viejas o de instalaciones a medias). | |
| 97 | +export async function reconcile() { | |
| 98 | + let espejo; | |
| 99 | + try { espejo = await maindb.get('kv', MIRROR); } catch { return; } // sin lectura fiable no se toca nada | |
| 100 | + const db = await open(); | |
| 101 | + const yaEscrito = await done(db.transaction('meta').objectStore('meta').get('mirrored')); | |
| 102 | + let recs = await list(); | |
| 103 | + if (Array.isArray(espejo)) { | |
| 104 | + const enLista = new Map(espejo.filter(e => e && e.id).map(e => [e.id, e])); | |
| 105 | + for (const r of recs) if (!enLista.has(r.id)) await remove(r.id); | |
| 106 | + } else if (espejo == null && yaEscrito) { | |
| 107 | + for (const r of recs) await remove(r.id); | |
| 108 | + } | |
| 109 | + recs = await list(); | |
| 110 | + const vivos = new Set(recs.map(r => `${r.id}@${r.version}/`)); | |
| 111 | + const tx = db.transaction('files', 'readwrite'); | |
| 112 | + const keys = await done(tx.objectStore('files').getAllKeys()); | |
| 113 | + let huerfanos = 0; | |
| 114 | + for (const k of keys) { | |
| 115 | + const i = String(k).indexOf('/'); | |
| 116 | + if (!vivos.has(String(k).slice(0, i + 1))) { tx.objectStore('files').delete(k); huerfanos++; } | |
| 117 | + } | |
| 118 | + await txDone(tx); | |
| 119 | + await writeMirror(); | |
| 120 | + return { huerfanos }; | |
| 121 | +} |
modified web/js/ide.js +41 −4
| @@ -1,11 +1,13 @@ | ||
| 1 | 1 | // IDE: Monaco (el editor de VS Code) + árbol de archivos + pestañas. |
| 2 | 2 | import * as code from './tools/code.js'; |
| 3 | +import * as db from './db.js'; | |
| 3 | 4 | import { fileIcon, folderIcon } from './icons.js'; |
| 4 | 5 | import { renderMarkdown } from './md.js'; |
| 5 | 6 | import { t } from './i18n.js'; |
| 6 | 7 | |
| 7 | 8 | let editor = null; |
| 8 | 9 | let monacoRef = null; |
| 10 | +let ext = null; // extensiones de VS Code (js/ext/host.js), ver loadExt() | |
| 9 | 11 | const tabs = []; // { path, model, dirty, preview } |
| 10 | 12 | let active = null; |
| 11 | 13 | let onDirtyChange = () => {}; |
| @@ -17,7 +19,8 @@ | ||
| 17 | 19 | cpp: 'cpp', sh: 'shell', yml: 'yaml', yaml: 'yaml', toml: 'ini', |
| 18 | 20 | svg: 'xml', xml: 'xml', sql: 'sql', txt: 'plaintext', |
| 19 | 21 | }; |
| 20 | -const langOf = p => LANG[p.split('.').pop().toLowerCase()] || 'plaintext'; | |
| 22 | +// las extensiones instaladas mandan (p. ej. .toml → toml en vez de ini) | |
| 23 | +const langOf = (p, primeraLinea = null) => ext?.languageForPath(p, primeraLinea) || LANG[p.split('.').pop().toLowerCase()] || 'plaintext'; | |
| 21 | 24 | const $ = id => document.getElementById(id); |
| 22 | 25 | |
| 23 | 26 | export async function initEditor() { |
| @@ -30,8 +33,9 @@ | ||
| 30 | 33 | window.require.config({ paths: { vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs' } }); |
| 31 | 34 | await new Promise(res => window.require(['vs/editor/editor.main'], res)); |
| 32 | 35 | monacoRef = window.monaco; |
| 36 | + ext = await loadExt(false); | |
| 33 | 37 | editor = monacoRef.editor.create($('editor'), { |
| 34 | - theme: 'vs-dark', | |
| 38 | + theme: ext ? ext.themeId() : 'vs-dark', | |
| 35 | 39 | automaticLayout: true, |
| 36 | 40 | fontSize: 13, |
| 37 | 41 | minimap: { enabled: false }, |
| @@ -93,8 +97,13 @@ | ||
| 93 | 97 | if (hits.length === 1 && hits[0] !== path) return openFile(hits[0]); |
| 94 | 98 | return alertBar(t('openFailed', { path, e: e.message })); |
| 95 | 99 | } |
| 96 | - tab = { path, model: monacoRef.editor.createModel(content, langOf(path)), dirty: false, preview: false }; | |
| 97 | - tabs.push(tab); | |
| 100 | + const lang = langOf(path, content.slice(0, 500).split('\n')[0]); | |
| 101 | + await ext?.prepareLanguage(lang); // la gramática, antes de que exista el modelo | |
| 102 | + tab = tabs.find(t => t.path === path); // otra llamada pudo abrirla mientras tanto | |
| 103 | + if (!tab) { | |
| 104 | + tab = { path, model: monacoRef.editor.createModel(content, lang), dirty: false, preview: false }; | |
| 105 | + tabs.push(tab); | |
| 106 | + } | |
| 98 | 107 | } |
| 99 | 108 | active = path; |
| 100 | 109 | code.setCurrentFile(path); |
| @@ -732,3 +741,31 @@ | ||
| 732 | 741 | } |
| 733 | 742 | return ul; |
| 734 | 743 | } |
| 744 | + | |
| 745 | +// ---------- extensiones de VS Code (js/ext/) ---------- | |
| 746 | +// Temas de color, gramáticas TextMate, snippets y lenguajes. El host solo se | |
| 747 | +// carga si hay alguna extensión activa o un tema elegido, o al abrir el panel | |
| 748 | +// de extensiones: sin ellas, Code arranca exactamente igual que siempre. | |
| 749 | +let extCarga = null; | |
| 750 | +async function hayExtensiones() { | |
| 751 | + try { const p = localStorage.getItem('elffusscode.theme'); if (p && p !== 'vs-dark') return true; } catch { /* sin almacenamiento */ } | |
| 752 | + const lista = await db.get('kv', 'extensions').catch(() => null); | |
| 753 | + return Array.isArray(lista) && lista.some(e => e && e.enabled); | |
| 754 | +} | |
| 755 | +export async function loadExt(force = true) { | |
| 756 | + if (ext) return ext; | |
| 757 | + if (!monacoRef || (!force && !(await hayExtensiones()))) return null; | |
| 758 | + extCarga ??= import('./ext/host.js').then(m => m.init(monacoRef, { onLanguagesChanged: refreshLanguages })); | |
| 759 | + try { ext = await extCarga; } | |
| 760 | + catch (e) { extCarga = null; console.warn('[elffuss] extensiones no disponibles:', e?.message || e); } | |
| 761 | + return ext; | |
| 762 | +} | |
| 763 | +// Tras instalar, activar o desactivar: cada pestaña abierta, con su lenguaje y | |
| 764 | +// su gramática al día (o de vuelta a lo de serie). | |
| 765 | +async function refreshLanguages() { | |
| 766 | + for (const tab of [...tabs]) { | |
| 767 | + const lang = langOf(tab.path, tab.model.getLineContent(1)); | |
| 768 | + await ext?.prepareLanguage(lang); | |
| 769 | + if (!tab.model.isDisposed() && tab.model.getLanguageId() !== lang) monacoRef.editor.setModelLanguage(tab.model, lang); | |
| 770 | + } | |
| 771 | +} |