Elffuss BraidHub

utopia-ia/elffuss-code public

fc9a8dba96f6 · 19.1 KiBRawPermalink
1// Life of real web extensions in Code, against the live Open VSX.
2//
3// node tests/x2_lifecycle.mjs
4// needs the network; offline (or X2_OFFLINE=1) it is NOT RUN, and
5// tests/x2_manager.mjs runs the same panel flows on the cached packages
6//
7// Everything goes through the Extensions panel and Code's own requests to
8// open-vsx.org (metadata, the published SHA-256, the .vsix). Only the search
9// listing is pinned, so the versions under test stay fixed: Tyriar.sort-lines
10// 1.9.1 and 1.12.0, esbenp.prettier-vscode 12.3.0 and 12.4.0.
11//
12// L0 sort-lines 1.9.1 declares a browser entry its package does not
13// contain: running its code is refused, and nothing is left installed
14// L1 sort-lines 1.12.0, search and detail: what will work, before installing
15// L2 "Install and run its code…": Cancel downloads nothing
16// L3 accept: Code's page downloads it, checks the published SHA-256
17// (pinned too) and starts its code
18// L4 its command runs from the panel and sorts the open file
19// L5 code off and on again without a reload
20// L6 Prettier 12.3.0 the same way; Format Document uses it
21// L7 update to 12.4.0 from the result row: still with its code, still on,
22// with the pinned SHA-256, the old version's files gone, and it formats
23// L8 disabling the extension stops its code (the built-in formatter is
24// back); enabling it brings Prettier back
25// L9 after a reload both are back, running, with what they did
26// L10 uninstall both: no files left in IndexedDB, no sandbox, nothing in kv
27// L11 only Code's page talked to Open VSX; the sandbox site was asked only
28// for its two documents; no page errors
29import { chromium } from 'playwright';
30import { startServer } from './lib/x2-server.mjs';
31import { PINNED, fetchVsix } from './lib/x2-vsix.mjs';
32
33let fails = 0;
34const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
35const sleep = ms => new Promise(r => setTimeout(r, ms));
36async function until(fn, { timeout = 30000, every = 200 } = {}) {
37 const end = Date.now() + timeout;
38 let v;
39 while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
40 return v;
41}
42const API = 'https://open-vsx.org';
43
44// ── ¿hay Open VSX? ──
45const live = {};
46try {
47 if (process.env.X2_OFFLINE === '1') throw new Error('X2_OFFLINE=1');
48 for (const [ns, name, v] of [['Tyriar', 'sort-lines', '1.9.1'], ['Tyriar', 'sort-lines', '1.12.0'], ['esbenp', 'prettier-vscode', '12.3.0'], ['esbenp', 'prettier-vscode', '12.4.0']]) {
49 const r = await fetch(`${API}/api/${ns}/${name}/${v}`, { signal: AbortSignal.timeout(20000), headers: { 'User-Agent': 'elffuss-code-tests' } });
50 if (!r.ok) throw new Error(`${ns}.${name}@${v}: HTTP ${r.status}`);
51 const j = await r.json();
52 if (!j.files?.download || !j.files?.sha256) throw new Error(`${ns}.${name}@${v}: no download or no published SHA-256`);
53 live[`${ns}.${name}@${v}`.toLowerCase()] = j;
54 }
55} catch (e) {
56 console.log(`⏭️ NOT RUN x2_lifecycle — Open VSX not reachable (${e.message}); tests/x2_manager.mjs runs these flows on the cached packages`);
57 process.exit(0);
58}
59const pinnedSha = Object.fromEntries(PINNED.map(p => [`${p.namespace}.${p.name}@${p.version}`.toLowerCase(), p.sha256]));
60
61const srv = await startServer();
62const browser = await chromium.launch();
63const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
64await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch { /* — */ } });
65// solo la lista de la búsqueda va fijada; lo demás sale a Open VSX de verdad
66let sortVersion = '1.9.1', prettierVersion = '12.3.0';
67const listing = () => [
68 { namespace: 'Tyriar', name: 'sort-lines', version: sortVersion, displayName: 'Sort lines', description: 'Sorts lines of text', downloadCount: 1000, verified: true, files: {} },
69 { namespace: 'esbenp', name: 'prettier-vscode', version: prettierVersion, displayName: 'Prettier - Code formatter', description: 'Code formatter using prettier', downloadCount: 1000, verified: true, files: {} },
70];
71await ctx.route(`${API}/api/-/search**`, route => {
72 const q = (new URL(route.request().url()).searchParams.get('query') || '').toLowerCase();
73 const hits = listing().filter(x => !q || `${x.namespace} ${x.name} ${x.displayName}`.toLowerCase().includes(q));
74 return route.fulfill({ status: 200, headers: { 'access-control-allow-origin': '*', 'content-type': 'application/json' }, body: JSON.stringify({ totalSize: hits.length, offset: 0, extensions: hits }) });
75});
76const page = await ctx.newPage();
77const errors = [];
78page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
79page.on('dialog', d => d.accept()); // confirmar desinstalar
80const outside = []; // peticiones fuera de Code y del CDN de Monaco
81ctx.on('request', r => {
82 let u;
83 try { u = new URL(r.url()); } catch { return; }
84 if (!/^https?:$/.test(u.protocol) || u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === 'cdn.jsdelivr.net') return;
85 let frame = '';
86 try { frame = r.frame()?.url() || ''; } catch { frame = '(worker)'; }
87 outside.push({ url: u.origin + u.pathname, frame, method: r.method() });
88});
89
90await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
91await page.evaluate(async () => {
92 const o = await navigator.storage.getDirectory();
93 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(); };
94 await w('fruits.txt', 'pear\napple\nfig\n');
95 await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
96});
97const openIde = async () => {
98 await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
99 await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
100};
101await openIde();
102const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
103const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
104const setValue = v => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
105const selectAll = () => page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; const m = ed.getModel(); ed.setSelection(m.getFullModelRange()); });
106const formatDoc = () => page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
107const panel = async () => { await page.click('#act-ext'); await until(() => page.evaluate(() => !document.getElementById('settings-panel').hidden && !!document.getElementById('ext-panel'))); };
108const row = id => page.locator(`#ext-results .ext-row[data-id="${id}"]`);
109const installed = id => page.locator(`#ext-installed .ext-row[data-id="${id}"]`);
110const search = async q => { await page.fill('#ext-q', q); await page.press('#ext-q', 'Enter'); };
111const codeState = id => page.evaluate(id => document.querySelector(`#ext-installed .ext-row[data-id="${id}"] .ext-x2-state`)?.textContent || null, id);
112const record = id => page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const r = h.list().find(e => e.id === id); return r ? { version: r.version, verified: r.verified, sha256: r.sha256, code: !!r.code, runs: !!r.runs, enabled: r.enabled } : null; }, id);
113const idbKeys = prefix => page.evaluate(prefix => new Promise((res, rej) => {
114 const r = indexedDB.open('elffuss-code-ext', 1);
115 r.onsuccess = () => { const q = r.result.transaction('files').objectStore('files').getAllKeys(); q.onsuccess = () => { res(q.result.filter(k => String(k).startsWith(prefix)).length); r.result.close(); }; q.onerror = () => rej(q.error); };
116 r.onerror = () => rej(r.error);
117}), prefix);
118const READY = s => s === 'running' || s === 'ready (starts when first used)';
119// (un HEAD solo mira lo que pesa, para el consentimiento: no es una descarga)
120const downloads = () => outside.filter(o => /\.vsix$/.test(o.url) && o.method !== 'HEAD').map(o => o.url.split('/').pop());
121const sizeLookups = () => outside.filter(o => /\.vsix$/.test(o.url) && o.method === 'HEAD').map(o => o.url.split('/').pop());
122const SORT = 'tyriar.sort-lines', PRETTIER = 'esbenp.prettier-vscode';
123async function sortFromPanel(text, want) {
124 await open('fruits.txt');
125 await setValue(text);
126 await selectAll();
127 await panel();
128 await installed(SORT).locator('[data-k="cmd:sortLines.sortLines"]').click();
129 return until(async () => (await value()) === want);
130}
131async function formatsTo(want, tries = 20) {
132 for (let i = 0; i < tries; i++) {
133 await formatDoc();
134 if (await until(async () => (await value()) === want, { timeout: 1500 })) return true;
135 }
136 return false;
137}
138
139// ── L0: una versión cuyo paquete no trae su entrada para el navegador ──
140await panel();
141await search('sort-lines');
142await until(async () => (await row('Tyriar.sort-lines').count()) === 1);
143await row('Tyriar.sort-lines').locator('.ext-name').click();
144await until(async () => (await row('Tyriar.sort-lines').locator('.ext-install-code').count()) === 1);
145await row('Tyriar.sort-lines').locator('.ext-install-code').click();
146await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
147await page.click('#x2-consent button:has-text("Install and run code")');
148const refused = await until(async () => { const t = await page.textContent('#ext-msg'); return /browser entry is not in the package/i.test(t) ? t : null; }, { timeout: 120000 });
149ok('L0 sort-lines 1.9.1 declares a browser entry its package lacks: its code is refused, nothing is installed', !!refused && !(await record(SORT)) && (await idbKeys(SORT + '@')) === 0, String(refused || await page.textContent('#ext-msg')));
150
151// ── L1 ──
152sortVersion = '1.12.0';
153await openIde();
154await panel();
155await search('sort-lines');
156await until(async () => (await row('Tyriar.sort-lines').count()) === 1);
157await row('Tyriar.sort-lines').locator('.ext-name').click();
158const det = await until(async () => { const t = await row('Tyriar.sort-lines').locator('.ext-detail').innerText(); return /Runs in Code’s sandbox/.test(t) ? t : null; });
159ok('L1 the detail says what will work, before installing', !!det && /No internet; sees only the files you open/.test(det), det);
160
161// ── L2 ──
162const before = downloads().length;
163await row('Tyriar.sort-lines').locator('.ext-install-code').click();
164const consentText = await until(() => page.evaluate(() => document.querySelector('#x2-consent [role="dialog"]')?.textContent || null));
165await page.keyboard.press('Escape');
166await sleep(800);
167ok('L2 Cancel in the consent dialog: nothing downloaded, nothing installed', downloads().length === before && !(await record(SORT)), JSON.stringify(downloads()));
168// (aquí la petición HEAD pasa por la intercepción de Playwright, que fija la
169// búsqueda, y Open VSX le contesta 403: el diálogo dice entonces que la baja al
170// aceptar. Sin intercepción, como en un navegador de verdad, se ve abajo, L2b)
171ok('L2 …the dialog opened at once and asked Open VSX for its size (a HEAD request), before anything was downloaded', sizeLookups().includes('Tyriar.sort-lines-1.12.0.vsix')
172 && /This extension: (checking its size|\d+\.\d MB|downloaded from Open VSX when you accept)/.test(consentText || ''), JSON.stringify({ heads: sizeLookups(), text: String(consentText).slice(-160) }));
173{
174 const ctx2 = await browser.newContext();
175 await ctx2.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch { /* — */ } });
176 const p2 = await ctx2.newPage();
177 await p2.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
178 const size = await p2.evaluate(async () => {
179 const ovsx = await import('/js/ext/openvsx.js');
180 return (await import('/js/ext2/manage.js')).downloadSize(await ovsx.metadata('Tyriar', 'sort-lines', '1.12.0'));
181 }).catch(e => String(e.message || e));
182 const pinned = PINNED.find(x => x.name === 'sort-lines');
183 const want = (await fetchVsix({ ...pinned, offline: true }).catch(() => null))?.bytes?.length;
184 ok('L2b in a browser without interception, the size the consent shows comes from Open VSX itself (HEAD) and is the pinned package’s', !!want && size === want, JSON.stringify({ size, want }));
185 await ctx2.close();
186}
187
188// ── L3 ──
189await row('Tyriar.sort-lines').locator('.ext-install-code').click();
190await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
191await page.click('#x2-consent button:has-text("Install and run code")');
192const st1 = await until(async () => { const s = await codeState(SORT); return READY(s) ? s : null; }, { timeout: 120000 });
193const r1 = await record(SORT);
194ok('L3 accepted: Code downloaded 1.12.0 from Open VSX, checked the published SHA-256 (the pinned one) and runs its code', !!st1 && r1?.version === '1.12.0' && r1.verified && r1.code && r1.runs
195 && r1.sha256 === pinnedSha['tyriar.sort-lines@1.12.0'] && downloads().includes('Tyriar.sort-lines-1.12.0.vsix') && outside.some(o => o.url.endsWith('Tyriar.sort-lines-1.12.0.sha256')), JSON.stringify({ st1, r1, d: downloads() }));
196
197// ── L4 ──
198ok('L4 its command runs from the panel and sorts the open file', !!(await sortFromPanel('pear\napple\nfig', 'apple\nfig\npear')), JSON.stringify(await value()));
199
200// ── L5: apagar y encender su código ──
201await panel();
202await installed(SORT).locator('[data-k="x2run"]').click();
203ok('L5 code off: the extension stays installed, the sandbox goes away', !!(await until(async () => (await codeState(SORT)) === 'off'))
204 && !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')))));
205await installed(SORT).locator('[data-k="x2run"]').click();
206ok('L5 code on again, no reload and no second consent (the runtime is cached)', !!(await until(async () => READY(await codeState(SORT)), { timeout: 60000 }))
207 && !(await page.evaluate(() => !!document.querySelector('#x2-consent'))));
208ok('L5 …and the command works', !!(await sortFromPanel('d\nc', 'c\nd')), JSON.stringify(await value()));
209
210// ── L6: Prettier 12.3.0 ──
211await panel();
212await search('prettier');
213await until(async () => (await row('esbenp.prettier-vscode').count()) === 1);
214await row('esbenp.prettier-vscode').locator('.ext-name').click();
215await until(async () => (await row('esbenp.prettier-vscode').locator('.ext-install-code').count()) === 1);
216await row('esbenp.prettier-vscode').locator('.ext-install-code').click();
217await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
218await page.click('#x2-consent button:has-text("Install and run code")');
219await until(async () => (await codeState(PRETTIER)) === 'running', { timeout: 120000 });
220const r3 = await record(PRETTIER);
221ok('L6 Prettier 12.3.0 installed with its code, the published SHA-256 checked', r3?.version === '12.3.0' && r3.verified && r3.code && r3.runs, JSON.stringify(r3));
222await open('ugly.js');
223await setValue('const x = {a:1,b:[1,2,3]}\n');
224ok('L6 Format Document uses Prettier', await formatsTo('const x = { a: 1, b: [1, 2, 3] };\n'), JSON.stringify(await value()));
225
226// ── L7: actualizar a 12.4.0 ──
227prettierVersion = '12.4.0';
228await panel();
229await search('prettier');
230const upd = row('esbenp.prettier-vscode').locator('.ext-install');
231await until(async () => /Update to 12\.4\.0/.test(await upd.textContent()));
232await upd.click();
233const r4 = await until(async () => { const r = await record(PRETTIER); return r?.version === '12.4.0' ? r : null; }, { timeout: 120000 });
234ok('L7 updated to 12.4.0 with its code, still on, with the pinned SHA-256', !!r4 && r4.verified && r4.code && r4.runs && r4.sha256 === pinnedSha['esbenp.prettier-vscode@12.4.0'], JSON.stringify(r4));
235ok('L7 the old version’s files are gone', (await idbKeys(PRETTIER + '@12.3.0/')) === 0);
236await until(async () => (await codeState(PRETTIER)) === 'running', { timeout: 60000 });
237await open('ugly.js');
238await setValue('const z = {c:3}\n');
239ok('L7 …and the new version formats', await formatsTo('const z = { c: 3 };\n'), JSON.stringify(await value()));
240
241// ── L8: desactivar la extensión entera, y volver ──
242await panel();
243await installed(PRETTIER).locator('.ext-toggle').click();
244await until(async () => (await record(PRETTIER))?.enabled === false);
245await open('ugly.js');
246await setValue('const x = {a:1}\n');
247await sleep(800);
248await formatDoc();
249ok('L8 disabled: its code stops and the built-in formatter is back', !!(await until(async () => (await value()) === 'const x = { a: 1 }\n', { timeout: 10000 })), JSON.stringify(await value()));
250await panel();
251await installed(PRETTIER).locator('.ext-toggle').click();
252await until(async () => (await record(PRETTIER))?.enabled === true && (await codeState(PRETTIER)) === 'running', { timeout: 60000 });
253await open('ugly.js');
254await setValue('const x = {a:1}\n');
255ok('L8 enabled again: Prettier formats', await formatsTo('const x = { a: 1 };\n'), JSON.stringify(await value()));
256
257// ── L9: recargar ──
258await openIde();
259await open('ugly.js');
260await setValue('const y = {b:2}\n');
261ok('L9 after a reload Prettier runs and formats', await formatsTo('const y = { b: 2 };\n', 40), JSON.stringify(await value()));
262await panel();
263await until(async () => READY(await codeState(SORT)), { timeout: 60000 });
264ok('L9 …and sort-lines is back too', !!(await sortFromPanel('z\ny', 'y\nz')), JSON.stringify(await value()));
265
266// ── L10: desinstalar ──
267await panel();
268await installed(SORT).locator('.ext-uninstall').click();
269ok('L10 sort-lines uninstalled: no row, no files', !!(await until(async () => (await installed(SORT).count()) === 0)) && (await idbKeys(SORT + '@')) === 0);
270ok('L10 the sandbox stays while Prettier runs', await page.evaluate(() => !!document.getElementById('x2-sandbox')));
271await installed(PRETTIER).locator('.ext-uninstall').click();
272await until(async () => (await installed(PRETTIER).count()) === 0);
273const mirror = await page.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions'));
274ok('L10 Prettier uninstalled: no files, no sandbox, nothing in kv', (await idbKeys(PRETTIER + '@')) === 0 && !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox'))))
275 && Array.isArray(mirror) && !mirror.length, JSON.stringify(mirror));
276
277// ── L11: privacidad ──
278const vsx = outside.filter(o => o.url.startsWith(API) || /openvsx|eclipsecontent/.test(o.url));
279const notPage = vsx.filter(o => !o.frame.startsWith(srv.codeOrigin));
280ok('L11 only Code’s page talked to Open VSX (no request from the sandbox)', vsx.length > 0 && notPage.length === 0, JSON.stringify(notPage.slice(0, 3)));
281const strangers = outside.filter(o => !vsx.includes(o));
282ok('L11 and nobody talked to anything else', strangers.length === 0, JSON.stringify(strangers.slice(0, 3)));
283const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
284ok('L11 the sandbox site was asked only for its two documents', sbx.length > 0 && sbx.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sbx.join(' '));
285ok('L11 no page errors', errors.length === 0, errors.slice(0, 3).join(' | '));
286
287await browser.close();
288await srv.close();
289console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
290process.exit(fails ? 1 : 0);