utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | d7be1ec7f98fef237f0cd857a020f0c3e9807335d558b6ee05ad7f1ac0ae9afd |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-10 16:37 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 14:16 +02:00 |
| Parents | 86f3b789392d |
26 files changed
modified NOTICE +8 −3
| @@ -11,9 +11,14 @@ | ||
| 11 | 11 | (https://github.com/Sendery/VibeCodeViewer, Apache-2.0) — implementación nativa propia. |
| 12 | 12 | |
| 13 | 13 | --- Extensiones de VS Code (crédito) --- |
| 14 | -Las gramáticas TextMate se aplican con vscode-textmate y vscode-oniguruma | |
| 15 | -(Microsoft, MIT), que se cargan del CDN jsDelivr solo cuando hacen falta; no se | |
| 16 | -incluyen en este repositorio. Los colores TextMate de los temas de serie | |
| 14 | +Las gramáticas TextMate se aplican con vscode-textmate 9.3.2 y vscode-oniguruma | |
| 15 | +2.0.1 (Microsoft, MIT). Su release/main.js va incluido SIN CAMBIOS en | |
| 16 | +web/js/ext/vendor/<paquete>@<versión>/main.js, dentro de un envoltorio de módulo | |
| 17 | +ES (la primera línea, la segunda y la última, que dicen el tamaño y la suma | |
| 18 | +sha384 del original; tests/ext_unit.mjs la comprueba), con su LICENSE al lado y, | |
| 19 | +en vscode-oniguruma, su NOTICES.txt (Oniguruma, K. Kosako, BSD-2-Clause). El | |
| 20 | +WebAssembly de Oniguruma (onig.wasm) se baja de jsDelivr solo cuando hace falta | |
| 21 | +y con comprobación de integridad (SRI). Los colores TextMate de los temas de serie | |
| 17 | 22 | (web/js/ext/themes.js) siguen los temas por defecto de VS Code (Microsoft, MIT). |
| 18 | 23 | Las extensiones se buscan e instalan desde Open VSX (Eclipse Foundation), con la |
| 19 | 24 | licencia que declara cada una. |
modified README.md +10 −3
| @@ -49,7 +49,8 @@ | ||
| 49 | 49 | |
| 50 | 50 | ## VS Code extensions: themes, grammars, snippets |
| 51 | 51 | |
| 52 | -The **Extensions** button in the activity bar searches [Open VSX](https://open-vsx.org) | |
| 52 | +The **Extensions** button in the activity bar (also *View → Extensions…*, or `/extensions` | |
| 53 | +in the chat on small screens) searches [Open VSX](https://open-vsx.org) | |
| 53 | 54 | and installs the *declarative* part of VS Code extensions: **color themes** (with a |
| 54 | 55 | Color Theme picker), **TextMate grammars**, **snippets** and **language configurations** |
| 55 | 56 | (comments, brackets, indentation). You can also install a `.vsix` file. |
| @@ -58,8 +59,14 @@ | ||
| 58 | 59 | extension applies and what would need an extension host (commands, views, debuggers…). |
| 59 | 60 | - **Your project stays in the browser.** Open VSX only sees what you search for and install. |
| 60 | 61 | - Packages are checked against the SHA-256 that Open VSX publishes and kept in IndexedDB. |
| 61 | -- Grammars run on the same engine as VS Code (vscode-textmate + Oniguruma), loaded from | |
| 62 | - the CDN only when a file needs one. Without extensions, nothing extra loads. | |
| 62 | +- Grammars run on the same engine as VS Code (vscode-textmate + Oniguruma), loaded only | |
| 63 | + when a file needs one: the engine is vendored in `web/js/ext/vendor/` (unchanged, MIT) | |
| 64 | + and the Oniguruma WebAssembly comes from jsDelivr with an integrity check. Without | |
| 65 | + extensions, nothing extra loads. | |
| 66 | +- What a package brings is treated as untrusted data: grammars and themes are cleaned | |
| 67 | + of names that would reach `Object.prototype`, snippet details are plain text (no remote | |
| 68 | + images), regular expressions that repeat a repetition are dropped, and `firstLine` | |
| 69 | + patterns run in a Worker with a time limit. The panel lists anything it had to skip. | |
| 63 | 70 | - `?noext` starts with every extension paused (to rescue a tab from a bad grammar). |
| 64 | 71 | |
| 65 | 72 | ## Run locally |
modified tests/ext_fixtures.mjs +106 −0
| @@ -193,3 +193,109 @@ | ||
| 193 | 193 | ['extension/snippets/js.json', JSON.stringify({ 'Elf log': { prefix: 'elflog', body: "console.log('elf', $1);$0", description: 'Log with an elf' } })], |
| 194 | 194 | ]); |
| 195 | 195 | } |
| 196 | + | |
| 197 | +// ── paquetes hostiles o rotos: seguridad y mensajes ────────────────────────── | |
| 198 | +const paquete = (pkg, ficheros) => zip([ | |
| 199 | + ...ENVOLTORIO, | |
| 200 | + ['extension/package.json', JSON.stringify({ publisher: 'elffuss-test', version: '1.0.0', engines: { vscode: '^1.80.0' }, license: 'MIT', ...pkg }, null, 2)], | |
| 201 | + ...ficheros, | |
| 202 | +]); | |
| 203 | + | |
| 204 | +// Gramática que intenta sacar al motor de su repositorio con nombres de | |
| 205 | +// Object.prototype: «#__proto__» escribía Object.prototype.id para TODA la | |
| 206 | +// página. Lleva también reglas legítimas (#kw, y una que se llama | |
| 207 | +// «constructor») que tienen que seguir pintando. El texto va a mano: un objeto | |
| 208 | +// JS con clave __proto__ no la serializaría. Y un tema con un ámbito | |
| 209 | +// «hasOwnProperty», que tumbaba el árbol de temas del motor. | |
| 210 | +export const EVIL = { lang: 'evilscript', ext: '.evil', scope: 'source.evil', kw: '#DD2200', ctor: '#22AA44' }; | |
| 211 | +export const EVIL_GRAMMAR = `{ | |
| 212 | + "scopeName": "source.evil", | |
| 213 | + "patterns": [ | |
| 214 | + { "include": "#__proto__" }, { "include": "#constructor" }, { "include": "#toString" }, | |
| 215 | + { "include": "source.evil#__proto__" }, { "include": "hasOwnProperty" }, { "include": "__proto__#x" }, | |
| 216 | + { "include": "#kw" }, | |
| 217 | + { "begin": "\\\\(", "end": "\\\\)", "id": 1, "__proto__": { "match": "x" }, "patterns": [{ "include": "#valueOf" }], | |
| 218 | + "captures": { "__proto__": { "name": "x" }, "0": { "name": "punctuation.paren.evil" } } } | |
| 219 | + ], | |
| 220 | + "repository": { | |
| 221 | + "kw": { "match": "\\\\bevil\\\\b", "name": "keyword.control.evil" }, | |
| 222 | + "constructor": { "match": "\\\\bctor\\\\b", "name": "entity.name.function.ctor.evil" } | |
| 223 | + } | |
| 224 | +}`; | |
| 225 | +export function hostileGrammarVsix() { | |
| 226 | + const theme = { | |
| 227 | + colors: { 'editor.background': '#101010', 'editor.foreground': '#EEEEEE' }, | |
| 228 | + tokenColors: [ | |
| 229 | + { scope: 'hasOwnProperty', settings: { foreground: '#123123' } }, | |
| 230 | + { scope: ['__proto__.x', 'keyword.control'], settings: { foreground: EVIL.kw } }, | |
| 231 | + { scope: 'entity.name.function', settings: { foreground: EVIL.ctor } }, | |
| 232 | + ], | |
| 233 | + }; | |
| 234 | + return paquete({ | |
| 235 | + name: 'evil', displayName: 'Evil Grammar', | |
| 236 | + contributes: { | |
| 237 | + languages: [{ id: EVIL.lang, extensions: [EVIL.ext] }], | |
| 238 | + grammars: [ | |
| 239 | + { language: EVIL.lang, scopeName: EVIL.scope, path: './evil.tmLanguage.json' }, | |
| 240 | + { scopeName: '__proto__', path: './evil.tmLanguage.json' }, | |
| 241 | + ], | |
| 242 | + themes: [{ label: 'Evil Theme', uiTheme: 'vs-dark', path: './evil-theme.json' }], | |
| 243 | + }, | |
| 244 | + }, [['extension/evil.tmLanguage.json', EVIL_GRAMMAR], ['extension/evil-theme.json', JSON.stringify(theme)]]); | |
| 245 | +} | |
| 246 | + | |
| 247 | +// Snippet cuya descripción y cuerpo llevan imágenes y enlaces en Markdown: si | |
| 248 | +// el detalle se pintara como Markdown, el navegador los pediría a `base`. | |
| 249 | +export function beaconSnippetVsix(base) { | |
| 250 | + const snippets = { Beacon: { | |
| 251 | + prefix: 'zzbeacon', | |
| 252 | + description: ` [click](${base}/link)`, | |
| 253 | + body: ['x', '```', ``, '```'], | |
| 254 | + } }; | |
| 255 | + return paquete({ name: 'beacon', displayName: 'Beacon Snippets', contributes: { snippets: [{ language: 'javascript', path: './s.json' }] } }, | |
| 256 | + [['extension/s.json', JSON.stringify(snippets)]]); | |
| 257 | +} | |
| 258 | + | |
| 259 | +// Dos temas, uno con JSON roto; o (onlyBroken) solo temas que no se pueden leer. | |
| 260 | +export function brokenThemeVsix({ onlyBroken = false } = {}) { | |
| 261 | + const bueno = JSON.stringify({ colors: { 'editor.background': '#0A1A2A', 'tab.activeBackground': '#0A1A2A' }, tokenColors: [] }); | |
| 262 | + const themes = onlyBroken | |
| 263 | + ? [{ label: 'Broken One', path: './themes/broken.json' }, { label: 'Missing One', path: './themes/missing.json' }] | |
| 264 | + : [{ label: 'Good One', uiTheme: 'vs-dark', path: './themes/good.json' }, { label: 'Broken One', path: './themes/broken.json' }]; | |
| 265 | + return paquete({ name: onlyBroken ? 'broken-only' : 'half-broken', displayName: onlyBroken ? 'Broken Only' : 'Half Broken', contributes: { themes } }, | |
| 266 | + [['extension/themes/good.json', bueno], ['extension/themes/broken.json', '{ "colors": { "editor.background": "#000000" ']]); | |
| 267 | +} | |
| 268 | + | |
| 269 | +// Gramática y configuración para JSON: Monaco lo trae sin Monarch, así que ni | |
| 270 | +// la gramática ni la configuración se aplican. | |
| 271 | +export function jsonGrammarVsix() { | |
| 272 | + return paquete({ | |
| 273 | + name: 'json-x', displayName: 'JSON X', | |
| 274 | + contributes: { | |
| 275 | + languages: [{ id: 'json', extensions: ['.json'], configuration: './conf.json' }], | |
| 276 | + grammars: [{ language: 'json', scopeName: 'source.json.x', path: './json.tmLanguage.json' }], | |
| 277 | + }, | |
| 278 | + }, [['extension/conf.json', '{ "comments": { "lineComment": "//" } }'], | |
| 279 | + ['extension/json.tmLanguage.json', JSON.stringify({ scopeName: 'source.json.x', patterns: [{ match: '"', name: 'string.json' }] })]]); | |
| 280 | +} | |
| 281 | + | |
| 282 | +// package.json sin publisher. | |
| 283 | +export function noPublisherVsix() { | |
| 284 | + return zip([...ENVOLTORIO, ['extension/package.json', JSON.stringify({ name: 'nopub', version: '1.0.0', contributes: { themes: [] } })]]); | |
| 285 | +} | |
| 286 | + | |
| 287 | +// Expresiones que pueden no terminar: una firstLine con alternativas que se | |
| 288 | +// solapan (no es repetición anidada, así que pasa la comprobación estática y | |
| 289 | +// la para el Worker), otra con repetición anidada y un wordPattern igual. | |
| 290 | +export const SLOW = { lang: 'slowlang', nest: 'nestlang', firstLine: '^(.|\\s)*z' }; | |
| 291 | +export function slowRegexVsix() { | |
| 292 | + return paquete({ | |
| 293 | + name: 'slow', displayName: 'Slow Regex', | |
| 294 | + contributes: { | |
| 295 | + languages: [ | |
| 296 | + { id: SLOW.lang, extensions: ['.slow'], firstLine: SLOW.firstLine }, | |
| 297 | + { id: SLOW.nest, extensions: ['.nest'], firstLine: '^(a+)+$', configuration: './conf.json' }, | |
| 298 | + ], | |
| 299 | + }, | |
| 300 | + }, [['extension/conf.json', JSON.stringify({ wordPattern: '(a+)+$', brackets: [['(', ')']] })]]); | |
| 301 | +} |
modified tests/ext_unit.mjs +167 −5
| @@ -1,17 +1,32 @@ | ||
| 1 | 1 | // Pruebas en Node (sin navegador) de lo que no necesita Monaco: lectura del |
| 2 | 2 | // .vsix, JSONC/plist, colores, mapeo de temas, lenguajes y snippets. |
| 3 | 3 | // node tests/ext_unit.mjs |
| 4 | -import { parseJsonc, parsePlist, hex6, isHexColor } from '../web/js/ext/formats.js'; | |
| 4 | +import { spawnSync } from 'node:child_process'; | |
| 5 | +import { readFileSync } from 'node:fs'; | |
| 6 | +import { createHash } from 'node:crypto'; | |
| 7 | +import { parseJsonc, parsePlist, hex6, isHexColor, NOMBRES_PROTO } from '../web/js/ext/formats.js'; | |
| 5 | 8 | import { openZip, crc32 } from '../web/js/ext/unzip.js'; |
| 6 | 9 | import { readVsix, analyzeManifest, resolveNls } from '../web/js/ext/vsix.js'; |
| 7 | 10 | import { toMonacoTheme, toTextMateTheme, monarchRules, resolveScope, themeIdFor, chromeCss, builtinTheme, joinPath } from '../web/js/ext/themes.js'; |
| 8 | -import { toLanguageConfiguration, matchLanguage, globToRegExp } from '../web/js/ext/languages.js'; | |
| 9 | -import { normalizeSnippets, replaceStart } from '../web/js/ext/snippets.js'; | |
| 10 | -import { zip, themeVsix, elfscriptVsix, THEME_DARK, ELFS } from './ext_fixtures.mjs'; | |
| 11 | +import { toLanguageConfiguration, matchLanguage, globToRegExp, nestedRepetition, unsafeConfigRegexes, firstLineCandidates, matchFirstLine, FIRST_LINE_MAX } from '../web/js/ext/languages.js'; | |
| 12 | +import { normalizeSnippets, replaceStart, registerSnippets } from '../web/js/ext/snippets.js'; | |
| 13 | +import { sanitizeGrammar } from '../web/js/ext/grammars.js'; | |
| 14 | +import { textoError, textoAviso } from '../web/js/ext/panel.js'; | |
| 15 | +import { STRINGS } from '../web/js/ext/i18n.js'; | |
| 16 | +import tm from '../web/js/ext/vendor/vscode-textmate@9.3.2/main.js'; | |
| 17 | +import { zip, themeVsix, elfscriptVsix, THEME_DARK, ELFS, EVIL_GRAMMAR, brokenThemeVsix, noPublisherVsix, slowRegexVsix, SLOW } from './ext_fixtures.mjs'; | |
| 11 | 18 | |
| 12 | 19 | let fails = 0; |
| 13 | 20 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 14 | 21 | const throws = async (fn, re) => { try { await fn(); return false; } catch (e) { return re ? re.test(e.message) : true; } }; |
| 22 | +const codigo = async fn => { try { await fn(); return null; } catch (e) { return e.code ?? 'sin código: ' + e.message; } }; | |
| 23 | +// En otro proceso, con tiempo tope: lo que ahí se rompa (el prototipo de todos | |
| 24 | +// los objetos) no contamina estas pruebas, y una expresión sin fin no las cuelga. | |
| 25 | +function enOtroProceso(js, timeout = 20000) { | |
| 26 | + const r = spawnSync(process.execPath, ['--input-type=module', '-e', js], { encoding: 'utf8', timeout }); | |
| 27 | + return { out: (r.stdout || '').trim(), err: (r.stderr || '').trim().split('\n').slice(-2).join(' '), colgado: r.error?.code === 'ETIMEDOUT' }; | |
| 28 | +} | |
| 29 | +const VENDOR = new URL('../web/js/ext/vendor/', import.meta.url); | |
| 15 | 30 | |
| 16 | 31 | // ── JSONC ── |
| 17 | 32 | { |
| @@ -113,7 +128,8 @@ | ||
| 113 | 128 | const c = [{ id: 'a', extensions: ['.mk'], filenames: ['Makefile'] }, ...elfs.languages]; |
| 114 | 129 | ok('lenguaje por nombre exacto', matchLanguage(c, 'src/Elffile') === ELFS.lang && matchLanguage(c, 'Makefile') === 'a'); |
| 115 | 130 | ok('lenguaje por extensión (sin distinguir mayúsculas)', matchLanguage(c, 'x/Y.ELFS') === ELFS.lang && matchLanguage(c, 'a.mk') === 'a'); |
| 116 | - ok('lenguaje por patrón y por primera línea', matchLanguage(c, 'book/spells/fire.spell') === ELFS.lang && matchLanguage(c, 'run', '#!/usr/bin/env elfs') === ELFS.lang && matchLanguage(c, 'run', '#!/bin/sh') === null); | |
| 131 | + const fl = firstLineCandidates(c); | |
| 132 | + ok('lenguaje por patrón y por primera línea', matchLanguage(c, 'book/spells/fire.spell') === ELFS.lang && matchFirstLine(fl, '#!/usr/bin/env elfs') === ELFS.lang && matchFirstLine(fl, '#!/bin/sh') === null && matchLanguage(c, 'run') === null); | |
| 117 | 133 | ok('glob: **, * y {a,b}', globToRegExp('**/*.{js,ts}').test('a/b/c.ts') && !globToRegExp('*.js').test('a/b.js')); |
| 118 | 134 | } |
| 119 | 135 | { |
| @@ -128,5 +144,151 @@ | ||
| 128 | 144 | ok('resolveNls: %clave% y {message}', resolveNls({ a: '%k%', b: ['%m%'], c: '%no%' }, { k: 'K', m: { message: 'M' } }).b[0] === 'M'); |
| 129 | 145 | ok('analyzeManifest de un paquete solo con código', (() => { const a = analyzeManifest({ main: 'x.js', contributes: { commands: [{}] } }); return a.hasCode && !a.any; })()); |
| 130 | 146 | |
| 147 | +// ── el motor TextMate va en el repo, sin cambios (y el de jsDelivr no) ── | |
| 148 | +{ | |
| 149 | + // los valores son los del paquete npm (integridad del registro comprobada) | |
| 150 | + const esperado = { 'vscode-textmate@9.3.2': [61242, 'sha384-aJzUwh8/jeVrg5exYESASC3qwtfGKKHUgNPuT5uEM0bmJvnwLbJhuy+//+fZ+tPJ'], | |
| 151 | + 'vscode-oniguruma@2.0.1': [20469, 'sha384-KznAEs+/b3fCQKg6wXrLJQvj0dOjyZQpdCrIpt7hC03S7EovcZMXlHRHRN291Uaj'] }; | |
| 152 | + for (const [dir, [bytes, sri]] of Object.entries(esperado)) { | |
| 153 | + const buf = readFileSync(new URL(dir + '/main.js', VENDOR)); | |
| 154 | + const l1 = buf.indexOf(10), l2 = buf.indexOf(10, l1 + 1); | |
| 155 | + const cabecera = buf.subarray(0, l1).toString(); | |
| 156 | + const original = buf.subarray(l2 + 1, l2 + 1 + bytes); | |
| 157 | + const hash = 'sha384-' + createHash('sha384').update(original).digest('base64'); | |
| 158 | + ok(`vendor ${dir}: el original intacto dentro del envoltorio`, hash === sri && cabecera.includes(`${bytes} bytes, ${sri}`) | |
| 159 | + && buf.subarray(l1 + 1, l2).toString() === 'const module = { exports: {} }, exports = module.exports;' | |
| 160 | + && buf.subarray(l2 + 1 + bytes).toString() === '\nexport default module.exports;\n', hash); | |
| 161 | + } | |
| 162 | + ok('vendor: el motor se importa como módulo ES', typeof tm.Registry === 'function' && typeof tm.INITIAL === 'object'); | |
| 163 | + const src = readFileSync(new URL('../web/js/ext/grammars.js', import.meta.url), 'utf8'); | |
| 164 | + ok('grammars.js no carga código de +esm ni de otro origen (solo onig.wasm, con SRI)', !/\+esm/.test(src) && !/import\(\s*['"`]https?:/.test(src) && /WASM_SRI = 'sha384-/.test(src)); | |
| 165 | +} | |
| 166 | + | |
| 167 | +// ── gramáticas: nada de salir del repositorio por Object.prototype ── | |
| 168 | +{ | |
| 169 | + const hostil = JSON.parse(EVIL_GRAMMAR); | |
| 170 | + const limpia = sanitizeGrammar(hostil); | |
| 171 | + const includes = [], claves = []; | |
| 172 | + (function recorre(v) { | |
| 173 | + if (Array.isArray(v)) return v.forEach(recorre); | |
| 174 | + if (!v || typeof v !== 'object') return; | |
| 175 | + for (const k of Object.keys(v)) { claves.push(k); if (k === 'include') includes.push(v[k]); recorre(v[k]); } | |
| 176 | + })(limpia); | |
| 177 | + const sinProto = inc => { const i = inc.indexOf('#'); return !NOMBRES_PROTO.has(i < 0 ? inc : inc.slice(i + 1)) && (i <= 0 || !NOMBRES_PROTO.has(inc.slice(0, i))); }; | |
| 178 | + ok('gramática: ningún include apunta a un nombre de Object.prototype', includes.length > 0 && includes.every(sinProto), includes.join(' ')); | |
| 179 | + ok('gramática: los include a una gramática llamada como Object.prototype, fuera', !includes.includes('hasOwnProperty') && !includes.some(i => i.startsWith('__proto__#'))); | |
| 180 | + ok('gramática: «constructor» legítimo renombrado a la vez en repository y en su include', '$elffuss-safe:constructor' in limpia.repository && includes.includes('#$elffuss-safe:constructor') && !Object.hasOwn(limpia.repository, 'constructor')); | |
| 181 | + ok('gramática: sin claves «__proto__» ni «id» (la marca del motor)', !claves.includes('__proto__') && !claves.includes('id'), claves.filter(k => k === '__proto__' || k === 'id').join()); | |
| 182 | + const elfs = JSON.parse(new TextDecoder().decode(await openZip(elfscriptVsix()).read('extension/syntaxes/elfs.tmLanguage.json'))); | |
| 183 | + ok('gramática legítima: sale igual que entra', JSON.stringify(sanitizeGrammar(elfs)) === JSON.stringify(elfs)); | |
| 184 | + ok('vsix: la gramática se guarda ya saneada', (await readVsix(elfscriptVsix())).grammars.every(g => JSON.stringify(g.data) === JSON.stringify(sanitizeGrammar(g.data)))); | |
| 185 | + | |
| 186 | + // con el motor de verdad, en otro proceso (Oniguruma de mentira: la escritura | |
| 187 | + // en el prototipo ocurre al compilar las reglas, antes de buscar nada) | |
| 188 | + const prueba = g => ` | |
| 189 | + const tm = (await import(${JSON.stringify(new URL('vscode-textmate@9.3.2/main.js', VENDOR).href)})).default; | |
| 190 | + const g0 = ${g}; | |
| 191 | + const onigLib = Promise.resolve({ createOnigScanner() { throw new Error('stub'); }, createOnigString: s => ({ content: s, dispose() {} }) }); | |
| 192 | + const reg = new tm.Registry({ onigLib, loadGrammar: async s => (s === g0.scopeName ? g0 : null) }); | |
| 193 | + const gr = await reg.loadGrammar(g0.scopeName); | |
| 194 | + try { gr.tokenizeLine('evil ctor (x)', tm.INITIAL); } catch {} | |
| 195 | + console.log(JSON.stringify({ proto: ({}).id ?? null, object: Object.id ?? null, toStr: Object.prototype.toString.id ?? null, valueOf: Object.prototype.valueOf.id ?? null, propia: Object.prototype.hasOwnProperty('id') }));`; | |
| 196 | + const antes = enOtroProceso(prueba(EVIL_GRAMMAR)); | |
| 197 | + ok('motor real SIN sanear: la gramática hostil escribe en Object.prototype (la prueba lo detecta)', /"proto":\d+/.test(antes.out) && /"propia":true/.test(antes.out), antes.out || antes.err); | |
| 198 | + const despues = enOtroProceso(prueba(JSON.stringify(limpia))); | |
| 199 | + ok('motor real con la gramática saneada: Object.prototype, Object y sus métodos intactos', despues.out === '{"proto":null,"object":null,"toStr":null,"valueOf":null,"propia":false}', despues.out || despues.err); | |
| 200 | +} | |
| 201 | + | |
| 202 | +// ── temas: un ámbito «hasOwnProperty» tumbaba el árbol de temas del motor ── | |
| 203 | +{ | |
| 204 | + const tema = { uiTheme: 'vs-dark', colors: {}, tokenColors: [ | |
| 205 | + { scope: ['hasOwnProperty'], settings: { foreground: '#123123' } }, | |
| 206 | + { scope: ['__proto__.x', 'keyword.control'], settings: { foreground: '#DD2200' } }, | |
| 207 | + { scope: ['entity.name.function.constructor'], settings: { foreground: '#22AA44' } }, | |
| 208 | + ] }; | |
| 209 | + const reg = new tm.Registry({ onigLib: Promise.resolve({}), loadGrammar: async () => null }); | |
| 210 | + let crudo = null; | |
| 211 | + try { reg.setTheme({ settings: [{ settings: { foreground: '#111111', background: '#EEEEEE' } }, ...tema.tokenColors] }); } catch (e) { crudo = e.message; } | |
| 212 | + ok('motor real: el ámbito «hasOwnProperty» tal cual revienta setTheme (la prueba lo detecta)', /hasOwnProperty is not a function/.test(crudo || ''), crudo); | |
| 213 | + const tmTema = toTextMateTheme(tema); | |
| 214 | + let limpio = null; | |
| 215 | + try { reg.setTheme(tmTema); } catch (e) { limpio = e.message; } | |
| 216 | + ok('toTextMateTheme: fuera los selectores peligrosos, el resto se queda (constructor incluido)', limpio === null | |
| 217 | + && tmTema.settings.some(s => s.scope?.join() === 'keyword.control') && tmTema.settings.some(s => s.scope?.[0] === 'entity.name.function.constructor') | |
| 218 | + && !tmTema.settings.some(s => s.scope?.some(x => /hasOwnProperty|__proto__/.test(x))), limpio); | |
| 219 | +} | |
| 220 | + | |
| 221 | +// ── plist y traducciones no cambian el prototipo de nada ── | |
| 222 | +{ | |
| 223 | + const p = parsePlist('<plist><dict><key>__proto__</key><dict><key>polluted</key><true/></dict><key>a</key><string>b</string></dict></plist>'); | |
| 224 | + ok('plist: una clave «__proto__» no cambia el prototipo', Object.getPrototypeOf(p) === Object.prototype && p.polluted === undefined && p.a === 'b'); | |
| 225 | + const r = resolveNls(JSON.parse('{"__proto__": {"contributes": {"themes": [1]}}, "a": "%k%"}'), { k: 'K' }); | |
| 226 | + ok('resolveNls: tampoco', Object.getPrototypeOf(r) === Object.prototype && r.contributes === undefined && r.a === 'K'); | |
| 227 | + ok('analyzeManifest: contribuciones que no son listas no lo rompen', analyzeManifest({ contributes: { snippets: {}, grammars: 'x', languages: null } }).any === false); | |
| 228 | +} | |
| 229 | + | |
| 230 | +// ── snippets: el detalle es texto, nunca Markdown (imágenes = peticiones) ── | |
| 231 | +{ | |
| 232 | + let proveedor = null; | |
| 233 | + const monacoFalso = { Range: class { constructor(...a) { this.a = a; } }, languages: { | |
| 234 | + CompletionItemKind: { Snippet: 27 }, CompletionItemInsertTextRule: { InsertAsSnippet: 4 }, | |
| 235 | + registerCompletionItemProvider: (l, p) => { proveedor = p; return { dispose() {} }; } } }; | |
| 236 | + registerSnippets(monacoFalso, 'javascript', async () => [{ prefix: 'zz', name: 'n', description: '', body: 'a\n```\n\n```' }], () => 'Ext'); | |
| 237 | + const { suggestions: [s] } = await proveedor.provideCompletionItems({ getLineContent: () => 'zz', getWordUntilPosition: () => ({ startColumn: 1 }) }, { lineNumber: 1, column: 3 }); | |
| 238 | + ok('snippets: detail y documentation son strings (Monaco los pinta como texto, no Markdown)', s.documentation === 'a\n```\n\n```' && s.detail === ' (Ext)', JSON.stringify([s.detail, s.documentation])); | |
| 239 | +} | |
| 240 | + | |
| 241 | +// ── expresiones de los paquetes: nada de repetición anidada ── | |
| 242 | +{ | |
| 243 | + const malas = ['^(a+)+$', '(a*)*', '(\\w+\\s?)*$', '(x|y+){2,}', '(?:a+){3}', '((a)+)*', '(?<n>b+)+', '(a{1,3})+']; | |
| 244 | + const buenas = ['^(\\t|[ ])*[ ]\\*[^/]*\\*/\\s*$', '^(\\t|[ ])*[ ]\\*([ ]([^\\*]|\\*(?!/))*)?$', '^\\s*/\\*\\*(?!/)([^\\*]|\\*(?!/))*$', | |
| 245 | + '^((.*=>\\s*)|((.*[^\\w]+|\\s*)(if|while|for)\\s*\\(.*\\)\\s*))$', '(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\\'\\"\\,\\.\\<\\>\\/\\?\\s]+)', | |
| 246 | + '[a+]+', '\\(a+\\)+', '(\\d{1,3}\\.)', '^#!.*\\b(bash|zsh|sh)\\b.*|^#\\s*-\\*-[^*]*mode:\\s*shell-script[^*]*-\\*-', '(a+)?b', '(?=a+)']; | |
| 247 | + ok('repetición anidada: detectada', malas.every(nestedRepetition), malas.filter(x => !nestedRepetition(x)).join(' ')); | |
| 248 | + ok('repetición anidada: las de VS Code y las simples pasan', !buenas.some(nestedRepetition), buenas.filter(nestedRepetition).join(' ')); | |
| 249 | + const conf = toLanguageConfiguration({ wordPattern: '(a+)+$', folding: { markers: { start: '^(#+)+region', end: '#end' } }, onEnterRules: [{ beforeText: '(x*)*y', action: { indent: 'indent' } }, { beforeText: '^\\s*x', action: { indent: 'indent' } }] }, { languages: { IndentAction: { None: 0, Indent: 1 } } }); | |
| 250 | + ok('config: las peligrosas se descartan, las demás se quedan', !conf.wordPattern && !conf.folding.markers && conf.onEnterRules.length === 1, JSON.stringify(Object.keys(conf))); | |
| 251 | + ok('config: se pueden listar para avisar', unsafeConfigRegexes({ wordPattern: '(a+)+$', onEnterRules: [{ beforeText: { pattern: '(x*)*y' } }] }).join(' ') === '(a+)+$ (x*)*y'); | |
| 252 | + const fl = firstLineCandidates([{ id: 'a', firstLine: 'elfs' }, { id: 'b', firstLine: '^(a+)+$' }, { id: 'c', firstLine: '(' }]); | |
| 253 | + ok('firstLine: anclada al principio, sin las anidadas ni las inválidas', fl.length === 1 && fl[0].src === '^elfs' && matchFirstLine(fl, 'x elfs') === null && matchFirstLine(fl, 'elfs x') === 'a'); | |
| 254 | + ok('firstLine: solo se miran los primeros ' + FIRST_LINE_MAX + ' caracteres', matchFirstLine([{ id: 'z', src: '^a{' + (FIRST_LINE_MAX + 1) + '}' }], 'a'.repeat(FIRST_LINE_MAX + 50)) === null && matchFirstLine([{ id: 'z', src: '^a{' + FIRST_LINE_MAX + '}' }], 'a'.repeat(FIRST_LINE_MAX + 50)) === 'z'); | |
| 255 | + // el caso de la revisión: antes no terminaba nunca | |
| 256 | + const lang = JSON.stringify(new URL('../web/js/ext/languages.js', import.meta.url).href); | |
| 257 | + const r = enOtroProceso(`const L = await import(${lang}); const c = [{ id: 'evil', extensions: ['.evil'], firstLine: '^(a+)+$' }]; | |
| 258 | + console.log(String(L.matchLanguage(c, 'src/main.js', 'a'.repeat(40) + '!')), String(L.matchFirstLine(L.firstLineCandidates(c), 'a'.repeat(40) + '!')));`, 10000); | |
| 259 | + ok('firstLine ^(a+)+$ con «aaaa…!»: termina (null null)', !r.colgado && r.out === 'null null', r.colgado ? 'COLGADO' : r.out || r.err); | |
| 260 | + const v = await readVsix(slowRegexVsix()); | |
| 261 | + const regex = v.warnings.filter(w => w.kind === 'regex').map(w => w.detail); | |
| 262 | + ok('vsix: firstLine y wordPattern anidados descartados con aviso; la otra firstLine se queda (la para el Worker)', regex.includes('^(a+)+$') && regex.includes('(a+)+$') && v.languages.find(l => l.id === SLOW.nest).firstLine === undefined && v.languages.find(l => l.id === SLOW.lang).firstLine === SLOW.firstLine, JSON.stringify(regex)); | |
| 263 | +} | |
| 264 | + | |
| 265 | +// ── partes rotas, errores con código y textos en los dos idiomas ── | |
| 266 | +{ | |
| 267 | + const medio = await readVsix(brokenThemeVsix()); | |
| 268 | + ok('vsix: el tema roto no tumba el bueno y queda su aviso (tipo, nombre y motivo)', medio.themes.length === 1 && medio.warnings.length === 1 && medio.warnings[0].kind === 'theme' && medio.warnings[0].name === 'Broken One' && medio.warnings[0].code === 'json', JSON.stringify(medio.warnings)); | |
| 269 | + ok('aviso legible: «Theme “Broken One”: not valid JSON (…)»', /^Theme “Broken One”: not valid JSON \(.+\)$/.test(textoAviso(medio.warnings[0])), textoAviso(medio.warnings[0])); | |
| 270 | + const roto = await readVsix(brokenThemeVsix({ onlyBroken: true })); | |
| 271 | + ok('vsix: si todas fallan, ningún tema y un aviso por cada una (JSON roto, fichero que falta)', roto.themes.length === 0 && roto.warnings.map(w => w.code).join() === 'json,missing', JSON.stringify(roto.warnings)); | |
| 272 | + ok('aviso legible de un fichero que falta', textoAviso(roto.warnings[1]) === 'Theme “Missing One”: the file is not in the package', textoAviso(roto.warnings[1])); | |
| 273 | + ok('aviso de la versión anterior (texto suelto): se enseña tal cual', textoAviso('tema x: roto') === 'tema x: roto'); | |
| 274 | + ok('package.json sin publisher → código noname', await codigo(() => readVsix(noPublisherVsix())) === 'noname'); | |
| 275 | + const malo = zip([['extension/package.json', '{ "name": "x", ']]); | |
| 276 | + ok('package.json que no es JSON → código badmanifest', await codigo(() => readVsix(malo)) === 'badmanifest'); | |
| 277 | + const dañado = themeVsix(); | |
| 278 | + const i = new TextDecoder('latin1').decode(dañado).indexOf('extension/package.json') + 'extension/package.json'.length; | |
| 279 | + dañado[i + 5] ^= 0xff; // un byte de los datos comprimidos del package.json | |
| 280 | + ok('zip dañado → código corrupt (con la entrada)', await codigo(() => readVsix(dañado)) === 'corrupt'); | |
| 281 | + const errores = [{ code: 'noname' }, { code: 'badmanifest', message: 'Unexpected end of JSON input' }, { code: 'notfound' }, { code: 'http', status: 503 }, | |
| 282 | + { code: 'big', mb: 130 }, { code: 'mismatch', got: 'a.b', want: 'c.d' }, { code: 'corrupt', entry: 'extension/x.json' }, { code: 'missing' }, | |
| 283 | + { code: 'unreadable', warning: roto.warnings[0] }, { code: 'blocked' }, { name: 'QuotaExceededError' }, { code: 'rate' }, { code: 'sha' }, | |
| 284 | + { code: 'nothing' }, { code: 'notvsix' }, { code: 'cancel' }]; | |
| 285 | + const textos = errores.map(textoError); | |
| 286 | + const español = /\b(sin|respondió|demasiado|paquete|versión|incorrecto|soportad|fichero|está|dice ser)\b/i; | |
| 287 | + ok('errores: todos con su texto en inglés, ninguno en español ni con «Could not do it»', textos.every(t => t && !español.test(t) && !/Could not do it/.test(t)), textos.filter(t => español.test(t) || /Could not do it/.test(t)).join(' | ')); | |
| 288 | + ok('errores: el detalle útil se conserva (estado HTTP, entrada, ids)', textos[3].includes('503') && textos[6].includes('extension/x.json') && textos[5].includes('a.b') && textos[5].includes('c.d'), textos.slice(3, 7).join(' | ')); | |
| 289 | + const faltan = l => Object.keys(STRINGS.en).filter(k => !(k in STRINGS[l])).concat(Object.keys(STRINGS[l]).filter(k => !(k in STRINGS.en))); | |
| 290 | + ok('textos del panel: ES y EN con las mismas claves', !faltan('es').length, faltan('es').join(' ')); | |
| 291 | +} | |
| 292 | + | |
| 131 | 293 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ EXTENSIONES (Node): vsix, formatos, temas, lenguajes y snippets OK'); |
| 132 | 294 | process.exit(fails ? 1 : 0); |
modified tests/extensions.mjs +219 −1
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | // (vscode.theme-monokai y vscode.make, de las «built-in» de VS Code, MIT); si |
| 9 | 9 | // no hay red, se marca NOT RUN y no cuenta como fallo. |
| 10 | 10 | import { chromium } from 'playwright'; |
| 11 | -import { themeVsix, elfscriptVsix, THEME_DARK } from './ext_fixtures.mjs'; | |
| 11 | +import { themeVsix, elfscriptVsix, THEME_DARK, EVIL, EVIL_GRAMMAR, hostileGrammarVsix, beaconSnippetVsix, brokenThemeVsix, jsonGrammarVsix, noPublisherVsix, slowRegexVsix } from './ext_fixtures.mjs'; | |
| 12 | 12 | |
| 13 | 13 | const OUT = (process.env.SCRATCH || '/tmp/elffuss-test'); |
| 14 | 14 | const BASE = process.env.BASE || 'http://localhost:8999'; |
| @@ -68,6 +68,10 @@ | ||
| 68 | 68 | await w('app.js', '// nota\nconst a = 1;\n'); |
| 69 | 69 | await w('notes.elfs', '# hola\nspell fire with 42\n cast "llama"\nend\nᚱune\n'); |
| 70 | 70 | await w('Makefile', '# build\nall: build\n\tgcc -o app main.c\n'); |
| 71 | + await w('a.evil', 'evil ctor (x)\n'); | |
| 72 | + await w('runme', '#!/usr/bin/env elfs\nspell x\nend\n'); | |
| 73 | + // sin extensión y con una primera línea que hace no terminar a ^(.|\s)*z | |
| 74 | + await w('slow-input', ' '.repeat(64) + 'x\n'); | |
| 71 | 75 | }); |
| 72 | 76 | pedidas.length = 0; |
| 73 | 77 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| @@ -101,6 +105,7 @@ | ||
| 101 | 105 | await abre('notes.elfs'); |
| 102 | 106 | ok('.elfs → lenguaje elfscript (de la extensión)', await hasta(async () => (await lenguaje()) === 'elfscript'), await lenguaje()); |
| 103 | 107 | ok('motor TextMate bajado solo ahora (al abrir un fichero con gramática)', await hasta(() => pedidas.some(u => /vscode-textmate@9\.3\.2/.test(u)) && pedidas.some(u => /onig\.wasm/.test(u)))); |
| 108 | +ok('…el motor del propio sitio (vendor/) y nada generado por el CDN (+esm)', pedidas.some(u => u.startsWith(BASE + '/js/ext/vendor/vscode-textmate@9.3.2/main.js')) && pedidas.some(u => u.startsWith(BASE + '/js/ext/vendor/vscode-oniguruma@2.0.1/main.js')) && !pedidas.some(u => /\+esm/.test(u)), pedidas.filter(u => /vscode-|\+esm/.test(u)).join(' ')); | |
| 104 | 109 | ok('gramática: keyword.control con el color exacto del tema', await colorDe('spell', THEME_DARK.control), JSON.stringify(await estilo('spell'))); |
| 105 | 110 | ok('gramática: comentario (color + cursiva) y cadena', (await colorDe('# hola', THEME_DARK.comment)) && (await estilo('# hola'))?.italic && await colorDe('"llama"', THEME_DARK.string), JSON.stringify([await estilo('# hola'), await estilo('"llama"')])); |
| 106 | 111 | ok('gramática: número y gramática incluida (plist .tmLanguage)', (await colorDe('42', THEME_DARK.number)) && await colorDe('ᚱune', THEME_DARK.keyword), JSON.stringify([await estilo('42'), await estilo('ᚱune')])); |
| @@ -155,22 +160,54 @@ | ||
| 155 | 160 | ok('la lista va al inventario del espacio de trabajo (kv «extensions»)', Array.isArray(espejo) && espejo.length === 2 && espejo.every(e => e.enabled), JSON.stringify(espejo)); |
| 156 | 161 | |
| 157 | 162 | // ── F. selector de tema: previsualiza, Escape deshace, Enter elige ── |
| 163 | +// lo que oye un lector de pantalla: combobox → listbox → opción activa | |
| 164 | +const combo = () => p.evaluate(() => { | |
| 165 | + const i = document.querySelector('#ext-themepick input'); | |
| 166 | + const lista = document.getElementById(i.getAttribute('aria-controls')); | |
| 167 | + const activa = document.getElementById(i.getAttribute('aria-activedescendant') || '-'); | |
| 168 | + return { | |
| 169 | + foco: document.activeElement === i, role: i.getAttribute('role'), expanded: i.getAttribute('aria-expanded'), lista: lista?.getAttribute('role'), | |
| 170 | + activa: activa && { role: activa.getAttribute('role'), sel: activa.getAttribute('aria-selected'), theme: activa.dataset.theme, marcada: activa.classList.contains('sel') }, | |
| 171 | + opciones: lista?.querySelectorAll('[role=option]').length, seleccionadas: lista?.querySelectorAll('[aria-selected=true]').length, | |
| 172 | + grupos: [...(lista?.querySelectorAll('[role=group]') || [])].map(g => g.getAttribute('aria-label')), | |
| 173 | + }; | |
| 174 | +}); | |
| 158 | 175 | await p.click('#ext-theme-btn'); |
| 159 | 176 | await p.waitForSelector('#ext-themepick'); |
| 177 | +const c0 = await combo(); | |
| 178 | +ok('selector: combobox con su listbox, una opción activa y grupos con nombre', c0.foco && c0.role === 'combobox' && c0.expanded === 'true' && c0.lista === 'listbox' && c0.opciones >= 5 && c0.seleccionadas === 1 && c0.activa?.role === 'option' && c0.activa.sel === 'true' && c0.grupos.includes('Built-in'), JSON.stringify(c0)); | |
| 160 | 179 | await p.keyboard.press('ArrowUp'); |
| 161 | 180 | const previa = await hasta(async () => (await fondo()) !== rgb(THEME_DARK.bg) && fondo()); |
| 162 | 181 | ok('selector: las flechas previsualizan', !!previa, String(previa)); |
| 182 | +const c1 = await combo(); | |
| 183 | +ok('selector: la opción activa cambia con las flechas y se anuncia (aria-activedescendant)', c1.activa && c1.activa.theme !== c0.activa.theme && c1.activa.sel === 'true' && c1.activa.marcada && c1.seleccionadas === 1, JSON.stringify([c0.activa, c1.activa])); | |
| 163 | 184 | await p.keyboard.press('Escape'); |
| 164 | 185 | ok('selector: Escape deja el tema que había', await hasta(async () => (await fondo()) === rgb(THEME_DARK.bg))); |
| 186 | +ok('selector: al cerrarlo, el foco vuelve al botón que lo abrió', await hasta(() => p.evaluate(() => document.activeElement?.id === 'ext-theme-btn')), await p.evaluate(() => document.activeElement?.id || document.activeElement?.tagName)); | |
| 165 | 187 | await p.click('#ext-theme-btn'); |
| 166 | 188 | await p.waitForSelector('#ext-themepick'); |
| 167 | 189 | await p.click('#ext-themepick .tp-item[data-theme="vs"]'); |
| 168 | 190 | ok('selector: tema claro de serie elegido', await hasta(async () => (await fondo()) === 'rgb(255, 255, 254)'), await fondo()); |
| 169 | 191 | ok('…y la gramática se repinta con colores de Light+', await colorDe('spell', '#AF00DB'), JSON.stringify(await estilo('spell'))); |
| 192 | +// el ● de «sin guardar» con un tema claro (era casi blanco sobre blanco, y es | |
| 193 | +// el único aviso: cerrar la pestaña no pregunta) | |
| 194 | +await abre('app.js'); | |
| 195 | +await p.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); ed.trigger('t', 'type', { text: ' ' }); }); | |
| 196 | +const punto = await hasta(() => p.evaluate(() => { | |
| 197 | + const tab = document.querySelector('#tabs-bar .tab.active'), dot = tab?.querySelector('b.dirty'); | |
| 198 | + if (!dot) return null; | |
| 199 | + const num = c => c.match(/[\d.]+/g).map(Number); | |
| 200 | + const [r, g, b, a = 1] = num(getComputedStyle(dot).color), fondo = num(getComputedStyle(tab).backgroundColor); | |
| 201 | + const L = c => { const [x, y, z] = c.map(v => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; }); return 0.2126 * x + 0.7152 * y + 0.0722 * z; }; | |
| 202 | + const l1 = L([r, g, b].map((v, k) => v * a + fondo[k] * (1 - a))), l2 = L(fondo.slice(0, 3)); | |
| 203 | + return { punto: getComputedStyle(dot).color, pestaña: getComputedStyle(tab).backgroundColor, opacidad: getComputedStyle(dot).opacity, contraste: Math.round((Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05) * 100) / 100 }; | |
| 204 | +})); | |
| 205 | +ok('tema claro: el ● de cambios sin guardar se ve (contraste ≥ 4.5:1 con su pestaña)', punto && punto.contraste >= 4.5 && +punto.opacidad === 1, JSON.stringify(punto)); | |
| 170 | 206 | await p.reload({ waitUntil: 'domcontentloaded' }); |
| 171 | 207 | await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length)); |
| 172 | 208 | ok('el tema elegido sobrevive a la recarga', await hasta(async () => (await fondo()) === 'rgb(255, 255, 254)'), await fondo()); |
| 173 | 209 | // por la paleta de comandos |
| 210 | +await abre('app.js'); | |
| 174 | 211 | await p.keyboard.press(process.platform === 'darwin' ? 'Meta+Shift+P' : 'Control+Shift+P'); |
| 175 | 212 | await p.fill('#pal-input', '>tema de color'); |
| 176 | 213 | let filas = await p.locator('#pal-list .pal-item').count(); |
| @@ -180,6 +217,7 @@ | ||
| 180 | 217 | await p.waitForSelector('#ext-themepick'); |
| 181 | 218 | await p.click(`#ext-themepick .tp-item[data-theme^="x-elffuss-test-elf-theme-elf-dark"]`); |
| 182 | 219 | ok('tema de la extensión elegido desde la paleta', await hasta(async () => (await fondo()) === rgb(THEME_DARK.bg))); |
| 220 | +ok('…y el foco vuelve al editor (la paleta ya no está)', await hasta(() => p.evaluate(() => !!document.activeElement?.closest('#editor'))), await p.evaluate(() => document.activeElement?.className || document.activeElement?.tagName)); | |
| 183 | 221 | |
| 184 | 222 | // ── G. ?noext: todo en pausa ── |
| 185 | 223 | await p.goto(BASE + '/?test-opfs&noext', { waitUntil: 'domcontentloaded' }); |
| @@ -229,6 +267,186 @@ | ||
| 229 | 267 | ok('sin restos en IndexedDB tras desinstalar', restos === 0, String(restos)); |
| 230 | 268 | ok('kv «extensions» vacía', JSON.stringify(await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions'))) === '[]'); |
| 231 | 269 | |
| 270 | +// ── J. paquetes hostiles o rotos, mensajes, teclado y lector de pantalla ── | |
| 271 | +const activo = () => p.evaluate(() => { const a = document.activeElement; return { id: a?.id, cls: a?.className, k: a?.dataset?.k, theme: a?.dataset?.theme, fila: a?.closest?.('.ext-row')?.dataset.id, label: a?.getAttribute?.('aria-label'), pressed: a?.getAttribute?.('aria-pressed') }; }); | |
| 272 | +// J1. cerrar el panel: la X tiene nombre, Escape lo cierra y el foco vuelve | |
| 273 | +await p.click('#settings-close'); | |
| 274 | +await abrePanel(); | |
| 275 | +ok('panel: la X de cerrar tiene nombre («Close»), no solo «✕»', (await p.getAttribute('#settings-close', 'aria-label')) === 'Close'); | |
| 276 | +await p.focus('#ext-q'); | |
| 277 | +await p.keyboard.press('Escape'); | |
| 278 | +ok('panel: Escape lo cierra y el foco vuelve al botón de Extensiones', await hasta(() => p.evaluate(() => document.getElementById('settings-panel').hidden && document.activeElement?.id === 'act-ext')), JSON.stringify(await activo())); | |
| 279 | + | |
| 280 | +// J2. errores en el idioma de la interfaz, como alerta | |
| 281 | +await abrePanel(); | |
| 282 | +const msgNoPub = await instalaFichero('nopub.vsix', noPublisherVsix()); | |
| 283 | +ok('error de un .vsix sin publisher: en inglés, nada de «sin name/publisher»', msgNoPub === 'The package.json does not give its name and publisher.', msgNoPub); | |
| 284 | +ok('…y se anuncia como alerta (role=alert)', (await p.getAttribute('#ext-msg', 'role')) === 'alert'); | |
| 285 | + | |
| 286 | +// J3. lo que no se pudo leer se dice, en la fila y al instalar | |
| 287 | +const msgMedio = await instalaFichero('half.vsix', brokenThemeVsix()); | |
| 288 | +ok('instalada, y el mensaje avisa de lo que no se pudo usar', msgMedio === '“Half Broken” installed. 1 part could not be used.', msgMedio); | |
| 289 | +ok('…anunciado (role=status)', (await p.getAttribute('#ext-msg', 'role')) === 'status'); | |
| 290 | +const filaMedio = filaInstalada('elffuss-test.half-broken'); | |
| 291 | +ok('la fila: «Applies: 1 theme» y el aviso plegado', /Applies: 1 theme\b/.test(await filaMedio.innerText()) && (await filaMedio.locator('details.ext-warn summary').innerText()) === '1 part could not be used', (await filaMedio.innerText()).replace(/\s+/g, ' ')); | |
| 292 | +await filaMedio.locator('details.ext-warn summary').focus(); | |
| 293 | +await p.keyboard.press('Enter'); | |
| 294 | +const desplegado = await filaMedio.locator('details.ext-warn').evaluate(d => ({ open: d.open, li: d.querySelector('li')?.getClientRects().length > 0, texto: d.querySelector('li')?.textContent })); | |
| 295 | +ok('…se despliega con el teclado y dice cuál y por qué', desplegado.open && desplegado.li && /^Theme “Broken One”: not valid JSON \(/.test(desplegado.texto), JSON.stringify(desplegado)); | |
| 296 | +const msgRoto = await instalaFichero('broken.vsix', brokenThemeVsix({ onlyBroken: true })); | |
| 297 | +ok('si no se puede leer nada: lo dice y por qué (no «no trae nada aplicable»)', /^None of the parts of this extension could be read\. Theme “Broken One”: not valid JSON/.test(msgRoto), msgRoto); | |
| 298 | + | |
| 299 | +// J4. lo que no se aplica no se cuenta como aplicado | |
| 300 | +await instalaFichero('json.vsix', jsonGrammarVsix()); | |
| 301 | +const textoJson = (await filaInstalada('elffuss-test.json-x').innerText()).replace(/\s+/g, ' '); | |
| 302 | +ok('gramática y configuración de JSON: «nada aplicable» y las dos en «Not applied»', textoJson.includes('Nothing in this extension can be applied here.') && textoJson.includes('Not applied: json grammar (Monaco keeps its built-in highlighting) · json settings (Monaco keeps its own)') && !/\b1 (grammar|language)\b/.test(textoJson), textoJson); | |
| 303 | + | |
| 304 | +// J5. el foco no se pierde al repintar la lista de instaladas | |
| 305 | +await filaMedio.locator('.ext-theme-chips .ext-chip').first().focus(); | |
| 306 | +await p.keyboard.press('Enter'); | |
| 307 | +ok('elegir tema con el teclado: el foco sigue en su ficha, ahora pulsada', await hasta(async () => { const a = await activo(); return a.fila === 'elffuss-test.half-broken' && a.theme?.startsWith('x-elffuss-test-half-broken') && a.pressed === 'true'; }), JSON.stringify(await activo())); | |
| 308 | +await filaMedio.locator('.ext-toggle').focus(); | |
| 309 | +await p.keyboard.press('Enter'); | |
| 310 | +ok('Desactivar con el teclado: el foco queda en el mismo botón, ahora «Enable Half Broken»', await hasta(async () => { const a = await activo(); return a.k === 'toggle' && a.fila === 'elffuss-test.half-broken' && a.label === 'Enable Half Broken'; }), JSON.stringify(await activo())); | |
| 311 | +await p.keyboard.press('Enter'); | |
| 312 | +ok('…y el aviso que estaba desplegado sigue desplegado tras repintar', await filaMedio.locator('details.ext-warn').evaluate(d => d.open)); | |
| 313 | +ok('Activar: igual («Disable Half Broken»)', await hasta(async () => { const a = await activo(); return a.k === 'toggle' && a.label === 'Disable Half Broken'; }), JSON.stringify(await activo())); | |
| 314 | +await filaMedio.locator('.ext-theme-chips .ext-chip').first().click(); // al desactivar se quitó su tema | |
| 315 | +p.once('dialog', d => d.accept()); | |
| 316 | +await filaInstalada('elffuss-test.json-x').locator('.ext-uninstall').focus(); | |
| 317 | +await p.keyboard.press('Enter'); | |
| 318 | +ok('Desinstalar con el teclado: el foco pasa a la fila siguiente', await hasta(async () => { const a = await activo(); return a.k === 'toggle' && a.fila === 'elffuss-test.half-broken'; }), JSON.stringify(await activo())); | |
| 319 | + | |
| 320 | +// J6. búsqueda (Open VSX simulado): detalle con teclado, nombres accesibles, | |
| 321 | +// estado anunciado, y las fichas de tema no pierden su «on» | |
| 322 | +const FALSA = { namespace: 'elffuss-test', name: 'fake', version: '1.0.0', displayName: 'Fake JSON', description: 'Grammar for JSON', downloadCount: 5, files: {} }; | |
| 323 | +await ctx.route('https://open-vsx.org/api/**', route => { | |
| 324 | + const u = new URL(route.request().url()); | |
| 325 | + const json = (cuerpo, status = 200) => route.fulfill({ status, headers: { 'access-control-allow-origin': '*', 'content-type': 'application/json' }, body: JSON.stringify(cuerpo) }); | |
| 326 | + if (u.pathname === '/api/-/search') return json({ totalSize: 1, offset: 0, extensions: [FALSA] }); | |
| 327 | + if (u.pathname === '/api/elffuss-test/fake/1.0.0') return json({ ...FALSA, license: 'MIT', files: { manifest: 'https://open-vsx.org/api/elffuss-test/fake/1.0.0/file/package.json' } }); | |
| 328 | + if (u.pathname.endsWith('/file/package.json')) return json({ name: 'fake', publisher: 'elffuss-test', contributes: { grammars: [{ language: 'json', scopeName: 'source.json.f', path: './j.json' }], languages: [{ id: 'json', configuration: './c.json' }] } }); | |
| 329 | + return json({ error: 'not found' }, 404); | |
| 330 | +}); | |
| 331 | +await p.fill('#ext-q', 'fake'); | |
| 332 | +await p.press('#ext-q', 'Enter'); | |
| 333 | +const filaFalsa = p.locator('#ext-results .ext-row[data-id="elffuss-test.fake"]'); | |
| 334 | +ok('búsqueda: el resultado llega y se anuncia («1 result»)', await hasta(async () => (await filaFalsa.count()) === 1 && (await p.textContent('#ext-status')) === '1 result'), await p.textContent('#ext-status')); | |
| 335 | +ok('Install con nombre propio para el lector («Install Fake JSON»)', (await filaFalsa.locator('.ext-install').getAttribute('aria-label')) === 'Install Fake JSON'); | |
| 336 | +await filaFalsa.locator('.ext-install').focus(); | |
| 337 | +await p.keyboard.press('Shift+Tab'); | |
| 338 | +const nombreBtn = await activo(); | |
| 339 | +ok('Shift+Tab desde Install: el nombre, que es un botón de detalle plegado', nombreBtn.cls === 'ext-name' && (await p.evaluate(() => document.activeElement.getAttribute('aria-expanded'))) === 'false', JSON.stringify(nombreBtn)); | |
| 340 | +await p.keyboard.press('Enter'); | |
| 341 | +const detalleAbierto = await hasta(() => p.evaluate(() => { const b = document.activeElement, d = document.getElementById(b.getAttribute('aria-controls')); return b.getAttribute('aria-expanded') === 'true' && d && !d.hidden && /Nothing in this extension/.test(d.textContent) && d.textContent; })); | |
| 342 | +ok('Enter: el detalle se despliega (aria-expanded) y dice qué aplicaría, también lo de JSON', !!detalleAbierto && /Not applied: json grammar/.test(detalleAbierto), String(detalleAbierto)); | |
| 343 | +// (isDisabled() de Playwright cuenta aria-disabled como deshabilitado: aquí se | |
| 344 | +// mira la propiedad del DOM, que es la que le quitaría el foco) | |
| 345 | +const inst = await filaFalsa.locator('.ext-install').evaluate(b => { b.focus(); return { aria: b.getAttribute('aria-disabled'), disabled: b.disabled, foco: document.activeElement === b }; }); | |
| 346 | +ok('…y como no aplicaría nada, Install queda inerte pero enfocable (aria-disabled, no disabled)', inst.aria === 'true' && !inst.disabled && inst.foco, JSON.stringify(inst)); | |
| 347 | +const fichaTema = filaMedio.locator('.ext-theme-chips .ext-chip').first(); | |
| 348 | +await hasta(async () => (await fichaTema.getAttribute('aria-pressed')) === 'true'); | |
| 349 | +await p.click('#ext-panel .ext-search .ext-chip[data-cat="Themes"]'); | |
| 350 | +await hasta(async () => (await p.getAttribute('#ext-panel .ext-search .ext-chip[data-cat="Themes"]', 'aria-pressed')) === 'true'); | |
| 351 | +await hasta(async () => (await filaFalsa.count()) === 1); | |
| 352 | +ok('pulsar una categoría no le quita el «on» a la ficha del tema actual', (await fichaTema.getAttribute('class')).includes(' on') && (await fichaTema.getAttribute('aria-pressed')) === 'true', await fichaTema.getAttribute('class')); | |
| 353 | +await p.click('#ext-panel .ext-search .ext-chip[data-cat="Themes"]'); // fuera la categoría (la búsqueda en vivo va sin ella) | |
| 354 | +await hasta(async () => (await p.getAttribute('#ext-panel .ext-search .ext-chip[data-cat="Themes"]', 'aria-pressed')) === 'false'); | |
| 355 | +await ctx.unroute('https://open-vsx.org/api/**'); | |
| 356 | + | |
| 357 | +// J7. gramática hostil: Object.prototype intacto, y las demás gramáticas bien | |
| 358 | +await instalaFichero('elfscript.vsix', elfscriptVsix()); | |
| 359 | +const msgEvil = await instalaFichero('evil.vsix', hostileGrammarVsix()); | |
| 360 | +ok('gramática hostil instalada (avisa del scopeName «__proto__» rechazado)', msgEvil === '“Evil Grammar” installed. 1 part could not be used.', msgEvil); | |
| 361 | +await p.click('#settings-close'); | |
| 362 | +const prototipo = () => p.evaluate(() => JSON.stringify({ proto: ({}).id ?? null, propia: Object.prototype.hasOwnProperty('id'), object: Object.id ?? null, toStr: Object.prototype.toString.id ?? null, enumerables: (() => { const k = []; for (const x in {}) k.push(x); return k; })() })); | |
| 363 | +const INTACTO = '{"proto":null,"propia":false,"object":null,"toStr":null,"enumerables":[]}'; | |
| 364 | +await abre('a.evil'); | |
| 365 | +ok('a.evil → evilscript', await hasta(async () => (await lenguaje()) === EVIL.lang), await lenguaje()); | |
| 366 | +const tiposEvil = () => p.evaluate(() => window.monaco.editor.tokenize('evil ctor (x)', 'evilscript')[0].map(t => t.type)); | |
| 367 | +ok('la gramática hostil pinta lo legítimo (#kw y la regla llamada «constructor»)', await hasta(async () => { const t = await tiposEvil(); return t.includes('keyword.control.evil') && t.includes('entity.name.function.ctor.evil'); }), JSON.stringify(await tiposEvil())); | |
| 368 | +ok('tras abrirlo: Object.prototype intacto ({}.id undefined, nada enumerable)', (await prototipo()) === INTACTO, await prototipo()); | |
| 369 | +await abre('notes.elfs'); | |
| 370 | +ok('…y las otras gramáticas compilan bien después («spell» → keyword.control.elfs)', await hasta(async () => (await p.evaluate(() => window.monaco.editor.tokenize('spell fire', 'elfscript')[0].map(t => t.type))).includes('keyword.control.elfs'))); | |
| 371 | +// el tema con un ámbito «hasOwnProperty» ya no tumba el motor | |
| 372 | +await abrePanel(); | |
| 373 | +await filaInstalada('elffuss-test.evil').locator('.ext-theme-chips .ext-chip').first().click(); | |
| 374 | +await p.click('#settings-close'); | |
| 375 | +await abre('a.evil'); | |
| 376 | +ok('tema con ámbito «hasOwnProperty»: se aplica y la gramática sigue con sus colores', await colorDe('evil', EVIL.kw) && await colorDe('ctor', EVIL.ctor), JSON.stringify([await estilo('evil'), await estilo('ctor')])); | |
| 377 | +// lo guardado ANTES de sanear al instalar: se sanea también al cargar | |
| 378 | +await p.evaluate(async raw => { | |
| 379 | + const db = await new Promise((res, rej) => { const r = indexedDB.open('elffuss-code-ext'); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); }); | |
| 380 | + const rec = await new Promise(res => { const q = db.transaction('ext').objectStore('ext').get('elffuss-test.evil'); q.onsuccess = () => res(q.result); }); | |
| 381 | + const key = rec.grammars.find(g => g.scopeName === 'source.evil').key; | |
| 382 | + await new Promise((res, rej) => { const tx = db.transaction('files', 'readwrite'); tx.objectStore('files').put(JSON.parse(raw), key); tx.oncomplete = res; tx.onerror = () => rej(tx.error); }); | |
| 383 | + db.close(); | |
| 384 | +}, EVIL_GRAMMAR); | |
| 385 | +await p.reload({ waitUntil: 'domcontentloaded' }); | |
| 386 | +await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length)); | |
| 387 | +await abre('a.evil'); | |
| 388 | +ok('gramática hostil guardada sin sanear: al cargarla, Object.prototype sigue intacto', await hasta(async () => (await tiposEvil()).includes('keyword.control.evil')) && (await prototipo()) === INTACTO, await prototipo()); | |
| 389 | + | |
| 390 | +// J8. snippets: el detalle no pide nada a ningún servidor | |
| 391 | +const BALIZA = 'http://127.0.0.1:8993'; // nadie escucha: basta con ver si el navegador lo pide | |
| 392 | +await abrePanel(); | |
| 393 | +await instalaFichero('beacon.vsix', beaconSnippetVsix(BALIZA)); | |
| 394 | +await p.click('#settings-close'); | |
| 395 | +await abre('app.js'); | |
| 396 | +await ponTexto(''); | |
| 397 | +pedidas.length = 0; | |
| 398 | +await p.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setPosition({ lineNumber: 1, column: 1 }); ed.focus(); }); | |
| 399 | +await p.keyboard.type('zzbea'); | |
| 400 | +await p.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'editor.action.triggerSuggest', {})); | |
| 401 | +await hasta(() => p.evaluate(() => [...document.querySelectorAll('.suggest-widget.visible .monaco-list-row')].some(r => r.textContent.includes('zzbeacon')))); | |
| 402 | +const detalleSnip = () => p.evaluate(() => { const d = document.querySelector('.suggest-details'); return d && d.getClientRects().length && d.textContent.includes('body.png') ? { imgs: d.querySelectorAll('img').length, enlaces: d.querySelectorAll('a').length, texto: d.textContent } : null; }); | |
| 403 | +if (!(await hasta(detalleSnip, { tiempo: 2000 }))) await p.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'toggleSuggestionDetails', {})); | |
| 404 | +const snip = await hasta(detalleSnip); | |
| 405 | +ok('snippet: el detalle enseña descripción y cuerpo como texto', !!snip && snip.texto.includes(``) && snip.texto.includes('```'), JSON.stringify(snip)); | |
| 406 | +ok('…sin imágenes ni enlaces', !!snip && snip.imgs === 0 && snip.enlaces === 0, JSON.stringify(snip && { imgs: snip.imgs, enlaces: snip.enlaces })); | |
| 407 | +await sleep(600); | |
| 408 | +ok('…y el navegador no pidió nada al servidor de la extensión', !pedidas.some(u => u.startsWith(BALIZA)), pedidas.filter(u => u.startsWith(BALIZA)).join(' ')); | |
| 409 | +await p.keyboard.press('Escape'); | |
| 410 | + | |
| 411 | +// J9. expresiones que no terminan: la pestaña sigue viva | |
| 412 | +await abrePanel(); | |
| 413 | +await instalaFichero('slow.vsix', slowRegexVsix()); | |
| 414 | +const filaSlow = filaInstalada('elffuss-test.slow'); | |
| 415 | +await filaSlow.locator('details.ext-warn summary').click(); | |
| 416 | +const avisosSlow = await filaSlow.locator('details.ext-warn').innerText(); | |
| 417 | +ok('expresiones con repetición anidada: descartadas y avisadas', /2 parts could not be used/.test(avisosSlow) && avisosSlow.includes('Expression discarded in nestlang, it could freeze the tab: ^(a+)+$') && avisosSlow.includes('(a+)+$'), avisosSlow.replace(/\s+/g, ' ')); | |
| 418 | +await p.click('#settings-close'); | |
| 419 | +const abierto = await Promise.race([abre('slow-input').then(() => 'ok'), sleep(20000).then(() => 'COLGADO')]); | |
| 420 | +const vivo = abierto === 'ok' && await Promise.race([p.evaluate(() => 1), sleep(5000).then(() => 0)]) === 1; | |
| 421 | +ok('firstLine que no termina (^(.|\\s)*z con 64 espacios): el fichero se abre y la pestaña responde', vivo, abierto); | |
| 422 | +if (!vivo) { console.log('\n❌ la página se quedó colgada: no se puede seguir'); await b.close(); process.exit(1); } | |
| 423 | +ok('…como texto plano', (await lenguaje()) === 'plaintext', await lenguaje()); | |
| 424 | +await abre('runme'); | |
| 425 | +ok('…y las otras firstLine siguen funcionando (#!/usr/bin/env elfs → elfscript)', await hasta(async () => (await lenguaje()) === 'elfscript'), await lenguaje()); | |
| 426 | + | |
| 427 | +// J10. menús: View en escritorio y «/» en pantalla estrecha | |
| 428 | +await p.click('#menubar button[data-menu="view"]'); | |
| 429 | +const menuView = await p.locator('#topmenu .menu-item b').allInnerTexts(); | |
| 430 | +ok('menú View: «Extensions…» y «Color Theme…»', menuView.includes('Extensions…') && menuView.includes('Color Theme…'), menuView.join(' | ')); | |
| 431 | +await p.locator('#topmenu .menu-item', { hasText: 'Extensions…' }).click(); | |
| 432 | +ok('…y «Extensions…» abre el panel', await hasta(() => p.evaluate(() => !!document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden))); | |
| 433 | +await p.click('#settings-close'); | |
| 434 | +const tamaño = p.viewportSize(); | |
| 435 | +await p.setViewportSize({ width: 700, height: 800 }); | |
| 436 | +ok('a 700 px no se ven ni la barra de actividad ni el menú', await p.evaluate(() => !document.getElementById('act-ext').getClientRects().length && !document.getElementById('menubar').getClientRects().length)); | |
| 437 | +await p.click('#btn-slash'); | |
| 438 | +const menuSlash = await p.locator('#menu .menu-item b').allInnerTexts(); | |
| 439 | +ok('…pero el menú «/» del chat trae /extensions y /theme', menuSlash.includes('/extensions') && menuSlash.includes('/theme'), menuSlash.join(' ')); | |
| 440 | +await p.locator('#menu .menu-item', { hasText: '/extensions' }).click(); | |
| 441 | +ok('…y /extensions abre el panel', await hasta(() => p.evaluate(() => !!document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden))); | |
| 442 | +await p.keyboard.press('Escape'); | |
| 443 | +await p.setViewportSize(tamaño); | |
| 444 | + | |
| 445 | +// J11. fuera todo lo de esta sección | |
| 446 | +await p.evaluate(async () => { const host = await (await import('/js/ide.js')).loadExt(); for (const e of host.list()) await host.uninstall(e.id); await host.setTheme('vs-dark'); }); | |
| 447 | +await abrePanel(); | |
| 448 | +ok('J: todo desinstalado', (await p.locator('#ext-installed .ext-row').count()) === 0); | |
| 449 | + | |
| 232 | 450 | // ── I. EN VIVO contra Open VSX ── |
| 233 | 451 | const red = await p.evaluate(async () => { try { return (await fetch('https://open-vsx.org/api/vscode/theme-monokai', { credentials: 'omit' })).ok; } catch { return false; } }); |
| 234 | 452 | if (!red) { |
modified web/css/ext.css +13 −2
| @@ -17,6 +17,10 @@ | ||
| 17 | 17 | .ext-msg { margin: 8px 0 0; padding: 6px 10px; border-radius: 8px; font-size: .78rem; background: rgba(63,185,112,.12); border: 1px solid rgba(63,185,112,.35); } |
| 18 | 18 | .ext-msg.err { background: rgba(255,107,139,.1); border-color: rgba(255,107,139,.4); } |
| 19 | 19 | .ext-msg[hidden] { display: none; } |
| 20 | +/* vacío sigue en la página (región viva), pero sin ocupar sitio */ | |
| 21 | +.ext-msg:empty { margin: 0; padding: 0; border: 0; } | |
| 22 | +/* solo para lectores de pantalla */ | |
| 23 | +.ext-sr { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; } | |
| 20 | 24 | .ext-hint { font-size: .78rem; margin: 10px 0 2px; } |
| 21 | 25 | .ext-results, .ext-installed { margin-top: 4px; } |
| 22 | 26 | .ext-row { display: flex; align-items: flex-start; gap: 10px; padding: 9px 10px; background: var(--bg3); border: 1px solid var(--line); border-radius: 9px; margin-bottom: 6px; font-size: .8rem; } |
| @@ -27,6 +31,10 @@ | ||
| 27 | 31 | .ext-results .ext-main { cursor: pointer; } |
| 28 | 32 | .ext-title { display: flex; align-items: baseline; gap: 4px; flex-wrap: wrap; } |
| 29 | 33 | .ext-title b { font-size: .84rem; overflow-wrap: anywhere; } |
| 34 | +.ext-name { background: none; border: none; padding: 0; margin: 0; font: inherit; font-size: .84rem; font-weight: 700; color: inherit; text-align: left; cursor: pointer; overflow-wrap: anywhere; } | |
| 35 | +.ext-name:hover { text-decoration: underline; } | |
| 36 | +.ext-link { background: none; border: none; padding: 0; font: inherit; color: var(--accent2); cursor: pointer; text-decoration: underline; } | |
| 37 | +.ext-panel button:focus-visible, .ext-panel summary:focus-visible, .ext-panel .sk-h:focus-visible { outline: 2px solid var(--accent2); outline-offset: 2px; } | |
| 30 | 38 | .ext-title .muted { font-size: .72rem; overflow-wrap: anywhere; } |
| 31 | 39 | .ext-badge { font-size: .66rem; color: #3fb970; } |
| 32 | 40 | .ext-desc { color: #b8c0d4; font-size: .76rem; margin-top: 2px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } |
| @@ -39,12 +47,15 @@ | ||
| 39 | 47 | .ext-theme-chips { margin-top: 6px; } |
| 40 | 48 | .ext-license { margin: 6px 0 0; max-height: 180px; overflow: auto; white-space: pre-wrap; font-size: .68rem; background: var(--bg); border: 1px solid var(--line); border-radius: 6px; padding: 6px 8px; } |
| 41 | 49 | .ext-license[hidden] { display: none; } |
| 50 | +.ext-warn { margin-top: 4px; font-size: .72rem; color: #e5a53a; } | |
| 51 | +.ext-warn summary { cursor: pointer; } | |
| 52 | +.ext-warn ul { margin: 4px 0 0 18px; padding: 0; color: var(--muted); overflow-wrap: anywhere; } | |
| 42 | 53 | .ext-actions { display: flex; flex-direction: column; gap: 6px; flex: 0 0 auto; } |
| 43 | 54 | .ext-actions button { font-size: .74rem; padding: 5px 11px; border-radius: 6px; cursor: pointer; white-space: nowrap; } |
| 44 | 55 | .ext-actions .primary { background: linear-gradient(135deg, var(--accent), var(--accent2)); border: none; color: #fff; } |
| 45 | 56 | .ext-actions .ghost { background: none; border: 1px solid var(--line); color: var(--muted); } |
| 46 | -.ext-actions .ghost:hover:not(:disabled) { color: var(--fg); border-color: var(--accent2); } | |
| 47 | -.ext-actions button:disabled { cursor: default; opacity: .75; } | |
| 57 | +.ext-actions .ghost:hover:not(:disabled):not([aria-disabled="true"]) { color: var(--fg); border-color: var(--accent2); } | |
| 58 | +.ext-actions button:disabled, .ext-actions button[aria-disabled="true"] { cursor: default; opacity: .75; } | |
| 48 | 59 | .ext-more { display: block; margin: 4px auto 10px; font-size: .76rem; } |
| 49 | 60 | @media (max-width: 560px) { |
| 50 | 61 | .ext-row { flex-wrap: wrap; } |
added web/js/ext/firstline-worker.js +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +// Las firstLine de los paquetes, fuera del hilo de la página: si una | |
| 2 | +// expresión no termina, host.js corta este Worker por tiempo y la pestaña | |
| 3 | +// sigue viva. Avisa ANTES de probar cada expresión: así el tiempo cuenta desde | |
| 4 | +// ahí (no desde la carga del Worker) y se sabe cuál fue la que se atascó. | |
| 5 | +import { matchFirstLine } from './languages.js'; | |
| 6 | + | |
| 7 | +self.onmessage = ({ data: { id, candidates, line } }) => { | |
| 8 | + for (let i = 0; i < candidates.length; i++) { | |
| 9 | + self.postMessage({ id, trying: i }); | |
| 10 | + if (matchFirstLine([candidates[i]], line)) { self.postMessage({ id, lang: candidates[i].id }); return; } | |
| 11 | + } | |
| 12 | + self.postMessage({ id, lang: null }); | |
| 13 | +}; |
modified web/js/ext/formats.js +9 −2
| @@ -2,6 +2,12 @@ | ||
| 2 | 2 | // plist XML (.tmTheme / .tmLanguage) y colores hex. Sin DOM ni dependencias: |
| 3 | 3 | // se prueban en Node igual que en el navegador. |
| 4 | 4 | |
| 5 | +// Nombres que un objeto normal hereda de Object.prototype (más «prototype»). | |
| 6 | +// Usados como clave de un objeto de datos, una búsqueda sale del objeto y una | |
| 7 | +// escritura toca el prototipo: los datos de una extensión nunca deben llegar | |
| 8 | +// con ellos a donde se busca o se escribe por nombre. | |
| 9 | +export const NOMBRES_PROTO = new Set([...Object.getOwnPropertyNames(Object.prototype), 'prototype']); | |
| 10 | + | |
| 5 | 11 | // JSONC como lo lee VS Code: comentarios // y /* */ y comas finales. Recorre |
| 6 | 12 | // el texto respetando las cadenas, así un "http://…" dentro de un string no se |
| 7 | 13 | // toma por comentario. |
| @@ -47,7 +53,7 @@ | ||
| 47 | 53 | export function parsePlist(text) { |
| 48 | 54 | const s = String(text ?? '').replace(/^/, ''); |
| 49 | 55 | let i = 0; |
| 50 | - const fallo = msg => { throw new Error(`plist: ${msg} (posición ${i})`); }; | |
| 56 | + const fallo = msg => { throw Object.assign(new Error(`plist: ${msg} (posición ${i})`), { code: 'plist' }); }; | |
| 51 | 57 | |
| 52 | 58 | // salta espacios, comentarios, <?xml?> y <!DOCTYPE> |
| 53 | 59 | function saltaRelleno() { |
| @@ -109,7 +115,8 @@ | ||
| 109 | 115 | const clave = k.vacia ? '' : texto('key'); |
| 110 | 116 | const v = etiqueta(); |
| 111 | 117 | if (v.cierre) fallo('falta el valor de ' + clave); |
| 112 | - o[clave] = valor(v); | |
| 118 | + const x = valor(v); | |
| 119 | + if (clave !== '__proto__') o[clave] = x; // asignarla cambiaría el prototipo de `o` | |
| 113 | 120 | } |
| 114 | 121 | } |
| 115 | 122 | case 'array': { |
modified web/js/ext/grammars.js +82 −7
| @@ -1,7 +1,8 @@ | ||
| 1 | 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. | |
| 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. | |
| 5 | 6 | // |
| 6 | 7 | // Los tokens van a Monaco en binario (tokenizeEncoded), igual que en VS Code: |
| 7 | 8 | // cada token lleva el índice de su color en el mapa de colores de TextMate, y |
| @@ -9,13 +10,85 @@ | ||
| 9 | 10 | // así los dos mapas coinciden índice a índice. Resultado: los colores exactos |
| 10 | 11 | // del tema (incluidos los selectores con contexto), cursivas/negritas, y el |
| 11 | 12 | // 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'; | |
| 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'; | |
| 14 | 17 | const WASM_URL = 'https://cdn.jsdelivr.net/npm/vscode-oniguruma@2.0.1/release/onig.wasm'; |
| 15 | 18 | const WASM_SRI = 'sha384-bmaXom6bK+vfssb0IcRH2lE1asksQiEsK/WnxAcnHDB3Cx8v3KxZ7BthuGq1DU8v'; |
| 16 | 19 | const LIMITE_MS = 500; // por línea, como VS Code: una gramática mala no congela la pestaña |
| 17 | 20 | const TIPOS = { other: 0, comment: 1, string: 2, regex: 3 }; |
| 18 | 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 | + | |
| 19 | 92 | let motor = null; |
| 20 | 93 | export function loadEngine() { |
| 21 | 94 | if (!motor) { |
| @@ -69,6 +142,7 @@ | ||
| 69 | 142 | this.injections = new Map(); |
| 70 | 143 | this.skipped = []; |
| 71 | 144 | for (const c of contribs) { |
| 145 | + if (!ambitoValido(c.scopeName)) continue; | |
| 72 | 146 | this.byScope.set(c.scopeName, c); |
| 73 | 147 | for (const destino of c.injectTo || []) { |
| 74 | 148 | if (!this.injections.has(destino)) this.injections.set(destino, []); |
| @@ -92,7 +166,8 @@ | ||
| 92 | 166 | loadGrammar: async scope => { |
| 93 | 167 | const c = this.byScope.get(scope); |
| 94 | 168 | if (!c) return null; |
| 95 | - try { const g = await this.loadFile(c.key); if (g) g.scopeName = scope; return g || null; } catch { 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; } | |
| 96 | 171 | }, |
| 97 | 172 | getInjections: scope => this.injections.get(scope), |
| 98 | 173 | }); |
| @@ -108,7 +183,7 @@ | ||
| 108 | 183 | // Tema TextMate actual → mapa de colores para encodedTokensColors (null si |
| 109 | 184 | // el motor aún no está activo: entonces no hay tokens TextMate que pintar). |
| 110 | 185 | setTheme(rawTheme) { |
| 111 | - this.rawTheme = rawTheme; | |
| 186 | + this.rawTheme = rawTheme; // ya sin ámbitos peligrosos: toTextMateTheme (themes.js) | |
| 112 | 187 | if (!this.registry) return null; |
| 113 | 188 | this.registry.setTheme(rawTheme); |
| 114 | 189 | return this.registry.getColorMap().slice(1); |
modified web/js/ext/host.js +74 −6
| @@ -10,13 +10,67 @@ | ||
| 10 | 10 | import * as store from './store.js'; |
| 11 | 11 | import { BASES, builtinTheme, toMonacoTheme, toTextMateTheme, chromeCss, themeIdFor } from './themes.js'; |
| 12 | 12 | import { registerSnippets } from './snippets.js'; |
| 13 | -import { toLanguageConfiguration, matchLanguage } from './languages.js'; | |
| 14 | -import { Grammars } from './grammars.js'; | |
| 13 | +import { toLanguageConfiguration, matchLanguage, firstLineCandidates } from './languages.js'; | |
| 14 | +import { Grammars, canOverride } from './grammars.js'; | |
| 15 | 15 | import { uiLang } from '../i18n.js'; |
| 16 | 16 | |
| 17 | 17 | export const THEME_PREF = 'elffusscode.theme'; |
| 18 | 18 | let instancia = null; |
| 19 | 19 | |
| 20 | +// ── primera línea (firstLine) en un Worker con tiempo tope ── | |
| 21 | +// Una expresión de un paquete puede no terminar nunca con según qué línea; en | |
| 22 | +// el hilo de la página congelaría la pestaña al abrir un fichero. El Worker | |
| 23 | +// avisa antes de probar cada expresión: si una se pasa de tiempo, se corta el | |
| 24 | +// Worker, esa expresión queda fuera hasta recargar y se repite con las demás. | |
| 25 | +const TOPE_EXPRESION_MS = 250; | |
| 26 | +const TOPE_ARRANQUE_MS = 8000; // el Worker ni contestó (no cargó) | |
| 27 | +const lentas = new Set(); | |
| 28 | +const peticiones = new Map(); | |
| 29 | +let trabajador = null, nPeticion = 0; | |
| 30 | + | |
| 31 | +function sueltaTrabajador() { | |
| 32 | + trabajador?.terminate(); | |
| 33 | + trabajador = null; | |
| 34 | + const resto = [...peticiones.values()]; | |
| 35 | + peticiones.clear(); | |
| 36 | + for (const p of resto) clearTimeout(p.timer); | |
| 37 | + return resto; | |
| 38 | +} | |
| 39 | +function alRecibir({ data }) { | |
| 40 | + const p = peticiones.get(data.id); | |
| 41 | + if (!p) return; | |
| 42 | + clearTimeout(p.timer); | |
| 43 | + if ('trying' in data) { | |
| 44 | + p.timer = setTimeout(() => { | |
| 45 | + const mala = p.candidatos[data.trying]; | |
| 46 | + lentas.add(mala.src); | |
| 47 | + console.warn(`[elffuss-ext] la firstLine de «${mala.id}» no termina a tiempo: no se usa en esta sesión`); | |
| 48 | + for (const q of sueltaTrabajador()) firstLineEnWorker(q.candidatos, q.linea).then(q.resolve); | |
| 49 | + }, TOPE_EXPRESION_MS); | |
| 50 | + return; | |
| 51 | + } | |
| 52 | + peticiones.delete(data.id); | |
| 53 | + p.resolve(data.lang ?? null); | |
| 54 | +} | |
| 55 | +function firstLineEnWorker(candidatos, linea) { | |
| 56 | + candidatos = candidatos.filter(c => !lentas.has(c.src)); | |
| 57 | + if (!candidatos.length || !linea) return Promise.resolve(null); | |
| 58 | + return new Promise(resolve => { | |
| 59 | + try { | |
| 60 | + if (!trabajador) { | |
| 61 | + trabajador = new Worker(new URL('./firstline-worker.js', import.meta.url), { type: 'module' }); | |
| 62 | + trabajador.onmessage = alRecibir; | |
| 63 | + trabajador.onerror = () => { for (const q of sueltaTrabajador()) q.resolve(null); }; | |
| 64 | + } | |
| 65 | + const id = ++nPeticion; | |
| 66 | + const p = { resolve, candidatos, linea, timer: null }; | |
| 67 | + p.timer = setTimeout(() => { if (peticiones.get(id) === p) { peticiones.delete(id); resolve(null); } }, TOPE_ARRANQUE_MS); | |
| 68 | + peticiones.set(id, p); | |
| 69 | + trabajador.postMessage({ id, candidates: candidatos, line: linea }); | |
| 70 | + } catch { resolve(null); } // sin Workers: sin detección por primera línea | |
| 71 | + }); | |
| 72 | +} | |
| 73 | + | |
| 20 | 74 | export function init(monaco, opts = {}) { |
| 21 | 75 | instancia ??= crear(monaco, opts).catch(e => { instancia = null; throw e; }); |
| 22 | 76 | return instancia; |
| @@ -93,7 +147,9 @@ | ||
| 93 | 147 | langContribs.push(l); |
| 94 | 148 | if (builtin.has(l.id)) continue; // los de serie conservan su configuración |
| 95 | 149 | 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 }); | |
| 150 | + // sin firstLine: Monaco la ejecutaría en la página; la detección por | |
| 151 | + // primera línea es nuestra y va en un Worker (languageForFirstLine) | |
| 152 | + monaco.languages.register({ id: l.id, extensions: l.extensions, filenames: l.filenames, filenamePatterns: l.filenamePatterns, aliases: l.aliases, mimetypes: l.mimetypes }); | |
| 97 | 153 | registrados.add(l.id); |
| 98 | 154 | } |
| 99 | 155 | if (l.configKey) { |
| @@ -156,9 +212,14 @@ | ||
| 156 | 212 | } |
| 157 | 213 | const { readVsix } = await import('./vsix.js'); |
| 158 | 214 | 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}`); | |
| 215 | + if (meta && v.id !== `${meta.namespace}.${meta.name}`.toLowerCase()) { | |
| 216 | + throw Object.assign(new Error(`el paquete dice ser ${v.id}, no ${meta.namespace}.${meta.name}`), { code: 'mismatch', got: v.id, want: `${meta.namespace}.${meta.name}` }); | |
| 217 | + } | |
| 160 | 218 | 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; | |
| 219 | + // declaraba cosas aplicables pero ninguna se pudo leer: no es lo mismo | |
| 220 | + // que no traer nada, y el usuario tiene que saber por qué | |
| 221 | + if (v.warnings.length) throw Object.assign(new Error('unreadable'), { code: 'unreadable', warning: v.warnings[0], warnings: v.warnings }); | |
| 222 | + throw Object.assign(new Error('nothing-applies'), { code: 'nothing' }); | |
| 162 | 223 | } |
| 163 | 224 | const previo = exts.find(e => e.id === v.id); |
| 164 | 225 | const usados = new Set(exts.filter(e => e.id !== v.id).flatMap(e => (e.themes || []).map(t => t.themeId))); |
| @@ -215,8 +276,15 @@ | ||
| 215 | 276 | themeId: () => monacoId, |
| 216 | 277 | setTheme: id => aplicaTema(id, { guardar: true }), |
| 217 | 278 | previewTheme: id => aplicaTema(id), |
| 218 | - languageForPath: (path, primeraLinea = null) => (paused ? null : matchLanguage(langContribs, path, primeraLinea)), | |
| 279 | + languageForPath: path => (paused ? null : matchLanguage(langContribs, path)), | |
| 280 | + // solo para ficheros que nadie reclama por su nombre (ide.js) | |
| 281 | + languageForFirstLine: line => (paused ? Promise.resolve(null) : firstLineEnWorker(firstLineCandidates(langContribs), line)), | |
| 219 | 282 | prepareLanguage: async lang => (paused || !grammars.hasGrammarFor(lang) ? false : grammars.prepare(lang)), |
| 220 | 283 | skippedGrammars: () => grammars.skipped.map(g => ({ ext: g.ext, language: g.language, scopeName: g.scopeName })), |
| 284 | + // lo que no se aplicaría aunque la extensión esté activa: la gramática de | |
| 285 | + // un lenguaje de serie sin Monarch (JSON) y la configuración de un lenguaje | |
| 286 | + // de serie (Monaco conserva la suya) | |
| 287 | + grammarSkippedFor: lang => typeof lang === 'string' && builtin.has(lang) && !canOverride(monaco, lang), | |
| 288 | + builtinLanguage: id => builtin.has(id), | |
| 221 | 289 | }; |
| 222 | 290 | } |
modified web/js/ext/i18n.js +48 −4
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | catAll: 'Todo', catThemes: 'Temas', catSnippets: 'Snippets', catLangs: 'Lenguajes', |
| 12 | 12 | vsix: 'Instalar .vsix…', themeBtn: 'Tema de color…', |
| 13 | 13 | installedH: 'Instaladas ({n})', none: 'Ninguna todavía. Busca arriba o instala un .vsix.', |
| 14 | - popular: 'Populares', results: '{n} resultados', noResults: 'Sin resultados.', searching: 'Buscando…', more: 'Más resultados', | |
| 14 | + popular: 'Populares', results: '{n} resultado|{n} resultados', noResults: 'Sin resultados.', searching: 'Buscando…', more: 'Más resultados', | |
| 15 | 15 | install: 'Instalar', installing: 'Instalando…', downloading: 'Descargando… {pct}%', installedOk: 'Instalada ✓', update: 'Actualizar a {v}', |
| 16 | 16 | enable: 'Activar', disable: 'Desactivar', disabled: 'desactivada', uninstall: 'Desinstalar', confirmUninstall: '¿Desinstalar «{name}»?', |
| 17 | 17 | details: 'Detalles', loadingDetails: 'Leyendo el manifiesto…', |
| @@ -28,8 +28,29 @@ | ||
| 28 | 28 | errSha: 'La suma SHA-256 del paquete no coincide con la publicada: no se instala.', |
| 29 | 29 | errNothing: 'Esta extensión no trae nada que se pueda aplicar aquí (temas, gramáticas, snippets o lenguajes).', |
| 30 | 30 | errNotVsix: 'Eso no es un .vsix de VS Code.', |
| 31 | + errNotFound: 'Open VSX no tiene esa extensión o esa versión.', | |
| 32 | + errHttp: 'Open VSX respondió con un error{status}.', | |
| 33 | + errBig: 'El paquete es demasiado grande para instalarlo aquí.', | |
| 34 | + errMismatch: 'El paquete dice ser {got}, no {want}: no se instala.', | |
| 35 | + errCorrupt: 'El paquete está dañado o usa un formato zip que no se admite{entry}.', | |
| 36 | + errBadManifest: 'No se pudo leer el package.json del paquete: {e}', | |
| 37 | + errNoName: 'El package.json del paquete no dice su nombre (name) y su editor (publisher).', | |
| 38 | + errUnreadable: 'No se pudo leer ninguna de las partes de esta extensión. {w}', | |
| 39 | + errBlocked: 'Otra pestaña de Elffuss Code tiene ocupada la base de extensiones: ciérrala y vuelve a intentarlo.', | |
| 40 | + errQuota: 'No queda espacio en el almacenamiento del navegador para instalarla.', | |
| 31 | 41 | err: 'No se pudo: {e}', cancelled: 'Cancelado.', |
| 32 | - installedMsg: '«{name}» instalada.', grammarSkipped: 'La gramática de {lang} no se aplica: Monaco conserva su coloreado de serie.', | |
| 42 | + installedMsg: '«{name}» instalada.', | |
| 43 | + grammarNotApplied: 'gramática de {lang} (Monaco conserva su coloreado de serie)', | |
| 44 | + settingsNotApplied: 'configuración de {lang} (Monaco conserva la suya)', | |
| 45 | + warnSummary: '{n} parte no se pudo usar|{n} partes no se pudieron usar', | |
| 46 | + warn_theme: 'Tema «{name}»: {why}', warn_grammar: 'Gramática {name}: {why}', warn_snippets: 'Snippets {name}: {why}', | |
| 47 | + warn_config: 'Configuración de {name}: {why}', warn_regex: 'Expresión descartada en {name}, podría congelar la pestaña: {why}', | |
| 48 | + whyMissing: 'el fichero no está en el paquete', whyCorrupt: 'el fichero está dañado', whyBig: 'el fichero es demasiado grande', | |
| 49 | + whyJson: 'no es JSON válido ({e})', whyPlist: 'no es un plist válido', whyNotGrammar: 'no es una gramática TextMate', | |
| 50 | + whyNotTheme: 'no es un tema válido', whyScope: 'nombre de ámbito no válido', whyOutside: 'la ruta sale del paquete', | |
| 51 | + installNamed: 'Instalar {name}', updateNamed: 'Actualizar {name} a {v}', installedNamed: '{name} ya está instalada', | |
| 52 | + enableNamed: 'Activar {name}', disableNamed: 'Desactivar {name}', uninstallNamed: 'Desinstalar {name}', | |
| 53 | + close: 'Cerrar', themeList: 'Temas de color', | |
| 33 | 54 | pickPh: 'Tema de color (↑↓ para previsualizar, Enter para elegir)', builtinGroup: 'Integrados', |
| 34 | 55 | builtinDark: 'Oscuro (por defecto)', builtinLight: 'Claro', builtinHc: 'Alto contraste oscuro', builtinHcLight: 'Alto contraste claro', |
| 35 | 56 | current: 'actual', palExt: 'Extensiones…', palTheme: 'Tema de color…', |
| @@ -42,7 +63,7 @@ | ||
| 42 | 63 | catAll: 'All', catThemes: 'Themes', catSnippets: 'Snippets', catLangs: 'Languages', |
| 43 | 64 | vsix: 'Install .vsix…', themeBtn: 'Color Theme…', |
| 44 | 65 | installedH: 'Installed ({n})', none: 'None yet. Search above or install a .vsix.', |
| 45 | - popular: 'Popular', results: '{n} results', noResults: 'No results.', searching: 'Searching…', more: 'More results', | |
| 66 | + popular: 'Popular', results: '{n} result|{n} results', noResults: 'No results.', searching: 'Searching…', more: 'More results', | |
| 46 | 67 | install: 'Install', installing: 'Installing…', downloading: 'Downloading… {pct}%', installedOk: 'Installed ✓', update: 'Update to {v}', |
| 47 | 68 | enable: 'Enable', disable: 'Disable', disabled: 'disabled', uninstall: 'Uninstall', confirmUninstall: 'Uninstall “{name}”?', |
| 48 | 69 | details: 'Details', loadingDetails: 'Reading the manifest…', |
| @@ -59,14 +80,37 @@ | ||
| 59 | 80 | errSha: 'The package SHA-256 does not match the published one: not installed.', |
| 60 | 81 | errNothing: 'This extension brings nothing that can be applied here (themes, grammars, snippets or languages).', |
| 61 | 82 | errNotVsix: 'That is not a VS Code .vsix.', |
| 83 | + errNotFound: 'Open VSX does not have that extension or version.', | |
| 84 | + errHttp: 'Open VSX answered with an error{status}.', | |
| 85 | + errBig: 'The package is too large to install here.', | |
| 86 | + errMismatch: 'The package says it is {got}, not {want}: not installed.', | |
| 87 | + errCorrupt: 'The package is damaged or uses an unsupported zip format{entry}.', | |
| 88 | + errBadManifest: 'The package.json could not be read: {e}', | |
| 89 | + errNoName: 'The package.json does not give its name and publisher.', | |
| 90 | + errUnreadable: 'None of the parts of this extension could be read. {w}', | |
| 91 | + errBlocked: 'Another Elffuss Code tab is holding the extensions database: close it and try again.', | |
| 92 | + errQuota: 'There is no browser storage left to install it.', | |
| 62 | 93 | err: 'Could not do it: {e}', cancelled: 'Cancelled.', |
| 63 | - installedMsg: '“{name}” installed.', grammarSkipped: 'The {lang} grammar is not applied: Monaco keeps its built-in highlighting.', | |
| 94 | + installedMsg: '“{name}” installed.', | |
| 95 | + grammarNotApplied: '{lang} grammar (Monaco keeps its built-in highlighting)', | |
| 96 | + settingsNotApplied: '{lang} settings (Monaco keeps its own)', | |
| 97 | + warnSummary: '{n} part could not be used|{n} parts could not be used', | |
| 98 | + warn_theme: 'Theme “{name}”: {why}', warn_grammar: 'Grammar {name}: {why}', warn_snippets: 'Snippets {name}: {why}', | |
| 99 | + warn_config: 'Settings for {name}: {why}', warn_regex: 'Expression discarded in {name}, it could freeze the tab: {why}', | |
| 100 | + whyMissing: 'the file is not in the package', whyCorrupt: 'the file is damaged', whyBig: 'the file is too large', | |
| 101 | + whyJson: 'not valid JSON ({e})', whyPlist: 'not a valid plist', whyNotGrammar: 'not a TextMate grammar', | |
| 102 | + whyNotTheme: 'not a valid theme', whyScope: 'invalid scope name', whyOutside: 'the path leaves the package', | |
| 103 | + installNamed: 'Install {name}', updateNamed: 'Update {name} to {v}', installedNamed: '{name} is installed', | |
| 104 | + enableNamed: 'Enable {name}', disableNamed: 'Disable {name}', uninstallNamed: 'Uninstall {name}', | |
| 105 | + close: 'Close', themeList: 'Color themes', | |
| 64 | 106 | pickPh: 'Color theme (↑↓ to preview, Enter to select)', builtinGroup: 'Built-in', |
| 65 | 107 | builtinDark: 'Dark (default)', builtinLight: 'Light', builtinHc: 'Dark High Contrast', builtinHcLight: 'Light High Contrast', |
| 66 | 108 | current: 'current', palExt: 'Extensions…', palTheme: 'Color Theme…', |
| 67 | 109 | }, |
| 68 | 110 | }; |
| 69 | 111 | |
| 112 | +export const STRINGS = L; // para comprobar en las pruebas que ES y EN tienen las mismas claves | |
| 113 | + | |
| 70 | 114 | export function tx(key, vars) { |
| 71 | 115 | const tabla = L[uiLang()] || L.en; |
| 72 | 116 | let s = tabla[key] ?? L.en[key] ?? key; |
modified web/js/ext/languages.js +92 −13
| @@ -1,15 +1,76 @@ | ||
| 1 | 1 | // Lenguajes de VS Code (contributes.languages + language-configuration.json) |
| 2 | 2 | // → registro de Monaco y su configuración (comentarios, corchetes, sangría…). |
| 3 | 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. | |
| 9 | +export 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 | + | |
| 4 | 52 | // Expresión de VS Code (cadena o { pattern, flags }) → RegExp. Las que no |
| 5 | -// compilan en JavaScript se descartan, como hace VS Code. | |
| 53 | +// compilan en JavaScript se descartan, como hace VS Code, y también las de | |
| 54 | +// repetición anidada (ver arriba). | |
| 6 | 55 | function re(v) { |
| 7 | 56 | try { |
| 8 | - if (typeof v === 'string') return new RegExp(v); | |
| 9 | - if (v && typeof v.pattern === 'string') return new RegExp(v.pattern, String(v.flags || '').replace(/[^dgimsuy]/g, '')); | |
| 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); | |
| 10 | 60 | } catch { /* inválida */ } |
| 11 | 61 | return undefined; |
| 12 | 62 | } |
| 63 | + | |
| 64 | +// Todas las expresiones de un language-configuration.json que se descartarían | |
| 65 | +// por peligrosas (para avisar al instalar). | |
| 66 | +export 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 | +} | |
| 13 | 74 | const par = p => (Array.isArray(p) && p.length === 2 && p.every(x => typeof x === 'string') ? { open: p[0], close: p[1] } |
| 14 | 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') }) } |
| 15 | 76 | : null); |
| @@ -83,9 +144,10 @@ | ||
| 83 | 144 | } |
| 84 | 145 | |
| 85 | 146 | // Lenguaje para una ruta según las contribuciones activas (las últimas |
| 86 | -// instaladas mandan). Como VS Code: nombre exacto, luego patrones, luego la | |
| 87 | -// extensión más larga y, si se da el texto, la primera línea. | |
| 88 | -export function matchLanguage(contribs, path, primeraLinea = null) { | |
| 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. | |
| 150 | +export function matchLanguage(contribs, path) { | |
| 89 | 151 | const base = String(path).split('/').pop(); |
| 90 | 152 | const low = base.toLowerCase(); |
| 91 | 153 | for (let i = contribs.length - 1; i >= 0; i--) if ((contribs[i].filenames || []).some(f => f === base)) return contribs[i].id; |
| @@ -101,13 +163,30 @@ | ||
| 101 | 163 | if (el && el.length > largo && low.endsWith(el)) { mejor = contribs[i].id; largo = el.length; } |
| 102 | 164 | } |
| 103 | 165 | } |
| 104 | - if (mejor) return mejor; | |
| 105 | - if (primeraLinea != null) { | |
| 106 | - for (let i = contribs.length - 1; i >= 0; i--) { | |
| 107 | - const fl = contribs[i].firstLine; | |
| 108 | - if (typeof fl !== 'string') continue; | |
| 109 | - try { if (new RegExp(fl).test(primeraLinea)) return contribs[i].id; } catch { /* inválida */ } | |
| 110 | - } | |
| 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. | |
| 171 | +export const FIRST_LINE_MAX = 200; // caracteres de la primera línea que se miran | |
| 172 | +export 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. | |
| 185 | +export 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 */ } | |
| 111 | 190 | } |
| 112 | 191 | return null; |
| 113 | 192 | } |
modified web/js/ext/openvsx.js +7 −6
| @@ -10,8 +10,9 @@ | ||
| 10 | 10 | export const BIG = 25 * 1024 * 1024; // por encima, se pregunta antes de bajar |
| 11 | 11 | const MAX = 120 * 1024 * 1024; // tope duro de un .vsix |
| 12 | 12 | |
| 13 | +// `code` lo traduce el panel; `status` y `mb` son datos para el mensaje. | |
| 13 | 14 | class OpenVsxError extends Error { |
| 14 | - constructor(msg, code) { super(msg); this.code = code; } | |
| 15 | + constructor(msg, code, extra = {}) { super(msg); this.code = code; Object.assign(this, extra); } | |
| 15 | 16 | } |
| 16 | 17 | |
| 17 | 18 | async function getJson(url, signal) { |
| @@ -19,7 +20,7 @@ | ||
| 19 | 20 | try { res = await fetch(url, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); } |
| 20 | 21 | catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); } |
| 21 | 22 | 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 | + if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, res.status === 404 ? 'notfound' : 'http', { status: res.status }); | |
| 23 | 24 | return res.json(); |
| 24 | 25 | } |
| 25 | 26 | // solo URLs de la propia API (las de ficheros redirigen después a su CDN) |
| @@ -65,7 +66,7 @@ | ||
| 65 | 66 | const u = deOpenVsx(url); |
| 66 | 67 | if (!u) throw new OpenVsxError('URL fuera de Open VSX', 'http'); |
| 67 | 68 | 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 | + if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, 'http', { status: res.status }); | |
| 69 | 70 | return (await res.text()).slice(0, max); |
| 70 | 71 | } |
| 71 | 72 | |
| @@ -84,9 +85,9 @@ | ||
| 84 | 85 | try { res = await fetch(meta.files.download, { signal: ctl.signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); } |
| 85 | 86 | catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); } |
| 86 | 87 | 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 | + if (!res.ok) throw new OpenVsxError(`descarga: ${res.status}`, res.status === 404 ? 'notfound' : 'http', { status: res.status }); | |
| 88 | 89 | 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 > MAX) { ctl.abort(); throw new OpenVsxError(`demasiado grande (${(total / 1048576).toFixed(0)} MB)`, 'big', { mb: Math.round(total / 1048576) }); } | |
| 90 | 91 | if (total > BIG && !(await confirmLarge(Math.round(total / 1048576)))) { ctl.abort(); throw new OpenVsxError('cancelado', 'cancel'); } |
| 91 | 92 | const reader = res.body.getReader(); |
| 92 | 93 | const trozos = []; |
| @@ -95,7 +96,7 @@ | ||
| 95 | 96 | const { done, value } = await reader.read(); |
| 96 | 97 | if (done) break; |
| 97 | 98 | n += value.length; |
| 98 | - if (n > MAX) { ctl.abort(); throw new OpenVsxError('demasiado grande', 'big'); } | |
| 99 | + if (n > MAX) { ctl.abort(); throw new OpenVsxError('demasiado grande', 'big', { mb: Math.round(n / 1048576) }); } | |
| 99 | 100 | trozos.push(value); |
| 100 | 101 | onProgress(n, total); |
| 101 | 102 | } |
modified web/js/ext/panel.js +290 −67
| @@ -3,6 +3,10 @@ | ||
| 3 | 3 | // el selector de tema de color. Mismo patrón que el panel de Skills: se pinta |
| 4 | 4 | // dentro de #settings-panel. Todo texto que viene de una extensión entra con |
| 5 | 5 | // textContent, nunca como HTML. |
| 6 | +// | |
| 7 | +// Teclado y lector de pantalla: todo lo que se pulsa es un botón (o un | |
| 8 | +// <summary>), los resultados y avisos se anuncian (role=status/alert), el | |
| 9 | +// foco no se pierde al repintar ni al cerrar, y Escape cierra el panel. | |
| 6 | 10 | import { tx } from './i18n.js'; |
| 7 | 11 | |
| 8 | 12 | const $ = id => document.getElementById(id); |
| @@ -14,6 +18,9 @@ | ||
| 14 | 18 | const estado = { q: '', cat: null, items: [], total: 0, cargando: false, msg: null, ctl: null }; |
| 15 | 19 | let temporizador = null; |
| 16 | 20 | let desuscribe = null; |
| 21 | +let abridor = null; // quién tenía el foco al abrir el panel | |
| 22 | +let focoPendiente = null; // control a recuperar tras repintar «Instaladas» | |
| 23 | +let nDetalle = 0; | |
| 17 | 24 | |
| 18 | 25 | function ponCss() { |
| 19 | 26 | if (cssPuesto) return; |
| @@ -24,37 +31,105 @@ | ||
| 24 | 31 | document.head.appendChild(l); |
| 25 | 32 | } |
| 26 | 33 | |
| 34 | +const visible = x => !!x && x.isConnected && x !== document.body && !x.disabled && x.getClientRects().length > 0; | |
| 35 | +// El foco vuelve a donde estaba; si eso ya no existe o no se ve (un menú que | |
| 36 | +// se cerró, la paleta), a lo primero que se vea de la lista. | |
| 37 | +function devuelveFoco(previo, ...alternativas) { | |
| 38 | + for (const x of [previo, ...alternativas]) { | |
| 39 | + if (typeof x === 'function') { if (x()) return; continue; } | |
| 40 | + if (visible(x)) { x.focus(); return; } | |
| 41 | + } | |
| 42 | +} | |
| 43 | +const enfocaEditor = () => { | |
| 44 | + const ed = window.monaco?.editor?.getEditors?.()[0]; | |
| 45 | + if (!ed || !visible(ed.getDomNode())) return false; | |
| 46 | + ed.focus(); | |
| 47 | + return true; | |
| 48 | +}; | |
| 49 | + | |
| 27 | 50 | export function open(h, { themes = false } = {}) { |
| 28 | 51 | host = h; |
| 29 | 52 | ponCss(); |
| 30 | 53 | desuscribe?.(); |
| 31 | 54 | desuscribe = h.onChange(() => { if ($('ext-panel')?.isConnected) pintaInstaladas(); }); |
| 32 | 55 | if (themes) return openThemePicker(h); |
| 56 | + const box = $('settings-panel'); | |
| 57 | + if (!$('ext-panel')?.isConnected || box.hidden) abridor = document.activeElement; | |
| 33 | 58 | estado.msg = null; // un aviso viejo no se repite al volver a abrir |
| 34 | 59 | pinta(); |
| 35 | 60 | } |
| 36 | 61 | |
| 37 | -// ── mensajes de error legibles ── | |
| 38 | -function textoError(e) { | |
| 39 | - if (e?.code === 'rate') return tx('errRate'); | |
| 40 | - if (e?.code === 'net') return tx('errNet', { e: e.message }); | |
| 41 | - if (e?.code === 'sha') return tx('errSha'); | |
| 42 | - if (e?.code === 'nothing') return tx('errNothing'); | |
| 43 | - if (e?.code === 'notvsix') return tx('errNotVsix'); | |
| 44 | - if (e?.code === 'cancel' || e?.name === 'AbortError') return tx('cancelled'); | |
| 62 | +function cierraPanel() { | |
| 63 | + $('settings-panel').hidden = true; | |
| 64 | + devuelveFoco(abridor, $('act-ext'), document.querySelector('#menubar button[data-menu="view"]'), enfocaEditor, $('prompt')); | |
| 65 | +} | |
| 66 | + | |
| 67 | +// ── mensajes legibles (exportados para las pruebas en Node) ── | |
| 68 | +const ERRORES = { | |
| 69 | + rate: 'errRate', sha: 'errSha', nothing: 'errNothing', notvsix: 'errNotVsix', notfound: 'errNotFound', | |
| 70 | + big: 'errBig', noname: 'errNoName', blocked: 'errBlocked', | |
| 71 | +}; | |
| 72 | +export function textoError(e) { | |
| 73 | + const code = e?.code; | |
| 74 | + if (code === 'cancel' || e?.name === 'AbortError') return tx('cancelled'); | |
| 75 | + if (e?.name === 'QuotaExceededError') return tx('errQuota'); | |
| 76 | + if (typeof code === 'string' && Object.hasOwn(ERRORES, code)) return tx(ERRORES[code]); | |
| 77 | + switch (code) { | |
| 78 | + case 'net': return tx('errNet', { e: e.message }); | |
| 79 | + case 'http': return tx('errHttp', { status: e.status ? ` (${e.status})` : '' }); | |
| 80 | + case 'mismatch': return tx('errMismatch', { got: e.got, want: e.want }); | |
| 81 | + case 'corrupt': case 'missing': return tx('errCorrupt', { entry: e.entry ? ` (${e.entry})` : '' }); | |
| 82 | + case 'badmanifest': return tx('errBadManifest', { e: e.message }); | |
| 83 | + case 'unreadable': return tx('errUnreadable', { w: e.warning ? textoAviso(e.warning) : '' }).trim(); | |
| 84 | + } | |
| 45 | 85 | return tx('err', { e: e?.message || String(e) }); |
| 46 | 86 | } |
| 87 | +// Una parte del paquete que no se pudo usar (vsix.js: { kind, name, code, detail }). | |
| 88 | +const MOTIVOS = { | |
| 89 | + missing: 'whyMissing', corrupt: 'whyCorrupt', big: 'whyBig', json: 'whyJson', plist: 'whyPlist', | |
| 90 | + notgrammar: 'whyNotGrammar', notheme: 'whyNotTheme', scope: 'whyScope', outside: 'whyOutside', | |
| 91 | +}; | |
| 92 | +const TIPOS_AVISO = new Set(['theme', 'grammar', 'snippets', 'config', 'regex']); | |
| 93 | +export function textoAviso(w) { | |
| 94 | + if (typeof w === 'string') return w; // instaladas antes de que hubiera códigos | |
| 95 | + if (!w || typeof w !== 'object') return ''; | |
| 96 | + const why = w.kind !== 'regex' && typeof w.code === 'string' && Object.hasOwn(MOTIVOS, w.code) ? tx(MOTIVOS[w.code], { e: w.detail }) : w.detail; | |
| 97 | + return TIPOS_AVISO.has(w.kind) ? tx('warn_' + w.kind, { name: w.name, why }) : `${w.name}: ${why}`; | |
| 98 | +} | |
| 99 | + | |
| 100 | +// Los avisos que importan: la configuración de un lenguaje de serie no se | |
| 101 | +// aplica, así que sus expresiones descartadas no cuentan (ya lo dice «No aplica»). | |
| 102 | +const avisosVisibles = ws => (ws || []).filter(w => !(w?.kind === 'regex' && w.where === 'config' && host.builtinLanguage?.(w.name))); | |
| 103 | + | |
| 47 | 104 | function aviso(texto, error = false) { |
| 48 | 105 | estado.msg = texto ? { texto, error } : null; |
| 49 | 106 | const m = $('ext-msg'); |
| 50 | 107 | if (!m) return; |
| 108 | + // vacío pero presente: una región viva que aparece a la vez que su texto | |
| 109 | + // no siempre se anuncia | |
| 110 | + m.setAttribute('role', error ? 'alert' : 'status'); | |
| 111 | + m.setAttribute('aria-live', error ? 'assertive' : 'polite'); | |
| 112 | + m.hidden = false; | |
| 51 | 113 | m.textContent = texto || ''; |
| 52 | - m.hidden = !texto; | |
| 53 | 114 | m.classList.toggle('err', !!error); |
| 54 | 115 | } |
| 116 | +// Estado de la búsqueda para el lector de pantalla (la cabecera visible se | |
| 117 | +// rehace en cada repintado y no podría anunciarse). | |
| 118 | +function anunciaBusqueda(texto) { | |
| 119 | + const s = $('ext-status'); | |
| 120 | + if (s && s.textContent !== texto) s.textContent = texto; | |
| 121 | +} | |
| 55 | 122 | |
| 56 | -// «Aplica: 2 temas · No aplica: commands (necesita su código)» | |
| 57 | -function lineasResumen({ themes = 0, grammars = 0, languages = 0, snippetLangs = [], ignored = [], hasCode = false, pack = [] }) { | |
| 123 | +// «Aplica: 2 temas · No aplica: commands (necesita su código)», con lo que de | |
| 124 | +// verdad se aplicaría aquí: la gramática de un lenguaje de serie sin Monarch | |
| 125 | +// (JSON) y la configuración de un lenguaje de serie no se aplican, y no cuentan. | |
| 126 | +function resumen({ themes = 0, grammarLangs = [], languageList = [], snippetLangs = [], ignored = [], hasCode = false, pack = [] }) { | |
| 127 | + const saltaGram = l => !!l && !!host.grammarSkippedFor?.(l); | |
| 128 | + const deSerie = id => !!host.builtinLanguage?.(id); | |
| 129 | + const gramSaltadas = [...new Set(grammarLangs.filter(saltaGram))]; | |
| 130 | + const confSaltadas = [...new Set(languageList.filter(l => l.config && deSerie(l.id)).map(l => l.id))]; | |
| 131 | + const grammars = grammarLangs.filter(l => !saltaGram(l)).length; | |
| 132 | + const languages = languageList.filter(l => !deSerie(l.id)).length; | |
| 58 | 133 | const aplica = []; |
| 59 | 134 | if (themes) aplica.push(tx('themes', { n: themes })); |
| 60 | 135 | if (grammars) aplica.push(tx('grammars', { n: grammars })); |
| @@ -62,16 +137,28 @@ | ||
| 62 | 137 | if (snippetLangs.length) aplica.push(tx('snippets', { langs: snippetLangs.slice(0, 6).join(', ') + (snippetLangs.length > 6 ? '…' : '') })); |
| 63 | 138 | const porMotivo = { code: [], later: [] }; |
| 64 | 139 | for (const i of ignored) (porMotivo[i.why] || porMotivo.later).push(i.key); |
| 65 | - const no = []; | |
| 140 | + const no = [...gramSaltadas.map(lang => tx('grammarNotApplied', { lang })), ...confSaltadas.map(lang => tx('settingsNotApplied', { lang }))]; | |
| 66 | 141 | if (porMotivo.code.length) no.push(`${porMotivo.code.join(', ')} (${tx('needsCode')})`); |
| 67 | 142 | if (porMotivo.later.length) no.push(`${porMotivo.later.join(', ')} (${tx('notYet')})`); |
| 68 | - const out = []; | |
| 69 | - out.push(aplica.length ? { cls: 'ext-applies', t: tx('applies', { list: aplica.join(' · ') }) } : { cls: 'ext-nothing', t: tx('nothing') }); | |
| 70 | - if (no.length) out.push({ cls: 'ext-ignored', t: tx('ignores', { list: no.join(' · ') }) }); | |
| 71 | - if (hasCode) out.push({ cls: 'ext-ignored', t: tx('hasCode') }); | |
| 72 | - if (pack.length) out.push({ cls: 'ext-ignored', t: tx('pack', { n: pack.length }) }); | |
| 73 | - return out; | |
| 143 | + const lineas = []; | |
| 144 | + lineas.push(aplica.length ? { cls: 'ext-applies', t: tx('applies', { list: aplica.join(' · ') }) } : { cls: 'ext-nothing', t: tx('nothing') }); | |
| 145 | + if (no.length) lineas.push({ cls: 'ext-ignored', t: tx('ignores', { list: no.join(' · ') }) }); | |
| 146 | + if (hasCode) lineas.push({ cls: 'ext-ignored', t: tx('hasCode') }); | |
| 147 | + if (pack.length) lineas.push({ cls: 'ext-ignored', t: tx('pack', { n: pack.length }) }); | |
| 148 | + return { lineas, any: aplica.length > 0 }; | |
| 149 | +} | |
| 150 | + | |
| 151 | +// Botón de acción: texto visible y nombre accesible con la extensión | |
| 152 | +// («Instalar Monokai»). Sin nombre accesible, el lector lee el texto visible | |
| 153 | +// (el progreso de la descarga, por ejemplo). | |
| 154 | +function rotula(b, texto, accesible = null) { | |
| 155 | + b.textContent = texto; | |
| 156 | + if (accesible) b.setAttribute('aria-label', accesible); else b.removeAttribute('aria-label'); | |
| 74 | 157 | } |
| 158 | +// Ocupado o ya hecho, pero SIN disabled: un botón deshabilitado pierde el foco | |
| 159 | +// y quien va con teclado se quedaría en ninguna parte. | |
| 160 | +const inerte = (b, si) => { if (si) b.setAttribute('aria-disabled', 'true'); else b.removeAttribute('aria-disabled'); }; | |
| 161 | +const esInerte = b => b.getAttribute('aria-disabled') === 'true'; | |
| 75 | 162 | |
| 76 | 163 | // ── panel ── |
| 77 | 164 | function pinta() { |
| @@ -80,9 +167,15 @@ | ||
| 80 | 167 | box.replaceChildren(); |
| 81 | 168 | const cerrar = el('button', null, '✕'); |
| 82 | 169 | cerrar.id = 'settings-close'; |
| 83 | - cerrar.onclick = () => { box.hidden = true; }; | |
| 170 | + cerrar.type = 'button'; | |
| 171 | + cerrar.title = tx('close'); | |
| 172 | + cerrar.setAttribute('aria-label', tx('close')); | |
| 173 | + cerrar.onclick = cierraPanel; | |
| 84 | 174 | const wrap = el('div', 'ext-panel'); |
| 85 | 175 | wrap.id = 'ext-panel'; |
| 176 | + const conEscape = e => { if (e.key === 'Escape' && !e.defaultPrevented) { e.preventDefault(); e.stopPropagation(); cierraPanel(); } }; | |
| 177 | + wrap.addEventListener('keydown', conEscape); | |
| 178 | + cerrar.addEventListener('keydown', conEscape); | |
| 86 | 179 | const h3 = el('h3', null, tx('title') + ' '); |
| 87 | 180 | h3.appendChild(el('span', 'muted', '· ' + tx('sub'))); |
| 88 | 181 | wrap.append(h3, el('p', 'muted ext-intro', tx('intro'))); |
| @@ -113,6 +206,7 @@ | ||
| 113 | 206 | inp.id = 'ext-q'; |
| 114 | 207 | inp.type = 'search'; |
| 115 | 208 | inp.placeholder = tx('searchPh'); |
| 209 | + inp.setAttribute('aria-label', tx('searchPh')); | |
| 116 | 210 | inp.autocomplete = 'off'; |
| 117 | 211 | inp.spellcheck = false; |
| 118 | 212 | inp.value = estado.q; |
| @@ -122,6 +216,7 @@ | ||
| 122 | 216 | for (const [cat, key] of CATS) { |
| 123 | 217 | const c = el('button', 'ext-chip' + (estado.cat === cat ? ' on' : ''), tx(key)); |
| 124 | 218 | c.dataset.cat = cat; |
| 219 | + c.setAttribute('aria-pressed', String(estado.cat === cat)); | |
| 125 | 220 | c.onclick = () => { estado.cat = estado.cat === cat && cat ? '' : cat; busca_(); }; |
| 126 | 221 | chips.appendChild(c); |
| 127 | 222 | } |
| @@ -130,8 +225,14 @@ | ||
| 130 | 225 | |
| 131 | 226 | const msg = el('div', 'ext-msg'); |
| 132 | 227 | msg.id = 'ext-msg'; |
| 133 | - msg.hidden = true; | |
| 228 | + msg.setAttribute('role', 'status'); | |
| 229 | + msg.setAttribute('aria-live', 'polite'); | |
| 134 | 230 | wrap.appendChild(msg); |
| 231 | + const estadoBusqueda = el('div', 'ext-sr'); | |
| 232 | + estadoBusqueda.id = 'ext-status'; | |
| 233 | + estadoBusqueda.setAttribute('role', 'status'); | |
| 234 | + estadoBusqueda.setAttribute('aria-live', 'polite'); | |
| 235 | + wrap.appendChild(estadoBusqueda); | |
| 135 | 236 | const res = el('div', 'ext-results'); |
| 136 | 237 | res.id = 'ext-results'; |
| 137 | 238 | wrap.appendChild(res); |
| @@ -156,7 +257,12 @@ | ||
| 156 | 257 | if (!mas) { estado.items = []; estado.total = 0; } |
| 157 | 258 | aviso(null); |
| 158 | 259 | pintaResultados(); |
| 159 | - document.querySelectorAll('.ext-chip').forEach(c => c.classList.toggle('on', c.dataset.cat === (estado.cat || '') && estado.cat != null)); | |
| 260 | + // solo las categorías: las fichas de tema de «Instaladas» también son .ext-chip | |
| 261 | + for (const c of document.querySelectorAll('#ext-panel .ext-search .ext-chip')) { | |
| 262 | + const on = c.dataset.cat === (estado.cat || '') && estado.cat != null; | |
| 263 | + c.classList.toggle('on', on); | |
| 264 | + c.setAttribute('aria-pressed', String(on)); | |
| 265 | + } | |
| 160 | 266 | try { |
| 161 | 267 | const r = await ovsx.search(estado.q, { category: estado.cat || '', offset: mas ? estado.items.length : 0, size: 20, signal: ctl.signal }); |
| 162 | 268 | if (estado.ctl !== ctl) return; |
| @@ -174,12 +280,21 @@ | ||
| 174 | 280 | const res = $('ext-results'); |
| 175 | 281 | if (!res) return; |
| 176 | 282 | res.replaceChildren(); |
| 177 | - if (estado.cargando && !estado.items.length) { res.appendChild(el('div', 'muted ext-hint', tx('searching'))); return; } | |
| 283 | + if (estado.cargando && !estado.items.length) { | |
| 284 | + res.appendChild(el('div', 'muted ext-hint', tx('searching'))); | |
| 285 | + anunciaBusqueda(tx('searching')); | |
| 286 | + return; | |
| 287 | + } | |
| 178 | 288 | if (!estado.items.length) { |
| 179 | - if (estado.q || estado.cat != null) res.appendChild(el('div', 'muted ext-hint', estado.cargando ? tx('searching') : tx('noResults'))); | |
| 289 | + if (estado.q || estado.cat != null) { | |
| 290 | + const t = estado.cargando ? tx('searching') : tx('noResults'); | |
| 291 | + res.appendChild(el('div', 'muted ext-hint', t)); | |
| 292 | + anunciaBusqueda(t); | |
| 293 | + } else anunciaBusqueda(''); | |
| 180 | 294 | return; |
| 181 | 295 | } |
| 182 | 296 | res.appendChild(el('div', 'sk-h', estado.q ? tx('results', { n: estado.total }) : tx('popular'))); |
| 297 | + anunciaBusqueda(tx('results', { n: estado.total })); | |
| 183 | 298 | const instaladas = new Map(host.list().map(e => [e.id, e])); |
| 184 | 299 | for (const it of estado.items) res.appendChild(filaResultado(it, instaladas.get(`${it.namespace}.${it.name}`.toLowerCase()))); |
| 185 | 300 | if (estado.items.length < estado.total) { |
| @@ -199,46 +314,62 @@ | ||
| 199 | 314 | img.onerror = () => img.replaceWith(icono(null, nombre)); |
| 200 | 315 | return img; |
| 201 | 316 | } |
| 202 | - return el('div', 'ext-ico ext-ico-letra', (nombre || '?').trim().charAt(0).toUpperCase()); | |
| 317 | + const letra = el('div', 'ext-ico ext-ico-letra', (nombre || '?').trim().charAt(0).toUpperCase()); | |
| 318 | + letra.setAttribute('aria-hidden', 'true'); | |
| 319 | + return letra; | |
| 203 | 320 | } |
| 204 | 321 | |
| 205 | 322 | function filaResultado(it, instalada) { |
| 206 | 323 | const row = el('div', 'ext-row'); |
| 207 | 324 | row.dataset.id = `${it.namespace}.${it.name}`; |
| 208 | 325 | const main = el('div', 'ext-main'); |
| 326 | + const det = el('div', 'ext-detail'); | |
| 327 | + det.id = 'ext-det-' + (++nDetalle); | |
| 328 | + det.hidden = true; | |
| 329 | + // el nombre es el botón que despliega el detalle (qué aplicaría y qué no): | |
| 330 | + // antes de instalar, también con teclado | |
| 209 | 331 | const t = el('div', 'ext-title'); |
| 210 | - t.append(el('b', null, it.displayName), el('span', 'muted', ` ${it.namespace} · v${it.version}`)); | |
| 332 | + const nombre = el('button', 'ext-name', it.displayName); | |
| 333 | + nombre.type = 'button'; | |
| 334 | + nombre.title = tx('details'); | |
| 335 | + nombre.setAttribute('aria-expanded', 'false'); | |
| 336 | + nombre.setAttribute('aria-controls', det.id); | |
| 337 | + nombre.onclick = e => { e.stopPropagation(); detalle(it, det, nombre); }; | |
| 338 | + t.append(nombre, el('span', 'muted', ` ${it.namespace} · v${it.version}`)); | |
| 211 | 339 | if (it.verified) t.appendChild(el('span', 'ext-badge', '✓')); |
| 212 | 340 | main.append(t, el('div', 'ext-desc', it.description)); |
| 213 | 341 | main.appendChild(el('div', 'ext-meta muted', tx('downloads', { n: it.downloadCount.toLocaleString() }))); |
| 214 | - const det = el('div', 'ext-detail'); | |
| 215 | - det.hidden = true; | |
| 216 | 342 | main.appendChild(det); |
| 217 | - main.onclick = () => detalle(it, det); | |
| 218 | - main.title = tx('details'); | |
| 343 | + main.onclick = e => { if (!e.target.closest('button, a, summary')) detalle(it, det, nombre); }; | |
| 219 | 344 | |
| 220 | 345 | const acc = el('div', 'ext-actions'); |
| 221 | 346 | const b = el('button', 'primary ext-install'); |
| 222 | - if (instalada && instalada.version === it.version) { b.textContent = tx('installedOk'); b.className = 'ghost ext-install'; b.disabled = true; } | |
| 223 | - else b.textContent = instalada ? tx('update', { v: it.version }) : tx('install'); | |
| 224 | - b.onclick = e => { e.stopPropagation(); instala(it, b); }; | |
| 347 | + b.type = 'button'; | |
| 348 | + if (instalada && instalada.version === it.version) { | |
| 349 | + rotula(b, tx('installedOk'), tx('installedNamed', { name: it.displayName })); | |
| 350 | + b.className = 'ghost ext-install'; | |
| 351 | + inerte(b, true); | |
| 352 | + } else if (instalada) rotula(b, tx('update', { v: it.version }), tx('updateNamed', { name: it.displayName, v: it.version })); | |
| 353 | + else rotula(b, tx('install'), tx('installNamed', { name: it.displayName })); | |
| 354 | + b.onclick = e => { e.stopPropagation(); if (!esInerte(b)) instala(it, b); }; | |
| 225 | 355 | acc.appendChild(b); |
| 226 | 356 | row.append(icono(it.icon, it.displayName), main, acc); |
| 227 | 357 | return row; |
| 228 | 358 | } |
| 229 | 359 | |
| 230 | -async function detalle(it, det) { | |
| 231 | - if (!det.hidden) { det.hidden = true; return; } | |
| 232 | - det.hidden = false; | |
| 233 | - if (det.dataset.listo) return; | |
| 360 | +async function detalle(it, det, boton) { | |
| 361 | + det.hidden = !det.hidden; | |
| 362 | + boton?.setAttribute('aria-expanded', String(!det.hidden)); | |
| 363 | + if (det.hidden || det.dataset.listo) return; | |
| 234 | 364 | det.replaceChildren(el('div', 'muted', tx('loadingDetails'))); |
| 235 | 365 | try { |
| 236 | 366 | const ovsx = await import('./openvsx.js'); |
| 237 | 367 | const { analyzeManifest } = await import('./vsix.js'); |
| 238 | 368 | const meta = await ovsx.metadata(it.namespace, it.name, it.version); |
| 239 | 369 | const a = analyzeManifest(await ovsx.manifest(meta)); |
| 370 | + const r = resumen({ themes: a.applies.themes, grammarLangs: a.grammarLangs, languageList: a.languageList, snippetLangs: a.snippetLangs, ignored: a.ignored, hasCode: a.hasCode, pack: a.pack }); | |
| 240 | 371 | det.replaceChildren(); |
| 241 | - for (const l of lineasResumen({ ...a.applies, snippetLangs: a.snippetLangs, ignored: a.ignored, hasCode: a.hasCode, pack: a.pack })) det.appendChild(el('div', l.cls, l.t)); | |
| 372 | + for (const l of r.lineas) det.appendChild(el('div', l.cls, l.t)); | |
| 242 | 373 | const lic = el('div', 'ext-meta muted', tx('license', { l: meta.license || tx('noLicense') }) + ' '); |
| 243 | 374 | if (meta.files.license) { |
| 244 | 375 | const a2 = el('a', null, tx('viewLicense')); |
| @@ -250,36 +381,58 @@ | ||
| 250 | 381 | det.appendChild(lic); |
| 251 | 382 | det.dataset.listo = '1'; |
| 252 | 383 | // nada aplicable: instalarla solo daría un error, mejor decirlo en el botón |
| 253 | - const boton = det.closest('.ext-row')?.querySelector('.ext-install'); | |
| 254 | - if (!a.any && boton && !boton.disabled) { boton.disabled = true; boton.title = tx('nothing'); boton.className = 'ghost ext-install'; } | |
| 384 | + const inst = det.closest('.ext-row')?.querySelector('.ext-install'); | |
| 385 | + if (!r.any && inst && !esInerte(inst)) { inerte(inst, true); inst.title = tx('nothing'); inst.className = 'ghost ext-install'; } | |
| 255 | 386 | } catch (e) { det.replaceChildren(el('div', 'ext-ignored', textoError(e))); } |
| 256 | 387 | } |
| 257 | 388 | |
| 258 | 389 | async function instala(src, boton) { |
| 259 | 390 | const nombre = src instanceof Blob ? src.name : src.displayName; |
| 260 | - const original = boton?.textContent; | |
| 261 | - if (boton) { boton.disabled = true; boton.textContent = tx('installing'); } | |
| 391 | + const original = boton ? { texto: boton.textContent, accesible: boton.getAttribute('aria-label') } : null; | |
| 392 | + if (boton) { inerte(boton, true); rotula(boton, tx('installing')); } | |
| 262 | 393 | aviso(null); |
| 263 | 394 | try { |
| 264 | 395 | const rec = await host.install(src instanceof Blob ? src : { namespace: src.namespace, name: src.name, version: src.version }, { |
| 265 | 396 | onProgress: (n, total) => { if (boton && total) boton.textContent = tx('downloading', { pct: Math.round(n / total * 100) }); }, |
| 266 | 397 | confirmLarge: async mb => confirm(tx('bigConfirm', { mb })), |
| 267 | 398 | }); |
| 268 | - if (boton) { boton.textContent = tx('installedOk'); boton.className = 'ghost ext-install'; } | |
| 269 | - aviso(tx('installedMsg', { name: rec.displayName || nombre })); | |
| 399 | + if (boton) { rotula(boton, tx('installedOk'), tx('installedNamed', { name: rec.displayName || nombre })); boton.className = 'ghost ext-install'; } | |
| 400 | + const nAvisos = avisosVisibles(rec.warnings).length; | |
| 401 | + aviso(tx('installedMsg', { name: rec.displayName || nombre }) + (nAvisos ? ' ' + tx('warnSummary', { n: nAvisos }) + '.' : '')); | |
| 270 | 402 | } catch (e) { |
| 271 | - if (boton) { boton.disabled = false; boton.textContent = original; } | |
| 403 | + if (boton) { inerte(boton, false); rotula(boton, original.texto, original.accesible); } | |
| 272 | 404 | aviso(textoError(e), true); |
| 273 | 405 | } |
| 274 | 406 | } |
| 275 | 407 | |
| 408 | +// ── instaladas ── | |
| 409 | +function claveFoco(x) { | |
| 410 | + const k = x?.closest?.('[data-k]')?.dataset.k; | |
| 411 | + const id = x?.closest?.('.ext-row')?.dataset.id; | |
| 412 | + return k && id ? { id, k } : null; | |
| 413 | +} | |
| 414 | +function recuperaFoco(box, f) { | |
| 415 | + if (!f) return; | |
| 416 | + if (f.heading) { $('ext-installed-h')?.focus(); return; } | |
| 417 | + const fila = [...box.querySelectorAll('.ext-row')].find(r => r.dataset.id === f.id); | |
| 418 | + const x = fila && ([...fila.querySelectorAll('[data-k]')].find(c => c.dataset.k === f.k) || fila.querySelector('[data-k="toggle"]')); | |
| 419 | + if (x) x.focus(); else $('ext-installed-h')?.focus(); | |
| 420 | +} | |
| 421 | + | |
| 276 | 422 | function pintaInstaladas() { |
| 277 | 423 | const box = $('ext-installed'); |
| 278 | 424 | if (!box) return; |
| 425 | + // se rehace entera: lo que tenía el foco aquí dentro lo recupera después | |
| 426 | + const foco = focoPendiente || (box.contains(document.activeElement) ? claveFoco(document.activeElement) : null); | |
| 427 | + focoPendiente = null; | |
| 428 | + // …y los avisos que estaban desplegados siguen desplegados | |
| 429 | + const desplegados = new Set([...box.querySelectorAll('details.ext-warn[open]')].map(d => d.closest('.ext-row')?.dataset.id)); | |
| 279 | 430 | const lista = host.list(); |
| 280 | - box.replaceChildren(el('div', 'sk-h', tx('installedH', { n: lista.length }))); | |
| 281 | - if (!lista.length) { box.appendChild(el('p', 'muted ext-hint', tx('none'))); return; } | |
| 282 | - const saltadas = host.skippedGrammars(); | |
| 431 | + const cab = el('div', 'sk-h', tx('installedH', { n: lista.length })); | |
| 432 | + cab.id = 'ext-installed-h'; | |
| 433 | + cab.tabIndex = -1; | |
| 434 | + box.replaceChildren(cab); | |
| 435 | + if (!lista.length) { box.appendChild(el('p', 'muted ext-hint', tx('none'))); recuperaFoco(box, foco && { heading: true }); return; } | |
| 283 | 436 | for (const e of lista.slice().reverse()) { |
| 284 | 437 | const row = el('div', 'ext-row installed' + (e.enabled ? '' : ' off')); |
| 285 | 438 | row.dataset.id = e.id; |
| @@ -288,42 +441,83 @@ | ||
| 288 | 441 | t.append(el('b', null, e.displayName), el('span', 'muted', ` ${e.id} · v${e.version}${e.enabled ? '' : ' · ' + tx('disabled')}`)); |
| 289 | 442 | main.append(t); |
| 290 | 443 | if (e.description) main.appendChild(el('div', 'ext-desc', e.description)); |
| 291 | - const langsSnip = [...new Set((e.snippets || []).map(s => s.language))]; | |
| 292 | - for (const l of lineasResumen({ themes: e.themes?.length, grammars: e.grammars?.length, languages: e.languages?.length, snippetLangs: langsSnip, ignored: e.ignored || [], hasCode: e.hasCode, pack: e.pack || [] })) main.appendChild(el('div', l.cls, l.t)); | |
| 293 | - for (const g of saltadas.filter(g => g.ext === e.id)) main.appendChild(el('div', 'ext-ignored', tx('grammarSkipped', { lang: g.language }))); | |
| 444 | + const r = resumen({ | |
| 445 | + themes: e.themes?.length || 0, | |
| 446 | + grammarLangs: (e.grammars || []).map(g => g.language ?? null), | |
| 447 | + languageList: (e.languages || []).map(l => ({ id: l.id, config: !!l.configKey })), | |
| 448 | + snippetLangs: [...new Set((e.snippets || []).map(s => s.language))], | |
| 449 | + ignored: e.ignored || [], hasCode: e.hasCode, pack: e.pack || [], | |
| 450 | + }); | |
| 451 | + for (const l of r.lineas) main.appendChild(el('div', l.cls, l.t)); | |
| 452 | + // lo que el paquete declaraba y no se pudo usar: plegado, sin esconderlo | |
| 453 | + const avisos = avisosVisibles(e.warnings).map(textoAviso).filter(Boolean); | |
| 454 | + if (avisos.length) { | |
| 455 | + const d = el('details', 'ext-warn'); | |
| 456 | + d.open = desplegados.has(e.id); | |
| 457 | + const s = el('summary', null, tx('warnSummary', { n: avisos.length })); | |
| 458 | + s.dataset.k = 'warn'; | |
| 459 | + const ul = el('ul'); | |
| 460 | + for (const a of avisos) ul.appendChild(el('li', null, a)); | |
| 461 | + d.append(s, ul); | |
| 462 | + main.appendChild(d); | |
| 463 | + } | |
| 294 | 464 | if (e.enabled && e.themes?.length) { |
| 295 | 465 | const chips = el('div', 'ext-chips ext-theme-chips'); |
| 296 | 466 | for (const th of e.themes) { |
| 297 | - const c = el('button', 'ext-chip' + (host.currentTheme() === th.themeId ? ' on' : ''), '◐ ' + th.label); | |
| 467 | + const on = host.currentTheme() === th.themeId; | |
| 468 | + const c = el('button', 'ext-chip' + (on ? ' on' : ''), '◐ ' + th.label); | |
| 469 | + c.type = 'button'; | |
| 298 | 470 | c.dataset.theme = th.themeId; |
| 299 | - c.onclick = async () => { await host.setTheme(th.themeId); pintaInstaladas(); }; | |
| 471 | + c.dataset.k = 'theme:' + th.themeId; | |
| 472 | + c.setAttribute('aria-pressed', String(on)); | |
| 473 | + c.onclick = async () => { focoPendiente = { id: e.id, k: c.dataset.k }; await host.setTheme(th.themeId); pintaInstaladas(); }; | |
| 300 | 474 | chips.appendChild(c); |
| 301 | 475 | } |
| 302 | 476 | main.appendChild(chips); |
| 303 | 477 | } |
| 304 | 478 | const meta = el('div', 'ext-meta muted', tx('license', { l: e.license || tx('noLicense') }) + ' · ' + (e.source === 'file' ? tx('fromFile') : e.verified ? tx('verified') : tx('unverified')) + ' '); |
| 305 | 479 | if (e.licenseKey) { |
| 306 | - const ver = el('a', null, tx('viewLicense')); | |
| 307 | - ver.href = '#'; | |
| 480 | + const ver = el('button', 'ext-link', tx('viewLicense')); | |
| 481 | + ver.type = 'button'; | |
| 482 | + ver.dataset.k = 'license'; | |
| 308 | 483 | const pre = el('pre', 'ext-license'); |
| 309 | 484 | pre.hidden = true; |
| 310 | - ver.onclick = async ev => { | |
| 311 | - ev.preventDefault(); | |
| 485 | + pre.id = 'ext-lic-' + (++nDetalle); | |
| 486 | + ver.setAttribute('aria-expanded', 'false'); | |
| 487 | + ver.setAttribute('aria-controls', pre.id); | |
| 488 | + ver.onclick = async () => { | |
| 312 | 489 | if (pre.hidden && !pre.textContent) pre.textContent = await host.licenseText(e.id); |
| 313 | 490 | pre.hidden = !pre.hidden; |
| 491 | + ver.setAttribute('aria-expanded', String(!pre.hidden)); | |
| 314 | 492 | }; |
| 315 | 493 | meta.appendChild(ver); |
| 316 | 494 | main.append(meta, pre); |
| 317 | 495 | } else main.appendChild(meta); |
| 318 | 496 | |
| 319 | 497 | const acc = el('div', 'ext-actions'); |
| 320 | - const bOn = el('button', 'ghost ext-toggle', e.enabled ? tx('disable') : tx('enable')); | |
| 321 | - bOn.onclick = async () => { bOn.disabled = true; try { await host.setEnabled(e.id, !e.enabled); } catch (err) { aviso(textoError(err), true); } pintaInstaladas(); }; | |
| 322 | - const bDel = el('button', 'ghost ext-uninstall', tx('uninstall')); | |
| 498 | + const bOn = el('button', 'ghost ext-toggle'); | |
| 499 | + bOn.type = 'button'; | |
| 500 | + bOn.dataset.k = 'toggle'; | |
| 501 | + rotula(bOn, e.enabled ? tx('disable') : tx('enable'), tx(e.enabled ? 'disableNamed' : 'enableNamed', { name: e.displayName })); | |
| 502 | + bOn.onclick = async () => { | |
| 503 | + focoPendiente = { id: e.id, k: 'toggle' }; | |
| 504 | + bOn.disabled = true; | |
| 505 | + try { await host.setEnabled(e.id, !e.enabled); } catch (err) { aviso(textoError(err), true); } | |
| 506 | + pintaInstaladas(); | |
| 507 | + }; | |
| 508 | + const bDel = el('button', 'ghost ext-uninstall'); | |
| 509 | + bDel.type = 'button'; | |
| 510 | + bDel.dataset.k = 'uninstall'; | |
| 511 | + rotula(bDel, tx('uninstall'), tx('uninstallNamed', { name: e.displayName })); | |
| 323 | 512 | bDel.onclick = async () => { |
| 324 | 513 | if (!confirm(tx('confirmUninstall', { name: e.displayName }))) return; |
| 514 | + // la fila desaparece: el foco pasa a la siguiente (o a la anterior, o al título) | |
| 515 | + const filas = [...box.querySelectorAll('.ext-row')]; | |
| 516 | + const i = filas.findIndex(f => f.dataset.id === e.id); | |
| 517 | + const otra = filas[i + 1] || filas[i - 1]; | |
| 518 | + focoPendiente = otra ? { id: otra.dataset.id, k: 'toggle' } : { heading: true }; | |
| 325 | 519 | bDel.disabled = true; |
| 326 | - try { await host.uninstall(e.id); } catch (err) { aviso(textoError(err), true); } | |
| 520 | + try { await host.uninstall(e.id); } catch (err) { focoPendiente = { id: e.id, k: 'uninstall' }; aviso(textoError(err), true); } | |
| 327 | 521 | pintaInstaladas(); |
| 328 | 522 | pintaResultados(); |
| 329 | 523 | }; |
| @@ -331,13 +525,18 @@ | ||
| 331 | 525 | row.append(icono(null, e.displayName), main, acc); |
| 332 | 526 | box.appendChild(row); |
| 333 | 527 | } |
| 528 | + recuperaFoco(box, foco); | |
| 334 | 529 | } |
| 335 | 530 | |
| 336 | 531 | // ── selector de tema (estilo «Color Theme» de VS Code) ── |
| 532 | +// Un combobox con su lista: las flechas mueven la opción activa (y la | |
| 533 | +// previsualizan), el lector la anuncia (aria-activedescendant), y al cerrar el | |
| 534 | +// foco vuelve a donde estaba. | |
| 337 | 535 | export function openThemePicker(h) { |
| 338 | 536 | host = h; |
| 339 | 537 | ponCss(); |
| 340 | 538 | $('ext-themepick')?.remove(); |
| 539 | + const previo = document.activeElement; | |
| 341 | 540 | const original = h.currentTheme(); |
| 342 | 541 | const caja = el('div'); |
| 343 | 542 | caja.id = 'ext-themepick'; |
| @@ -345,7 +544,15 @@ | ||
| 345 | 544 | inp.placeholder = tx('pickPh'); |
| 346 | 545 | inp.autocomplete = 'off'; |
| 347 | 546 | inp.spellcheck = false; |
| 547 | + inp.setAttribute('role', 'combobox'); | |
| 548 | + inp.setAttribute('aria-label', tx('pickPh')); | |
| 549 | + inp.setAttribute('aria-expanded', 'true'); | |
| 550 | + inp.setAttribute('aria-autocomplete', 'list'); | |
| 551 | + inp.setAttribute('aria-controls', 'ext-tp-list'); | |
| 348 | 552 | const lista = el('div', 'tp-list'); |
| 553 | + lista.id = 'ext-tp-list'; | |
| 554 | + lista.setAttribute('role', 'listbox'); | |
| 555 | + lista.setAttribute('aria-label', tx('themeList')); | |
| 349 | 556 | caja.append(inp, lista); |
| 350 | 557 | document.body.appendChild(caja); |
| 351 | 558 | |
| @@ -356,6 +563,7 @@ | ||
| 356 | 563 | cerrado = true; |
| 357 | 564 | document.removeEventListener('mousedown', fuera, true); |
| 358 | 565 | caja.remove(); |
| 566 | + devuelveFoco(previo, $('ext-theme-btn'), enfocaEditor, $('act-ext')); | |
| 359 | 567 | if (aplicar) await h.setTheme(aplicar); |
| 360 | 568 | else await h.previewTheme(original); |
| 361 | 569 | if ($('ext-panel')?.isConnected) pintaInstaladas(); |
| @@ -368,23 +576,38 @@ | ||
| 368 | 576 | const todos = h.themes(); |
| 369 | 577 | items = todos.filter(t => !q || (etiqueta(t) + ' ' + (t.extName || '')).toLowerCase().includes(q)); |
| 370 | 578 | lista.replaceChildren(); |
| 371 | - let grupo = null; | |
| 579 | + let grupo = null, caja2 = null; | |
| 372 | 580 | items.forEach((t, i) => { |
| 373 | 581 | const g = t.builtin ? tx('builtinGroup') : t.extName; |
| 374 | - if (g !== grupo) { grupo = g; lista.appendChild(el('div', 'tp-group', g)); } | |
| 375 | - const row = el('button', 'tp-item' + (i === sel ? ' sel' : '')); | |
| 582 | + if (g !== grupo || !caja2) { | |
| 583 | + grupo = g; | |
| 584 | + caja2 = el('div', 'tp-grupo'); | |
| 585 | + caja2.setAttribute('role', 'group'); | |
| 586 | + caja2.setAttribute('aria-label', g); | |
| 587 | + const cab = el('div', 'tp-group', g); | |
| 588 | + cab.setAttribute('aria-hidden', 'true'); | |
| 589 | + caja2.appendChild(cab); | |
| 590 | + lista.appendChild(caja2); | |
| 591 | + } | |
| 592 | + const row = el('div', 'tp-item' + (i === sel ? ' sel' : '')); | |
| 593 | + row.id = 'ext-tp-' + i; | |
| 594 | + row.setAttribute('role', 'option'); | |
| 595 | + row.setAttribute('aria-selected', String(i === sel)); | |
| 376 | 596 | row.dataset.theme = t.id; |
| 377 | 597 | row.append(el('span', null, etiqueta(t))); |
| 378 | 598 | if (t.id === original) row.appendChild(el('span', 'muted', tx('current'))); |
| 379 | 599 | row.onclick = () => cerrar(t.id); |
| 380 | - lista.appendChild(row); | |
| 600 | + caja2.appendChild(row); | |
| 381 | 601 | }); |
| 382 | 602 | } |
| 383 | 603 | const marca = () => { |
| 384 | - lista.querySelectorAll('.tp-item').forEach((r, i) => r.classList.toggle('sel', i === sel)); | |
| 385 | - lista.querySelectorAll('.tp-item')[sel]?.scrollIntoView({ block: 'nearest' }); | |
| 604 | + const filas = lista.querySelectorAll('.tp-item'); | |
| 605 | + filas.forEach((r, i) => { r.classList.toggle('sel', i === sel); r.setAttribute('aria-selected', String(i === sel)); }); | |
| 606 | + const activa = filas[sel]; | |
| 607 | + if (activa) { inp.setAttribute('aria-activedescendant', activa.id); activa.scrollIntoView({ block: 'nearest' }); } | |
| 608 | + else inp.removeAttribute('aria-activedescendant'); | |
| 386 | 609 | }; |
| 387 | - inp.oninput = () => { sel = 0; pintaLista(); }; | |
| 610 | + inp.oninput = () => { sel = 0; pintaLista(); marca(); }; | |
| 388 | 611 | inp.onkeydown = e => { |
| 389 | 612 | if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { |
| 390 | 613 | e.preventDefault(); |
modified web/js/ext/snippets.js +10 −2
| @@ -36,6 +36,10 @@ | ||
| 36 | 36 | return wordStart; |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | +// Cabecera de la sugerencia: «descripción (Extensión)». `detail` y un | |
| 40 | +// `documentation` string son texto para Monaco, no Markdown. | |
| 41 | +export const cabecera = (s, ext = '') => (s.description || s.name) + (ext ? ` (${ext})` : ''); | |
| 42 | + | |
| 39 | 43 | // Un proveedor por lenguaje. `cargar()` devuelve (una vez, en diferido) la |
| 40 | 44 | // lista de snippets de todas las extensiones activas para ese lenguaje. |
| 41 | 45 | export function registerSnippets(monaco, language, cargar, origen = () => '') { |
| @@ -51,8 +55,12 @@ | ||
| 51 | 55 | const suggestions = lista.map(s => ({ |
| 52 | 56 | label: s.prefix, |
| 53 | 57 | kind: K, |
| 54 | - detail: s.description || s.name, | |
| 55 | - documentation: { value: (s.description ? s.description + '\n\n' : '') + '```\n' + s.body + '\n```' + (origen(s) ? '\n\n' + origen(s) : '') }, | |
| 58 | + // como VS Code: arriba la descripción y de qué extensión viene, y en el | |
| 59 | + // detalle el cuerpo. Todo texto plano, NUNCA Markdown: Monaco pintaría | |
| 60 | + // las imágenes y enlaces que escriba la extensión y el navegador las | |
| 61 | + // pediría a cualquier servidor (IP, hora y origen de quien mira). | |
| 62 | + detail: cabecera(s, origen(s)), | |
| 63 | + documentation: s.body, | |
| 56 | 64 | insertText: s.body, |
| 57 | 65 | insertTextRules: R, |
| 58 | 66 | range: new monaco.Range(position.lineNumber, replaceStart(antes, s.prefix, palabra.startColumn), position.lineNumber, position.column), |
modified web/js/ext/store.js +1 −1
| @@ -28,7 +28,7 @@ | ||
| 28 | 28 | resolve(db); |
| 29 | 29 | }; |
| 30 | 30 | req.onerror = () => { dbp = null; reject(req.error); }; |
| 31 | - req.onblocked = () => { dbp = null; reject(new Error('base de extensiones bloqueada por otra pestaña')); }; | |
| 31 | + req.onblocked = () => { dbp = null; reject(Object.assign(new Error('base de extensiones bloqueada por otra pestaña'), { code: 'blocked' })); }; | |
| 32 | 32 | }); |
| 33 | 33 | return dbp; |
| 34 | 34 | } |
modified web/js/ext/themes.js +17 −5
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | const out = []; |
| 19 | 19 | for (const seg of (base ? base + '/' : '').concat(String(rel)).split('/')) { |
| 20 | 20 | if (!seg || seg === '.') continue; |
| 21 | - if (seg === '..') { if (!out.length) throw new Error('ruta fuera del paquete: ' + rel); out.pop(); } else out.push(seg); | |
| 21 | + if (seg === '..') { if (!out.length) throw Object.assign(new Error('ruta fuera del paquete: ' + rel), { code: 'outside' }); out.pop(); } else out.push(seg); | |
| 22 | 22 | } |
| 23 | 23 | return out.join('/'); |
| 24 | 24 | } |
| @@ -48,7 +48,7 @@ | ||
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | async function cargaEn(path, readText, out, prof) { |
| 51 | - if (prof > 8) throw new Error('demasiados include en el tema'); | |
| 51 | + if (prof > 8) throw Object.assign(new Error('demasiados include en el tema'), { code: 'notheme' }); | |
| 52 | 52 | if (/\.json$/i.test(path)) { |
| 53 | 53 | const j = parseJsonc(await readText(path)); |
| 54 | 54 | if (typeof j.include === 'string') await cargaEn(joinPath(dirname(path), j.include), readText, out, prof + 1); |
| @@ -67,7 +67,7 @@ | ||
| 67 | 67 | if (typeof j.type === 'string') out.type = j.type; |
| 68 | 68 | } else { |
| 69 | 69 | const t = parsePlist(await readText(path)); |
| 70 | - if (!Array.isArray(t?.settings)) throw new Error('el .tmTheme no tiene settings'); | |
| 70 | + if (!Array.isArray(t?.settings)) throw Object.assign(new Error('el .tmTheme no tiene settings'), { code: 'notheme' }); | |
| 71 | 71 | convertSettings(t.settings, out); |
| 72 | 72 | } |
| 73 | 73 | } |
| @@ -235,11 +235,20 @@ | ||
| 235 | 235 | // (el alfa mezclado sobre el fondo): Monaco no admite otra forma en su mapa de |
| 236 | 236 | // colores y los dos mapas tienen que deduplicar igual para que los índices |
| 237 | 237 | // coincidan. |
| 238 | +// | |
| 239 | +// El motor guarda los ámbitos del tema en un árbol de objetos normales y | |
| 240 | +// pregunta con `hijos.hasOwnProperty(trozo)`: un trozo «hasOwnProperty» tapa | |
| 241 | +// ese método y el motor revienta con TODOS los temas siguientes; uno | |
| 242 | +// «__proto__» cambia el prototipo del nodo. Esos selectores no pasan. | |
| 243 | +const TROZOS_PELIGROSOS = new Set(['__proto__', 'hasOwnProperty']); | |
| 244 | +const selectorSeguro = s => !s.split(/[^\w$]+/).some(t => TROZOS_PELIGROSOS.has(t)); | |
| 238 | 245 | export function toTextMateTheme(theme) { |
| 239 | 246 | const { fg, bg } = defaults(theme); |
| 240 | 247 | const settings = [{ settings: { foreground: fg, background: bg } }]; |
| 241 | - for (const r of theme.tokenColors || []) { | |
| 242 | - if (!r.scope || !r.scope.length) continue; | |
| 248 | + for (const r0 of theme.tokenColors || []) { | |
| 249 | + if (!r0?.settings || !Array.isArray(r0.scope)) continue; | |
| 250 | + const r = { ...r0, scope: r0.scope.filter(s => typeof s === 'string' && selectorSeguro(s)) }; | |
| 251 | + if (!r.scope.length) continue; | |
| 243 | 252 | const st = {}; |
| 244 | 253 | const f = hex6(r.settings.foreground, bg); if (f) st.foreground = f; |
| 245 | 254 | const b = hex6(r.settings.background, bg); if (b) st.background = b; |
| @@ -327,6 +336,9 @@ | ||
| 327 | 336 | `#tabs-bar { background: ${tabs};${borde ? ` border-bottom-color: ${borde};` : ''} }`, |
| 328 | 337 | `#tabs-bar .tab { color: ${texto};${borde ? ` border-right-color: ${borde};` : ''} }`, |
| 329 | 338 | `#tabs-bar .tab.active { background: ${activa}; color: ${textoActiva};${acento ? ` box-shadow: inset 0 2px 0 ${acento};` : ''} }`, |
| 339 | + // el ● de «sin guardar» lleva el color claro del IDE (code.css): con un | |
| 340 | + // tema claro desaparecería, y es el único aviso de cambios sin guardar | |
| 341 | + `#tabs-bar .tab b.dirty { color: inherit; }`, | |
| 330 | 342 | `#editor-empty { background: ${bg}; color: ${texto}; }`, |
| 331 | 343 | ].join('\n'); |
| 332 | 344 | } |
modified web/js/ext/unzip.js +17 −12
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | // verdad, no lo que dice la cabecera. |
| 7 | 7 | |
| 8 | 8 | const u16 = (b, o) => b[o] | (b[o + 1] << 8); |
| 9 | +// Errores con código (el panel los traduce) y, si la hay, la entrada del zip. | |
| 10 | +const fallo = (msg, code, entry) => Object.assign(new Error(msg), { code, ...(entry && { entry }) }); | |
| 9 | 11 | const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; |
| 10 | 12 | |
| 11 | 13 | let CRC_TABLA = null; |
| @@ -34,12 +36,12 @@ | ||
| 34 | 36 | if (eocd < 0) throw Object.assign(new Error('no es un zip (falta el directorio central)'), { code: 'notvsix' }); |
| 35 | 37 | const total = u16(b, eocd + 10); |
| 36 | 38 | const cdOffset = u32(b, eocd + 16); |
| 37 | - if (total === 0xffff || cdOffset === 0xffffffff) throw new Error('zip64 no soportado'); | |
| 39 | + if (total === 0xffff || cdOffset === 0xffffffff) throw fallo('zip64 no soportado', 'corrupt'); | |
| 38 | 40 | const entries = []; |
| 39 | 41 | const dec = new TextDecoder(); |
| 40 | 42 | let p = cdOffset; |
| 41 | 43 | for (let k = 0; k < total; k++) { |
| 42 | - if (p + 46 > b.length || u32(b, p) !== 0x02014b50) throw new Error('directorio central corrupto'); | |
| 44 | + if (p + 46 > b.length || u32(b, p) !== 0x02014b50) throw fallo('directorio central corrupto', 'corrupt'); | |
| 43 | 45 | const flags = u16(b, p + 8); |
| 44 | 46 | const method = u16(b, p + 10); |
| 45 | 47 | const crc = u32(b, p + 16); |
| @@ -63,7 +65,7 @@ | ||
| 63 | 65 | const { done, value } = await lector.read(); |
| 64 | 66 | if (done) break; |
| 65 | 67 | n += value.length; |
| 66 | - if (n > tope) { lector.cancel().catch(() => {}); throw new Error('entrada demasiado grande al descomprimir'); } | |
| 68 | + if (n > tope) { lector.cancel().catch(() => {}); throw fallo('entrada demasiado grande al descomprimir', 'big'); } | |
| 67 | 69 | trozos.push(value); |
| 68 | 70 | } |
| 69 | 71 | const out = new Uint8Array(n); |
| @@ -81,19 +83,22 @@ | ||
| 81 | 83 | let gastado = 0; |
| 82 | 84 | async function read(name) { |
| 83 | 85 | const e = porNombre.get(name); |
| 84 | - if (!e) throw new Error('no está en el paquete: ' + name); | |
| 85 | - if (e.flags & 1) throw new Error('entrada cifrada: ' + name); | |
| 86 | - if (e.usize > maxEntry) throw new Error(`${name} pesa demasiado (${e.usize} bytes)`); | |
| 87 | - if (gastado + e.usize > maxTotal) throw new Error('el paquete descomprime demasiado'); | |
| 88 | - if (e.local + 30 > b.length || u32(b, e.local) !== 0x04034b50) throw new Error('cabecera local corrupta: ' + name); | |
| 86 | + if (!e) throw fallo('no está en el paquete: ' + name, 'missing', name); | |
| 87 | + if (e.flags & 1) throw fallo('entrada cifrada: ' + name, 'corrupt', name); | |
| 88 | + if (e.usize > maxEntry) throw fallo(`${name} pesa demasiado (${e.usize} bytes)`, 'big', name); | |
| 89 | + if (gastado + e.usize > maxTotal) throw fallo('el paquete descomprime demasiado', 'big', name); | |
| 90 | + if (e.local + 30 > b.length || u32(b, e.local) !== 0x04034b50) throw fallo('cabecera local corrupta: ' + name, 'corrupt', name); | |
| 89 | 91 | const inicio = e.local + 30 + u16(b, e.local + 26) + u16(b, e.local + 28); |
| 90 | 92 | const datos = b.subarray(inicio, inicio + e.csize); |
| 91 | - if (datos.length !== e.csize) throw new Error('entrada truncada: ' + name); | |
| 93 | + if (datos.length !== e.csize) throw fallo('entrada truncada: ' + name, 'corrupt', name); | |
| 92 | 94 | let out; |
| 93 | 95 | if (e.method === 0) out = datos.slice(); |
| 94 | - else if (e.method === 8) out = await inflateRaw(datos, Math.min(maxEntry, e.usize)); | |
| 95 | - else throw new Error(`compresión ${e.method} no soportada: ${name}`); | |
| 96 | - if (out.length !== e.usize || crc32(out) !== e.crc) throw new Error('CRC incorrecto: ' + name); | |
| 96 | + else if (e.method === 8) { | |
| 97 | + try { out = await inflateRaw(datos, Math.min(maxEntry, e.usize)); } | |
| 98 | + catch (err) { throw err?.code === 'big' ? err : fallo('no se pudo descomprimir: ' + name, 'corrupt', name); } // el resto: datos que no son deflate | |
| 99 | + } | |
| 100 | + else throw fallo(`compresión ${e.method} no soportada: ${name}`, 'corrupt', name); | |
| 101 | + if (out.length !== e.usize || crc32(out) !== e.crc) throw fallo('CRC incorrecto: ' + name, 'corrupt', name); | |
| 97 | 102 | gastado += out.length; |
| 98 | 103 | return out; |
| 99 | 104 | } |
added web/js/ext/vendor/vscode-oniguruma@2.0.1/LICENSE.txt +23 −0
| @@ -0,0 +1,23 @@ | ||
| 1 | +VS Code Oniguruma Bindings | |
| 2 | + | |
| 3 | +MIT License | |
| 4 | + | |
| 5 | +Copyright (c) Microsoft Corporation. | |
| 6 | + | |
| 7 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 8 | +of this software and associated documentation files (the "Software"), to deal | |
| 9 | +in the Software without restriction, including without limitation the rights | |
| 10 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 11 | +copies of the Software, and to permit persons to whom the Software is | |
| 12 | +furnished to do so, subject to the following conditions: | |
| 13 | + | |
| 14 | +The above copyright notice and this permission notice shall be included in all | |
| 15 | +copies or substantial portions of the Software. | |
| 16 | + | |
| 17 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 18 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 19 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 20 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 21 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 22 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 23 | +SOFTWARE. |
added web/js/ext/vendor/vscode-oniguruma@2.0.1/NOTICES.txt +41 −0
| @@ -0,0 +1,41 @@ | ||
| 1 | +THIRD-PARTY SOFTWARE NOTICES AND INFORMATION | |
| 2 | +Do Not Translate or Localize | |
| 3 | + | |
| 4 | +This project incorporates material from the project(s) listed below (collectively, “Third Party Code”). | |
| 5 | +Microsoft is not the original author of the Third Party Code. The original copyright notice and license | |
| 6 | +under which Microsoft received such Third Party Code are set out below. This Third Party Code is licensed | |
| 7 | +to you under their original license terms set forth below. Microsoft reserves all other rights not | |
| 8 | +expressly granted, whether by implication, estoppel or otherwise. | |
| 9 | + | |
| 10 | +The following files/folders contain third party software: | |
| 11 | + | |
| 12 | +========================================================================================================= | |
| 13 | +deps/oniguruma/ --- oniguruma version 6.9.5_rev1 https://github.com/kkos/oniguruma/tree/v6.9.5_rev1 | |
| 14 | +--------------------------------------------------------------------------------------------------------- | |
| 15 | + | |
| 16 | +Oniguruma LICENSE | |
| 17 | +----------------- | |
| 18 | + | |
| 19 | +Copyright (c) 2002-2020 K.Kosako <kkosako0@gmail.com> | |
| 20 | +All rights reserved. | |
| 21 | + | |
| 22 | +Redistribution and use in source and binary forms, with or without | |
| 23 | +modification, are permitted provided that the following conditions | |
| 24 | +are met: | |
| 25 | +1. Redistributions of source code must retain the above copyright | |
| 26 | + notice, this list of conditions and the following disclaimer. | |
| 27 | +2. Redistributions in binary form must reproduce the above copyright | |
| 28 | + notice, this list of conditions and the following disclaimer in the | |
| 29 | + documentation and/or other materials provided with the distribution. | |
| 30 | + | |
| 31 | +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND | |
| 32 | +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
| 33 | +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
| 34 | +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE | |
| 35 | +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
| 36 | +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS | |
| 37 | +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) | |
| 38 | +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | |
| 39 | +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | |
| 40 | +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF | |
| 41 | +SUCH DAMAGE. |
added web/js/ext/vendor/vscode-oniguruma@2.0.1/main.js +4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +// vscode-oniguruma 2.0.1 (MIT, Microsoft): release/main.js del paquete npm, SIN CAMBIOS, dentro de este envoltorio de módulo ES (esta línea, la siguiente y la última). Original: 20469 bytes, sha384-KznAEs+/b3fCQKg6wXrLJQvj0dOjyZQpdCrIpt7hC03S7EovcZMXlHRHRN291Uaj. Licencia: LICENSE.txt y NOTICES.txt. Comprobación: tests/ext_unit.mjs. | |
| 2 | +const module = { exports: {} }, exports = module.exports; | |
| 3 | +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.onig=t():e.onig=t()}(this,(()=>{return e={770:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setDefaultDebugCall=t.createOnigScanner=t.createOnigString=t.loadWASM=t.OnigScanner=t.OnigString=void 0;const i=r(n(418));let o=null,a=!1;class s{static _utf8ByteLength(e){let t=0;for(let n=0,r=e.length;n<r;n++){const i=e.charCodeAt(n);let o=i,a=!1;if(i>=55296&&i<=56319&&n+1<r){const t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(o=65536+(i-55296<<10)|t-56320,a=!0)}t+=o<=127?1:o<=2047?2:o<=65535?3:4,a&&n++}return t}constructor(e){const t=e.length,n=s._utf8ByteLength(e),r=n!==t,i=r?new Uint32Array(t+1):null;r&&(i[t]=n);const o=r?new Uint32Array(n+1):null;r&&(o[n]=t);const a=new Uint8Array(n);let f=0;for(let n=0;n<t;n++){const s=e.charCodeAt(n);let u=s,c=!1;if(s>=55296&&s<=56319&&n+1<t){const t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(u=65536+(s-55296<<10)|t-56320,c=!0)}r&&(i[n]=f,c&&(i[n+1]=f),u<=127?o[f+0]=n:u<=2047?(o[f+0]=n,o[f+1]=n):u<=65535?(o[f+0]=n,o[f+1]=n,o[f+2]=n):(o[f+0]=n,o[f+1]=n,o[f+2]=n,o[f+3]=n)),u<=127?a[f++]=u:u<=2047?(a[f++]=192|(1984&u)>>>6,a[f++]=128|(63&u)>>>0):u<=65535?(a[f++]=224|(61440&u)>>>12,a[f++]=128|(4032&u)>>>6,a[f++]=128|(63&u)>>>0):(a[f++]=240|(1835008&u)>>>18,a[f++]=128|(258048&u)>>>12,a[f++]=128|(4032&u)>>>6,a[f++]=128|(63&u)>>>0),c&&n++}this.utf16Length=t,this.utf8Length=n,this.utf16Value=e,this.utf8Value=a,this.utf16OffsetToUtf8=i,this.utf8OffsetToUtf16=o}createString(e){const t=e._omalloc(this.utf8Length);return e.HEAPU8.set(this.utf8Value,t),t}}class f{constructor(e){if(this.id=++f.LAST_ID,!o)throw new Error("Must invoke loadWASM first.");this._onigBinding=o,this.content=e;const t=new s(e);this.utf16Length=t.utf16Length,this.utf8Length=t.utf8Length,this.utf16OffsetToUtf8=t.utf16OffsetToUtf8,this.utf8OffsetToUtf16=t.utf8OffsetToUtf16,this.utf8Length<1e4&&!f._sharedPtrInUse?(f._sharedPtr||(f._sharedPtr=o._omalloc(1e4)),f._sharedPtrInUse=!0,o.HEAPU8.set(t.utf8Value,f._sharedPtr),this.ptr=f._sharedPtr):this.ptr=t.createString(o)}convertUtf8OffsetToUtf16(e){return this.utf8OffsetToUtf16?e<0?0:e>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[e]:e}convertUtf16OffsetToUtf8(e){return this.utf16OffsetToUtf8?e<0?0:e>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[e]:e}dispose(){this.ptr===f._sharedPtr?f._sharedPtrInUse=!1:this._onigBinding._ofree(this.ptr)}}t.OnigString=f,f.LAST_ID=0,f._sharedPtr=0,f._sharedPtrInUse=!1;class u{constructor(e,t){var n,r;if(!o)throw new Error("Must invoke loadWASM first.");const i=[],a=[];for(let t=0,n=e.length;t<n;t++){const n=new s(e[t]);i[t]=n.createString(o),a[t]=n.utf8Length}const f=o._omalloc(4*e.length);o.HEAPU32.set(i,f/4);const u=o._omalloc(4*e.length);o.HEAPU32.set(a,u/4),this._onigBinding=o,this._options=null!==(n=null==t?void 0:t.options)&&void 0!==n?n:[10];const c=this.onigOptions(this._options),_=this.onigSyntax(null!==(r=null==t?void 0:t.syntax)&&void 0!==r?r:0),d=o._createOnigScanner(f,u,e.length,c,_);this._ptr=d;for(let t=0,n=e.length;t<n;t++)o._ofree(i[t]);o._ofree(u),o._ofree(f),0===d&&function(e){throw new Error(e.UTF8ToString(e._getLastOnigError()))}(o)}dispose(){this._onigBinding._freeOnigScanner(this._ptr)}findNextMatchSync(e,t,n){let r=a,i=this._options;if(Array.isArray(n)?(n.includes(25)&&(r=!0),i=i.concat(n)):"boolean"==typeof n&&(r=n),"string"==typeof e){e=new f(e);const n=this._findNextMatchSync(e,t,r,i);return e.dispose(),n}return this._findNextMatchSync(e,t,r,i)}_findNextMatchSync(e,t,n,r){const i=this._onigBinding,o=this.onigOptions(r);let a;if(a=n?i._findNextOnigScannerMatchDbg(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(t),o):i._findNextOnigScannerMatch(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(t),o),0===a)return null;const s=i.HEAPU32;let f=a/4;const u=s[f++],c=s[f++];let _=[];for(let t=0;t<c;t++){const n=e.convertUtf8OffsetToUtf16(s[f++]),r=e.convertUtf8OffsetToUtf16(s[f++]);_[t]={start:n,end:r,length:r-n}}return{index:u,captureIndices:_}}onigOptions(e){return e.map((e=>this.onigOption(e))).reduce(((e,t)=>e|t),this._onigBinding.ONIG_OPTION_NONE)}onigSyntax(e){switch(e){case 0:return this._onigBinding.ONIG_SYNTAX_DEFAULT;case 1:return this._onigBinding.ONIG_SYNTAX_ASIS;case 2:return this._onigBinding.ONIG_SYNTAX_POSIX_BASIC;case 3:return this._onigBinding.ONIG_SYNTAX_POSIX_EXTENDED;case 4:return this._onigBinding.ONIG_SYNTAX_EMACS;case 5:return this._onigBinding.ONIG_SYNTAX_GREP;case 6:return this._onigBinding.ONIG_SYNTAX_GNU_REGEX;case 7:return this._onigBinding.ONIG_SYNTAX_JAVA;case 8:return this._onigBinding.ONIG_SYNTAX_PERL;case 9:return this._onigBinding.ONIG_SYNTAX_PERL_NG;case 10:return this._onigBinding.ONIG_SYNTAX_RUBY;case 11:return this._onigBinding.ONIG_SYNTAX_PYTHON;case 12:return this._onigBinding.ONIG_SYNTAX_ONIGURUMA}}onigOption(e){switch(e){case 1:return this._onigBinding.ONIG_OPTION_NONE;case 0:case 25:return this._onigBinding.ONIG_OPTION_DEFAULT;case 2:return this._onigBinding.ONIG_OPTION_IGNORECASE;case 3:return this._onigBinding.ONIG_OPTION_EXTEND;case 4:return this._onigBinding.ONIG_OPTION_MULTILINE;case 5:return this._onigBinding.ONIG_OPTION_SINGLELINE;case 6:return this._onigBinding.ONIG_OPTION_FIND_LONGEST;case 7:return this._onigBinding.ONIG_OPTION_FIND_NOT_EMPTY;case 8:return this._onigBinding.ONIG_OPTION_NEGATE_SINGLELINE;case 9:return this._onigBinding.ONIG_OPTION_DONT_CAPTURE_GROUP;case 10:return this._onigBinding.ONIG_OPTION_CAPTURE_GROUP;case 11:return this._onigBinding.ONIG_OPTION_NOTBOL;case 12:return this._onigBinding.ONIG_OPTION_NOTEOL;case 13:return this._onigBinding.ONIG_OPTION_CHECK_VALIDITY_OF_STRING;case 14:return this._onigBinding.ONIG_OPTION_IGNORECASE_IS_ASCII;case 15:return this._onigBinding.ONIG_OPTION_WORD_IS_ASCII;case 16:return this._onigBinding.ONIG_OPTION_DIGIT_IS_ASCII;case 17:return this._onigBinding.ONIG_OPTION_SPACE_IS_ASCII;case 18:return this._onigBinding.ONIG_OPTION_POSIX_IS_ASCII;case 19:return this._onigBinding.ONIG_OPTION_TEXT_SEGMENT_EXTENDED_GRAPHEME_CLUSTER;case 20:return this._onigBinding.ONIG_OPTION_TEXT_SEGMENT_WORD;case 21:return this._onigBinding.ONIG_OPTION_NOT_BEGIN_STRING;case 22:return this._onigBinding.ONIG_OPTION_NOT_END_STRING;case 23:return this._onigBinding.ONIG_OPTION_NOT_BEGIN_POSITION;case 24:return this._onigBinding.ONIG_OPTION_CALLBACK_EACH_MATCH}}}t.OnigScanner=u;let c=!1,_=null;t.loadWASM=function(e){if(c)return _;let t,n,r,a;if(c=!0,function(e){return"function"==typeof e.instantiator}(e))t=e.instantiator,n=e.print;else{let r;!function(e){return void 0!==e.data}(e)?r=e:(r=e.data,n=e.print),t=function(e){return"undefined"!=typeof Response&&e instanceof Response}(r)?"function"==typeof WebAssembly.instantiateStreaming?function(e){return t=>WebAssembly.instantiateStreaming(e,t)}(r):function(e){return async t=>{const n=await e.arrayBuffer();return WebAssembly.instantiate(n,t)}}(r):function(e){return t=>WebAssembly.instantiate(e,t)}(r)}return _=new Promise(((e,t)=>{r=e,a=t})),function(e,t,n,r){(0,i.default)({print:t,instantiateWasm:(t,n)=>{if("undefined"==typeof performance){const e=()=>Date.now();t.env.emscripten_get_now=e,t.wasi_snapshot_preview1.emscripten_get_now=e}return e(t).then((e=>n(e.instance)),r),{}}}).then((e=>{o=e,n()}))}(t,n,r,a),_},t.createOnigString=function(e){return new f(e)},t.createOnigScanner=function(e){return new u(e)},t.setDefaultDebugCall=function(e){a=e}},418:e=>{var t=("undefined"!=typeof document&&document.currentScript&&document.currentScript.src,function(e={}){var t,n,r=e;r.ready=new Promise(((e,r)=>{t=e,n=r}));var i,o=Object.assign({},r);"undefined"!=typeof read&&read,i=e=>{if("function"==typeof readbuffer)return new Uint8Array(readbuffer(e));let t=read(e,"binary");return"object"==typeof t||P(n),t;var n},"undefined"==typeof clearTimeout&&(globalThis.clearTimeout=e=>{}),"undefined"==typeof setTimeout&&(globalThis.setTimeout=e=>"function"==typeof e?e():P()),"undefined"!=typeof scriptArgs&&scriptArgs,"undefined"!=typeof onig_print&&("undefined"==typeof console&&(console={}),console.log=onig_print,console.warn=console.error="undefined"!=typeof printErr?printErr:onig_print);var a,s,f=r.print||console.log.bind(console),u=r.printErr||console.error.bind(console);Object.assign(r,o),o=null,r.arguments&&r.arguments,r.thisProgram&&r.thisProgram,r.quit&&r.quit,r.wasmBinary&&(a=r.wasmBinary),r.noExitRuntime,"object"!=typeof WebAssembly&&P("no native wasm support detected");var c,_,d,g,l,h,p,O,v=!1;function m(){var e=s.buffer;r.HEAP8=c=new Int8Array(e),r.HEAP16=d=new Int16Array(e),r.HEAPU8=_=new Uint8Array(e),r.HEAPU16=g=new Uint16Array(e),r.HEAP32=l=new Int32Array(e),r.HEAPU32=h=new Uint32Array(e),r.HEAPF32=p=new Float32Array(e),r.HEAPF64=O=new Float64Array(e)}var y=[],I=[],T=[];var N=0,A=null,S=null;function P(e){r.onAbort&&r.onAbort(e),u(e="Aborted("+e+")"),v=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw n(t),t}var E,w;function b(e){return e.startsWith("data:application/octet-stream;base64,")}function C(e){if(e==E&&a)return new Uint8Array(a);if(i)return i(e);throw"both async and sync fetching of the wasm failed"}function U(e,t,n){return function(e){return Promise.resolve().then((()=>C(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(n,(e=>{u(`failed to asynchronously prepare wasm: ${e}`),P(e)}))}b(E="onig.wasm")||(w=E,E=r.locateFile?r.locateFile(w,""):""+w);var G=e=>{for(;e.length>0;)e.shift()(r)},B=void 0,R=e=>{for(var t="",n=e;_[n];)t+=B[_[n++]];return t},W={},L={},D={},x=void 0,M=e=>{throw new x(e)},F=void 0,X=(e,t,n)=>{function r(t){var r=n(t);r.length!==e.length&&(e=>{throw new F(e)})("Mismatched type converter count");for(var i=0;i<e.length;++i)k(e[i],r[i])}e.forEach((function(e){D[e]=t}));var i=new Array(t.length),o=[],a=0;t.forEach(((e,t)=>{L.hasOwnProperty(e)?i[t]=L[e]:(o.push(e),W.hasOwnProperty(e)||(W[e]=[]),W[e].push((()=>{i[t]=L[e],++a===o.length&&r(i)})))})),0===o.length&&r(i)};function k(e,t,n={}){if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(e,t,n={}){var r=t.name;if(e||M(`type "${r}" must have a positive integer typeid pointer`),L.hasOwnProperty(e)){if(n.ignoreDuplicateRegistrations)return;M(`Cannot register type '${r}' twice`)}if(L[e]=t,delete D[e],W.hasOwnProperty(e)){var i=W[e];delete W[e],i.forEach((e=>e()))}}(e,t,n)}function H(){this.allocated=[void 0],this.freelist=[]}var Y=new H,j=()=>{for(var e=0,t=Y.reserved;t<Y.allocated.length;++t)void 0!==Y.allocated[t]&&++e;return e},V=e=>(e||M("Cannot use deleted val. handle = "+e),Y.get(e).value),$=e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Y.allocate({refcount:1,value:e})}};function z(e){return this.fromWireType(l[e>>2])}var q=(e,t)=>{switch(t){case 4:return function(e){return this.fromWireType(p[e>>2])};case 8:return function(e){return this.fromWireType(O[e>>3])};default:throw new TypeError(`invalid float width (${t}): ${e}`)}},K=(e,t,n)=>{switch(t){case 1:return n?e=>c[e>>0]:e=>_[e>>0];case 2:return n?e=>d[e>>1]:e=>g[e>>1];case 4:return n?e=>l[e>>2]:e=>h[e>>2];default:throw new TypeError(`invalid integer width (${t}): ${e}`)}};function J(e){return this.fromWireType(h[e>>2])}var Q,Z="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,ee=(e,t,n)=>{for(var r=t+n,i=t;e[i]&&!(i>=r);)++i;if(i-t>16&&e.buffer&&Z)return Z.decode(e.subarray(t,i));for(var o="";t<i;){var a=e[t++];if(128&a){var s=63&e[t++];if(192!=(224&a)){var f=63&e[t++];if((a=224==(240&a)?(15&a)<<12|s<<6|f:(7&a)<<18|s<<12|f<<6|63&e[t++])<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|1023&u)}}else o+=String.fromCharCode((31&a)<<6|s)}else o+=String.fromCharCode(a)}return o},te=(e,t)=>e?ee(_,e,t):"",ne="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,re=(e,t)=>{for(var n=e,r=n>>1,i=r+t/2;!(r>=i)&&g[r];)++r;if((n=r<<1)-e>32&&ne)return ne.decode(_.subarray(e,n));for(var o="",a=0;!(a>=t/2);++a){var s=d[e+2*a>>1];if(0==s)break;o+=String.fromCharCode(s)}return o},ie=(e,t,n)=>{if(void 0===n&&(n=2147483647),n<2)return 0;for(var r=t,i=(n-=2)<2*e.length?n/2:e.length,o=0;o<i;++o){var a=e.charCodeAt(o);d[t>>1]=a,t+=2}return d[t>>1]=0,t-r},oe=e=>2*e.length,ae=(e,t)=>{for(var n=0,r="";!(n>=t/4);){var i=l[e+4*n>>2];if(0==i)break;if(++n,i>=65536){var o=i-65536;r+=String.fromCharCode(55296|o>>10,56320|1023&o)}else r+=String.fromCharCode(i)}return r},se=(e,t,n)=>{if(void 0===n&&(n=2147483647),n<4)return 0;for(var r=t,i=r+n-4,o=0;o<e.length;++o){var a=e.charCodeAt(o);if(a>=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++o)),l[t>>2]=a,(t+=4)+4>i)break}return l[t>>2]=0,t-r},fe=e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);r>=55296&&r<=57343&&++n,t+=4}return t};Q=()=>performance.now();var ue=e=>{var t=(e-s.buffer.byteLength+65535)/65536;try{return s.grow(t),m(),1}catch(e){}},ce=[null,[],[]];(()=>{for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);B=e})(),x=r.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},F=r.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}},Object.assign(H.prototype,{get(e){return this.allocated[e]},has(e){return void 0!==this.allocated[e]},allocate(e){var t=this.freelist.pop()||this.allocated.length;return this.allocated[t]=e,t},free(e){this.allocated[e]=void 0,this.freelist.push(e)}}),Y.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Y.reserved=Y.allocated.length,r.count_emval_handles=j;var _e,de={_embind_register_bigint:(e,t,n,r,i)=>{},_embind_register_bool:(e,t,n,r)=>{k(e,{name:t=R(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?n:r},argPackAdvance:8,readValueFromPointer:function(e){return this.fromWireType(_[e])},destructorFunction:null})},_embind_register_constant:(e,t,n)=>{e=R(e),X([],[t],(function(t){return t=t[0],r[e]=t.fromWireType(n),[]}))},_embind_register_emval:(e,t)=>{k(e,{name:t=R(t),fromWireType:e=>{var t=V(e);return(e=>{e>=Y.reserved&&0==--Y.get(e).refcount&&Y.free(e)})(e),t},toWireType:(e,t)=>$(t),argPackAdvance:8,readValueFromPointer:z,destructorFunction:null})},_embind_register_float:(e,t,n)=>{k(e,{name:t=R(t),fromWireType:e=>e,toWireType:(e,t)=>t,argPackAdvance:8,readValueFromPointer:q(t,n),destructorFunction:null})},_embind_register_integer:(e,t,n,r,i)=>{t=R(t),-1===i&&(i=4294967295);var o=e=>e;if(0===r){var a=32-8*n;o=e=>e<<a>>>a}var s=t.includes("unsigned");k(e,{name:t,fromWireType:o,toWireType:s?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:K(t,n,0!==r),destructorFunction:null})},_embind_register_memory_view:(e,t,n)=>{var r=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function i(e){var t=h[e>>2],n=h[e+4>>2];return new r(c.buffer,n,t)}k(e,{name:n=R(n),fromWireType:i,argPackAdvance:8,readValueFromPointer:i},{ignoreDuplicateRegistrations:!0})},_embind_register_std_string:(e,t)=>{var n="std::string"===(t=R(t));k(e,{name:t,fromWireType:e=>{var t,r=h[e>>2],i=e+4;if(n)for(var o=i,a=0;a<=r;++a){var s=i+a;if(a==r||0==_[s]){var f=te(o,s-o);void 0===t?t=f:(t+=String.fromCharCode(0),t+=f),o=s+1}}else{var u=new Array(r);for(a=0;a<r;++a)u[a]=String.fromCharCode(_[i+a]);t=u.join("")}return he(e),t},toWireType:(e,t)=>{var r;t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i="string"==typeof t;i||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||M("Cannot pass non-string to std::string"),r=n&&i?(e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);r<=127?t++:r<=2047?t+=2:r>=55296&&r<=57343?(t+=4,++n):t+=3}return t})(t):t.length;var o=le(4+r+1),a=o+4;if(h[o>>2]=r,n&&i)((e,t,n,r)=>{if(!(r>0))return 0;for(var i=n,o=n+r-1,a=0;a<e.length;++a){var s=e.charCodeAt(a);if(s>=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(n>=o)break;t[n++]=s}else if(s<=2047){if(n+1>=o)break;t[n++]=192|s>>6,t[n++]=128|63&s}else if(s<=65535){if(n+2>=o)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|63&s}else{if(n+3>=o)break;t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}}t[n]=0})(t,_,a,r+1);else if(i)for(var s=0;s<r;++s){var f=t.charCodeAt(s);f>255&&(he(a),M("String has UTF-16 code units that do not fit in 8 bits")),_[a+s]=f}else for(s=0;s<r;++s)_[a+s]=t[s];return null!==e&&e.push(he,o),o},argPackAdvance:8,readValueFromPointer:J,destructorFunction:e=>he(e)})},_embind_register_std_wstring:(e,t,n)=>{var r,i,o,a,s;n=R(n),2===t?(r=re,i=ie,a=oe,o=()=>g,s=1):4===t&&(r=ae,i=se,a=fe,o=()=>h,s=2),k(e,{name:n,fromWireType:e=>{for(var n,i=h[e>>2],a=o(),f=e+4,u=0;u<=i;++u){var c=e+4+u*t;if(u==i||0==a[c>>s]){var _=r(f,c-f);void 0===n?n=_:(n+=String.fromCharCode(0),n+=_),f=c+t}}return he(e),n},toWireType:(e,r)=>{"string"!=typeof r&&M(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),f=le(4+o+t);return h[f>>2]=o>>s,i(r,f+4,o+t),null!==e&&e.push(he,f),f},argPackAdvance:8,readValueFromPointer:z,destructorFunction:e=>he(e)})},_embind_register_void:(e,t)=>{k(e,{isVoid:!0,name:t=R(t),argPackAdvance:0,fromWireType:()=>{},toWireType:(e,t)=>{}})},emscripten_get_now:Q,emscripten_memcpy_big:(e,t,n)=>_.copyWithin(e,t,t+n),emscripten_resize_heap:e=>{var t=_.length,n=2147483648;if((e>>>=0)>n)return!1;for(var r,i=1;i<=4;i*=2){var o=t*(1+.2/i);o=Math.min(o,e+100663296);var a=Math.min(n,(r=Math.max(e,o))+(65536-r%65536)%65536);if(ue(a))return!0}return!1},fd_write:(e,t,n,r)=>{for(var i=0,o=0;o<n;o++){var a=h[t>>2],s=h[t+4>>2];t+=8;for(var c=0;c<s;c++)d=e,g=_[a+c],l=void 0,l=ce[d],0===g||10===g?((1===d?f:u)(ee(l,0)),l.length=0):l.push(g);i+=s}var d,g,l;return h[r>>2]=i,0}},ge=function(){var e,t,i,o,f={env:de,wasi_snapshot_preview1:de};function c(e,t){var n,i=e.exports;return s=(ge=i).memory,m(),ge.__indirect_function_table,n=ge.__wasm_call_ctors,I.unshift(n),function(e){if(N--,r.monitorRunDependencies&&r.monitorRunDependencies(N),0==N&&(null!==A&&(clearInterval(A),A=null),S)){var t=S;S=null,t()}}(),i}if(N++,r.monitorRunDependencies&&r.monitorRunDependencies(N),r.instantiateWasm)try{return r.instantiateWasm(f,c)}catch(e){u(`Module.instantiateWasm callback failed with error: ${e}`),n(e)}return(e=a,t=E,i=f,o=function(e){c(e.instance)},e||"function"!=typeof WebAssembly.instantiateStreaming||b(t)||"function"!=typeof fetch?U(t,i,o):fetch(t,{credentials:"same-origin"}).then((e=>WebAssembly.instantiateStreaming(e,i).then(o,(function(e){return u(`wasm streaming compile failed: ${e}`),u("falling back to ArrayBuffer instantiation"),U(t,i,o)}))))).catch(n),{}}(),le=e=>(le=ge.malloc)(e),he=e=>(he=ge.free)(e);function pe(){function e(){_e||(_e=!0,r.calledRun=!0,v||(G(I),t(r),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)e=r.postRun.shift(),T.unshift(e);var e;G(T)}()))}N>0||(function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)e=r.preRun.shift(),y.unshift(e);var e;G(y)}(),N>0||(r.setStatus?(r.setStatus("Running..."),setTimeout((function(){setTimeout((function(){r.setStatus("")}),1),e()}),1)):e()))}if(r._omalloc=e=>(r._omalloc=ge.omalloc)(e),r._ofree=e=>(r._ofree=ge.ofree)(e),r._getLastOnigError=()=>(r._getLastOnigError=ge.getLastOnigError)(),r._createOnigScanner=(e,t,n,i,o)=>(r._createOnigScanner=ge.createOnigScanner)(e,t,n,i,o),r._freeOnigScanner=e=>(r._freeOnigScanner=ge.freeOnigScanner)(e),r._findNextOnigScannerMatch=(e,t,n,i,o,a)=>(r._findNextOnigScannerMatch=ge.findNextOnigScannerMatch)(e,t,n,i,o,a),r._findNextOnigScannerMatchDbg=(e,t,n,i,o,a)=>(r._findNextOnigScannerMatchDbg=ge.findNextOnigScannerMatchDbg)(e,t,n,i,o,a),r.__embind_initialize_bindings=()=>(r.__embind_initialize_bindings=ge._embind_initialize_bindings)(),r.dynCall_jiji=(e,t,n,i,o)=>(r.dynCall_jiji=ge.dynCall_jiji)(e,t,n,i,o),r.UTF8ToString=te,S=function e(){_e||pe(),_e||(S=e)},r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return pe(),e.ready});e.exports=t}},t={},function n(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,n),o.exports}(770);var e,t})); | |
| 4 | +export default module.exports; |
added web/js/ext/vendor/vscode-textmate@9.3.2/LICENSE.md +21 −0
| @@ -0,0 +1,21 @@ | ||
| 1 | +The MIT License (MIT) | |
| 2 | + | |
| 3 | +Copyright (c) Microsoft Corporation | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
added web/js/ext/vendor/vscode-textmate@9.3.2/main.js +5 −0
| @@ -0,0 +1,5 @@ | ||
| 1 | +// vscode-textmate 9.3.2 (MIT, Microsoft): release/main.js del paquete npm, SIN CAMBIOS, dentro de este envoltorio de módulo ES (esta línea, la siguiente y la última). Original: 61242 bytes, sha384-aJzUwh8/jeVrg5exYESASC3qwtfGKKHUgNPuT5uEM0bmJvnwLbJhuy+//+fZ+tPJ. Licencia: LICENSE.md. Comprobación: tests/ext_unit.mjs. | |
| 2 | +const module = { exports: {} }, exports = module.exports; | |
| 3 | +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.vscodetextmate=t():e.vscodetextmate=t()}(this,(()=>(()=>{"use strict";var e={185:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UseOnigurumaFindOptions=t.DebugFlags=void 0,t.DebugFlags={InDebugMode:"undefined"!=typeof process&&!!process.env.VSCODE_TEXTMATE_DEBUG},t.UseOnigurumaFindOptions=!1},151:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.applyStateStackDiff=t.diffStateStacksRefEq=void 0;const s=n(752);t.diffStateStacksRefEq=function(e,t){let n=0;const s=[];let r=e,i=t;for(;r!==i;)r&&(!i||r.depth>=i.depth)?(n++,r=r.parent):(s.push(i.toStateStackFrame()),i=i.parent);return{pops:n,newFrames:s.reverse()}},t.applyStateStackDiff=function(e,t){let n=e;for(let e=0;e<t.pops;e++)n=n.parent;for(const e of t.newFrames)n=s.StateStackImpl.pushFrame(n,e);return n}},490:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toOptionalTokenType=t.EncodedTokenAttributes=t.FontAttribute=void 0;class n{constructor(e,t,n){this.fontFamily=e,this.fontSize=t,this.lineHeight=n}static _getKey(e,t,n){return`${e}|${t}|${n}`}static _get(e,t,s){const r=this._getKey(e,t,s);let i=this._map.get(r);return i||(i=new n(e,t,s),this._map.set(r,i)),i}static from(e,t,s){return new n(e,t,s)}with(e){return e?n._get(e.fontFamily||this.fontFamily,e.fontSize||this.fontSize,e.lineHeight||this.lineHeight):this}}var s;t.FontAttribute=n,n._map=new Map,(s=t.EncodedTokenAttributes||(t.EncodedTokenAttributes={})).toBinaryStr=function(e){return e.toString(2).padStart(32,"0")},s.print=function(e){const t=s.getLanguageId(e),n=s.getTokenType(e),r=s.getFontStyle(e),i=s.getForeground(e),o=s.getBackground(e);console.log({languageId:t,tokenType:n,fontStyle:r,foreground:i,background:o})},s.getLanguageId=function(e){return(255&e)>>>0},s.getTokenType=function(e){return(768&e)>>>8},s.containsBalancedBrackets=function(e){return!!(1024&e)},s.getFontStyle=function(e){return(30720&e)>>>11},s.getForeground=function(e){return(16744448&e)>>>15},s.getBackground=function(e){return(4278190080&e)>>>24},s.set=function(e,t,n,r,i,o,a){let c=s.getLanguageId(e),l=s.getTokenType(e),u=s.containsBalancedBrackets(e)?1:0,h=s.getFontStyle(e),p=s.getForeground(e),d=s.getBackground(e);return 0!==t&&(c=t),8!==n&&(l=n),null!==r&&(u=r?1:0),-1!==i&&(h=i),0!==o&&(p=o),0!==a&&(d=a),(c|l<<8|u<<10|h<<11|p<<15|d<<24)>>>0},t.toOptionalTokenType=function(e){return e}},214:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BasicScopeAttributesProvider=t.BasicScopeAttributes=void 0;const s=n(807);class r{constructor(e,t){this.languageId=e,this.tokenType=t}}t.BasicScopeAttributes=r;class i{constructor(e,t){this._getBasicScopeAttributes=new s.CachedFn((e=>{const t=this._scopeToLanguage(e),n=this._toStandardTokenType(e);return new r(t,n)})),this._defaultAttributes=new r(e,8),this._embeddedLanguagesMatcher=new o(Object.entries(t||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(e){return null===e?i._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(e)}_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(e){const t=e.match(i.STANDARD_TOKEN_TYPE_REGEXP);if(!t)return 8;switch(t[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}}t.BasicScopeAttributesProvider=i,i._NULL_SCOPE_METADATA=new r(0,0),i.STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/;class o{constructor(e){if(0===e.length)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);const t=e.map((([e,t])=>s.escapeRegExpCharacters(e)));t.sort(),t.reverse(),this.scopesRegExp=new RegExp(`^((${t.join(")|(")}))($|\\.)`,"")}}match(e){if(!this.scopesRegExp)return;const t=e.match(this.scopesRegExp);return t?this.values.get(t[1]):void 0}}},929:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LineFonts=t.FontInfo=t.LineTokens=t.BalancedBracketSelectors=t.StateStackImpl=t.AttributedScopeStack=t.Grammar=t.createGrammar=void 0;const s=n(185),r=n(490),i=n(916),o=n(810),a=n(666),c=n(63),l=n(807),u=n(214),h=n(398);function p(e,t,n,s,r){const o=i.createMatchers(t,d),c=a.RuleFactory.getCompiledRuleId(n,s,r.repository);for(const n of o)e.push({debugSelector:t,matcher:n.matcher,ruleId:c,grammar:r,priority:n.priority})}function d(e,t){if(t.length<e.length)return!1;let n=0;return e.every((e=>{for(let s=n;s<t.length;s++)if(f(t[s],e))return n=s+1,!0;return!1}))}function f(e,t){if(!e)return!1;if(e===t)return!0;const n=t.length;return e.length>n&&e.substr(0,n)===t&&"."===e[n]}t.createGrammar=function(e,t,n,s,r,i,o,a){return new m(e,t,n,s,r,i,o,a)};class m{constructor(e,t,n,s,r,o,a,c){if(this._rootScopeName=e,this.balancedBracketSelectors=o,this._onigLib=c,this._basicScopeAttributesProvider=new u.BasicScopeAttributesProvider(n,s),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=a,this._grammar=g(t,null),this._injections=null,this._tokenTypeMatchers=[],r)for(const e of Object.keys(r)){const t=i.createMatchers(e,d);for(const n of t)this._tokenTypeMatchers.push({matcher:n.matcher,type:r[e]})}}get themeProvider(){return this._grammarRepository}dispose(){for(const e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){const e=[],t=this._rootScopeName,n=(e=>e===this._rootScopeName?this._grammar:this.getExternalGrammar(e))(t);if(n){const s=n.injections;if(s)for(let t in s)p(e,t,s[t],this,n);const r=this._grammarRepository.injections(t);r&&r.forEach((t=>{const n=this.getExternalGrammar(t);if(n){const t=n.injectionSelector;t&&p(e,t,n,this,n)}}))}return e.sort(((e,t)=>e.priority-t.priority)),e}getInjections(){if(null===this._injections&&(this._injections=this._collectInjections(),s.DebugFlags.InDebugMode&&this._injections.length>0)){console.log(`Grammar ${this._rootScopeName} contains the following injections:`);for(const e of this._injections)console.log(` - ${e.debugSelector}`)}return this._injections}registerRule(e){const t=++this._lastRuleId,n=e(a.ruleIdFromNumber(t));return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[a.ruleIdToNumber(e)]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){const n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=g(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){const s=this._tokenize(e,t,!1,n);return{tokens:s.lineTokens.getResult(s.ruleStack,s.lineLength),ruleStack:s.ruleStack,stoppedEarly:s.stoppedEarly,fonts:s.lineFonts.getResult()}}tokenizeLine2(e,t,n=0){const s=this._tokenize(e,t,!0,n);return{tokens:s.lineTokens.getBinaryResult(s.ruleStack,s.lineLength),ruleStack:s.ruleStack,stoppedEarly:s.stoppedEarly,fonts:s.lineFonts.getResult()}}_tokenize(e,t,n,s){let i;if(-1===this._rootId&&(this._rootId=a.RuleFactory.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections()),t&&t!==b.NULL)i=!1,t.reset();else{i=!0;const e=this._basicScopeAttributesProvider.getDefaultAttributes(),n=this.themeProvider.getDefaults(),s=r.EncodedTokenAttributes.set(0,e.languageId,e.tokenType,null,n.fontStyle,n.foregroundId,n.backgroundId),o=r.FontAttribute.from(n.fontFamily,n.fontSize,n.lineHeight),a=this.getRule(this._rootId).getName(null,null);let c;c=a?_.createRootAndLookUpScopeName(a,s,o,this):_.createRoot("unknown",s,o),t=new b(null,this._rootId,-1,-1,!1,null,c,c)}e+="\n";const c=this.createOnigString(e),l=c.content.length,u=new y(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),p=new k,d=h._tokenizeString(this,c,i,0,t,u,p,!0,s);return o.disposeOnigString(c),{lineLength:l,lineTokens:u,lineFonts:p,ruleStack:d.stack,stoppedEarly:d.stoppedEarly}}}function g(e,t){return(e=l.clone(e)).repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}t.Grammar=m;class _{constructor(e,t,n,s,r){this.parent=e,this.scopePath=t,this.tokenAttributes=n,this.fontAttributes=s,this.styleAttributes=r}static fromExtension(e,t){let n=e,s=e?.scopePath??null;for(const e of t)s=c.ScopeStack.push(s,e.scopeNames),n=new _(n,s,e.encodedTokenAttributes,null,null);return n}static createRoot(e,t,n){return new _(null,new c.ScopeStack(null,e),t,n,null)}static createRootAndLookUpScopeName(e,t,n,s){const r=s.getMetadataForScope(e),i=new c.ScopeStack(null,e),o=s.themeProvider.themeMatch(i),a=_.mergeAttributes(t,r,o),l=n.with(o);return new _(null,i,a,l,o)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(e){return _.equals(this,e)}static equals(e,t){for(;;){if(e===t)return!0;if(!e&&!t)return!0;if(!e||!t)return!1;if(e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}}static mergeAttributes(e,t,n){let s=-1,i=0,o=0;return null!==n&&(s=n.fontStyle,i=n.foregroundId,o=n.backgroundId),r.EncodedTokenAttributes.set(e,t.languageId,t.tokenType,null,s,i,o)}pushAttributed(e,t){if(null===e)return this;if(-1===e.indexOf(" "))return _._pushAttributed(this,e,t);const n=e.split(/ /g);let s=this;for(const e of n)s=_._pushAttributed(s,e,t);return s}static _pushAttributed(e,t,n){const s=n.getMetadataForScope(t),r=e.scopePath.push(t),i=n.themeProvider.themeMatch(r),o=_.mergeAttributes(e.tokenAttributes,s,i),a=e.fontAttributes?.with(i)??null;return new _(e,r,o,a,i)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){const t=[];let n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}}t.AttributedScopeStack=_;class b{constructor(e,t,n,s,r,i,o,a){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=r,this.endRule=i,this.nameScopesList=o,this.contentNameScopesList=a,this._stackElementBrand=void 0,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=s}equals(e){return null!==e&&b._equals(this,e)}static _equals(e,t){return e===t||!!this._structuralEquals(e,t)&&_.equals(e.contentNameScopesList,t.contentNameScopesList)}static _structuralEquals(e,t){for(;;){if(e===t)return!0;if(!e&&!t)return!0;if(!e||!t)return!1;if(e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){b._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(e,t,n,s,r,i,o){return new b(this,e,t,n,s,r,i,o)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){const e=[];return this._writeString(e,0),"["+e.join(",")+"]"}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(e){return this.endRule===e?this:new b(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,e,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:a.ruleIdToNumber(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(e,t){const n=_.fromExtension(e?.nameScopesList??null,t.nameScopesList);return new b(e,a.ruleIdFromNumber(t.ruleId),t.enterPos??-1,t.anchorPos??-1,t.beginRuleCapturedEOL,t.endRule,n,_.fromExtension(n,t.contentNameScopesList))}}t.StateStackImpl=b,b.NULL=new b(null,0,0,0,!1,null,null,null),t.BalancedBracketSelectors=class{constructor(e,t){this.allowAny=!1,this.balancedBracketScopes=e.flatMap((e=>"*"===e?(this.allowAny=!0,[]):i.createMatchers(e,d).map((e=>e.matcher)))),this.unbalancedBracketScopes=t.flatMap((e=>i.createMatchers(e,d).map((e=>e.matcher))))}get matchesAlways(){return this.allowAny&&0===this.unbalancedBracketScopes.length}get matchesNever(){return 0===this.balancedBracketScopes.length&&!this.allowAny}match(e){for(const t of this.unbalancedBracketScopes)if(t(e))return!1;for(const t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}};class y{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,s.DebugFlags.InDebugMode?this._lineText=t:this._lineText=null,this._mergeConsecutiveTokensWithEqualMetadata=!l.containsRTL(t),this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let n=e?.tokenAttributes??0,i=!1;if(this.balancedBracketSelectors?.matchesAlways&&(i=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){const t=e?.getScopeNames()??[];for(const e of this._tokenTypeOverrides)e.matcher(t)&&(n=r.EncodedTokenAttributes.set(n,0,r.toOptionalTokenType(e.type),null,-1,0,0));this.balancedBracketSelectors&&(i=this.balancedBracketSelectors.match(t))}if(i&&(n=r.EncodedTokenAttributes.set(n,0,8,i,-1,0,0)),this._mergeConsecutiveTokensWithEqualMetadata&&this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===n)return void(this._lastTokenEndIndex=t);if(s.DebugFlags.InDebugMode){const n=e?.getScopeNames()??[];console.log(" token: |"+this._lineText.substring(this._lastTokenEndIndex,t).replace(/\n$/,"\\n")+"|");for(let e=0;e<n.length;e++)console.log(" * "+n[e])}return this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(n),void(this._lastTokenEndIndex=t)}const n=e?.getScopeNames()??[];if(s.DebugFlags.InDebugMode){console.log(" token: |"+this._lineText.substring(this._lastTokenEndIndex,t).replace(/\n$/,"\\n")+"|");for(let e=0;e<n.length;e++)console.log(" * "+n[e])}this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),0===this._tokens.length&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),0===this._binaryTokens.length&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);const n=new Uint32Array(this._binaryTokens.length);for(let e=0,t=this._binaryTokens.length;e<t;e++)n[e]=this._binaryTokens[e];return n}}t.LineTokens=y;class S{constructor(e,t,n,s,r){this.startIndex=e,this.endIndex=t,this.fontFamily=n,this.fontSizeMultiplier=s,this.lineHeightMultiplier=r}optionsEqual(e){return this.fontFamily===e.fontFamily&&this.fontSizeMultiplier===e.fontSizeMultiplier&&this.lineHeightMultiplier===e.lineHeightMultiplier}}t.FontInfo=S;class k{constructor(){this._fonts=[],this._lastIndex=0}produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(!e?.fontAttributes)return void(this._lastIndex=t);const n=e.fontAttributes.fontFamily,s=e.fontAttributes.fontSize,r=e.fontAttributes.lineHeight;if(!n&&!s&&!r)return void(this._lastIndex=t);const i=new S(this._lastIndex,t,n,s,r),o=this._fonts[this._fonts.length-1];o&&o.endIndex===this._lastIndex&&o.optionsEqual(i)?o.endIndex=i.endIndex:this._fonts.push(i),this._lastIndex=t}getResult(){return this._fonts}}t.LineFonts=k},784:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseInclude=t.TopLevelRepositoryReference=t.TopLevelReference=t.RelativeReference=t.SelfReference=t.BaseReference=t.ScopeDependencyProcessor=t.ExternalReferenceCollector=t.TopLevelRepositoryRuleReference=t.TopLevelRuleReference=void 0;const s=n(807);class r{constructor(e){this.scopeName=e}toKey(){return this.scopeName}}t.TopLevelRuleReference=r;class i{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}}t.TopLevelRepositoryRuleReference=i;class o{constructor(){this._references=[],this._seenReferenceKeys=new Set,this.visitedRule=new Set}get references(){return this._references}add(e){const t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}}function a(e,t,n,s){const i=n.lookup(e.scopeName);if(!i){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}const o=n.lookup(t);e instanceof r?l({baseGrammar:o,selfGrammar:i},s):c(e.ruleName,{baseGrammar:o,selfGrammar:i,repository:i.repository},s);const a=n.injections(e.scopeName);if(a)for(const e of a)s.add(new r(e))}function c(e,t,n){t.repository&&t.repository[e]&&u([t.repository[e]],t,n)}function l(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&u(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&u(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function u(e,t,n){for(const o of e){if(n.visitedRule.has(o))continue;n.visitedRule.add(o);const e=o.repository?s.mergeObjects({},t.repository,o.repository):t.repository;Array.isArray(o.patterns)&&u(o.patterns,{...t,repository:e},n);const a=o.include;if(!a)continue;const h=g(a);switch(h.kind){case 0:l({...t,selfGrammar:t.baseGrammar},n);break;case 1:l(t,n);break;case 2:c(h.ruleName,{...t,repository:e},n);break;case 3:case 4:const s=h.scopeName===t.selfGrammar.scopeName?t.selfGrammar:h.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(s){const r={baseGrammar:t.baseGrammar,selfGrammar:s,repository:e};4===h.kind?c(h.ruleName,r,n):l(r,n)}else 4===h.kind?n.add(new i(h.scopeName,h.ruleName)):n.add(new r(h.scopeName))}}}t.ExternalReferenceCollector=o,t.ScopeDependencyProcessor=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests=new Set,this.seenPartialScopeRequests=new Set,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new r(this.initialScopeName)]}processQueue(){const e=this.Q;this.Q=[];const t=new o;for(const n of e)a(n,this.initialScopeName,this.repo,t);for(const e of t.references)if(e instanceof r){if(this.seenFullScopeRequests.has(e.scopeName))continue;this.seenFullScopeRequests.add(e.scopeName),this.Q.push(e)}else{if(this.seenFullScopeRequests.has(e.scopeName))continue;if(this.seenPartialScopeRequests.has(e.toKey()))continue;this.seenPartialScopeRequests.add(e.toKey()),this.Q.push(e)}}};class h{constructor(){this.kind=0}}t.BaseReference=h;class p{constructor(){this.kind=1}}t.SelfReference=p;class d{constructor(e){this.ruleName=e,this.kind=2}}t.RelativeReference=d;class f{constructor(e){this.scopeName=e,this.kind=3}}t.TopLevelReference=f;class m{constructor(e,t){this.scopeName=e,this.ruleName=t,this.kind=4}}function g(e){if("$base"===e)return new h;if("$self"===e)return new p;const t=e.indexOf("#");if(-1===t)return new f(e);if(0===t)return new d(e.substring(1));{const n=e.substring(0,t),s=e.substring(t+1);return new m(n,s)}}t.TopLevelRepositoryReference=m,t.parseInclude=g},752:function(e,t,n){var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||s(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(929),t)},398:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LocalStackElement=t._tokenizeString=void 0;const s=n(185),r=n(810),i=n(666),o=n(807);class a{constructor(e,t){this.stack=e,this.stoppedEarly=t}}function c(e,t,n,r,c,h,d,f,m){const g=(e,t)=>{h.produce(e,t),d.produce(e,t)},_=t.content.length;let b=!1,y=-1;if(f){const o=function(e,t,n,r,o,a,c){const l=(e,t)=>{a.produce(e,t),c.produce(e,t)};let h=o.beginRuleCapturedEOL?0:-1;const d=[];for(let t=o;t;t=t.pop()){const n=t.getRule(e);n instanceof i.BeginWhileRule&&d.push({rule:n,stack:t})}for(let f=d.pop();f;f=d.pop()){const{ruleScanner:d,findOptions:m}=u(f.rule,e,f.stack.endRule,n,r===h),g=d.findNextMatchSync(t,r,m);if(s.DebugFlags.InDebugMode&&(console.log(" scanning for while rule"),console.log(d.toString())),!g){s.DebugFlags.InDebugMode&&console.log(" popping "+f.rule.debugName+" - "+f.rule.debugWhileRegExp),o=f.stack.pop();break}if(g.ruleId!==i.whileRuleId){o=f.stack.pop();break}g.captureIndices&&g.captureIndices.length&&(l(f.stack,g.captureIndices[0].start),p(e,t,n,f.stack,a,c,f.rule.whileCaptures,g.captureIndices),l(f.stack,g.captureIndices[0].end),h=g.captureIndices[0].end,g.captureIndices[0].end>r&&(r=g.captureIndices[0].end,n=!1))}return{stack:o,linePos:r,anchorPosition:h,isFirstLine:n}}(e,t,n,r,c,h,d);c=o.stack,r=o.linePos,n=o.isFirstLine,y=o.anchorPosition}const S=Date.now();for(;!b;){if(0!==m&&Date.now()-S>m)return new a(c,!0);k()}return new a(c,!1);function k(){s.DebugFlags.InDebugMode&&(console.log(""),console.log(`@@scanNext ${r}: |${t.content.substr(r).replace(/\n$/,"\\n")}|`));const a=function(e,t,n,r,i,a){const c=function(e,t,n,r,i,a){const c=i.getRule(e),{ruleScanner:u,findOptions:h}=l(c,e,i.endRule,n,r===a);let p=0;s.DebugFlags.InDebugMode&&(p=o.performanceNow());const d=u.findNextMatchSync(t,r,h);if(s.DebugFlags.InDebugMode){const e=o.performanceNow()-p;e>5&&console.warn(`Rule ${c.debugName} (${c.id}) matching took ${e} against '${t}'`),console.log(` scanning for (linePos: ${r}, anchorPosition: ${a})`),console.log(u.toString()),d&&console.log(`matched rule id: ${d.ruleId} from ${d.captureIndices[0].start} to ${d.captureIndices[0].end}`)}return d?{captureIndices:d.captureIndices,matchedRuleId:d.ruleId}:null}(e,t,n,r,i,a),u=e.getInjections();if(0===u.length)return c;const h=function(e,t,n,r,i,o,a){let c,u=Number.MAX_VALUE,h=null,p=0;const d=o.contentNameScopesList.getScopeNames();for(let o=0,f=e.length;o<f;o++){const f=e[o];if(!f.matcher(d))continue;const m=t.getRule(f.ruleId),{ruleScanner:g,findOptions:_}=l(m,t,null,r,i===a),b=g.findNextMatchSync(n,i,_);if(!b)continue;s.DebugFlags.InDebugMode&&(console.log(` matched injection: ${f.debugSelector}`),console.log(g.toString()));const y=b.captureIndices[0].start;if(!(y>=u)&&(u=y,h=b.captureIndices,c=b.ruleId,p=f.priority,u===i))break}return h?{priorityMatch:-1===p,captureIndices:h,matchedRuleId:c}:null}(u,e,t,n,r,i,a);if(!h)return c;if(!c)return h;const p=c.captureIndices[0].start,d=h.captureIndices[0].start;return d<p||h.priorityMatch&&d===p?h:c}(e,t,n,r,c,y);if(!a)return s.DebugFlags.InDebugMode&&console.log(" no more matches."),g(c,_),void(b=!0);const u=a.captureIndices,f=a.matchedRuleId,m=!!(u&&u.length>0)&&u[0].end>r;if(f===i.endRuleId){const i=c.getRule(e);s.DebugFlags.InDebugMode&&console.log(" popping "+i.debugName+" - "+i.debugEndRegExp),g(c,u[0].start),c=c.withContentNameScopesList(c.nameScopesList),p(e,t,n,c,h,d,i.endCaptures,u),g(c,u[0].end);const o=c;if(c=c.parent,y=o.getAnchorPos(),!m&&o.getEnterPos()===r)return s.DebugFlags.InDebugMode&&console.error("[1] - Grammar is in an endless loop - Grammar pushed & popped a rule without advancing"),g(c=o,_),void(b=!0)}else{const o=e.getRule(f);g(c,u[0].start);const a=c,l=o.getName(t.content,u),S=c.contentNameScopesList.pushAttributed(l,e);if(c=c.push(f,r,y,u[0].end===_,null,S,S),o instanceof i.BeginEndRule){const r=o;s.DebugFlags.InDebugMode&&console.log(" pushing "+r.debugName+" - "+r.debugBeginRegExp),p(e,t,n,c,h,d,r.beginCaptures,u),g(c,u[0].end),y=u[0].end;const i=r.getContentName(t.content,u),l=S.pushAttributed(i,e);if(c=c.withContentNameScopesList(l),r.endHasBackReferences&&(c=c.withEndRule(r.getEndWithResolvedBackReferences(t.content,u))),!m&&a.hasSameRuleAs(c))return s.DebugFlags.InDebugMode&&console.error("[2] - Grammar is in an endless loop - Grammar pushed the same rule without advancing"),c=c.pop(),g(c,_),void(b=!0)}else if(o instanceof i.BeginWhileRule){const r=o;s.DebugFlags.InDebugMode&&console.log(" pushing "+r.debugName),p(e,t,n,c,h,d,r.beginCaptures,u),g(c,u[0].end),y=u[0].end;const i=r.getContentName(t.content,u),l=S.pushAttributed(i,e);if(c=c.withContentNameScopesList(l),r.whileHasBackReferences&&(c=c.withEndRule(r.getWhileWithResolvedBackReferences(t.content,u))),!m&&a.hasSameRuleAs(c))return s.DebugFlags.InDebugMode&&console.error("[3] - Grammar is in an endless loop - Grammar pushed the same rule without advancing"),c=c.pop(),g(c,_),void(b=!0)}else{const r=o;if(s.DebugFlags.InDebugMode&&console.log(" matched "+r.debugName+" - "+r.debugMatchRegExp),p(e,t,n,c,h,d,r.captures,u),g(c,u[0].end),c=c.pop(),!m)return s.DebugFlags.InDebugMode&&console.error("[4] - Grammar is in an endless loop - Grammar is not advancing, nor is it pushing/popping"),c=c.safePop(),g(c,_),void(b=!0)}}u[0].end>r&&(r=u[0].end,n=!1)}}function l(e,t,n,r,i){return s.UseOnigurumaFindOptions?{ruleScanner:e.compile(t,n),findOptions:h(r,i)}:{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function u(e,t,n,r,i){return s.UseOnigurumaFindOptions?{ruleScanner:e.compileWhile(t,n),findOptions:h(r,i)}:{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function h(e,t){let n=0;return e||(n|=1),t||(n|=4),n}function p(e,t,n,s,i,o,a,l){const u=(e,t)=>{i.produceFromScopes(e,t),o.produceFromScopes(e,t)},h=(e,t)=>{i.produce(e,t),o.produce(e,t)};if(0===a.length)return;const p=t.content,f=Math.min(a.length,l.length),m=[],g=l[0].end;for(let t=0;t<f;t++){const f=a[t];if(null===f)continue;const _=l[t];if(0===_.length)continue;if(_.start>g)break;for(;m.length>0&&m[m.length-1].endPos<=_.start;)u(m[m.length-1].scopes,m[m.length-1].endPos),m.pop();if(m.length>0?u(m[m.length-1].scopes,_.start):h(s,_.start),f.retokenizeCapturedWithRuleId){const t=f.getName(p,l),a=s.contentNameScopesList.pushAttributed(t,e),u=f.getContentName(p,l),h=a.pushAttributed(u,e),d=s.push(f.retokenizeCapturedWithRuleId,_.start,-1,!1,null,a,h),m=e.createOnigString(p.substring(0,_.end));c(e,m,n&&0===_.start,_.start,d,i,o,!1,0),r.disposeOnigString(m);continue}const b=f.getName(p,l);if(null!==b){const t=(m.length>0?m[m.length-1].scopes:s.contentNameScopesList).pushAttributed(b,e);m.push(new d(t,_.end))}}for(;m.length>0;)u(m[m.length-1].scopes,m[m.length-1].endPos),m.pop()}t._tokenizeString=c;class d{constructor(e,t){this.scopes=e,this.endPos=t}}t.LocalStackElement=d},726:(e,t)=>{function n(e,t){throw new Error("Near offset "+e.pos+": "+t+" ~~~"+e.source.substr(e.pos,50)+"~~~")}Object.defineProperty(t,"__esModule",{value:!0}),t.parseJSON=void 0,t.parseJSON=function(e,t,o){let a=new s(e),c=new r,l=0,u=null,h=[],p=[];function d(){h.push(l),p.push(u)}function f(){l=h.pop(),u=p.pop()}function m(e){n(a,e)}for(;i(a,c);){if(0===l){if(null!==u&&m("too many constructs in root"),3===c.type){u={},o&&(u.$vscodeTextmateLocation=c.toLocation(t)),d(),l=1;continue}if(2===c.type){u=[],d(),l=4;continue}m("unexpected token in root")}if(2===l){if(5===c.type){f();continue}if(7===c.type){l=3;continue}m("expected , or }")}if(1===l||3===l){if(1===l&&5===c.type){f();continue}if(1===c.type){let e=c.value;if(i(a,c)&&6===c.type||m("expected colon"),i(a,c)||m("expected value"),l=2,1===c.type){u[e]=c.value;continue}if(8===c.type){u[e]=null;continue}if(9===c.type){u[e]=!0;continue}if(10===c.type){u[e]=!1;continue}if(11===c.type){u[e]=parseFloat(c.value);continue}if(2===c.type){let t=[];u[e]=t,d(),l=4,u=t;continue}if(3===c.type){let n={};o&&(n.$vscodeTextmateLocation=c.toLocation(t)),u[e]=n,d(),l=1,u=n;continue}}m("unexpected token in dict")}if(5===l){if(4===c.type){f();continue}if(7===c.type){l=6;continue}m("expected , or ]")}if(4===l||6===l){if(4===l&&4===c.type){f();continue}if(l=5,1===c.type){u.push(c.value);continue}if(8===c.type){u.push(null);continue}if(9===c.type){u.push(!0);continue}if(10===c.type){u.push(!1);continue}if(11===c.type){u.push(parseFloat(c.value));continue}if(2===c.type){let e=[];u.push(e),d(),l=4,u=e;continue}if(3===c.type){let e={};o&&(e.$vscodeTextmateLocation=c.toLocation(t)),u.push(e),d(),l=1,u=e;continue}m("unexpected token in array")}m("unknown state")}return 0!==p.length&&m("unclosed constructs"),u};class s{constructor(e){this.source=e,this.pos=0,this.len=e.length,this.line=1,this.char=0}}class r{constructor(){this.value=null,this.type=0,this.offset=-1,this.len=-1,this.line=-1,this.char=-1}toLocation(e){return{filename:e,line:this.line,char:this.char}}}function i(e,t){t.value=null,t.type=0,t.offset=-1,t.len=-1,t.line=-1,t.char=-1;let s,r=e.source,i=e.pos,o=e.len,a=e.line,c=e.char;for(;;){if(i>=o)return!1;if(s=r.charCodeAt(i),32!==s&&9!==s&&13!==s){if(10!==s)break;i++,a++,c=0}else i++,c++}if(t.offset=i,t.line=a,t.char=c,34===s){for(t.type=1,i++,c++;;){if(i>=o)return!1;if(s=r.charCodeAt(i),i++,c++,92!==s){if(34===s)break}else i++,c++}t.value=r.substring(t.offset+1,i-1).replace(/\\u([0-9A-Fa-f]{4})/g,((e,t)=>String.fromCodePoint(parseInt(t,16)))).replace(/\\(.)/g,((t,s)=>{switch(s){case'"':return'"';case"\\":return"\\";case"/":return"/";case"b":return"\b";case"f":return"\f";case"n":return"\n";case"r":return"\r";case"t":return"\t";default:n(e,"invalid escape sequence")}throw new Error("unreachable")}))}else if(91===s)t.type=2,i++,c++;else if(123===s)t.type=3,i++,c++;else if(93===s)t.type=4,i++,c++;else if(125===s)t.type=5,i++,c++;else if(58===s)t.type=6,i++,c++;else if(44===s)t.type=7,i++,c++;else if(110===s){if(t.type=8,i++,c++,s=r.charCodeAt(i),117!==s)return!1;if(i++,c++,s=r.charCodeAt(i),108!==s)return!1;if(i++,c++,s=r.charCodeAt(i),108!==s)return!1;i++,c++}else if(116===s){if(t.type=9,i++,c++,s=r.charCodeAt(i),114!==s)return!1;if(i++,c++,s=r.charCodeAt(i),117!==s)return!1;if(i++,c++,s=r.charCodeAt(i),101!==s)return!1;i++,c++}else if(102===s){if(t.type=10,i++,c++,s=r.charCodeAt(i),97!==s)return!1;if(i++,c++,s=r.charCodeAt(i),108!==s)return!1;if(i++,c++,s=r.charCodeAt(i),115!==s)return!1;if(i++,c++,s=r.charCodeAt(i),101!==s)return!1;i++,c++}else for(t.type=11;;){if(i>=o)return!1;if(s=r.charCodeAt(i),!(46===s||s>=48&&s<=57||101===s||69===s||45===s||43===s))break;i++,c++}return t.len=i-t.offset,null===t.value&&(t.value=r.substr(t.offset,t.len)),e.pos=i,e.line=a,e.char=c,!0}},625:function(e,t,n){var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||s(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.applyStateStackDiff=t.diffStateStacksRefEq=t.parseRawGrammar=t.INITIAL=t.Registry=void 0;const i=n(752),o=n(150),a=n(583),c=n(63),l=n(784),u=n(151);Object.defineProperty(t,"applyStateStackDiff",{enumerable:!0,get:function(){return u.applyStateStackDiff}}),Object.defineProperty(t,"diffStateStacksRefEq",{enumerable:!0,get:function(){return u.diffStateStacksRefEq}}),r(n(810),t),t.Registry=class{constructor(e){this._options=e,this._syncRegistry=new a.SyncRegistry(c.Theme.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(c.Theme.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,n){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,t,n){return this._loadGrammar(e,t,n.embeddedLanguages,n.tokenTypes,new i.BalancedBracketSelectors(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}async _loadGrammar(e,t,n,s,r){const i=new l.ScopeDependencyProcessor(this._syncRegistry,e);for(;i.Q.length>0;)await Promise.all(i.Q.map((e=>this._loadSingleGrammar(e.scopeName)))),i.processQueue();return this._grammarForScopeName(e,t,n,s,r)}async _loadSingleGrammar(e){return this._ensureGrammarCache.has(e)||this._ensureGrammarCache.set(e,this._doLoadSingleGrammar(e)),this._ensureGrammarCache.get(e)}async _doLoadSingleGrammar(e){const t=await this._options.loadGrammar(e);if(t){const n="function"==typeof this._options.getInjections?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}async addGrammar(e,t=[],n=0,s=null){return this._syncRegistry.addGrammar(e,t),await this._grammarForScopeName(e.scopeName,n,s)}_grammarForScopeName(e,t=0,n=null,s=null,r=null){return this._syncRegistry.grammarForScopeName(e,t,n,s,r)}},t.INITIAL=i.StateStackImpl.NULL,t.parseRawGrammar=o.parseRawGrammar},916:(e,t)=>{function n(e){return!!e&&!!e.match(/[\w\.:]+/)}Object.defineProperty(t,"__esModule",{value:!0}),t.createMatchers=void 0,t.createMatchers=function(e,t){const s=[],r=function(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;const s=n[0];return n=t.exec(e),s}}}(e);let i=r.next();for(;null!==i;){let e=0;if(2===i.length&&":"===i.charAt(1)){switch(i.charAt(0)){case"R":e=1;break;case"L":e=-1;break;default:console.log(`Unknown priority ${i} in scope selector`)}i=r.next()}let t=a();if(s.push({matcher:t,priority:e}),","!==i)break;i=r.next()}return s;function o(){if("-"===i){i=r.next();const e=o();return t=>!!e&&!e(t)}if("("===i){i=r.next();const e=function(){const e=[];let t=a();for(;t&&(e.push(t),"|"===i||","===i);){do{i=r.next()}while("|"===i||","===i);t=a()}return t=>e.some((e=>e(t)))}();return")"===i&&(i=r.next()),e}if(n(i)){const e=[];do{e.push(i),i=r.next()}while(n(i));return n=>t(e,n)}return null}function a(){const e=[];let t=o();for(;t;)e.push(t),t=o();return t=>e.every((e=>e(t)))}}},810:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.disposeOnigString=void 0,t.disposeOnigString=function(e){"function"==typeof e.dispose&&e.dispose()}},150:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseRawGrammar=void 0;const s=n(578),r=n(185),i=n(726);t.parseRawGrammar=function(e,t=null){return null!==t&&/\.json$/.test(t)?(n=e,o=t,r.DebugFlags.InDebugMode?i.parseJSON(n,o,!0):JSON.parse(n)):function(e,t){return r.DebugFlags.InDebugMode?s.parseWithLocation(e,t,"$vscodeTextmateLocation"):s.parsePLIST(e)}(e,t);var n,o}},578:(e,t)=>{function n(e,t,n){const s=e.length;let r=0,i=1,o=0;function a(t){if(null===n)r+=t;else for(;t>0;)10===e.charCodeAt(r)?(r++,i++,o=0):(r++,o++),t--}function c(e){null===n?r=e:a(e-r)}function l(){for(;r<s;){let t=e.charCodeAt(r);if(32!==t&&9!==t&&13!==t&&10!==t)break;a(1)}}function u(t){return e.substr(r,t.length)===t&&(a(t.length),!0)}function h(t){let n=e.indexOf(t,r);c(-1!==n?n+t.length:s)}function p(t){let n=e.indexOf(t,r);if(-1!==n){let s=e.substring(r,n);return c(n+t.length),s}{let t=e.substr(r);return c(s),t}}s>0&&65279===e.charCodeAt(0)&&(r=1);let d=0,f=null,m=[],g=[],_=null;function b(e,t){m.push(d),g.push(f),d=e,f=t}function y(){if(0===m.length)return S("illegal state stack");d=m.pop(),f=g.pop()}function S(t){throw new Error("Near offset "+r+": "+t+" ~~~"+e.substr(r,50)+"~~~")}const k=function(){if(null===_)return S("missing <key>");let e={};null!==n&&(e[n]={filename:t,line:i,char:o}),f[_]=e,_=null,b(1,e)},C=function(){if(null===_)return S("missing <key>");let e=[];f[_]=e,_=null,b(2,e)},R=function(){let e={};null!==n&&(e[n]={filename:t,line:i,char:o}),f.push(e),b(1,e)},A=function(){let e=[];f.push(e),b(2,e)};function w(){if(1!==d)return S("unexpected </dict>");y()}function I(){return 1===d||2!==d?S("unexpected </array>"):void y()}function P(e){if(1===d){if(null===_)return S("missing <key>");f[_]=e,_=null}else 2===d?f.push(e):f=e}function v(e){if(isNaN(e))return S("cannot parse float");if(1===d){if(null===_)return S("missing <key>");f[_]=e,_=null}else 2===d?f.push(e):f=e}function x(e){if(isNaN(e))return S("cannot parse integer");if(1===d){if(null===_)return S("missing <key>");f[_]=e,_=null}else 2===d?f.push(e):f=e}function N(e){if(1===d){if(null===_)return S("missing <key>");f[_]=e,_=null}else 2===d?f.push(e):f=e}function E(e){if(1===d){if(null===_)return S("missing <key>");f[_]=e,_=null}else 2===d?f.push(e):f=e}function F(e){if(1===d){if(null===_)return S("missing <key>");f[_]=e,_=null}else 2===d?f.push(e):f=e}function T(){let e=p(">"),t=!1;return 47===e.charCodeAt(e.length-1)&&(t=!0,e=e.substring(0,e.length-1)),{name:e.trim(),isClosed:t}}function D(e){if(e.isClosed)return"";let t=p("</");return h(">"),t.replace(/&#([0-9]+);/g,(function(e,t){return String.fromCodePoint(parseInt(t,10))})).replace(/&#x([0-9a-f]+);/g,(function(e,t){return String.fromCodePoint(parseInt(t,16))})).replace(/&|<|>|"|'/g,(function(e){switch(e){case"&":return"&";case"<":return"<";case">":return">";case""":return'"';case"'":return"'"}return e}))}for(;r<s&&(l(),!(r>=s));){const c=e.charCodeAt(r);if(a(1),60!==c)return S("expected <");if(r>=s)return S("unexpected end of input");const p=e.charCodeAt(r);if(63===p){a(1),h("?>");continue}if(33===p){if(a(1),u("--")){h("--\x3e");continue}h(">");continue}if(47===p){if(a(1),l(),u("plist")){h(">");continue}if(u("dict")){h(">"),w();continue}if(u("array")){h(">"),I();continue}return S("unexpected closed tag")}let m=T();switch(m.name){case"dict":1===d?k():2===d?R():(f={},null!==n&&(f[n]={filename:t,line:i,char:o}),b(1,f)),m.isClosed&&w();continue;case"array":1===d?C():2===d?A():(f=[],b(2,f)),m.isClosed&&I();continue;case"key":G=D(m),1!==d?S("unexpected <key>"):null!==_?S("too many <key>"):_=G;continue;case"string":P(D(m));continue;case"real":v(parseFloat(D(m)));continue;case"integer":x(parseInt(D(m),10));continue;case"date":N(new Date(D(m)));continue;case"data":E(D(m));continue;case"true":D(m),F(!0);continue;case"false":D(m),F(!1);continue}if(!/^plist/.test(m.name))return S("unexpected opened tag "+m.name)}var G;return f}Object.defineProperty(t,"__esModule",{value:!0}),t.parsePLIST=t.parseWithLocation=void 0,t.parseWithLocation=function(e,t,s){return n(e,t,s)},t.parsePLIST=function(e){return n(e,null,null)}},583:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SyncRegistry=void 0;const s=n(752);t.SyncRegistry=class{constructor(e,t){this._onigLibPromise=t,this._grammars=new Map,this._rawGrammars=new Map,this._injectionGrammars=new Map,this._theme=e}dispose(){for(const e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}async grammarForScopeName(e,t,n,r,i){if(!this._grammars.has(e)){let o=this._rawGrammars.get(e);if(!o)return null;this._grammars.set(e,s.createGrammar(e,o,t,n,r,i,this,await this._onigLibPromise))}return this._grammars.get(e)}}},666:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CompiledRule=t.RegExpSourceList=t.RegExpSource=t.RuleFactory=t.BeginWhileRule=t.BeginEndRule=t.IncludeOnlyRule=t.MatchRule=t.CaptureRule=t.Rule=t.ruleIdToNumber=t.ruleIdFromNumber=t.whileRuleId=t.endRuleId=void 0;const s=n(807),r=n(784),i=/\\(\d+)/,o=/\\(\d+)/g;Symbol("RuleId"),t.endRuleId=-1,t.whileRuleId=-2,t.ruleIdFromNumber=function(e){return e},t.ruleIdToNumber=function(e){return e};class a{constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=s.RegexSource.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=s.RegexSource.hasCaptures(this._contentName)}get debugName(){const e=this.$location?`${s.basename(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return this._nameIsCapturing&&null!==this._name&&null!==e&&null!==t?s.RegexSource.replaceCaptures(this._name,e,t):this._name}getContentName(e,t){return this._contentNameIsCapturing&&null!==this._contentName?s.RegexSource.replaceCaptures(this._contentName,e,t):this._contentName}}t.Rule=a;class c extends a{constructor(e,t,n,s,r){super(e,t,n,s),this.retokenizeCapturedWithRuleId=r}dispose(){}collectPatterns(e,t){throw new Error("Not supported!")}compile(e,t){throw new Error("Not supported!")}compileAG(e,t,n,s){throw new Error("Not supported!")}}t.CaptureRule=c;class l extends a{constructor(e,t,n,s,r){super(e,t,n,null),this._match=new f(s,this.id),this.captures=r,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,s){return this._getCachedCompiledPatterns(e).compileAG(e,n,s)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new m,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}}t.MatchRule=l;class u extends a{constructor(e,t,n,s,r){super(e,t,n,s),this.patterns=r.patterns,this.hasMissingPatterns=r.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(e,t){for(const n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,s){return this._getCachedCompiledPatterns(e).compileAG(e,n,s)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new m,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}}t.IncludeOnlyRule=u;class h extends a{constructor(e,t,n,s,r,i,o,a,c,l){super(e,t,n,s),this._begin=new f(r,this.id),this.beginCaptures=i,this._end=new f(o||"",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=a,this.applyEndPatternLast=c||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,s){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,s)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new m;for(const t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}}t.BeginEndRule=h;class p extends a{constructor(e,n,s,r,i,o,a,c,l){super(e,n,s,r),this._begin=new f(i,this.id),this.beginCaptures=o,this.whileCaptures=c,this._while=new f(a,t.whileRuleId),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,s){return this._getCachedCompiledPatterns(e).compileAG(e,n,s)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new m;for(const t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,s){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,s)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new m,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||""),this._cachedCompiledWhilePatterns}}t.BeginWhileRule=p;class d{static createCaptureRule(e,t,n,s,r){return e.registerRule((e=>new c(t,e,n,s,r)))}static getCompiledRuleId(e,t,n){return e.id||t.registerRule((r=>{if(e.id=r,e.match)return new l(e.$vscodeTextmateLocation,e.id,e.name,e.match,d._compileCaptures(e.captures,t,n));if(void 0===e.begin){e.repository&&(n=s.mergeObjects({},n,e.repository));let r=e.patterns;return void 0===r&&e.include&&(r=[{include:e.include}]),new u(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,d._compilePatterns(r,t,n))}return e.while?new p(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,e.begin,d._compileCaptures(e.beginCaptures||e.captures,t,n),e.while,d._compileCaptures(e.whileCaptures||e.captures,t,n),d._compilePatterns(e.patterns,t,n)):new h(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,e.begin,d._compileCaptures(e.beginCaptures||e.captures,t,n),e.end,d._compileCaptures(e.endCaptures||e.captures,t,n),e.applyEndPatternLast,d._compilePatterns(e.patterns,t,n))})),e.id}static _compileCaptures(e,t,n){let s=[];if(e){let r=0;for(const t in e){if("$vscodeTextmateLocation"===t)continue;const e=parseInt(t,10);e>r&&(r=e)}for(let e=0;e<=r;e++)s[e]=null;for(const r in e){if("$vscodeTextmateLocation"===r)continue;const i=parseInt(r,10);let o=0;e[r].patterns&&(o=d.getCompiledRuleId(e[r],t,n)),s[i]=d.createCaptureRule(t,e[r].$vscodeTextmateLocation,e[r].name,e[r].contentName,o)}}return s}static _compilePatterns(e,t,n){let s=[];if(e)for(let i=0,o=e.length;i<o;i++){const o=e[i];let a=-1;if(o.include){const e=r.parseInclude(o.include);switch(e.kind){case 0:case 1:a=d.getCompiledRuleId(n[o.include],t,n);break;case 2:let s=n[e.ruleName];s&&(a=d.getCompiledRuleId(s,t,n));break;case 3:case 4:const r=e.scopeName,i=4===e.kind?e.ruleName:null,c=t.getExternalGrammar(r,n);if(c)if(i){let e=c.repository[i];e&&(a=d.getCompiledRuleId(e,t,c.repository))}else a=d.getCompiledRuleId(c.repository.$self,t,c.repository)}}else a=d.getCompiledRuleId(o,t,n);if(-1!==a){const e=t.getRule(a);let n=!1;if((e instanceof u||e instanceof h||e instanceof p)&&e.hasMissingPatterns&&0===e.patterns.length&&(n=!0),n)continue;s.push(a)}}return{patterns:s,hasMissingPatterns:(e?e.length:0)!==s.length}}}t.RuleFactory=d;class f{constructor(e,t){if(e){const t=e.length;let n=0,s=[],r=!1;for(let i=0;i<t;i++)if("\\"===e.charAt(i)&&i+1<t){const t=e.charAt(i+1);"z"===t?(s.push(e.substring(n,i)),s.push("$(?!\\n)(?<!\\n)"),n=i+2):"A"!==t&&"G"!==t||(r=!0),i++}this.hasAnchor=r,0===n?this.source=e:(s.push(e.substring(n,t)),this.source=s.join(""))}else this.hasAnchor=!1,this.source=e;this.hasAnchor?this._anchorCache=this._buildAnchorCache():this._anchorCache=null,this.ruleId=t,this.hasBackReferences=i.test(this.source)}clone(){return new f(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){let n=t.map((t=>e.substring(t.start,t.end)));return o.lastIndex=0,this.source.replace(o,((e,t)=>s.escapeRegExpCharacters(n[parseInt(t,10)]||"")))}_buildAnchorCache(){let e,t,n,s,r=[],i=[],o=[],a=[];for(e=0,t=this.source.length;e<t;e++)n=this.source.charAt(e),r[e]=n,i[e]=n,o[e]=n,a[e]=n,"\\"===n&&e+1<t&&(s=this.source.charAt(e+1),"A"===s?(r[e+1]="",i[e+1]="",o[e+1]="A",a[e+1]="A"):"G"===s?(r[e+1]="",i[e+1]="G",o[e+1]="",a[e+1]="G"):(r[e+1]=s,i[e+1]=s,o[e+1]=s,a[e+1]=s),e++);return{A0_G0:r.join(""),A0_G1:i.join(""),A1_G0:o.join(""),A1_G1:a.join("")}}resolveAnchors(e,t){return this.hasAnchor&&this._anchorCache?e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0:this.source}}t.RegExpSource=f;class m{constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&(this._cached.dispose(),this._cached=null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map((e=>e.source));this._cached=new g(e,t,this._items.map((e=>e.ruleId)))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){let s=this._items.map((e=>e.resolveAnchors(t,n)));return new g(e,s,this._items.map((e=>e.ruleId)))}}t.RegExpSourceList=m;class g{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}dispose(){"function"==typeof this.scanner.dispose&&this.scanner.dispose()}toString(){const e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push(" - "+this.rules[t]+": "+this.regExps[t]);return e.join("\n")}findNextMatchSync(e,t,n){const s=this.scanner.findNextMatchSync(e,t,n);return s?{ruleId:this.rules[s.index],captureIndices:s.captureIndices}:null}}t.CompiledRule=g},63:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ThemeTrieElement=t.ThemeTrieElementRule=t.ColorMap=t.fontStyleToString=t.ParsedThemeRule=t.parseTheme=t.StyleAttributes=t.ScopeStack=t.Theme=void 0;const s=n(807);class r{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n,this._cachedMatchRoot=new s.CachedFn((e=>this._root.match(e)))}static createFromRawTheme(e,t){return this.createFromParsedTheme(c(e),t)}static createFromParsedTheme(e,t){return function(e,t){e.sort(((e,t)=>{let n=s.strcmp(e.scope,t.scope);return 0!==n?n:(n=s.strArrCmp(e.parentScopes,t.parentScopes),0!==n?n:e.index-t.index)}));let n=0,i="#000000",o="#ffffff",c="",l=0,h=0;for(;e.length>=1&&""===e[0].scope;){let t=e.shift();-1!==t.fontStyle&&(n=t.fontStyle),null!==t.foreground&&(i=t.foreground),null!==t.background&&(o=t.background),null!==t.fontFamily&&(c=t.fontFamily),null!==t.fontSize&&(l=t.fontSize),null!==t.lineHeight&&(h=t.lineHeight)}let f=new u(t),m=new a(n,f.getId(i),f.getId(o),c,l,h),g=new d(new p(0,null,-1,0,0,c,l,h),[]);for(let t=0,n=e.length;t<n;t++){let n=e[t];g.insert(0,n.scope,n.parentScopes,n.fontStyle,f.getId(n.foreground),f.getId(n.background),n.fontFamily,n.fontSize,n.lineHeight)}return new r(f,m,g)}(e,t)}getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(null===e)return this._defaults;const t=e.scopeName,n=this._cachedMatchRoot.get(t).find((t=>function(e,t){if(0===t.length)return!0;for(let n=0;n<t.length;n++){let s=t[n],r=!1;if(">"===s){if(n===t.length-1)return!1;s=t[++n],r=!0}for(;e&&!o(e.scopeName,s);){if(r)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}(e.parent,t.parentScopes)));return n?new a(n.fontStyle,n.foreground,n.background,n.fontFamily,n.fontSize,n.lineHeight):null}}t.Theme=r;class i{constructor(e,t){this.parent=e,this.scopeName=t}static push(e,t){for(const n of t)e=new i(e,n);return e}static from(...e){let t=null;for(let n=0;n<e.length;n++)t=new i(t,e[n]);return t}push(e){return new i(this,e)}getSegments(){let e=this;const t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(" ")}extends(e){return this===e||null!==this.parent&&this.parent.extends(e)}getExtensionIfDefined(e){const t=[];let n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}}function o(e,t){return t===e||e.startsWith(t)&&"."===e[t.length]}t.ScopeStack=i;class a{constructor(e,t,n,s,r,i){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n,this.fontFamily=s,this.fontSize=r,this.lineHeight=i}}function c(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let e=0,i=t.length;e<i;e++){let i,o=t[e];if(!o.settings)continue;if("string"==typeof o.scope){let e=o.scope;e=e.replace(/^[,]+/,""),e=e.replace(/[,]+$/,""),i=e.split(",")}else i=Array.isArray(o.scope)?o.scope:[""];let a=-1;if("string"==typeof o.settings.fontStyle){a=0;let e=o.settings.fontStyle.split(" ");for(let t=0,n=e.length;t<n;t++)switch(e[t]){case"italic":a|=1;break;case"bold":a|=2;break;case"underline":a|=4;break;case"strikethrough":a|=8}}let c=null;"string"==typeof o.settings.foreground&&s.isValidHexColor(o.settings.foreground)&&(c=o.settings.foreground);let u=null;"string"==typeof o.settings.background&&s.isValidHexColor(o.settings.background)&&(u=o.settings.background);let h="";"string"==typeof o.settings.fontFamily&&(h=o.settings.fontFamily);let p=0;"number"==typeof o.settings.fontSize&&(p=o.settings.fontSize);let d=0;"number"==typeof o.settings.lineHeight&&(d=o.settings.lineHeight);for(let t=0,s=i.length;t<s;t++){let s=i[t].trim().split(" "),o=s[s.length-1],f=null;s.length>1&&(f=s.slice(0,s.length-1),f.reverse()),n[r++]=new l(o,f,e,a,c,u,h,p,d)}}return n}t.StyleAttributes=a,t.parseTheme=c;class l{constructor(e,t,n,s,r,i,o,a,c){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=s,this.foreground=r,this.background=i,this.fontFamily=o,this.fontSize=a,this.lineHeight=c}}t.ParsedThemeRule=l,t.fontStyleToString=function(e){if(-1===e)return"not set";let t="";return 1&e&&(t+="italic "),2&e&&(t+="bold "),4&e&&(t+="underline "),8&e&&(t+="strikethrough "),""===t&&(t="none"),t.trim()};class u{constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(null===e)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw new Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}}t.ColorMap=u;const h=Object.freeze([]);class p{constructor(e,t,n,s,r,i,o,a){this.scopeDepth=e,this.parentScopes=t||h,this.fontStyle=n,this.foreground=s,this.background=r,this.fontFamily=i,this.fontSize=o,this.lineHeight=a}clone(){return new p(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background,this.fontFamily,this.fontSize,this.lineHeight)}static cloneArr(e){let t=[];for(let n=0,s=e.length;n<s;n++)t[n]=e[n].clone();return t}acceptOverwrite(e,t,n,s,r,i,o){this.scopeDepth>e?console.log("how did this happen?"):this.scopeDepth=e,-1!==t&&(this.fontStyle=t),0!==n&&(this.foreground=n),0!==s&&(this.background=s),""!==r&&(this.fontFamily=r),0!==i&&(this.fontSize=i),0!==o&&(this.lineHeight=o)}}t.ThemeTrieElementRule=p;class d{constructor(e,t=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=t}static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let n=0,s=0;for(;">"===e.parentScopes[n]&&n++,">"===t.parentScopes[s]&&s++,!(n>=e.parentScopes.length||s>=t.parentScopes.length);){const r=t.parentScopes[s].length-e.parentScopes[n].length;if(0!==r)return r;n++,s++}return t.parentScopes.length-e.parentScopes.length}match(e){if(""!==e){let t,n,s=e.indexOf(".");if(-1===s?(t=e,n=""):(t=e.substring(0,s),n=e.substring(s+1)),this._children.hasOwnProperty(t))return this._children[t].match(n)}const t=this._rulesWithParentScopes.concat(this._mainRule);return t.sort(d._cmpBySpecificity),t}insert(e,t,n,s,r,i,o,a,c){if(""===t)return void this._doInsertHere(e,n,s,r,i,o,a,c);let l,u,h,f=t.indexOf(".");-1===f?(l=t,u=""):(l=t.substring(0,f),u=t.substring(f+1)),this._children.hasOwnProperty(l)?h=this._children[l]:(h=new d(this._mainRule.clone(),p.cloneArr(this._rulesWithParentScopes)),this._children[l]=h),h.insert(e+1,u,n,s,r,i,o,a,c)}_doInsertHere(e,t,n,r,i,o,a,c){if(null!==t){for(let l=0,u=this._rulesWithParentScopes.length;l<u;l++){let u=this._rulesWithParentScopes[l];if(0===s.strArrCmp(u.parentScopes,t))return void u.acceptOverwrite(e,n,r,i,o,a,c)}-1===n&&(n=this._mainRule.fontStyle),0===r&&(r=this._mainRule.foreground),0===i&&(i=this._mainRule.background),""===o&&(o=this._mainRule.fontFamily),0===a&&(a=this._mainRule.fontSize),0===c&&(c=this._mainRule.lineHeight),this._rulesWithParentScopes.push(new p(e,t,n,r,i,o,a,c))}else this._mainRule.acceptOverwrite(e,n,r,i,o,a,c)}}t.ThemeTrieElement=d},807:(e,t)=>{function n(e){return Array.isArray(e)?function(e){let t=[];for(let s=0,r=e.length;s<r;s++)t[s]=n(e[s]);return t}(e):"object"==typeof e?function(e){let t={};for(let s in e)t[s]=n(e[s]);return t}(e):e}Object.defineProperty(t,"__esModule",{value:!0}),t.containsRTL=t.performanceNow=t.CachedFn=t.escapeRegExpCharacters=t.isValidHexColor=t.strArrCmp=t.strcmp=t.RegexSource=t.basename=t.mergeObjects=t.clone=void 0,t.clone=function(e){return n(e)},t.mergeObjects=function(e,...t){return t.forEach((t=>{for(let n in t)e[n]=t[n]})),e},t.basename=function e(t){const n=~t.lastIndexOf("/")||~t.lastIndexOf("\\");return 0===n?t:~n==t.length-1?e(t.substring(0,t.length-1)):t.substr(1+~n)};let s,r=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g;function i(e,t){return e<t?-1:e>t?1:0}t.RegexSource=class{static hasCaptures(e){return null!==e&&(r.lastIndex=0,r.test(e))}static replaceCaptures(e,t,n){return e.replace(r,((e,s,r,i)=>{let o=n[parseInt(s||r,10)];if(!o)return e;{let e=t.substring(o.start,o.end);for(;"."===e[0];)e=e.substring(1);switch(i){case"downcase":return e.toLowerCase();case"upcase":return e.toUpperCase();default:return e}}}))}},t.strcmp=i,t.strArrCmp=function(e,t){if(null===e&&null===t)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,s=t.length;if(n===s){for(let s=0;s<n;s++){let n=i(e[s],t[s]);if(0!==n)return n}return 0}return n-s},t.isValidHexColor=function(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))},t.escapeRegExpCharacters=function(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&")},t.CachedFn=class{constructor(e){this.fn=e,this.cache=new Map}get(e){if(this.cache.has(e))return this.cache.get(e);const t=this.fn(e);return this.cache.set(e,t),t}},t.performanceNow="undefined"==typeof performance?function(){return Date.now()}:function(){return performance.now()},t.containsRTL=function(e){return s||(s=/(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDC7\uFDF0-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE35\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDD23\uDE80-\uDEA9\uDEAD-\uDF45\uDF51-\uDF81\uDF86-\uDFF6]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD4B-\uDFFF]|\uD83B[\uDC00-\uDEBB])/),s.test(e)}}},t={};return function n(s){var r=t[s];if(void 0!==r)return r.exports;var i=t[s]={exports:{}};return e[s].call(i.exports,i,i.exports,n),i.exports}(625)})())); | |
| 4 | +//# sourceMappingURL=main.js.map | |
| 5 | +export default module.exports; |
modified web/js/ext/vsix.js +49 −18
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | import { parseJsonc, parsePlist } from './formats.js'; |
| 7 | 7 | import { loadTheme, joinPath } from './themes.js'; |
| 8 | 8 | import { normalizeSnippets } from './snippets.js'; |
| 9 | +import { sanitizeGrammar, ambitoValido } from './grammars.js'; | |
| 10 | +import { nestedRepetition, unsafeConfigRegexes } from './languages.js'; | |
| 9 | 11 | |
| 10 | 12 | export const SUPPORTED = ['themes', 'grammars', 'snippets', 'languages']; |
| 11 | 13 | |
| @@ -23,8 +25,8 @@ | ||
| 23 | 25 | // (sirve igual con el manifiesto que publica Open VSX que con el del .vsix). |
| 24 | 26 | export function analyzeManifest(pkg) { |
| 25 | 27 | const c = pkg && typeof pkg.contributes === 'object' && pkg.contributes ? pkg.contributes : {}; |
| 26 | - const n = k => (Array.isArray(c[k]) ? c[k].length : 0); | |
| 27 | - const applies = { themes: n('themes'), grammars: n('grammars'), snippets: n('snippets'), languages: n('languages') }; | |
| 28 | + const arr = k => (Array.isArray(c[k]) ? c[k] : []); | |
| 29 | + const applies = { themes: arr('themes').length, grammars: arr('grammars').length, snippets: arr('snippets').length, languages: arr('languages').length }; | |
| 28 | 30 | const ignored = []; |
| 29 | 31 | for (const k of Object.keys(c)) { |
| 30 | 32 | if (SUPPORTED.includes(k)) continue; |
| @@ -32,9 +34,13 @@ | ||
| 32 | 34 | } |
| 33 | 35 | const hasCode = typeof pkg?.main === 'string' || typeof pkg?.browser === 'string'; |
| 34 | 36 | const pack = Array.isArray(pkg?.extensionPack) ? pkg.extensionPack.filter(x => typeof x === 'string') : []; |
| 35 | - const snippetLangs = [...new Set((c.snippets || []).map(s => s?.language).filter(x => typeof x === 'string'))]; | |
| 36 | - const languages = [...new Set([...(c.languages || []).map(l => l?.id), ...(c.grammars || []).map(g => g?.language)].filter(x => typeof x === 'string'))]; | |
| 37 | - return { applies, ignored, hasCode, pack, snippetLangs, languages, any: Object.values(applies).some(Boolean) }; | |
| 37 | + const snippetLangs = [...new Set(arr('snippets').map(s => s?.language).filter(x => typeof x === 'string'))]; | |
| 38 | + const languages = [...new Set([...arr('languages').map(l => l?.id), ...arr('grammars').map(g => g?.language)].filter(x => typeof x === 'string'))]; | |
| 39 | + // para decir qué NO se aplicaría aunque se instale (panel.js): el lenguaje | |
| 40 | + // de cada gramática y si cada lenguaje trae configuración | |
| 41 | + const grammarLangs = arr('grammars').map(g => (typeof g?.language === 'string' ? g.language : null)); | |
| 42 | + const languageList = arr('languages').filter(l => typeof l?.id === 'string' && l.id).map(l => ({ id: l.id, config: typeof l.configuration === 'string' })); | |
| 43 | + return { applies, ignored, hasCode, pack, snippetLangs, languages, grammarLangs, languageList, any: Object.values(applies).some(Boolean) }; | |
| 38 | 44 | } |
| 39 | 45 | |
| 40 | 46 | // %clave% → texto de package.nls(.<idioma>).json, en todo el manifiesto. |
| @@ -46,7 +52,8 @@ | ||
| 46 | 52 | return m && msg(nls?.[m[1]]) != null ? msg(nls[m[1]]) : v; |
| 47 | 53 | } |
| 48 | 54 | if (Array.isArray(v)) return v.map(walk); |
| 49 | - if (v && typeof v === 'object') { const o = {}; for (const [k, x] of Object.entries(v)) o[k] = walk(x); return o; } | |
| 55 | + // «__proto__» (propia, de JSON.parse) asignada cambiaría el prototipo de `o` | |
| 56 | + if (v && typeof v === 'object') { const o = {}; for (const [k, x] of Object.entries(v)) if (k !== '__proto__') o[k] = walk(x); return o; } | |
| 50 | 57 | return v; |
| 51 | 58 | }; |
| 52 | 59 | return walk(pkg); |
| @@ -60,23 +67,35 @@ | ||
| 60 | 67 | return o; |
| 61 | 68 | }; |
| 62 | 69 | |
| 70 | +// Un fallo de una contribución suelta: qué era, cómo se llama y por qué (un | |
| 71 | +// código que el panel traduce; `detail` es el mensaje técnico, de apoyo). | |
| 72 | +function aviso(kind, name, e, extra = {}) { | |
| 73 | + const code = e?.code || (e instanceof SyntaxError ? 'json' : ''); | |
| 74 | + return { kind, name: String(name ?? '').slice(0, 200), code, detail: String(e?.message ?? e ?? '').slice(0, 300), ...extra }; | |
| 75 | +} | |
| 76 | + | |
| 63 | 77 | // Lee el paquete entero. Los fallos de una contribución suelta van a |
| 64 | 78 | // `warnings` y no tumban la instalación del resto. |
| 65 | 79 | export async function readVsix(bytes, { lang = 'en' } = {}) { |
| 66 | 80 | const zip = openZip(bytes); |
| 67 | 81 | const dec = new TextDecoder(); |
| 68 | 82 | const readText = async p => { |
| 69 | - if (!p.startsWith('extension/')) throw new Error('ruta fuera de la extensión: ' + p); | |
| 83 | + if (!p.startsWith('extension/')) throw Object.assign(new Error('ruta fuera de la extensión: ' + p), { code: 'outside' }); | |
| 70 | 84 | return dec.decode(await zip.read(p)); |
| 71 | 85 | }; |
| 72 | 86 | if (!zip.has('extension/package.json')) throw Object.assign(new Error('no es una extensión de VS Code (falta extension/package.json)'), { code: 'notvsix' }); |
| 73 | - let pkg = parseJsonc(await readText('extension/package.json')); | |
| 87 | + let pkg; | |
| 88 | + try { pkg = parseJsonc(await readText('extension/package.json')); } | |
| 89 | + catch (e) { throw e?.code ? e : Object.assign(new Error(e?.message || String(e)), { code: 'badmanifest' }); } | |
| 90 | + if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg)) throw Object.assign(new Error('package.json no es un objeto'), { code: 'badmanifest' }); | |
| 74 | 91 | let nls = {}; |
| 75 | 92 | for (const f of ['extension/package.nls.json', `extension/package.nls.${lang}.json`]) { |
| 76 | 93 | if (zip.has(f)) { try { nls = { ...nls, ...parseJsonc(await readText(f)) }; } catch { /* traducción rota: se queda la clave */ } } |
| 77 | 94 | } |
| 78 | 95 | pkg = resolveNls(pkg, nls); |
| 79 | - if (typeof pkg.name !== 'string' || typeof pkg.publisher !== 'string') throw new Error('package.json sin name/publisher'); | |
| 96 | + if (typeof pkg.name !== 'string' || typeof pkg.publisher !== 'string' || !pkg.name || !pkg.publisher) { | |
| 97 | + throw Object.assign(new Error('package.json sin name/publisher'), { code: 'noname' }); | |
| 98 | + } | |
| 80 | 99 | |
| 81 | 100 | const warnings = []; |
| 82 | 101 | const ruta = p => joinPath('extension', String(p)); |
| @@ -88,17 +107,20 @@ | ||
| 88 | 107 | try { |
| 89 | 108 | const data = await loadTheme(ruta(t.path), readText, { label: t.label || t.id || t.path, uiTheme: t.uiTheme }); |
| 90 | 109 | themes.push({ index: i, id: typeof t.id === 'string' ? t.id : '', label: data.label, uiTheme: data.uiTheme, path: ruta(t.path), data }); |
| 91 | - } catch (e) { warnings.push(`tema ${t.label || t.path}: ${e.message}`); } | |
| 110 | + } catch (e) { warnings.push(aviso('theme', t.label || t.id || t.path, e)); } | |
| 92 | 111 | } |
| 93 | 112 | |
| 94 | 113 | const grammars = []; |
| 95 | 114 | for (const g of Array.isArray(c.grammars) ? c.grammars : []) { |
| 96 | 115 | if (!g || typeof g.path !== 'string' || typeof g.scopeName !== 'string') continue; |
| 97 | 116 | try { |
| 117 | + if (!ambitoValido(g.scopeName)) throw Object.assign(new Error('scopeName no válido: ' + g.scopeName), { code: 'scope' }); | |
| 98 | 118 | const p = ruta(g.path); |
| 99 | 119 | const text = await readText(p); |
| 100 | - const data = /\.json$/i.test(p) ? parseJsonc(text) : parsePlist(text); | |
| 101 | - if (!data || typeof data !== 'object' || !Array.isArray(data.patterns) && !data.injectionSelector) throw new Error('no parece una gramática TextMate'); | |
| 120 | + const leida = /\.json$/i.test(p) ? parseJsonc(text) : parsePlist(text); | |
| 121 | + if (!leida || typeof leida !== 'object' || !Array.isArray(leida.patterns) && !leida.injectionSelector) throw Object.assign(new Error('no parece una gramática TextMate'), { code: 'notgrammar' }); | |
| 122 | + // sin nombres que lleven al motor fuera de la gramática (grammars.js) | |
| 123 | + const data = sanitizeGrammar(leida); | |
| 102 | 124 | grammars.push({ |
| 103 | 125 | path: p, scopeName: g.scopeName, data, |
| 104 | 126 | language: typeof g.language === 'string' ? g.language : undefined, |
| @@ -106,31 +128,40 @@ | ||
| 106 | 128 | injectTo: strs(g.injectTo), balancedBracketScopes: Array.isArray(g.balancedBracketScopes) ? strs(g.balancedBracketScopes) : undefined, |
| 107 | 129 | unbalancedBracketScopes: Array.isArray(g.unbalancedBracketScopes) ? strs(g.unbalancedBracketScopes) : undefined, |
| 108 | 130 | }); |
| 109 | - } catch (e) { warnings.push(`gramática ${g.scopeName}: ${e.message}`); } | |
| 131 | + } catch (e) { warnings.push(aviso('grammar', g.scopeName, e)); } | |
| 110 | 132 | } |
| 111 | 133 | |
| 112 | 134 | const snippets = []; |
| 113 | 135 | const porRuta = new Map(); |
| 114 | 136 | for (const s of Array.isArray(c.snippets) ? c.snippets : []) { |
| 115 | 137 | if (!s || typeof s.path !== 'string' || typeof s.language !== 'string') continue; |
| 116 | - const p = ruta(s.path); | |
| 117 | 138 | try { |
| 139 | + const p = ruta(s.path); | |
| 118 | 140 | if (!porRuta.has(p)) porRuta.set(p, normalizeSnippets(parseJsonc(await readText(p)))); |
| 119 | 141 | if (porRuta.get(p).length) snippets.push({ language: s.language, path: p, data: porRuta.get(p) }); |
| 120 | - } catch (e) { warnings.push(`snippets ${s.path}: ${e.message}`); } | |
| 142 | + } catch (e) { warnings.push(aviso('snippets', s.path, e)); } | |
| 121 | 143 | } |
| 122 | 144 | |
| 145 | + // Las expresiones de un lenguaje (firstLine y las del language-configuration) | |
| 146 | + // con repetición anidada se descartan: podrían congelar la pestaña. Aquí | |
| 147 | + // solo se avisa; languages.js las descarta también al aplicarlas. | |
| 123 | 148 | const languages = []; |
| 124 | 149 | for (const l of Array.isArray(c.languages) ? c.languages : []) { |
| 125 | 150 | if (!l || typeof l.id !== 'string' || !l.id) continue; |
| 151 | + let firstLine = typeof l.firstLine === 'string' && l.firstLine ? l.firstLine : undefined; | |
| 152 | + if (firstLine && nestedRepetition(firstLine)) { warnings.push(aviso('regex', l.id, { code: 'nested', message: firstLine }, { where: 'firstLine' })); firstLine = undefined; } | |
| 126 | 153 | const entry = { |
| 127 | 154 | id: l.id, aliases: strs(l.aliases), extensions: strs(l.extensions), filenames: strs(l.filenames), |
| 128 | 155 | filenamePatterns: strs(l.filenamePatterns), mimetypes: strs(l.mimetypes), |
| 129 | - firstLine: typeof l.firstLine === 'string' ? l.firstLine : undefined, configPath: null, config: null, | |
| 156 | + firstLine, configPath: null, config: null, | |
| 130 | 157 | }; |
| 131 | 158 | if (typeof l.configuration === 'string') { |
| 132 | - try { entry.configPath = ruta(l.configuration); entry.config = parseJsonc(await readText(entry.configPath)); } | |
| 133 | - catch (e) { warnings.push(`configuración de ${l.id}: ${e.message}`); entry.configPath = null; } | |
| 159 | + try { | |
| 160 | + entry.configPath = ruta(l.configuration); | |
| 161 | + entry.config = parseJsonc(await readText(entry.configPath)); | |
| 162 | + // (solo cuenta si el lenguaje es nuevo: la de uno de serie no se aplica) | |
| 163 | + for (const src of unsafeConfigRegexes(entry.config)) warnings.push(aviso('regex', l.id, { code: 'nested', message: src }, { where: 'config' })); | |
| 164 | + } catch (e) { warnings.push(aviso('config', l.id, e)); entry.configPath = null; entry.config = null; } | |
| 134 | 165 | } |
| 135 | 166 | languages.push(entry); |
| 136 | 167 | } |
modified web/js/ide.js +9 −3
| @@ -20,7 +20,12 @@ | ||
| 20 | 20 | svg: 'xml', xml: 'xml', sql: 'sql', txt: 'plaintext', |
| 21 | 21 | }; |
| 22 | 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'; | |
| 23 | +const porNombre = p => ext?.languageForPath(p) || LANG[p.split('.').pop().toLowerCase()] || null; | |
| 24 | +const langOf = p => porNombre(p) || 'plaintext'; | |
| 25 | +// …y, como en VS Code, la primera línea (firstLine de una extensión) solo | |
| 26 | +// cuenta si nadie reclama el fichero por su nombre. Va en un Worker con tiempo | |
| 27 | +// tope: una expresión de un paquete puede no terminar nunca. | |
| 28 | +const langDe = async (p, primeraLinea) => porNombre(p) || (ext && primeraLinea ? await ext.languageForFirstLine(primeraLinea) : null) || 'plaintext'; | |
| 24 | 29 | const $ = id => document.getElementById(id); |
| 25 | 30 | |
| 26 | 31 | export async function initEditor() { |
| @@ -97,7 +102,7 @@ | ||
| 97 | 102 | if (hits.length === 1 && hits[0] !== path) return openFile(hits[0]); |
| 98 | 103 | return alertBar(t('openFailed', { path, e: e.message })); |
| 99 | 104 | } |
| 100 | - const lang = langOf(path, content.slice(0, 500).split('\n')[0]); | |
| 105 | + const lang = await langDe(path, content.slice(0, 500).split('\n')[0]); | |
| 101 | 106 | await ext?.prepareLanguage(lang); // la gramática, antes de que exista el modelo |
| 102 | 107 | tab = tabs.find(t => t.path === path); // otra llamada pudo abrirla mientras tanto |
| 103 | 108 | if (!tab) { |
| @@ -764,7 +769,8 @@ | ||
| 764 | 769 | // su gramática al día (o de vuelta a lo de serie). |
| 765 | 770 | async function refreshLanguages() { |
| 766 | 771 | for (const tab of [...tabs]) { |
| 767 | - const lang = langOf(tab.path, tab.model.getLineContent(1)); | |
| 772 | + if (tab.model.isDisposed()) continue; | |
| 773 | + const lang = await langDe(tab.path, tab.model.getLineContent(1)); | |
| 768 | 774 | await ext?.prepareLanguage(lang); |
| 769 | 775 | if (!tab.model.isDisposed() && tab.model.getLanguageId() !== lang) monacoRef.editor.setModelLanguage(tab.model, lang); |
| 770 | 776 | } |
modified web/js/main.js +5 −0
| @@ -2085,6 +2085,9 @@ | ||
| 2085 | 2085 | { label: '/tree', hint: t('slTree'), run: () => send(t('pTree')) }, |
| 2086 | 2086 | { label: '/search', hint: t('slSearch'), run: () => { $('prompt').value = t('pSearch'); $('prompt').focus(); } }, |
| 2087 | 2087 | { label: '/skills', hint: t('slSkills'), run: () => openSkillsPanel() }, |
| 2088 | + // en pantallas estrechas no hay barra de actividad ni menú View: esto sí se ve | |
| 2089 | + { label: '/extensions', hint: extTexto('temas, gramáticas, snippets', 'themes, grammars, snippets'), run: () => openExtensions() }, | |
| 2090 | + { label: '/theme', hint: extTexto('tema de color', 'color theme'), run: () => openExtensions({ themes: true }) }, | |
| 2088 | 2091 | { label: '/model', hint: t('slModel'), run: () => $('btn-settings').click() }, |
| 2089 | 2092 | // «/clear» abría una conversación NUEVA (no limpiaba la actual): se llama |
| 2090 | 2093 | // por lo que hace. |
| @@ -2667,6 +2670,8 @@ | ||
| 2667 | 2670 | { label: t('tCity'), run: () => openView('city') }, |
| 2668 | 2671 | { label: t('mPalette'), hint: atajo('P', true), run: () => openPalette('>') }, |
| 2669 | 2672 | { label: 'Skills', run: () => openSkillsPanel() }, |
| 2673 | + { label: extTexto('Extensiones…', 'Extensions…'), run: () => openExtensions() }, | |
| 2674 | + { label: extTexto('Tema de color…', 'Color Theme…'), run: () => openExtensions({ themes: true }) }, | |
| 2670 | 2675 | { label: t('mLab'), hint: '↗', run: () => abrirLab() }, |
| 2671 | 2676 | { label: t('mAbout'), hint: '↗', run: () => window.open('https://github.com/KikoCis/elffuss-code', '_blank', 'noopener') }, |
| 2672 | 2677 | ]; |