| 1 | // Extensions panel: the "Popular" list and the "Only ones that work in Code" |
| 2 | // filter on search results. |
| 3 | // |
| 4 | // CENSUS=<extensions.tsv> BASE=http://127.0.0.1:8999 node tests/ext_popular.mjs |
| 5 | // |
| 6 | // 1. (no browser) web/js/ext/popular.json against the static census of Open |
| 7 | // VSX (tests/catalog_census.mjs writes it; CENSUS= points to another copy): |
| 8 | // no entry has code of its own, every one gets the panel's "works" verdict, |
| 9 | // no built-in language pack, ordered by downloads, three kinds in the top 10. |
| 10 | // 2. (browser, Open VSX mocked) Popular shows on opening with no request to |
| 11 | // Open VSX; a search hides what does nothing, says how many, fetches more |
| 12 | // pages to fill the view, and "show" / the checkbox bring them back. |
| 13 | // 3. LIVE: installs a few entries of the real list from Open VSX. Without |
| 14 | // network it is NOT RUN and does not count as a failure. |
| 15 | import fs from 'node:fs'; |
| 16 | import path from 'node:path'; |
| 17 | import { fileURLToPath } from 'node:url'; |
| 18 | import { chromium } from 'playwright'; |
| 19 | import { describe, factsFromManifest, works } from '../web/js/ext/verdict.js'; |
| 20 | |
| 21 | const HERE = path.dirname(fileURLToPath(import.meta.url)); |
| 22 | const BASE = process.env.BASE || 'http://localhost:8999'; |
| 23 | const OUT = process.env.SCRATCH || '/tmp/elffuss-test'; |
| 24 | fs.mkdirSync(OUT, { recursive: true }); |
| 25 | let fails = 0; |
| 26 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 27 | const notRun = (n, e) => console.log('⏭️ NOT RUN ' + n + (e ? ' — ' + e : '')); |
| 28 | const sleep = ms => new Promise(r => setTimeout(r, ms)); |
| 29 | async function hasta(fn, { tiempo = 12000, cada = 150 } = {}) { |
| 30 | const fin = Date.now() + tiempo; |
| 31 | let v; |
| 32 | while (Date.now() < fin) { try { v = await fn(); if (v) return v; } catch { /* retry */ } await sleep(cada); } |
| 33 | return v; |
| 34 | } |
| 35 | const NOMBRE_VETADO = /Claude[-_ ]?Code/i; |
| 36 | |
| 37 | // ── 1. the list itself ── |
| 38 | const POP = JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext/popular.json'), 'utf8')); |
| 39 | const items = POP.items; |
| 40 | { |
| 41 | ok(`popular.json: between 30 and 40 entries (${items.length})`, items.length >= 30 && items.length <= 40); |
| 42 | const CENSUS = process.env.CENSUS || path.join(HERE, 'catalog-census/extensions.tsv'); |
| 43 | if (!fs.existsSync(CENSUS)) ok('census found (CENSUS=<extensions.tsv>)', false, CENSUS + ' does not exist: this check cannot run without it'); |
| 44 | else { |
| 45 | const [head, ...lines] = fs.readFileSync(CENSUS, 'utf8').trim().split('\n'); |
| 46 | const cols = head.split('\t'); |
| 47 | const census = new Map(lines.map(l => { const r = Object.fromEntries(l.split('\t').map((v, i) => [cols[i], v])); return [r.id.toLowerCase(), r]; })); |
| 48 | ok(`census read (${census.size} extensions)`, census.size > 10000); |
| 49 | const fuera = items.filter(p => !census.has(p.id.toLowerCase())); |
| 50 | ok('every entry is in the census', !fuera.length, fuera.map(p => p.id).join(' ')); |
| 51 | const conCodigo = items.filter(p => census.get(p.id.toLowerCase())?.runtime !== 'none'); |
| 52 | ok('no entry needs Node, or any code of its own (census runtime=none)', !conCodigo.length, conCodigo.map(p => `${p.id}=${census.get(p.id.toLowerCase())?.runtime}`).join(' ')); |
| 53 | const noFunciona = items.filter(p => census.get(p.id.toLowerCase())?.works !== '1' || census.get(p.id.toLowerCase())?.declarative !== '1'); |
| 54 | ok('every entry works in Code by the census (works=1, declarative=1)', !noFunciona.length, noFunciona.map(p => p.id).join(' ')); |
| 55 | const orden = items.map(p => Number(census.get(p.id.toLowerCase())?.rank)); |
| 56 | ok('ordered by downloads (census rank ascending)', orden.every((r, i) => i === 0 || r > orden[i - 1]), orden.join(',')); |
| 57 | } |
| 58 | ok('no built-in vscode.* language pack', !items.some(p => /^vscode\./i.test(p.id))); |
| 59 | // (every language exists here: which ones Monaco has is the generator's job, |
| 60 | // checked against Monaco's own bundle when the list is built) |
| 61 | const host = { builtinLanguage: () => false, grammarSkippedFor: () => false, languageName: id => id, languageExtensions: () => [] }; |
| 62 | const malas = items.filter(p => p.analysis.hasCode || !works(describe(factsFromManifest(host, p.analysis))) || describe(factsFromManifest(host, p.analysis)).kind !== 'full'); |
| 63 | ok('the panel\'s own verdict on each stored analysis: «Works in Code», no code', !malas.length, malas.map(p => p.id).join(' ')); |
| 64 | const top = new Set(items.slice(0, 10).map(p => p.kind)); |
| 65 | ok('the top 10 mixes themes, languages and snippets', top.has('theme') && top.has('language') && top.has('snippets'), [...top].join(',')); |
| 66 | ok('each entry: id, name, kind and a one-line description in es and en', items.every(p => p.id && p.displayName && ['theme', 'language', 'snippets'].includes(p.kind) && p.description?.es?.trim() && p.description?.en?.trim() && !/\n/.test(p.description.es + p.description.en))); |
| 67 | const texto = fs.readFileSync(path.join(HERE, '../web/js/ext/popular.json'), 'utf8') + fs.readFileSync(path.join(HERE, '../web/js/ext/i18n.js'), 'utf8'); |
| 68 | ok('the list and the panel strings never name that other product', !NOMBRE_VETADO.test(texto)); |
| 69 | } |
| 70 | |
| 71 | // ── 2. the panel, Open VSX mocked ── |
| 72 | const b = await chromium.launch(); |
| 73 | async function nuevaPagina(locale, viewport = { width: 1280, height: 860 }) { |
| 74 | const ctx = await b.newContext({ locale, viewport }); |
| 75 | await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); |
| 76 | const p = await ctx.newPage(); |
| 77 | p.errores = []; |
| 78 | p.on('pageerror', e => { if (e.message !== 'Canceled') p.errores.push(e.message); }); |
| 79 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 80 | await p.evaluate(async () => { |
| 81 | const o = await navigator.storage.getDirectory(); |
| 82 | for await (const k of o.keys()) await o.removeEntry(k, { recursive: true }).catch(() => {}); |
| 83 | 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(); }; |
| 84 | await w('app.js', '// app\nconst a = 1;\n'); |
| 85 | await w('.env', 'API_KEY=abc # secret\n'); |
| 86 | }); |
| 87 | await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); |
| 88 | await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length), { tiempo: 30000 }); |
| 89 | return { ctx, p }; |
| 90 | } |
| 91 | const abrePanel = async p => { |
| 92 | if (await p.locator('#ext-panel').isVisible().catch(() => false)) return; |
| 93 | await p.evaluate(() => document.getElementById('act-ext').click()); // on a phone the activity bar is in the drawer |
| 94 | await p.waitForSelector('#ext-panel', { timeout: 10000 }); |
| 95 | }; |
| 96 | |
| 97 | // 60 results in three pages of 20; two of each page work, the rest only run |
| 98 | // their own code (one of them is published per platform, so its package.json |
| 99 | // is only under /linux-x64/: before, that row came with no verdict and stayed) |
| 100 | const TOTAL = 60; |
| 101 | const mock = i => { |
| 102 | const funciona = i % 20 < 2; |
| 103 | const id = funciona ? `works-${i}` : `node-${i}`; |
| 104 | return { namespace: 'elffuss-test', name: id, version: '1.0.0', displayName: funciona ? `Theme ${i}` : `Tool ${i}`, description: '', downloadCount: 1000 - i, |
| 105 | files: { download: `https://open-vsx.org/api/elffuss-test/${id}/${i === 5 ? 'linux-x64/' : ''}1.0.0/file/x.vsix` } }; |
| 106 | }; |
| 107 | const manifiesto = name => (name.startsWith('works-') |
| 108 | ? { publisher: 'elffuss-test', name, version: '1.0.0', categories: ['Themes'], contributes: { themes: [{ label: `Mock ${name}`, path: './t.json' }] } } |
| 109 | : { publisher: 'elffuss-test', name, version: '1.0.0', categories: ['Linters'], main: './out/extension.js', contributes: { commands: [{ command: 'x' }], configuration: {} } }); |
| 110 | async function simula(ctx) { |
| 111 | const log = { search: [], openvsx: [] }; |
| 112 | await ctx.route(/open-vsx\.org|eclipsecontent\.org/, route => { |
| 113 | const u = new URL(route.request().url()); |
| 114 | log.openvsx.push(u.pathname); |
| 115 | const json = (o, status = 200) => route.fulfill({ status, contentType: 'application/json', headers: { 'access-control-allow-origin': '*' }, body: JSON.stringify(o) }); |
| 116 | if (u.pathname === '/api/-/search') { |
| 117 | const off = Number(u.searchParams.get('offset')) || 0, size = Number(u.searchParams.get('size')) || 20; |
| 118 | log.search.push(off); |
| 119 | return json({ totalSize: TOTAL, offset: off, extensions: Array.from({ length: Math.max(0, Math.min(size, TOTAL - off)) }, (_, k) => mock(off + k)) }); |
| 120 | } |
| 121 | const m = /^\/api\/elffuss-test\/([^/]+)\/(?:([^/]+)\/)?1\.0\.0\/file\/package\.json$/.exec(u.pathname); |
| 122 | if (m && (m[1] === 'node-5') === (m[2] === 'linux-x64')) return json(manifiesto(m[1])); |
| 123 | return json({ error: 'not found' }, 404); |
| 124 | }); |
| 125 | return log; |
| 126 | } |
| 127 | const visibles = p => p.locator('#ext-list .ext-row:not([hidden])').count(); |
| 128 | const ocultasDom = p => p.locator('#ext-list .ext-row[hidden]').count(); |
| 129 | |
| 130 | { |
| 131 | const { ctx, p } = await nuevaPagina('en-US'); |
| 132 | const log = await simula(ctx); |
| 133 | await abrePanel(p); |
| 134 | const filas = p.locator('#ext-list.ext-popular .ext-row'); |
| 135 | ok('opening the panel: Popular is there at once, with every entry of the list', await hasta(async () => (await filas.count()) === items.length), String(await filas.count())); |
| 136 | const veredictos = await hasta(async () => { const v = await filas.locator('.ext-verdict').allInnerTexts(); return v.length === items.length && v; }); |
| 137 | ok('each popular row has its verdict line «Works in Code: …»', !!veredictos && veredictos.every(t => /^Works in Code: /.test(t)), (veredictos || []).find(t => !/^Works in Code: /.test(t)) || ''); |
| 138 | const kinds = await filas.locator('.ext-kind').allInnerTexts(); |
| 139 | ok('each popular row is tagged with its kind', kinds.length === items.length && kinds.every(k => /^(theme|language|snippets)$/i.test(k)), kinds.slice(0, 5).join(',')); |
| 140 | ok('…in the order of the list', (await filas.evaluateAll(rs => rs.map(r => r.dataset.id))).join() === items.map(x => `${x.namespace}.${x.name}`).join()); |
| 141 | ok('Popular asked Open VSX for nothing (verdicts precomputed, no icons)', log.openvsx.length === 0, log.openvsx.join(' ')); |
| 142 | ok('the filter is on by default', await p.isChecked('#ext-only-works')); |
| 143 | await p.screenshot({ path: OUT + '/extpop-popular.png' }); |
| 144 | |
| 145 | await p.fill('#ext-q', 'tool'); |
| 146 | await p.press('#ext-q', 'Enter'); |
| 147 | const lleno = await hasta(async () => log.search.length === 3 && (await p.textContent('#ext-status')) === '60 results · 54 hidden because they do not work in Code', { tiempo: 20000 }); |
| 148 | ok('filter on: it fetched more pages by itself to fill the view (3 searches)', !!lleno && log.search.join() === '0,20,40', log.search.join()); |
| 149 | ok('filter on: only the 6 that work are shown', (await visibles(p)) === 6, String(await visibles(p))); |
| 150 | const linea = (await p.locator('#ext-hidden').innerText()).replace(/\s+/g, ' '); |
| 151 | ok('the hidden count is said: «54 hidden because they do not work in Code · show»', linea === '54 hidden because they do not work in Code · show', linea); |
| 152 | ok('…and it is right: 54 rows hidden in the page', (await ocultasDom(p)) === 54, String(await ocultasDom(p))); |
| 153 | ok('…the status says it too (screen readers)', (await p.textContent('#ext-status')) === '60 results · 54 hidden because they do not work in Code', await p.textContent('#ext-status')); |
| 154 | ok('the per-platform build got its verdict too (and is hidden)', await p.locator('#ext-list .ext-row[data-id="elffuss-test.node-5"] .ext-verdict').count() === 1 && !(await p.locator('#ext-list .ext-row[data-id="elffuss-test.node-5"]').isVisible())); |
| 155 | ok('all fetched: no «More results»', await p.locator('#ext-more').count() === 0); |
| 156 | await p.screenshot({ path: OUT + '/extpop-filtered.png' }); |
| 157 | |
| 158 | await p.click('#ext-show-hidden'); |
| 159 | ok('«show»: all 60 visible, the filter unticked, the hidden line gone', await hasta(async () => (await visibles(p)) === 60 && !(await p.isChecked('#ext-only-works')) && !(await p.locator('#ext-hidden').isVisible()))); |
| 160 | ok('…focus goes to the filter checkbox', await p.evaluate(() => document.activeElement?.id) === 'ext-only-works'); |
| 161 | const honesto = (await p.locator('#ext-list .ext-row[data-id="elffuss-test.node-3"] .ext-verdict').innerText()).replace(/\s+/g, ' '); |
| 162 | ok('filter off: the ones that do not work carry the honest verdict', /does not work in Code/.test(honesto), honesto); |
| 163 | ok('filter off: the status gives no hidden count', (await p.textContent('#ext-status')) === '60 results', await p.textContent('#ext-status')); |
| 164 | await p.keyboard.press('Space'); |
| 165 | ok('keyboard: Space on the checkbox turns the filter back on (6 visible, 54 hidden)', await hasta(async () => (await p.isChecked('#ext-only-works')) && (await visibles(p)) === 6 && /^54 hidden/.test(await p.locator('#ext-hidden').innerText()))); |
| 166 | ok('the choice is remembered in this browser', await p.evaluate(() => localStorage.getItem('elffusscode.ext.onlyWorks')) === '1'); |
| 167 | |
| 168 | await p.fill('#ext-q', ''); |
| 169 | await p.press('#ext-q', 'Enter'); |
| 170 | ok('clearing the search brings Popular back', await hasta(async () => (await p.locator('#ext-list.ext-popular .ext-row').count()) === items.length)); |
| 171 | ok('no page errors', !p.errores.length, p.errores.slice(0, 3).join(' | ')); |
| 172 | await ctx.close(); |
| 173 | } |
| 174 | |
| 175 | // Spanish, phone width |
| 176 | { |
| 177 | const { ctx, p } = await nuevaPagina('es-ES', { width: 390, height: 844 }); |
| 178 | await simula(ctx); |
| 179 | await abrePanel(p); |
| 180 | await hasta(async () => (await p.locator('#ext-list.ext-popular .ext-row .ext-verdict').count()) === items.length); |
| 181 | const primera = (await p.locator('#ext-list.ext-popular .ext-row').first().innerText()).replace(/\s+/g, ' '); |
| 182 | ok('es: Popular en castellano («Funciona en Code: …», descripción y tipo)', /Funciona en Code: /.test(primera) && primera.includes(items[0].description.es) && /snippets|tema|lenguaje/i.test(primera), primera); |
| 183 | ok('es: «Solo las que funcionan en Code»', (await p.locator('label.ext-filter').innerText()).trim() === 'Solo las que funcionan en Code'); |
| 184 | const ancho = () => p.evaluate(() => { const x = document.getElementById('ext-panel'); return [x.scrollWidth, x.clientWidth, document.documentElement.scrollWidth, innerWidth]; }); |
| 185 | let a = await ancho(); |
| 186 | ok('phone width, Popular: no horizontal overflow', a[0] <= a[1] + 1 && a[2] <= a[3] + 1, a.join(',')); |
| 187 | await p.screenshot({ path: OUT + '/extpop-phone-es.png' }); |
| 188 | await p.fill('#ext-q', 'tool'); |
| 189 | await p.press('#ext-q', 'Enter'); |
| 190 | const linea = await hasta(async () => { const t = (await p.locator('#ext-hidden').innerText()).replace(/\s+/g, ' '); return /^54 /.test(t) && t; }, { tiempo: 20000 }); |
| 191 | ok('es: «54 ocultas porque no funcionan en Code · mostrar»', linea === '54 ocultas porque no funcionan en Code · mostrar', String(linea)); |
| 192 | a = await ancho(); |
| 193 | ok('phone width, filtered search: no horizontal overflow', a[0] <= a[1] + 1 && a[2] <= a[3] + 1, a.join(',')); |
| 194 | const fuera = await p.evaluate(() => [...document.querySelectorAll('#ext-panel button, #ext-panel label')].filter(b => { const r = b.getBoundingClientRect(); return r.width && (r.right > innerWidth + 1 || r.left < -1); }).length); |
| 195 | ok('phone width: every button fits on screen', fuera === 0, String(fuera)); |
| 196 | await p.screenshot({ path: OUT + '/extpop-phone-es-search.png' }); |
| 197 | ok('es: sin errores de página', !p.errores.length, p.errores.slice(0, 3).join(' | ')); |
| 198 | await ctx.close(); |
| 199 | } |
| 200 | |
| 201 | // ── 3. LIVE: install some of the real list from the Popular section ── |
| 202 | { |
| 203 | const vivo = await fetch('https://open-vsx.org/api/dracula-theme/theme-dracula', { signal: AbortSignal.timeout(8000) }).then(r => r.ok).catch(() => false); |
| 204 | if (!vivo) notRun('live installs from Popular', 'no network'); |
| 205 | else { |
| 206 | const { p } = await nuevaPagina('en-US'); |
| 207 | await abrePanel(p); |
| 208 | const fila = id => p.locator(`#ext-list.ext-popular .ext-row[data-id="${id}"]`); |
| 209 | const instala = async id => { |
| 210 | await fila(id).locator('.ext-install').focus(); |
| 211 | await p.keyboard.press('Enter'); // with the keyboard |
| 212 | return hasta(async () => (await p.locator(`#ext-installed .ext-row[data-id="${id.toLowerCase()}"]`).count()) === 1, { tiempo: 60000 }); |
| 213 | }; |
| 214 | const fondo = () => p.evaluate(() => getComputedStyle(document.querySelector('#editor .monaco-editor-background') || document.querySelector('#editor .monaco-editor')).backgroundColor); |
| 215 | await fila('dracula-theme.theme-dracula').waitFor({ timeout: 10000 }); |
| 216 | ok('live: Dracula installs from Popular', !!(await instala('dracula-theme.theme-dracula'))); |
| 217 | ok('live: …and its theme is applied', await hasta(async () => (await fondo()) === 'rgb(40, 42, 54)', { tiempo: 20000 }), await fondo()); |
| 218 | ok('live: DotENV installs from Popular', !!(await instala('mikestead.dotenv'))); |
| 219 | const lang = await p.evaluate(async () => { await (await import('/js/ide.js')).openFile('.env'); await new Promise(r => setTimeout(r, 800)); return window.monaco.editor.getEditors()[0].getModel().getLanguageId(); }); |
| 220 | ok('live: …a .env file opens as dotenv', lang === 'dotenv', lang); |
| 221 | const tipos = await p.evaluate(() => window.monaco.editor.tokenize('API_KEY=abc # secret', 'dotenv')[0].map(t => t.type).join(' ')); |
| 222 | ok('live: …with its own grammar (comment scope)', /comment/.test(tipos), tipos); |
| 223 | await abrePanel(p); |
| 224 | ok('live: JavaScript (ES6) snippets install from Popular', !!(await instala('xabikos.JavaScriptSnippets'))); |
| 225 | const tarjeta = (await p.locator('#ext-done').innerText().catch(() => '')).replace(/\s+/g, ' '); |
| 226 | ok('live: …the notice counts its snippets', /\d+ snippets for JavaScript/.test(tarjeta), tarjeta.slice(0, 200)); |
| 227 | ok('live: Nix installs from Popular', !!(await instala('bbenoist.Nix'))); |
| 228 | const nix = await p.evaluate(() => window.monaco.languages.getLanguages().some(l => l.id === 'nix')); |
| 229 | ok('live: …and Code now knows the Nix language', nix); |
| 230 | await p.screenshot({ path: OUT + '/extpop-live.png' }); |
| 231 | ok('live: no page errors', !p.errores.length, p.errores.slice(0, 3).join(' | ')); |
| 232 | await p.context().close(); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | console.log(fails ? `\n❌ ${fails} FAILURE(S)` : '\n✅ EXTENSIONS: POPULAR AND «ONLY ONES THAT WORK» OK'); |
| 237 | await b.close(); |
| 238 | process.exit(fails ? 1 : 0); |