Elffuss BraidHub

utopia-ia/elffuss-code public

main · 12.3 KiBRawPermalink
1// Formatting with a real web extension: Prettier in Code.
2//
3// node tests/x2_format.mjs (own server; without the pinned .vsix in
4// tests/.cache and no network: NOT RUN)
5//
6// esbenp.prettier-vscode 12.4.0 (pinned, SHA-256 checked) is installed with its
7// code through Code's own install path for a .vsix file.
8//
9// F1 before it, Format Document uses Monaco's built-in formatter (the
10// reference for F6 and F7)
11// F2 Format Document with Prettier: `const x = {a:1,b:[1,2,3]}` becomes
12// `const x = { a: 1, b: [1, 2, 3] };`
13// F3 one undo step brings the text back; the tab shows unsaved changes;
14// Cmd+S writes the formatted file to the project
15// F4 Shift+Alt+F formats too
16// F5 {"prettier.semi": false} in its settings changes the output
17// F6 "built-in" as the formatter for javascript: Monaco formats again;
18// back to Prettier
19// F7 its code turned off: the sandbox stops and the built-in formatter is
20// back; turned on again: Prettier formats
21// F8 a race with an agent write: the extension's edit computed on the old
22// text is discarded, the status bar says so, the agent's text stays, and
23// the next format works on the new text
24// F9 the beacon gets nothing, the sandbox site only its two documents, no
25// page errors
26import { chromium } from 'playwright';
27import { startServer } from './lib/x2-server.mjs';
28import { startBeacon } from './lib/beacon.mjs';
29import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
30
31let fails = 0;
32const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
33const sleep = ms => new Promise(r => setTimeout(r, ms));
34async function until(fn, { timeout = 20000, every = 150 } = {}) {
35 const end = Date.now() + timeout;
36 let v;
37 while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
38 return v;
39}
40const MOD = process.platform === 'darwin' ? 'Meta' : 'Control';
41
42let prettier;
43try { prettier = (await fetchVsix({ ...PINNED.find(p => p.name === 'prettier-vscode'), offline: process.env.X2_OFFLINE === '1' })).bytes; }
44catch (e) { console.log(`⏭️ NOT RUN x2_format — esbenp.prettier-vscode@12.4.0: ${e.message}`); process.exit(0); }
45
46const UGLY = 'const x = {a:1,b:[1,2,3]}\n';
47const PRETTY = 'const x = { a: 1, b: [1, 2, 3] };\n';
48const NOSEMI = 'const x = { a: 1, b: [1, 2, 3] }\n';
49// un fichero largo: a Prettier le cuesta más que al agente escribir encima
50const BIG = Array.from({ length: 1500 }, (_, i) => `const v${i} = {k:${i},list:[${i},${i + 1}]}`).join('\n') + '\n';
51
52const srv = await startServer();
53const beacon = await startBeacon();
54const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
55const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
56await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
57const page = await ctx.newPage();
58const errors = [];
59page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
60await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
61await page.evaluate(async ({ UGLY, BIG }) => {
62 const o = await navigator.storage.getDirectory();
63 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(); };
64 await w('ugly.js', UGLY);
65 await w('big.js', BIG);
66}, { UGLY, BIG });
67await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
68await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
69
70const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
71const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
72const setValue = v => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
73const readOpfs = name => page.evaluate(async n => { const o = await navigator.storage.getDirectory(); return (await (await o.getFileHandle(n)).getFile()).text(); }, name);
74const dirty = () => page.evaluate(() => document.querySelector('#tabs-bar .tab.active .tab-x')?.classList.contains('dirty') || false);
75const focusEditor = async () => { await page.evaluate(() => window.monaco.editor.getEditors()[0].focus()); await sleep(100); };
76const formatDoc = () => page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
77const host = fn => page.evaluate(fn);
78const bridgeState = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
79// formatea hasta obtener `want` (la primera vez Prettier carga sus analizadores)
80async function formatsTo(want, tries = 20) {
81 for (let i = 0; i < tries; i++) {
82 await formatDoc();
83 if (await until(async () => (await value()) === want, { timeout: 1500 })) return true;
84 }
85 return false;
86}
87
88// ── F1: la referencia, sin extensiones ──
89await open('ugly.js');
90// (el formateador de serie necesita su worker listo: se reintenta)
91let builtin = null;
92for (let i = 0; i < 20 && !builtin; i++) {
93 await formatDoc();
94 builtin = await until(async () => { const v = await value(); return v !== UGLY ? v : null; }, { timeout: 1500 });
95}
96ok('F1 with no extension, Format Document uses Monaco’s built-in formatter', builtin === NOSEMI, JSON.stringify(builtin));
97await setValue(UGLY);
98
99// ── instalar Prettier con su código ──
100const id = await page.evaluate(async b64 => {
101 const bin = atob(b64);
102 const u8 = new Uint8Array(bin.length);
103 for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
104 const h = await (await import('/js/ide.js')).loadExt();
105 return (await h.install(new File([u8], 'prettier.vsix'), { withCode: true })).id;
106}, Buffer.from(prettier).toString('base64'));
107const active = await until(async () => { const s = await bridgeState(); return s.state === 'running' && s.extensions.find(e => e.id === id)?.state === 'active' ? s : null; }, { timeout: 90000 });
108ok('Prettier installed with its code, running in the sandbox', !!active, JSON.stringify((await bridgeState()).extensions.map(e => [e.id, e.state, e.text])));
109
110// ── F2–F3 ──
111await page.keyboard.press(`${MOD}+KeyS`);
112await until(async () => !(await dirty()));
113ok('F2 Format Document with Prettier', await formatsTo(PRETTY), JSON.stringify(await value()));
114ok('F3 the tab shows unsaved changes', !!(await until(() => dirty())));
115await focusEditor();
116await page.keyboard.press(`${MOD}+KeyZ`);
117ok('F3 one undo step brings the text back', !!(await until(async () => (await value()) === UGLY)), JSON.stringify(await value()));
118await page.keyboard.press(`${MOD}+Shift+KeyZ`);
119await until(async () => (await value()) === PRETTY);
120await page.keyboard.press(`${MOD}+KeyS`);
121ok('F3 Cmd+S writes the formatted file to the project', !!(await until(async () => (await readOpfs('ugly.js')) === PRETTY && !(await dirty()))), JSON.stringify(await readOpfs('ugly.js')));
122
123// ── F4: Shift+Alt+F ──
124await setValue(UGLY);
125let viaKeys = false;
126for (let i = 0; i < 10 && !viaKeys; i++) {
127 await focusEditor();
128 await page.keyboard.press('Shift+Alt+KeyF');
129 viaKeys = !!(await until(async () => (await value()) === PRETTY, { timeout: 1500 }));
130}
131ok('F4 Shift+Alt+F formats with Prettier', viaKeys, JSON.stringify(await value()));
132
133// ── F5: sus ajustes ──
134await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setSettings('esbenp.prettier-vscode', { 'prettier.semi': false }); });
135await setValue(UGLY);
136ok('F5 {"prettier.semi": false} changes the output', await formatsTo(NOSEMI), JSON.stringify(await value()));
137await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setSettings('esbenp.prettier-vscode', {}); });
138await setValue(UGLY);
139ok('F5 and without it, the semicolons come back', await formatsTo(PRETTY), JSON.stringify(await value()));
140
141// ── F6: el formateador de serie para javascript, y vuelta ──
142await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setFormatter('esbenp.prettier-vscode', 'javascript', 'builtin'); });
143await setValue(UGLY);
144await sleep(500);
145await formatDoc();
146ok('F6 "built-in" for javascript: Monaco formats, as with no extension', !!(await until(async () => (await value()) === builtin, { timeout: 8000 })), JSON.stringify(await value()));
147await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setFormatter('esbenp.prettier-vscode', 'javascript', 'extension'); });
148await setValue(UGLY);
149ok('F6 back to Prettier', await formatsTo(PRETTY), JSON.stringify(await value()));
150
151// ── F7: su código apagado y encendido ──
152await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns('esbenp.prettier-vscode', false); });
153const off = await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')), { timeout: 15000 });
154await setValue(UGLY);
155await sleep(300);
156await formatDoc();
157ok('F7 its code off: the sandbox is gone and the built-in formatter is back', !!off && !!(await until(async () => (await value()) === builtin, { timeout: 8000 })), JSON.stringify(await value()));
158await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns('esbenp.prettier-vscode', true, { confirm: async () => true }); });
159await until(async () => { const s = await bridgeState(); return s.state === 'running' && s.extensions.find(e => e.id === id)?.state === 'active'; }, { timeout: 90000 });
160await setValue(UGLY);
161ok('F7 on again: Prettier formats', await formatsTo(PRETTY), JSON.stringify(await value()));
162
163// ── F8: carrera con una escritura del agente ──
164// Para que la carrera sea la que importa (el cambio de la extensión llega a la
165// página DESPUÉS de que el fichero cambiara), la página se queda ocupada justo
166// tras pedir el formateo: el recinto (otro sitio, otro proceso) formatea y
167// manda su cambio mientras tanto, y el agente escribe antes de que la página
168// lo lea. Sin esa pausa, el propio VS Code del recinto suele tirar el cambio
169// viejo, que también es seguro pero no prueba la comprobación de la página.
170await open('big.js');
171await sleep(500);
172const agentText = BIG.replace('const v0 =', 'const fromAgent =');
173await page.evaluate(async t => {
174 document.getElementById('statusbar').textContent = '';
175 const bridge = await import('/js/ext2/bridge.js');
176 window.__race = bridge.runCommand('prettier.forceFormatDocument'); // Prettier, sobre el texto de ahora
177 const end = Date.now() + 3000;
178 while (Date.now() < end) { /* la página, ocupada; el recinto, no */ }
179 window.monaco.editor.getEditors()[0].getModel().setValue(t); // lo que hace una escritura del agente al fichero abierto
180}, agentText);
181await page.evaluate(async t => { await (await import('/js/tools/code.js')).write({ path: 'big.js', content: t }); }, agentText);
182await page.evaluate(() => window.__race);
183const said = await until(() => page.evaluate(() => { const t = document.getElementById('statusbar').textContent; return /discarded because the file changed meanwhile/.test(t) ? t : null; }), { timeout: 15000 });
184await sleep(800);
185ok('F8 the edit Prettier computed on the old text is discarded, and the status bar says so', !!said && (await value()) === agentText, JSON.stringify({ said, v: (await value()).slice(0, 60) }));
186ok('F8 the agent’s text is in the project', (await readOpfs('big.js')) === agentText);
187await open('ugly.js');
188await setValue('const y = {b:2}\n');
189ok('F8 the next format works', await formatsTo('const y = { b: 2 };\n'), JSON.stringify(await value()));
190
191// ── F9: privacidad ──
192const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
193ok('F9 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(' '));
194ok('F9 beacon: 0 hits', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3)));
195ok('F9 no page errors', errors.length === 0, errors.slice(0, 3).join(' | '));
196
197await browser.close();
198await beacon.close();
199await srv.close();
200console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
201process.exit(fails ? 1 : 0);