| 1 | // Extensiones de VS Code en Elffuss Code (nivel 1: temas, gramáticas, |
| 2 | // snippets y lenguajes; nada de código de extensión). |
| 3 | // |
| 4 | // BASE=http://localhost:8999 node tests/extensions.mjs |
| 5 | // |
| 6 | // Las extensiones de prueba se fabrican aquí (ext_fixtures.mjs): sin red ni |
| 7 | // licencias. La parte EN VIVO instala dos extensiones reales de Open VSX |
| 8 | // (vscode.theme-monokai y vscode.make, de las «built-in» de VS Code, MIT); si |
| 9 | // no hay red, se marca NOT RUN y no cuenta como fallo. |
| 10 | import { chromium } from 'playwright'; |
| 11 | import { themeVsix, elfscriptVsix, THEME_DARK, EVIL, EVIL_GRAMMAR, hostileGrammarVsix, beaconSnippetVsix, brokenThemeVsix, jsonGrammarVsix, noPublisherVsix, slowRegexVsix } from './ext_fixtures.mjs'; |
| 12 | |
| 13 | const OUT = (process.env.SCRATCH || '/tmp/elffuss-test'); |
| 14 | const BASE = process.env.BASE || 'http://localhost:8999'; |
| 15 | let fails = 0; |
| 16 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 17 | const notRun = (n, e) => console.log('⏭️ NOT RUN ' + n + (e ? ' — ' + e : '')); |
| 18 | const rgb = hex => { const h = hex.replace('#', ''); return `rgb(${parseInt(h.slice(0, 2), 16)}, ${parseInt(h.slice(2, 4), 16)}, ${parseInt(h.slice(4, 6), 16)})`; }; |
| 19 | const sleep = ms => new Promise(r => setTimeout(r, ms)); |
| 20 | async function hasta(fn, { tiempo = 15000, cada = 150 } = {}) { |
| 21 | const fin = Date.now() + tiempo; |
| 22 | let v; |
| 23 | while (Date.now() < fin) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(cada); } |
| 24 | return v; |
| 25 | } |
| 26 | |
| 27 | // Modo con extensiones (tests/lib/x2-mode.mjs): dos extensiones de código ya |
| 28 | // están instaladas antes de empezar. Esta suite cuenta, comprueba y desinstala |
| 29 | // solo las suyas; en el modo por defecto PREVIAS está vacía y nada cambia. |
| 30 | const PREVIAS = (process.env.X2_SEEDED || '').split(',').filter(Boolean); |
| 31 | const propias = sel => sel + PREVIAS.map(id => `:not([data-id="${id}"])`).join(''); |
| 32 | const sinPrevias = lista => (Array.isArray(lista) ? lista.filter(e => !PREVIAS.includes(e.id)) : lista); |
| 33 | |
| 34 | const b = await chromium.launch(); |
| 35 | const ctx = await b.newContext(); |
| 36 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); |
| 37 | const p = await ctx.newPage(); |
| 38 | const errores = []; |
| 39 | // «Canceled»: Monaco deja escapar esa promesa si se cambia de fichero justo |
| 40 | // después de aceptar una sugerencia; pasa igual SIN extensiones, no es de aquí. |
| 41 | p.on('pageerror', e => { if (e.message !== 'Canceled') errores.push(e.message); }); |
| 42 | const pedidas = []; |
| 43 | p.on('request', r => pedidas.push(r.url())); |
| 44 | |
| 45 | // ── helpers dentro de la página ── |
| 46 | const fondo = () => p.evaluate(() => getComputedStyle(document.querySelector('#editor .monaco-editor-background') || document.querySelector('#editor .monaco-editor')).backgroundColor); |
| 47 | const abre = path => p.evaluate(async path => { await (await import('/js/ide.js')).openFile(path); }, path); |
| 48 | const lenguaje = () => p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getLanguageId()); |
| 49 | // estilo del primer span pintado cuyo texto es `txt` |
| 50 | const estilo = txt => p.evaluate(txt => { |
| 51 | for (const s of document.querySelectorAll('#editor .view-lines span span')) { |
| 52 | // Monaco pinta los espacios como U+00A0 |
| 53 | if (s.textContent.replace(/ /g, ' ').trim() === txt) { const cs = getComputedStyle(s); return { color: cs.color, italic: cs.fontStyle === 'italic' }; } |
| 54 | } |
| 55 | return null; |
| 56 | }, txt); |
| 57 | const colorDe = async (txt, hex) => hasta(async () => (await estilo(txt))?.color === rgb(hex), { tiempo: 8000 }); |
| 58 | const ponTexto = (texto) => p.evaluate(texto => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue(texto); }, texto); |
| 59 | const instalaFichero = async (nombre, bytes) => { |
| 60 | await p.evaluate(() => { const m = document.getElementById('ext-msg'); if (m) { m.hidden = true; m.textContent = ''; } }); |
| 61 | await p.setInputFiles('#ext-file', { name: nombre, mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) }); |
| 62 | return hasta(() => p.evaluate(() => { const m = document.getElementById('ext-msg'); return m && !m.hidden && m.textContent; }), { tiempo: 15000 }); |
| 63 | }; |
| 64 | const abrePanel = async () => { |
| 65 | await p.click('#act-ext'); |
| 66 | await p.waitForSelector('#ext-panel', { timeout: 10000 }); |
| 67 | }; |
| 68 | const filaInstalada = id => p.locator(`#ext-installed .ext-row[data-id="${id}"]`); |
| 69 | |
| 70 | // ── A. primer arranque: sin extensiones no se carga NADA nuevo ── |
| 71 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 72 | await p.evaluate(async () => { |
| 73 | const o = await navigator.storage.getDirectory(); |
| 74 | const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); }; |
| 75 | await w('app.js', '// nota\nconst a = 1;\n'); |
| 76 | await w('notes.elfs', '# hola\nspell fire with 42\n cast "llama"\nend\nᚱune\n'); |
| 77 | await w('Makefile', '# build\nall: build\n\tgcc -o app main.c\n'); |
| 78 | await w('a.evil', 'evil ctor (x)\n'); |
| 79 | await w('runme', '#!/usr/bin/env elfs\nspell x\nend\n'); |
| 80 | // sin extensión y con una primera línea que hace no terminar a ^(.|\s)*z |
| 81 | await w('slow-input', ' '.repeat(64) + 'x\n'); |
| 82 | }); |
| 83 | pedidas.length = 0; |
| 84 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 85 | await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length)); |
| 86 | await sleep(800); |
| 87 | const extras = pedidas.filter(u => /\/js\/ext\/|\/css\/ext\.css|vscode-textmate|vscode-oniguruma|open-vsx|eclipsecontent/.test(u)); |
| 88 | if (PREVIAS.length) notRun('primer arranque sin extensiones', 'en el modo con extensiones hay dos instaladas: el camino por defecto lo mide x2_bytes.mjs'); |
| 89 | else ok('primer arranque sin extensiones: ni host, ni panel, ni motor TextMate, ni Open VSX', extras.length === 0, extras.join(' ')); |
| 90 | ok('tema de serie (vs-dark)', (await fondo()) === 'rgb(30, 30, 30)', await fondo()); |
| 91 | |
| 92 | // ── B. panel + tema desde un .vsix ── |
| 93 | await abrePanel(); |
| 94 | ok('el panel abre sin pedir nada a Open VSX (solo al buscar)', !pedidas.some(u => /open-vsx/.test(u))); |
| 95 | await instalaFichero('elf-theme.vsix', themeVsix()); |
| 96 | ok('tema instalado desde .vsix', await hasta(async () => (await filaInstalada('elffuss-test.elf-theme').count()) === 1), await p.locator('#ext-msg').textContent()); |
| 97 | const textoFila = await filaInstalada('elffuss-test.elf-theme').innerText(); |
| 98 | ok('la fila dice en llano qué hace ahora y qué no funciona (sus acciones necesitan su código)', /Active theme: “Elf Dark”/.test(textoFila) && /Does not work: .*its own actions/.test(textoFila) && !/commands|main\/browser|extension host/.test(textoFila), textoFila.replace(/\s+/g, ' ').slice(0, 320)); |
| 99 | const chipOscuro = filaInstalada('elffuss-test.elf-theme').locator('.ext-theme-chips .ext-chip').first(); |
| 100 | await chipOscuro.click(); |
| 101 | ok('tema aplicado: fondo del editor', await hasta(async () => (await fondo()) === rgb(THEME_DARK.bg)), await fondo()); |
| 102 | ok('pestañas con los colores del tema (sin el url() malicioso)', await hasta(() => p.evaluate(() => (document.getElementById('ext-theme-chrome')?.textContent || '').includes('#203040') && !document.getElementById('ext-theme-chrome').textContent.includes('url(')))); |
| 103 | await p.click('#settings-close'); |
| 104 | await abre('app.js'); |
| 105 | ok('JS (Monarch): keyword con el color del tema', await colorDe('const', THEME_DARK.keyword), JSON.stringify(await estilo('const'))); |
| 106 | ok('JS (Monarch): comentario con color y cursiva del tema', (await colorDe('// nota', THEME_DARK.comment)) && (await estilo('// nota'))?.italic, JSON.stringify(await estilo('// nota'))); |
| 107 | |
| 108 | // ── C. lenguaje nuevo + gramática TextMate + snippets ── |
| 109 | await abrePanel(); |
| 110 | await instalaFichero('elfscript.vsix', elfscriptVsix()); |
| 111 | ok('extensión de lenguaje instalada', await hasta(async () => (await filaInstalada('elffuss-test.elfscript').count()) === 1)); |
| 112 | await p.click('#settings-close'); |
| 113 | await abre('notes.elfs'); |
| 114 | ok('.elfs → lenguaje elfscript (de la extensión)', await hasta(async () => (await lenguaje()) === 'elfscript'), await lenguaje()); |
| 115 | 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)))); |
| 116 | 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(' ')); |
| 117 | ok('gramática: keyword.control con el color exacto del tema', await colorDe('spell', THEME_DARK.control), JSON.stringify(await estilo('spell'))); |
| 118 | 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"')])); |
| 119 | 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')])); |
| 120 | ok('gramática: selector con contexto («source.elfs keyword») que Monarch no sabría aplicar', await colorDe('with', '#123456'), JSON.stringify(await estilo('with'))); |
| 121 | const ambitos = await p.evaluate(() => window.monaco.editor.tokenize('spell x\n# c', 'elfscript').flat().map(t => t.type)); |
| 122 | ok('tokens con los ámbitos de la gramática', ambitos.includes('keyword.control.elfs') && ambitos.includes('comment.line.number-sign.elfs'), ambitos.join(' ')); |
| 123 | await p.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setPosition({ lineNumber: 2, column: 1 }); ed.focus(); ed.trigger('t', 'editor.action.commentLine', {}); }); |
| 124 | ok('configuración del lenguaje: comentar línea usa «#»', (await p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getLineContent(2))).startsWith('# spell')); |
| 125 | // snippet en el lenguaje nuevo |
| 126 | await ponTexto(''); |
| 127 | await p.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setPosition({ lineNumber: 1, column: 1 }); ed.focus(); }); |
| 128 | await p.keyboard.type('elfsp'); |
| 129 | await p.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'editor.action.triggerSuggest', {})); |
| 130 | const visto = await hasta(() => p.evaluate(() => [...document.querySelectorAll('.suggest-widget.visible .monaco-list-row')].some(r => r.textContent.includes('elfspell')))); |
| 131 | ok('snippet sugerido al escribir el prefijo', visto); |
| 132 | await p.keyboard.press('Enter'); |
| 133 | // el \t del snippet sale con la sangría del fichero, como en VS Code |
| 134 | ok('snippet expandido (cuerpo en varias líneas con sus valores)', await hasta(async () => /^spell name\n(\t| +)cast fire\nend$/.test(await p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue()))), JSON.stringify(await p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue()))); |
| 135 | await p.keyboard.press('Escape'); |
| 136 | // snippet de la misma extensión para JavaScript |
| 137 | await abre('app.js'); |
| 138 | await ponTexto(''); |
| 139 | await p.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setPosition({ lineNumber: 1, column: 1 }); ed.focus(); }); |
| 140 | await p.keyboard.type('elflo'); |
| 141 | await p.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'editor.action.triggerSuggest', {})); |
| 142 | await hasta(() => p.evaluate(() => [...document.querySelectorAll('.suggest-widget.visible .monaco-list-row')].some(r => r.textContent.includes('elflog')))); |
| 143 | await p.keyboard.press('Enter'); |
| 144 | ok('snippet en JavaScript (otro lenguaje de la misma extensión)', await hasta(async () => (await p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue())) === "console.log('elf', );"), await p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue())); |
| 145 | await p.keyboard.press('Escape'); |
| 146 | |
| 147 | // ── D. las herramientas code.* del agente siguen trabajando sobre los modelos ── |
| 148 | await abre('notes.elfs'); |
| 149 | await p.evaluate(async () => { const code = await import('/js/tools/code.js'); await code.write({ path: 'notes.elfs', content: 'spell agent\n cast 7\nend\n' }); }); |
| 150 | ok('code.write refresca el modelo abierto', await hasta(async () => (await p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue())) === 'spell agent\n cast 7\nend\n')); |
| 151 | ok('…y la gramática sigue pintándolo', await colorDe('cast', THEME_DARK.control)); |
| 152 | const editado = await p.evaluate(async () => { const code = await import('/js/tools/code.js'); return code.edit({ path: 'notes.elfs', search: 'cast 7', replace: 'cast 8' }); }); |
| 153 | ok('code.edit sobre un fichero de la extensión', await hasta(async () => (await p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue())).includes('cast 8')), String(editado).slice(0, 80)); |
| 154 | ok('code.read devuelve el contenido', /cast 8/.test(await p.evaluate(async () => (await import('/js/tools/code.js')).read({ path: 'notes.elfs' })))); |
| 155 | await p.screenshot({ path: OUT + '/ext-grammar.png' }); |
| 156 | |
| 157 | // ── E. recargar conserva el estado ── |
| 158 | pedidas.length = 0; |
| 159 | await p.reload({ waitUntil: 'domcontentloaded' }); |
| 160 | await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length)); |
| 161 | ok('tras recargar: el host se carga al arrancar (hay extensiones)', await hasta(() => pedidas.some(u => /\/js\/ext\/host\.js/.test(u)))); |
| 162 | ok('tras recargar: el tema sigue', await hasta(async () => (await fondo()) === rgb(THEME_DARK.bg)), await fondo()); |
| 163 | await abre('notes.elfs'); |
| 164 | ok('tras recargar: la gramática sigue', await colorDe('spell', THEME_DARK.control), JSON.stringify(await estilo('spell'))); |
| 165 | await abrePanel(); |
| 166 | ok('tras recargar: las dos extensiones siguen instaladas', (await p.locator(propias('#ext-installed .ext-row')).count()) === 2); |
| 167 | const espejo = sinPrevias(await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions'))); |
| 168 | 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)); |
| 169 | |
| 170 | // ── F. selector de tema: previsualiza, Escape deshace, Enter elige ── |
| 171 | // lo que oye un lector de pantalla: combobox → listbox → opción activa |
| 172 | const combo = () => p.evaluate(() => { |
| 173 | const i = document.querySelector('#ext-themepick input'); |
| 174 | const lista = document.getElementById(i.getAttribute('aria-controls')); |
| 175 | const activa = document.getElementById(i.getAttribute('aria-activedescendant') || '-'); |
| 176 | return { |
| 177 | foco: document.activeElement === i, role: i.getAttribute('role'), expanded: i.getAttribute('aria-expanded'), lista: lista?.getAttribute('role'), |
| 178 | activa: activa && { role: activa.getAttribute('role'), sel: activa.getAttribute('aria-selected'), theme: activa.dataset.theme, marcada: activa.classList.contains('sel') }, |
| 179 | opciones: lista?.querySelectorAll('[role=option]').length, seleccionadas: lista?.querySelectorAll('[aria-selected=true]').length, |
| 180 | grupos: [...(lista?.querySelectorAll('[role=group]') || [])].map(g => g.getAttribute('aria-label')), |
| 181 | }; |
| 182 | }); |
| 183 | await p.click('#ext-theme-btn'); |
| 184 | await p.waitForSelector('#ext-themepick'); |
| 185 | const c0 = await combo(); |
| 186 | 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)); |
| 187 | await p.keyboard.press('ArrowUp'); |
| 188 | const previa = await hasta(async () => (await fondo()) !== rgb(THEME_DARK.bg) && fondo()); |
| 189 | ok('selector: las flechas previsualizan', !!previa, String(previa)); |
| 190 | const c1 = await combo(); |
| 191 | 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])); |
| 192 | await p.keyboard.press('Escape'); |
| 193 | ok('selector: Escape deja el tema que había', await hasta(async () => (await fondo()) === rgb(THEME_DARK.bg))); |
| 194 | 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)); |
| 195 | await p.click('#ext-theme-btn'); |
| 196 | await p.waitForSelector('#ext-themepick'); |
| 197 | await p.click('#ext-themepick .tp-item[data-theme="vs"]'); |
| 198 | ok('selector: tema claro de serie elegido', await hasta(async () => (await fondo()) === 'rgb(255, 255, 254)'), await fondo()); |
| 199 | ok('…y la gramática se repinta con colores de Light+', await colorDe('spell', '#AF00DB'), JSON.stringify(await estilo('spell'))); |
| 200 | // El selector cuelga de <body>, fuera de la caja del panel: el «clic fuera |
| 201 | // cierra Ajustes» tomaba cualquier clic en él por uno de fuera y cerraba el panel |
| 202 | // de debajo; el foco acababa en el editor (o en <body> en el móvil). |
| 203 | const trasElegir = () => p.evaluate(() => ({ panel: !document.getElementById('settings-panel').hidden && !!document.getElementById('ext-panel')?.isConnected, foco: document.activeElement?.id || document.activeElement?.className })); |
| 204 | ok('selector: elegir con el ratón deja el panel abierto y el foco vuelve a su botón', await hasta(async () => { const e = await trasElegir(); return e.panel && e.foco === 'ext-theme-btn'; }), JSON.stringify(await trasElegir())); |
| 205 | await p.click('#ext-theme-btn'); |
| 206 | await p.waitForSelector('#ext-themepick'); |
| 207 | await p.click('#ext-themepick input'); |
| 208 | await sleep(200); |
| 209 | ok('selector: pinchar en su buscador tampoco cierra el panel', await p.evaluate(() => !document.getElementById('settings-panel').hidden && !!document.getElementById('ext-themepick'))); |
| 210 | await p.keyboard.press('Escape'); |
| 211 | await hasta(() => p.evaluate(() => !document.getElementById('ext-themepick'))); |
| 212 | // el ● de «sin guardar» con un tema claro (era casi blanco sobre blanco, y es |
| 213 | // el único aviso: cerrar la pestaña no pregunta) |
| 214 | await abre('app.js'); |
| 215 | await p.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); ed.trigger('t', 'type', { text: ' ' }); }); |
| 216 | const punto = await hasta(() => p.evaluate(() => { |
| 217 | const tab = document.querySelector('#tabs-bar .tab.active'), dot = tab?.querySelector('.tab-x.dirty'); |
| 218 | if (!dot) return null; |
| 219 | const num = c => c.match(/[\d.]+/g).map(Number); |
| 220 | const [r, g, b, a = 1] = num(getComputedStyle(dot).color), fondo = num(getComputedStyle(tab).backgroundColor); |
| 221 | 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; }; |
| 222 | const l1 = L([r, g, b].map((v, k) => v * a + fondo[k] * (1 - a))), l2 = L(fondo.slice(0, 3)); |
| 223 | 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 }; |
| 224 | })); |
| 225 | 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)); |
| 226 | await p.reload({ waitUntil: 'domcontentloaded' }); |
| 227 | await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length)); |
| 228 | ok('el tema elegido sobrevive a la recarga', await hasta(async () => (await fondo()) === 'rgb(255, 255, 254)'), await fondo()); |
| 229 | // por la paleta de comandos |
| 230 | await abre('app.js'); |
| 231 | await p.keyboard.press(process.platform === 'darwin' ? 'Meta+Shift+P' : 'Control+Shift+P'); |
| 232 | await p.fill('#pal-input', '>tema de color'); |
| 233 | let filas = await p.locator('#pal-list .pal-item').count(); |
| 234 | if (!filas) { await p.fill('#pal-input', '>color theme'); filas = await p.locator('#pal-list .pal-item').count(); } |
| 235 | ok('comando «Tema de color…» en la paleta', filas === 1); |
| 236 | await p.keyboard.press('Enter'); |
| 237 | await p.waitForSelector('#ext-themepick'); |
| 238 | await p.click(`#ext-themepick .tp-item[data-theme^="x-elffuss-test-elf-theme-elf-dark"]`); |
| 239 | ok('tema de la extensión elegido desde la paleta', await hasta(async () => (await fondo()) === rgb(THEME_DARK.bg))); |
| 240 | 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)); |
| 241 | |
| 242 | // ── G. ?noext: todo en pausa ── |
| 243 | await p.goto(BASE + '/?test-opfs&noext', { waitUntil: 'domcontentloaded' }); |
| 244 | await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length)); |
| 245 | await sleep(600); |
| 246 | ok('?noext: se arranca sin aplicar extensiones', (await fondo()) === 'rgb(30, 30, 30)', await fondo()); |
| 247 | await abre('notes.elfs'); |
| 248 | ok('?noext: el .elfs queda en texto plano', (await lenguaje()) === 'plaintext'); |
| 249 | await abrePanel(); |
| 250 | ok('?noext: el panel lo avisa', await p.locator('.ext-paused').count() === 1); |
| 251 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 252 | await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length)); |
| 253 | |
| 254 | // ── H. desactivar y desinstalar lo deshacen todo ── |
| 255 | await abre('notes.elfs'); |
| 256 | await colorDe('spell', THEME_DARK.control); |
| 257 | await abrePanel(); |
| 258 | await filaInstalada('elffuss-test.elf-theme').locator('.ext-toggle').click(); |
| 259 | ok('desactivar el tema → vuelve el oscuro de serie y las pestañas de siempre', await hasta(async () => (await fondo()) === 'rgb(30, 30, 30)' && !(await p.evaluate(() => document.getElementById('ext-theme-chrome')?.textContent))), await fondo()); |
| 260 | ok('…y la gramática se repinta con Dark+', await colorDe('spell', '#C586C0'), JSON.stringify(await estilo('spell'))); |
| 261 | await filaInstalada('elffuss-test.elfscript').locator('.ext-toggle').click(); |
| 262 | ok('desactivar el lenguaje → el .elfs vuelve a texto plano', await hasta(async () => (await lenguaje()) === 'plaintext'), await lenguaje()); |
| 263 | await p.click('#settings-close'); |
| 264 | await abre('app.js'); |
| 265 | await ponTexto(''); |
| 266 | await p.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setPosition({ lineNumber: 1, column: 1 }); ed.focus(); }); |
| 267 | await p.keyboard.type('elflo'); |
| 268 | await p.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'editor.action.triggerSuggest', {})); |
| 269 | await sleep(1200); |
| 270 | ok('…y sus snippets ya no se ofrecen', !(await p.evaluate(() => [...document.querySelectorAll('.suggest-widget.visible .monaco-list-row')].some(r => r.textContent.includes('elflog'))))); |
| 271 | await p.keyboard.press('Escape'); |
| 272 | await abrePanel(); |
| 273 | await filaInstalada('elffuss-test.elfscript').locator('.ext-toggle').click(); |
| 274 | await abre('notes.elfs'); |
| 275 | ok('reactivar el lenguaje lo devuelve', await hasta(async () => (await lenguaje()) === 'elfscript') && await colorDe('spell', '#C586C0')); |
| 276 | p.once('dialog', d => d.accept()); |
| 277 | await filaInstalada('elffuss-test.elfscript').locator('.ext-uninstall').click(); |
| 278 | ok('desinstalar el lenguaje', await hasta(async () => (await filaInstalada('elffuss-test.elfscript').count()) === 0 && (await lenguaje()) === 'plaintext')); |
| 279 | p.once('dialog', d => d.accept()); |
| 280 | await filaInstalada('elffuss-test.elf-theme').locator('.ext-uninstall').click(); |
| 281 | ok('desinstalar el tema', await hasta(async () => (await p.locator(propias('#ext-installed .ext-row')).count()) === 0)); |
| 282 | const restos = await p.evaluate(previas => new Promise(res => { |
| 283 | const r = indexedDB.open('elffuss-code-ext'); |
| 284 | r.onsuccess = () => { const q = r.result.transaction('files').objectStore('files').getAllKeys(); q.onsuccess = () => { res(q.result.filter(k => !previas.some(id => String(k).startsWith(id + '@'))).length); r.result.close(); }; }; |
| 285 | r.onerror = () => res(-1); |
| 286 | }), PREVIAS); |
| 287 | ok('sin restos en IndexedDB tras desinstalar', restos === 0, String(restos)); |
| 288 | ok('kv «extensions» vacía', JSON.stringify(sinPrevias(await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions')))) === '[]'); |
| 289 | |
| 290 | // ── J. paquetes hostiles o rotos, mensajes, teclado y lector de pantalla ── |
| 291 | 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') }; }); |
| 292 | // J1. cerrar el panel: la X tiene nombre, Escape lo cierra y el foco vuelve |
| 293 | await p.click('#settings-close'); |
| 294 | await abrePanel(); |
| 295 | ok('panel: la X de cerrar tiene nombre («Close»), no solo «✕»', (await p.getAttribute('#settings-close', 'aria-label')) === 'Close'); |
| 296 | await p.focus('#ext-q'); |
| 297 | await p.keyboard.press('Escape'); |
| 298 | 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())); |
| 299 | // J1b. Es un diálogo con nombre, se haya abierto Ajustes antes o no. La caja es |
| 300 | // la de Ajustes, y Ajustes le deja aria-labelledby a SU título, que aquí no |
| 301 | // existe: el panel era un diálogo sin nombre (o, sin pasar por Ajustes, ni |
| 302 | // siquiera un diálogo). |
| 303 | const dialogo = async () => ({ |
| 304 | ...(await p.evaluate(() => { const box = document.getElementById('settings-panel'); const lb = box.getAttribute('aria-labelledby'); return { role: box.getAttribute('role'), nombre: lb ? (document.getElementById(lb)?.textContent ?? 'NO EXISTE') : null }; })), |
| 305 | arbol: (await p.locator('#settings-panel').ariaSnapshot()).split('\n')[0], |
| 306 | }); |
| 307 | await abrePanel(); |
| 308 | let d = await dialogo(); |
| 309 | ok('panel: un diálogo que se llama «Extensions…»', d.role === 'dialog' && /^Extensions\b/.test(d.nombre || '') && /^- dialog "Extensions/.test(d.arbol), JSON.stringify(d)); |
| 310 | await p.click('#settings-close'); |
| 311 | await p.click('#btn-settings'); |
| 312 | await p.waitForSelector('#settings-title'); |
| 313 | await p.keyboard.press('Escape'); |
| 314 | await abrePanel(); |
| 315 | d = await dialogo(); |
| 316 | ok('…también después de abrir y cerrar Ajustes (antes: un diálogo sin nombre)', d.role === 'dialog' && /^Extensions\b/.test(d.nombre || '') && /^- dialog "Extensions/.test(d.arbol), JSON.stringify(d)); |
| 317 | // J1c. Escape con el foco fuera de los controles del panel (tras pinchar en su |
| 318 | // texto, el foco está en <body>): lo cierra el Escape general de la página, y el |
| 319 | // foco también vuelve a quien lo abrió (antes se quedaba en <body>). |
| 320 | await p.click('#ext-panel .ext-intro'); |
| 321 | await p.keyboard.press('Escape'); |
| 322 | ok('panel: Escape con el foco en <body> 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())); |
| 323 | |
| 324 | // J2. errores en el idioma de la interfaz, como alerta |
| 325 | await abrePanel(); |
| 326 | const msgNoPub = await instalaFichero('nopub.vsix', noPublisherVsix()); |
| 327 | 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); |
| 328 | ok('…y se anuncia como alerta (role=alert)', (await p.getAttribute('#ext-msg', 'role')) === 'alert'); |
| 329 | |
| 330 | // J3. lo que no se pudo leer se dice, en la fila y al instalar |
| 331 | const msgMedio = await instalaFichero('half.vsix', brokenThemeVsix()); |
| 332 | ok('instalada, y el mensaje avisa de lo que no se pudo usar', msgMedio === '“Half Broken” installed. Theme “Good One” applied. 1 part could not be used.', msgMedio); |
| 333 | ok('…anunciado (role=status)', (await p.getAttribute('#ext-msg', 'role')) === 'status'); |
| 334 | const filaMedio = filaInstalada('elffuss-test.half-broken'); |
| 335 | ok('la fila: «Active theme: “Good One”» y el aviso plegado', /Active theme: “Good One”/.test(await filaMedio.innerText()) && (await filaMedio.locator('details.ext-warn summary').innerText()) === '1 part could not be used', (await filaMedio.innerText()).replace(/\s+/g, ' ')); |
| 336 | await filaMedio.locator('details.ext-warn summary').focus(); |
| 337 | await p.keyboard.press('Enter'); |
| 338 | 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 })); |
| 339 | 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)); |
| 340 | const msgRoto = await instalaFichero('broken.vsix', brokenThemeVsix({ onlyBroken: true })); |
| 341 | 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); |
| 342 | |
| 343 | // J4. lo que no se aplica no se cuenta como aplicado |
| 344 | await instalaFichero('json.vsix', jsonGrammarVsix()); |
| 345 | const textoJson = (await filaInstalada('elffuss-test.json-x').innerText()).replace(/\s+/g, ' '); |
| 346 | ok('gramática y configuración de JSON: «nada aplicable» y que Code mantiene su resaltado de JSON', textoJson.includes('Nothing in this extension can be applied here.') && textoJson.includes('Code already highlights JSON its own way and keeps it.') && !/Monaco|\b1 (grammar|language)\b/.test(textoJson), textoJson); |
| 347 | |
| 348 | // J5. el foco no se pierde al repintar la lista de instaladas |
| 349 | await filaMedio.locator('.ext-theme-chips .ext-chip').first().focus(); |
| 350 | await p.keyboard.press('Enter'); |
| 351 | 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())); |
| 352 | await filaMedio.locator('.ext-toggle').focus(); |
| 353 | await p.keyboard.press('Enter'); |
| 354 | 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())); |
| 355 | await p.keyboard.press('Enter'); |
| 356 | ok('…y el aviso que estaba desplegado sigue desplegado tras repintar', await filaMedio.locator('details.ext-warn').evaluate(d => d.open)); |
| 357 | 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())); |
| 358 | await filaMedio.locator('.ext-theme-chips .ext-chip').first().click(); // al desactivar se quitó su tema |
| 359 | p.once('dialog', d => d.accept()); |
| 360 | await filaInstalada('elffuss-test.json-x').locator('.ext-uninstall').focus(); |
| 361 | await p.keyboard.press('Enter'); |
| 362 | 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())); |
| 363 | |
| 364 | // J6. búsqueda (Open VSX simulado): detalle con teclado, nombres accesibles, |
| 365 | // estado anunciado, y las fichas de tema no pierden su «on» |
| 366 | const FALSA = { namespace: 'elffuss-test', name: 'fake', version: '1.0.0', displayName: 'Fake JSON', description: 'Grammar for JSON', downloadCount: 5, files: {} }; |
| 367 | await ctx.route('https://open-vsx.org/api/**', route => { |
| 368 | const u = new URL(route.request().url()); |
| 369 | const json = (cuerpo, status = 200) => route.fulfill({ status, headers: { 'access-control-allow-origin': '*', 'content-type': 'application/json' }, body: JSON.stringify(cuerpo) }); |
| 370 | if (u.pathname === '/api/-/search') return json({ totalSize: 1, offset: 0, extensions: [FALSA] }); |
| 371 | 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' } }); |
| 372 | 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' }] } }); |
| 373 | return json({ error: 'not found' }, 404); |
| 374 | }); |
| 375 | await p.fill('#ext-q', 'fake'); |
| 376 | await p.press('#ext-q', 'Enter'); |
| 377 | const filaFalsa = p.locator('#ext-results .ext-row[data-id="elffuss-test.fake"]'); |
| 378 | // con «Solo las que funcionan en Code» (encendido de serie) no se ve: no aplica nada |
| 379 | ok('búsqueda con el filtro: la que no hace nada queda oculta y se dice («1 hidden»)', await hasta(async () => (await filaFalsa.count()) === 1 && !(await filaFalsa.isVisible()) && (await p.textContent('#ext-status')) === '1 result · 1 hidden because it does not work in Code'), await p.textContent('#ext-status')); |
| 380 | await p.uncheck('#ext-only-works'); |
| 381 | ok('búsqueda: el resultado llega y se anuncia («1 result»)', await hasta(async () => (await filaFalsa.isVisible()) && (await p.textContent('#ext-status')) === '1 result'), await p.textContent('#ext-status')); |
| 382 | ok('el botón dice que no hay nada que aplicar, con nombre propio para el lector', await hasta(async () => (await filaFalsa.locator('.ext-install').getAttribute('aria-label')) === 'Nothing to apply: Fake JSON'), await filaFalsa.locator('.ext-install').getAttribute('aria-label')); |
| 383 | await filaFalsa.locator('.ext-install').focus(); |
| 384 | await p.keyboard.press('Shift+Tab'); |
| 385 | const nombreBtn = await activo(); |
| 386 | 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)); |
| 387 | await p.keyboard.press('Enter'); |
| 388 | 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 && /Licence/.test(d.textContent) && d.textContent; })); |
| 389 | const veredictoFalsa = await filaFalsa.locator('.ext-verdict').innerText().catch(() => ''); |
| 390 | ok('Enter: el detalle se despliega (aria-expanded) y la fila dice qué aplicaría, también lo de JSON', !!detalleAbierto && /Nothing in this extension/.test(veredictoFalsa) && /Code already highlights JSON/.test(veredictoFalsa), String(detalleAbierto) + ' | ' + veredictoFalsa); |
| 391 | // (isDisabled() de Playwright cuenta aria-disabled como deshabilitado: aquí se |
| 392 | // mira la propiedad del DOM, que es la que le quitaría el foco) |
| 393 | const inst = await filaFalsa.locator('.ext-install').evaluate(b => { b.focus(); return { aria: b.getAttribute('aria-disabled'), disabled: b.disabled, foco: document.activeElement === b }; }); |
| 394 | 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)); |
| 395 | const fichaTema = filaMedio.locator('.ext-theme-chips .ext-chip').first(); |
| 396 | await hasta(async () => (await fichaTema.getAttribute('aria-pressed')) === 'true'); |
| 397 | await p.click('#ext-panel .ext-search .ext-chip[data-cat="Themes"]'); |
| 398 | await hasta(async () => (await p.getAttribute('#ext-panel .ext-search .ext-chip[data-cat="Themes"]', 'aria-pressed')) === 'true'); |
| 399 | await hasta(async () => (await filaFalsa.count()) === 1); |
| 400 | 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')); |
| 401 | await p.click('#ext-panel .ext-search .ext-chip[data-cat="Themes"]'); // fuera la categoría (la búsqueda en vivo va sin ella) |
| 402 | await hasta(async () => (await p.getAttribute('#ext-panel .ext-search .ext-chip[data-cat="Themes"]', 'aria-pressed')) === 'false'); |
| 403 | await ctx.unroute('https://open-vsx.org/api/**'); |
| 404 | |
| 405 | // J7. gramática hostil: Object.prototype intacto, y las demás gramáticas bien |
| 406 | await instalaFichero('elfscript.vsix', elfscriptVsix()); |
| 407 | const msgEvil = await instalaFichero('evil.vsix', hostileGrammarVsix()); |
| 408 | ok('gramática hostil instalada (avisa del scopeName «__proto__» rechazado)', msgEvil === '“Evil Grammar” installed. 1 part could not be used.', msgEvil); |
| 409 | await p.click('#settings-close'); |
| 410 | 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; })() })); |
| 411 | const INTACTO = '{"proto":null,"propia":false,"object":null,"toStr":null,"enumerables":[]}'; |
| 412 | await abre('a.evil'); |
| 413 | ok('a.evil → evilscript', await hasta(async () => (await lenguaje()) === EVIL.lang), await lenguaje()); |
| 414 | const tiposEvil = () => p.evaluate(() => window.monaco.editor.tokenize('evil ctor (x)', 'evilscript')[0].map(t => t.type)); |
| 415 | 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())); |
| 416 | ok('tras abrirlo: Object.prototype intacto ({}.id undefined, nada enumerable)', (await prototipo()) === INTACTO, await prototipo()); |
| 417 | await abre('notes.elfs'); |
| 418 | 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'))); |
| 419 | // el tema con un ámbito «hasOwnProperty» ya no tumba el motor |
| 420 | await abrePanel(); |
| 421 | await filaInstalada('elffuss-test.evil').locator('.ext-theme-chips .ext-chip').first().click(); |
| 422 | await p.click('#settings-close'); |
| 423 | await abre('a.evil'); |
| 424 | 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')])); |
| 425 | // lo guardado ANTES de sanear al instalar: se sanea también al cargar |
| 426 | await p.evaluate(async raw => { |
| 427 | const db = await new Promise((res, rej) => { const r = indexedDB.open('elffuss-code-ext'); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); }); |
| 428 | const rec = await new Promise(res => { const q = db.transaction('ext').objectStore('ext').get('elffuss-test.evil'); q.onsuccess = () => res(q.result); }); |
| 429 | const key = rec.grammars.find(g => g.scopeName === 'source.evil').key; |
| 430 | 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); }); |
| 431 | db.close(); |
| 432 | }, EVIL_GRAMMAR); |
| 433 | await p.reload({ waitUntil: 'domcontentloaded' }); |
| 434 | await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length)); |
| 435 | await abre('a.evil'); |
| 436 | 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()); |
| 437 | |
| 438 | // J8. snippets: el detalle no pide nada a ningún servidor |
| 439 | const BALIZA = 'http://127.0.0.1:8993'; // nadie escucha: basta con ver si el navegador lo pide |
| 440 | await abrePanel(); |
| 441 | await instalaFichero('beacon.vsix', beaconSnippetVsix(BALIZA)); |
| 442 | await p.click('#settings-close'); |
| 443 | await abre('app.js'); |
| 444 | await ponTexto(''); |
| 445 | pedidas.length = 0; |
| 446 | await p.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setPosition({ lineNumber: 1, column: 1 }); ed.focus(); }); |
| 447 | await p.keyboard.type('zzbea'); |
| 448 | await p.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'editor.action.triggerSuggest', {})); |
| 449 | await hasta(() => p.evaluate(() => [...document.querySelectorAll('.suggest-widget.visible .monaco-list-row')].some(r => r.textContent.includes('zzbeacon')))); |
| 450 | 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; }); |
| 451 | if (!(await hasta(detalleSnip, { tiempo: 2000 }))) await p.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'toggleSuggestionDetails', {})); |
| 452 | const snip = await hasta(detalleSnip); |
| 453 | ok('snippet: el detalle enseña descripción y cuerpo como texto', !!snip && snip.texto.includes(``) && snip.texto.includes('```'), JSON.stringify(snip)); |
| 454 | ok('…sin imágenes ni enlaces', !!snip && snip.imgs === 0 && snip.enlaces === 0, JSON.stringify(snip && { imgs: snip.imgs, enlaces: snip.enlaces })); |
| 455 | await sleep(600); |
| 456 | 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(' ')); |
| 457 | await p.keyboard.press('Escape'); |
| 458 | |
| 459 | // J9. expresiones que no terminan: la pestaña sigue viva |
| 460 | await abrePanel(); |
| 461 | await instalaFichero('slow.vsix', slowRegexVsix()); |
| 462 | const filaSlow = filaInstalada('elffuss-test.slow'); |
| 463 | await filaSlow.locator('details.ext-warn summary').click(); |
| 464 | const avisosSlow = await filaSlow.locator('details.ext-warn').innerText(); |
| 465 | 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, ' ')); |
| 466 | await p.click('#settings-close'); |
| 467 | const abierto = await Promise.race([abre('slow-input').then(() => 'ok'), sleep(20000).then(() => 'COLGADO')]); |
| 468 | const vivo = abierto === 'ok' && await Promise.race([p.evaluate(() => 1), sleep(5000).then(() => 0)]) === 1; |
| 469 | ok('firstLine que no termina (^(.|\\s)*z con 64 espacios): el fichero se abre y la pestaña responde', vivo, abierto); |
| 470 | if (!vivo) { console.log('\n❌ la página se quedó colgada: no se puede seguir'); await b.close(); process.exit(1); } |
| 471 | ok('…como texto plano', (await lenguaje()) === 'plaintext', await lenguaje()); |
| 472 | await abre('runme'); |
| 473 | ok('…y las otras firstLine siguen funcionando (#!/usr/bin/env elfs → elfscript)', await hasta(async () => (await lenguaje()) === 'elfscript'), await lenguaje()); |
| 474 | |
| 475 | // J10. menús: View en escritorio y «/» en pantalla estrecha |
| 476 | await p.click('#menubar button[data-menu="view"]'); |
| 477 | const menuView = await p.locator('#topmenu .menu-item b').allInnerTexts(); |
| 478 | ok('menú View: «Extensions…» y «Color Theme…»', menuView.includes('Extensions…') && menuView.includes('Color Theme…'), menuView.join(' | ')); |
| 479 | await p.locator('#topmenu .menu-item', { hasText: 'Extensions…' }).click(); |
| 480 | ok('…y «Extensions…» abre el panel', await hasta(() => p.evaluate(() => !!document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden))); |
| 481 | await p.click('#settings-close'); |
| 482 | const tamaño = p.viewportSize(); |
| 483 | await p.setViewportSize({ width: 700, height: 800 }); |
| 484 | 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)); |
| 485 | await p.click('#btn-slash'); |
| 486 | const menuSlash = await p.locator('#menu .menu-item b').allInnerTexts(); |
| 487 | ok('…pero el menú «/» del chat trae /extensions y /theme', menuSlash.includes('/extensions') && menuSlash.includes('/theme'), menuSlash.join(' ')); |
| 488 | await p.locator('#menu .menu-item', { hasText: '/extensions' }).click(); |
| 489 | ok('…y /extensions abre el panel', await hasta(() => p.evaluate(() => !!document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden))); |
| 490 | await p.keyboard.press('Escape'); |
| 491 | await p.setViewportSize(tamaño); |
| 492 | |
| 493 | // J11. fuera todo lo de esta sección |
| 494 | await p.evaluate(async previas => { const host = await (await import('/js/ide.js')).loadExt(); for (const e of host.list()) if (!previas.includes(e.id)) await host.uninstall(e.id); await host.setTheme('vs-dark'); }, PREVIAS); |
| 495 | await abrePanel(); |
| 496 | ok('J: todo desinstalado', (await p.locator(propias('#ext-installed .ext-row')).count()) === 0); |
| 497 | |
| 498 | // ── I. EN VIVO contra Open VSX ── |
| 499 | const red = await p.evaluate(async () => { try { return (await fetch('https://open-vsx.org/api/vscode/theme-monokai', { credentials: 'omit' })).ok; } catch { return false; } }); |
| 500 | if (!red) { |
| 501 | notRun('instalación en vivo desde Open VSX', 'sin acceso a open-vsx.org'); |
| 502 | } else { |
| 503 | await p.fill('#ext-q', 'monokai'); |
| 504 | const fila = p.locator('#ext-results .ext-row[data-id="vscode.theme-monokai"]'); |
| 505 | ok('Open VSX: búsqueda con resultados', await hasta(async () => (await fila.count()) === 1, { tiempo: 20000 })); |
| 506 | await fila.locator('.ext-main').click(); |
| 507 | ok('Open VSX: la fila dice qué aplicaría (sin bajar el .vsix), sin claves %sin traducir%', await hasta(async () => (t => /^Works in Code: adds a colour theme\.$/.test(t) && !/%\w+%/.test(t))(await fila.locator('.ext-verdict').innerText()), { tiempo: 20000 }), await fila.locator('.ext-verdict').innerText().catch(() => '')); |
| 508 | await fila.locator('.ext-install').click(); |
| 509 | ok('Open VSX: vscode.theme-monokai instalada (SHA-256 comprobada)', await hasta(async () => (await filaInstalada('vscode.theme-monokai').count()) === 1, { tiempo: 30000 }) && /SHA-256/.test(await filaInstalada('vscode.theme-monokai').innerText())); |
| 510 | await filaInstalada('vscode.theme-monokai').locator('.ext-theme-chips .ext-chip').first().click(); |
| 511 | ok('Monokai aplicado', await hasta(async () => (await fondo()) === 'rgb(39, 40, 34)'), await fondo()); |
| 512 | const r = await p.evaluate(async () => { |
| 513 | const host = await (await import('/js/ide.js')).loadExt(); |
| 514 | try { const rec = await host.install({ namespace: 'vscode', name: 'make', version: '1.95.3' }); return rec.id; } catch (e) { return 'ERR ' + e.message; } |
| 515 | }); |
| 516 | ok('Open VSX: vscode.make instalada', r === 'vscode.make', r); |
| 517 | await p.click('#settings-close').catch(() => {}); |
| 518 | await abre('Makefile'); |
| 519 | ok('Makefile → lenguaje makefile', await hasta(async () => (await lenguaje()) === 'makefile'), await lenguaje()); |
| 520 | const tipos = await p.evaluate(() => window.monaco.editor.tokenize('all: build\n# c', 'makefile').flat().map(t => t.type)); |
| 521 | ok('Makefile: ámbitos de la gramática real', tipos.some(t => /entity\.name\.function\.target\.makefile/.test(t)) && tipos.some(t => /comment/.test(t)), tipos.join(' ')); |
| 522 | ok('Makefile: el objetivo con el color de función de Monokai', await colorDe('all', '#A6E22E'), JSON.stringify(await estilo('all'))); |
| 523 | await p.screenshot({ path: OUT + '/ext-monokai-make.png' }); |
| 524 | // una gramática para un lenguaje que Monaco YA tiene (JavaScript): la |
| 525 | // sustituye, y al desactivarla vuelve el coloreado de serie (Monarch) |
| 526 | const js = await p.evaluate(async () => { |
| 527 | const host = await (await import('/js/ide.js')).loadExt(); |
| 528 | try { await host.install({ namespace: 'vscode', name: 'javascript', version: '1.95.3' }); return 'ok'; } catch (e) { return 'ERR ' + e.message; } |
| 529 | }); |
| 530 | ok('Open VSX: vscode.javascript instalada', js === 'ok', js); |
| 531 | await abre('app.js'); |
| 532 | await ponTexto('const a = 1; // x\n'); |
| 533 | ok('JS con la gramática TextMate de VS Code (storage.type.js)', await hasta(async () => (await p.evaluate(() => window.monaco.editor.tokenize('const a = 1;', 'javascript')[0].map(t => t.type))).includes('storage.type.js'))); |
| 534 | await p.evaluate(async () => { const host = await (await import('/js/ide.js')).loadExt(); await host.setEnabled('vscode.javascript', false); }); |
| 535 | ok('desactivarla devuelve el Monarch de serie de Monaco (keyword.js)', await hasta(async () => (await p.evaluate(() => window.monaco.editor.tokenize('const a = 1;', 'javascript')[0].map(t => t.type))).includes('keyword.js'))); |
| 536 | ok('…y el fichero abierto se repinta con Monokai vía Monarch', await colorDe('const', '#F92672'), JSON.stringify(await estilo('const'))); |
| 537 | } |
| 538 | |
| 539 | ok('sin errores de página', !errores.length, errores.slice(0, 3).join(' | ')); |
| 540 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ EXTENSIONES DE VS CODE (nivel 1) OK'); |
| 541 | await b.close(); |
| 542 | process.exit(fails ? 1 : 0); |