Elffuss BraidHub

utopia-ia/elffuss-code public

main · 20.0 KiBRawPermalink
1// Extensions: what the user SEES after installing one, and what is offered
2// before. Level 1 only applies themes, grammars, snippets and language
3// settings; an install that changes nothing visible felt pointless.
4//
5// BASE=http://localhost:8999 node tests/ext_feedback.mjs
6//
7// Fixtures are built in ext_fixtures.mjs and Open VSX is mocked with routes,
8// so it runs offline. The LIVE part at the end installs real extensions from
9// Open VSX; without network it is NOT RUN and does not count as a failure.
10import { chromium } from 'playwright';
11import { pureThemeVsix, PURE_DARK, partialLangVsix, TOMLISH, jsSnippetsVsix, codeOnlyVsix } from './ext_fixtures.mjs';
12
13const BASE = process.env.BASE || 'http://localhost:8999';
14const OUT = process.env.SCRATCH || '/tmp/elffuss-test';
15let fails = 0;
16const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
17const notRun = (n, e) => console.log('⏭️ NOT RUN ' + n + (e ? ' — ' + e : ''));
18const sleep = ms => new Promise(r => setTimeout(r, ms));
19const 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)})`; };
20async function hasta(fn, { tiempo = 12000, 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 { /* retry */ } await sleep(cada); }
24 return v;
25}
26// internal words a user should never read in the panel
27const JERGA = /contributes|customEditors|extension host|host de extensiones|main\/browser|activationEvents/i;
28
29const b = await chromium.launch();
30
31async function nuevaPagina(locale, viewport = { width: 1280, height: 860 }) {
32 const ctx = await b.newContext({ locale, viewport });
33 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
34 const p = await ctx.newPage();
35 p.errores = [];
36 p.on('pageerror', e => { if (e.message !== 'Canceled') p.errores.push(e.message); });
37 await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
38 await p.evaluate(async () => {
39 const o = await navigator.storage.getDirectory();
40 for await (const k of o.keys()) await o.removeEntry(k, { recursive: true }).catch(() => {});
41 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(); };
42 await w('app.js', '// app\nconst a = 1;\n');
43 await w('data.tomlish', 'name = "x"\n# note\n');
44 });
45 await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
46 await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length), { tiempo: 30000 });
47 return { ctx, p };
48}
49const pulsa = (p, sel) => p.click(sel, { timeout: 3000 }).catch(() => {});
50const abre = (p, path) => p.evaluate(async path => { await (await import('/js/ide.js')).openFile(path); }, path);
51const fondo = p => p.evaluate(() => getComputedStyle(document.querySelector('#editor .monaco-editor-background') || document.querySelector('#editor .monaco-editor')).backgroundColor);
52const abrePanel = async p => { if (!(await p.locator('#ext-panel').isVisible().catch(() => false))) { await p.click('#act-ext'); await p.waitForSelector('#ext-panel', { timeout: 10000 }); } };
53const instalaFichero = async (p, nombre, bytes) => {
54 await abrePanel(p);
55 await p.evaluate(() => { const m = document.getElementById('ext-msg'); if (m) { m.hidden = true; m.textContent = ''; } document.getElementById('ext-done')?.remove(); });
56 await p.setInputFiles('#ext-file', { name: nombre, mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) });
57 const msg = await hasta(() => p.evaluate(() => { const m = document.getElementById('ext-msg'); return m && !m.hidden && m.textContent; }), { tiempo: 15000 });
58 // Un .vsix que además trae código para el navegador abre el consentimiento
59 // del nivel 2 («¿ejecutar también su código?»). Aquí solo se quería lo
60 // declarativo: se rechaza, como haría quien lo instala por su resaltado.
61 if (await hasta(() => p.evaluate(() => !!document.querySelector('#x2-consent')), { tiempo: 1500 })) {
62 await p.keyboard.press('Escape');
63 await hasta(() => p.evaluate(() => !document.querySelector('#x2-consent')), { tiempo: 5000 });
64 }
65 return msg;
66};
67const tarjeta = p => p.evaluate(() => document.getElementById('ext-done')?.innerText.replace(/\s+/g, ' ') || '');
68const fila = (p, id) => p.locator(`#ext-installed .ext-row[data-id="${id}"]`);
69
70// ── 1. Theme-only extension: applied on install, with Undo and the picker ──
71{
72 const { p } = await nuevaPagina('en-US');
73 await abre(p, 'app.js');
74 await instalaFichero(p, 'pure.vsix', pureThemeVsix());
75 ok('theme: the first theme is applied on install (editor background)', await hasta(async () => (await fondo(p)) === rgb(PURE_DARK)), await fondo(p));
76 const t = await tarjeta(p);
77 ok('theme: the notice names the theme and says it is applied', /Pure Night/.test(t) && /applied/i.test(t), t);
78 ok('theme: Undo and Choose theme… buttons', await p.locator('#ext-done button[data-act="undo-theme"]').count() === 1 && await p.locator('#ext-done button[data-act="pick-theme"]').count() === 1);
79 await pulsa(p, '#ext-done button[data-act="undo-theme"]');
80 ok('theme: Undo restores the previous theme', await hasta(async () => (await fondo(p)) === 'rgb(30, 30, 30)'), await fondo(p));
81 ok('theme: after Undo, an Apply now button', await hasta(() => p.locator('#ext-done button[data-act="apply-theme"]').count()));
82 await pulsa(p, '#ext-done button[data-act="apply-theme"]');
83 ok('theme: Apply now applies it', await hasta(async () => (await fondo(p)) === rgb(PURE_DARK)), await fondo(p));
84 await pulsa(p, '#ext-done button[data-act="pick-theme"]');
85 ok('theme: Choose theme… opens the Color Theme picker', await hasta(() => p.locator('#ext-themepick').count()));
86 await p.keyboard.press('Escape');
87 const now = (await fila(p, 'elffuss-test.pure-theme').locator('.ext-now').innerText().catch(() => '')).replace(/\s+/g, ' ');
88 ok('installed list: says which theme is active right now', /Active theme/i.test(now) && /Pure Night/.test(now), now);
89 await p.screenshot({ path: OUT + '/extfb-theme.png' });
90
91 // ── 2. Language with grammar + settings + code: open file highlighted at once ──
92 await abre(p, 'data.tomlish');
93 ok('language: before installing, the file is plain text', (await p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getLanguageId())) === 'plaintext');
94 await instalaFichero(p, 'tomlish.vsix', partialLangVsix());
95 ok('language: the open file switches to the new language', await hasta(() => p.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getLanguageId() === 'tomlish')));
96 const tipos = await hasta(async () => { const x = await p.evaluate(() => window.monaco.editor.tokenize('name = 1', 'tomlish').flat().map(t => t.type)); return x.some(t => /variable\.other\.key/.test(t)) && x; });
97 ok('language: the grammar tokenizes', !!tipos, JSON.stringify(tipos));
98 const t2 = await tarjeta(p);
99 ok('language: notice says highlighting for Tomlish (.tomlish)', /Tomlish/.test(t2) && /\.tomlish/.test(t2) && /highlight/i.test(t2), t2);
100 ok('language: notice says the open file is already highlighted, with a button to go there', /data\.tomlish/.test(t2) && await p.locator('#ext-done button[data-act="goto"]').count() >= 1, t2);
101 ok('language: notice says what the settings change (comment with #, brackets)', /#/.test(t2) && /\[\s?\]/.test(t2), t2);
102 ok('language: notice says what does not work, in plain words, and that it comes with the next version', /format/i.test(t2) && /next version/i.test(t2) && !JERGA.test(t2), t2);
103 const now2 = (await fila(p, 'elffuss-test.tomlish').locator('.ext-now').innerText().catch(() => '')).replace(/\s+/g, ' ');
104 ok('installed list: «Highlighting 1 open file»', /Highlighting 1 open file/i.test(now2), now2);
105 await p.screenshot({ path: OUT + '/extfb-lang.png' });
106
107 // ── 3. Snippets: count, languages and prefixes to try ──
108 await instalaFichero(p, 'snips.vsix', jsSnippetsVsix());
109 const t3 = await tarjeta(p);
110 ok('snippets: «4 snippets for JavaScript and TypeScript»', /4 snippets/.test(t3) && /JavaScript/.test(t3) && /TypeScript/.test(t3), t3);
111 ok('snippets: shows prefixes to type (clg, imp…) and how to accept', /clg/.test(t3) && /imp/.test(t3) && /Tab/.test(t3), t3);
112 const now3 = (await fila(p, 'elffuss-test.js-snips').locator('.ext-now').innerText().catch(() => '')).replace(/\s+/g, ' ');
113 ok('installed list: «4 snippets» with a link to try them', /4 snippets/.test(now3) && await fila(p, 'elffuss-test.js-snips').locator('button[data-act="try-snippet"]').count() === 1, now3);
114 await pulsa(p, '#ext-done button[data-act="try-snippet"]');
115 ok('snippets: Try opens a JavaScript file and puts the cursor in the editor', await hasta(() => p.evaluate(() => {
116 const ed = window.monaco.editor.getEditors()[0];
117 return document.getElementById('settings-panel').hidden && ed.getModel().getLanguageId() === 'javascript' && ed.hasTextFocus();
118 })));
119
120 // ── 4. Code-only .vsix: not installed, said plainly ──
121 const m4 = await instalaFichero(p, 'previewer.vsix', codeOnlyVsix());
122 ok('code-only: not installed', await fila(p, 'elffuss-test.previewer').count() === 0, m4);
123 ok('code-only: says its main feature needs its own code, in plain words', /own code/i.test(m4 || '') && !JERGA.test(m4 || ''), m4);
124 ok('code-only (custom editors): does not promise the next version', !/next version/i.test(m4 || ''), m4);
125
126 // ── 5. Plain language everywhere in the panel ──
127 const todo = await p.evaluate(() => document.getElementById('ext-panel').innerText);
128 ok('panel text: no internal terms (contributes, customEditors, main/browser…)', !JERGA.test(todo), (todo.match(JERGA) || [''])[0]);
129 ok('no page errors', !p.errores.length, p.errores.slice(0, 3).join(' | '));
130 await p.context().close();
131}
132
133// ── 6. Search results (Open VSX mocked): verdict before installing ──
134{
135 const { ctx, p } = await nuevaPagina('en-US');
136 const manifests = {
137 'elffuss-test/previewer': { publisher: 'elffuss-test', name: 'previewer', version: '1.0.0', displayName: 'Rich Previewer', description: 'LaTeX, STL and video preview with right-click copy', categories: ['Visualization', 'Other'], main: './dist/extension.js',
138 contributes: { languages: [{ id: 'csv', aliases: ['CSV'], extensions: ['.csv'] }, { id: 'tsv', extensions: ['.tsv'] }], commands: [{}], menus: {}, customEditors: [{}], configuration: {} } },
139 'elffuss-test/tomlish': { publisher: 'elffuss-test', name: 'tomlish', version: '1.0.0', displayName: 'Tomlish Support', categories: ['Programming Languages', 'Formatters'], main: './x.js', browser: './b.js',
140 contributes: { languages: [{ id: 'tomlish', aliases: ['Tomlish'], extensions: ['.tomlish'], configuration: './c.json' }], grammars: [{ language: 'tomlish', scopeName: 'source.tomlish', path: './g.json' }], commands: [{}] } },
141 'elffuss-test/heavy': { publisher: 'elffuss-test', name: 'heavy', version: '1.0.0', displayName: 'Heavy Workshop', categories: ['Programming Languages', 'Linters'], main: './x.js',
142 contributes: { languages: [{ id: 'heavy', aliases: ['Heavy'], extensions: ['.hv'], configuration: './c.json' }], grammars: [{ language: 'heavy', scopeName: 'source.hv', path: './g.json' }], commands: new Array(12).fill({}), views: { x: [{ type: 'webview' }] }, customEditors: [{}] } },
143 'elffuss-test/pure-theme': { publisher: 'elffuss-test', name: 'pure-theme', version: '1.0.0', displayName: 'Pure Theme', categories: ['Themes'], contributes: { themes: [{ label: 'Pure Night', path: './n.json' }, { label: 'Pure Dusk', path: './d.json' }] } },
144 };
145 const descargas = [];
146 await ctx.route('https://open-vsx.org/**', route => {
147 const u = new URL(route.request().url());
148 const json = o => route.fulfill({ status: 200, contentType: 'application/json', headers: { 'access-control-allow-origin': '*' }, body: JSON.stringify(o) });
149 if (u.pathname === '/api/-/search') {
150 return json({ totalSize: 4, offset: 0, extensions: Object.values(manifests).map(m => ({ namespace: m.publisher, name: m.name, version: m.version, displayName: m.displayName, description: m.description || '', downloadCount: 10 })) });
151 }
152 const mm = /^\/api\/([^/]+)\/([^/]+)\/([^/]+)\/file\/package\.json$/.exec(u.pathname);
153 if (mm) return json(manifests[`${mm[1]}/${mm[2]}`]);
154 const md = /^\/api\/([^/]+)\/([^/]+)(?:\/([^/]+))?$/.exec(u.pathname);
155 if (md && manifests[`${md[1]}/${md[2]}`]) {
156 const m = manifests[`${md[1]}/${md[2]}`];
157 return json({ namespace: m.publisher, name: m.name, version: m.version, displayName: m.displayName, license: 'MIT', files: { manifest: `https://open-vsx.org/api/${m.publisher}/${m.name}/${m.version}/file/package.json`, download: `https://open-vsx.org/api/${m.publisher}/${m.name}/${m.version}/file/x.vsix` } });
158 }
159 descargas.push(u.pathname);
160 return route.fulfill({ status: 404, body: '' });
161 });
162 await abrePanel(p);
163 await p.uncheck('#ext-only-works'); // this section reads every verdict, the ones that do nothing too
164 await p.fill('#ext-q', 'anything');
165 await p.press('#ext-q', 'Enter');
166 const r = id => p.locator(`#ext-results .ext-row[data-id="${id}"]`);
167 await r('elffuss-test.pure-theme').waitFor({ timeout: 10000 }).catch(() => {});
168 const listo = await hasta(() => p.evaluate(() => document.querySelectorAll('#ext-results .ext-verdict').length >= 4));
169 ok('results: every row gets a verdict before installing', !!listo);
170 const v = async id => (await r(id).locator('.ext-verdict').innerText().catch(() => '')).replace(/\s+/g, ' ');
171 const btn = id => r(id).locator('.ext-install');
172 const vPrev = await v('elffuss-test.previewer');
173 ok('code-only: «The main thing … does not work in Code: it needs to run its own code»', /main/i.test(vPrev) && /does not work in Code/i.test(vPrev) && /own code/i.test(vPrev), vPrev);
174 ok('code-only: Install is disabled and labelled so', (await btn('elffuss-test.previewer').getAttribute('aria-disabled')) === 'true' && !/^Install$/.test((await btn('elffuss-test.previewer').innerText()).trim()), await btn('elffuss-test.previewer').innerText());
175 ok('code-only with custom editors: no «next version» promise', !/next version/i.test(vPrev), vPrev);
176 await btn('elffuss-test.previewer').click({ timeout: 3000 }).catch(() => {});
177 await sleep(400);
178 ok('code-only: clicking it downloads nothing', !descargas.some(x => /previewer/.test(x)), descargas.join(' '));
179 const vToml = await v('elffuss-test.tomlish');
180 ok('partial: «Partly works» naming the language, and the missing part in plain words', /Tomlish/.test(vToml) && /format/i.test(vToml) && /next version/i.test(vToml) && !JERGA.test(vToml), vToml);
181 ok('partial: the button says what you get («Install only the highlighting»)', /only the highlighting/i.test(await btn('elffuss-test.tomlish').innerText()), await btn('elffuss-test.tomlish').innerText());
182 const vHeavy = await v('elffuss-test.heavy');
183 ok('mostly code: leads with the main feature not working, then «Only … would apply: highlighting for Heavy»', /does not work in Code/i.test(vHeavy) && /Only/.test(vHeavy) && /Heavy/.test(vHeavy), vHeavy);
184 ok('mostly code: install is a secondary button', /ghost/.test(await btn('elffuss-test.heavy').getAttribute('class')) && /only/i.test(await btn('elffuss-test.heavy').innerText()));
185 const vPure = await v('elffuss-test.pure-theme');
186 ok('declarative: plain Install and the theme names', (await btn('elffuss-test.pure-theme').innerText()).trim() === 'Install' && /Pure Night/.test(vPure), vPure);
187 await r('elffuss-test.previewer').locator('.ext-name').click({ timeout: 3000 }).catch(() => {});
188 const det = await hasta(async () => { const x = await r('elffuss-test.previewer').locator('.ext-detail').innerText({ timeout: 2000 }); return !/Reading/.test(x) && x; });
189 ok('details: plain language, no raw contribution names', !!det && !JERGA.test(det) && !/commands|menus|configuration/.test(det), det);
190 const todo = await p.evaluate(() => document.getElementById('ext-panel').innerText);
191 ok('results panel: no internal terms', !JERGA.test(todo), (todo.match(JERGA) || [''])[0]);
192 await p.screenshot({ path: OUT + '/extfb-results.png' });
193 // keyboard: the disabled button still takes focus and is announced as such
194 await btn('elffuss-test.previewer').focus({ timeout: 3000 }).catch(() => {});
195 const nombre = await btn('elffuss-test.previewer').evaluate(b => (b.getAttribute('aria-label') || b.textContent) + ' | ' + (b.getAttribute('aria-describedby') ? document.getElementById(b.getAttribute('aria-describedby'))?.textContent : ''));
196 ok('a11y: the disabled button is focusable and its reason is linked (aria-describedby)', /does not work/i.test(nombre), nombre);
197 await ctx.close();
198}
199
200// ── 7. Spanish + phone width ──
201{
202 const { p } = await nuevaPagina('es-ES');
203 await abrePanel(p); // the activity bar is in the drawer on a phone
204 await p.setViewportSize({ width: 390, height: 800 });
205 await instalaFichero(p, 'pure.vsix', pureThemeVsix());
206 const t = await tarjeta(p);
207 ok('es: «Tema «Pure Night» aplicado»', /Tema «Pure Night» aplicado/.test(t), t);
208 ok('es: botones Deshacer y Elegir tema…', /Deshacer/.test(t) && /Elegir tema/.test(t), t);
209 const ancho = await p.evaluate(() => { const x = document.getElementById('ext-panel'); return [x.scrollWidth, x.clientWidth, document.documentElement.scrollWidth, innerWidth]; });
210 ok('phone width: no horizontal overflow', ancho[0] <= ancho[1] + 1 && ancho[2] <= ancho[3] + 1, ancho.join(','));
211 const fuera = await p.evaluate(() => [...document.querySelectorAll('#ext-done button')].filter(b => { const r = b.getBoundingClientRect(); return r.right > innerWidth + 1 || r.left < -1; }).length);
212 ok('phone width: notice buttons fit on screen', fuera === 0, String(fuera));
213 await p.screenshot({ path: OUT + '/extfb-phone-es.png' });
214 const todo = await p.evaluate(() => document.getElementById('ext-panel').innerText);
215 ok('es: sin términos internos', !JERGA.test(todo), (todo.match(JERGA) || [''])[0]);
216 await p.context().close();
217}
218
219// ── LIVE: real Open VSX ──
220{
221 const vivo = await fetch('https://open-vsx.org/api/esbenp/prettier-vscode', { signal: AbortSignal.timeout(8000) }).then(r => r.ok).catch(() => false);
222 if (!vivo) notRun('live Open VSX', 'no network');
223 else {
224 const { p } = await nuevaPagina('en-US');
225 await abrePanel(p);
226 await p.fill('#ext-q', 'prettier');
227 await p.press('#ext-q', 'Enter');
228 const row = p.locator('#ext-results .ext-row[data-id="esbenp.prettier-vscode"]');
229 await row.waitFor({ state: 'attached', timeout: 20000 }).catch(() => {});
230 // Con el nivel 2, el código para el navegador de Prettier puede correr en el
231 // recinto: ya no se esconde ni se da por «no funciona». La fila lo dice, y
232 // «Instalar» lleva a su botón de código en vez de ser un botón muerto.
233 const visto = await hasta(async () => (await row.isVisible()) && /Code’s sandbox/.test(await row.innerText()), { tiempo: 20000 });
234 ok('live: Prettier (browser code) shows even with «Only ones that work in Code» on, and says it can run in Code’s sandbox', !!visto, await row.innerText().catch(() => ''));
235 ok('live: …and its Install is not a dead button', (await row.locator('.ext-install').getAttribute('aria-disabled')) !== 'true', await row.innerText().catch(() => ''));
236 await p.fill('#ext-q', 'dracula');
237 await p.press('#ext-q', 'Enter');
238 const d = p.locator('#ext-results .ext-row[data-id="dracula-theme.theme-dracula"]');
239 await d.waitFor({ timeout: 20000 }).catch(() => {});
240 await d.locator('.ext-install').click().catch(() => {});
241 ok('live: Dracula applied on install', await hasta(async () => (await fondo(p)) === 'rgb(40, 42, 54)', { tiempo: 40000 }), await fondo(p));
242 await p.screenshot({ path: OUT + '/extfb-live-dracula.png' });
243 ok('live: no page errors', !p.errores.length, p.errores.slice(0, 3).join(' | '));
244 await p.context().close();
245 }
246}
247
248console.log(fails ? `\n❌ ${fails} FAILURE(S)` : '\n✅ EXTENSIONS: VISIBLE EFFECT AFTER INSTALL OK');
249await b.close();
250process.exit(fails ? 1 : 0);