Elffuss BraidHub

utopia-ia/elffuss-code public

9ce12407e99b · 13.9 KiBRawPermalink
1// What people who never turn on an extension's code download, compared with
2// Code's main before level 2 (84cc38b, which has level 1), and what turning it
3// on downloads.
4//
5// node tests/x2_bytes.mjs
6//
7// The tip's web/ comes from `git archive` into a temporary folder and is served
8// by a second test server on another loopback port. The same steps run against
9// both, each in a fresh browser profile, and the requests of the measured page
10// are compared. Four states:
11// 1. no extensions;
12// 2. level 1 only: a theme installed and chosen;
13// 3. a code extension installed with its code turned off (Prettier's real
14// .vsix; on the tip, the same file gives its declarative parts);
15// 4. the Extensions panel open and a search done (Open VSX mocked the same
16// way for both).
17// In each: the same request URLs (path and query; Code's site and the CDN)
18// and the same count; nothing under /vendor/x2/ or /js/ext2/ and nothing from
19// the sandbox site. Code's bytes (each file counted at its size on disk, the
20// way the test server sends it, uncompressed): with no extension at all, within
21// +1 KB of the tip (the two hooks in ide.js and main.js). With level 1
22// extensions the level 1 modules carry level 2's hooks (host.js decides when
23// to load js/ext2/host2.js; the panel shows everyone what will work, the
24// "Works in Code" filter and how isolation works), so those states have a
25// budget instead, printed file by file: +5 KB with an extension active (2, 3)
26// and +20 KB with the panel open (4).
27// Then, with the code turned on: the manifest's three files fetched once each
28// and verified, and after a reload none of them asked from the server again.
29// (Tampering, ?noext, ?noext2 and the kill switch: tests/x2_smoke.mjs D and E.)
30import fs from 'node:fs';
31import os from 'node:os';
32import path from 'node:path';
33import { execFileSync } from 'node:child_process';
34import { fileURLToPath } from 'node:url';
35import { chromium } from 'playwright';
36import { startServer } from './lib/x2-server.mjs';
37import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
38import { mockOpenVsx } from './lib/openvsx-mock.mjs';
39import { themeVsix } from './ext_fixtures.mjs';
40
41const HERE = path.dirname(fileURLToPath(import.meta.url));
42const REPO = path.resolve(HERE, '..');
43const TIP = '84cc38b'; // main before level 2 (level 1 included)
44const BUDGET = { 1: 1024, 2: 5 * 1024, 3: 5 * 1024, 4: 20 * 1024 };
45let fails = 0;
46const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
47const sleep = ms => new Promise(r => setTimeout(r, ms));
48async function until(fn, { timeout = 30000, every = 150 } = {}) {
49 const end = Date.now() + timeout;
50 let v;
51 while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
52 return v;
53}
54
55// ── el árbol del nivel 1, tal cual ──
56const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'x2-bytes-'));
57execFileSync('/bin/sh', ['-c', `/usr/bin/git -C "$1" archive ${TIP} web | tar -x -C "$2"`, 'sh', REPO, tmp]);
58const tipWeb = path.join(tmp, 'web');
59if (!fs.existsSync(path.join(tipWeb, 'js/ide.js'))) { console.log('❌ git archive of the tip gave no web/'); process.exit(1); }
60
61let prettier;
62try { prettier = (await fetchVsix({ ...PINNED.find(p => p.name === 'prettier-vscode'), offline: process.env.X2_OFFLINE === '1' })).bytes; }
63catch (e) { console.log(`⏭️ NOT RUN x2_bytes — esbenp.prettier-vscode@12.4.0: ${e.message}`); fs.rmSync(tmp, { recursive: true, force: true }); process.exit(0); }
64const theme = themeVsix();
65
66const now = await startServer();
67const tip = await startServer({ webRoot: tipWeb });
68const trees = { now: { srv: now, web: path.join(REPO, 'web') }, tip: { srv: tip, web: tipWeb } };
69const browser = await chromium.launch();
70
71// tamaño de lo que manda el servidor de pruebas: el fichero tal cual, o «not found»
72function sizeOf(web, urlPath) {
73 try { const st = fs.statSync(path.join(web, decodeURIComponent(urlPath))); return st.isDirectory() ? fs.statSync(path.join(web, decodeURIComponent(urlPath), 'index.html')).size : st.size; }
74 catch { return 'not found'.length; }
75}
76
77async function freshPage(tree) {
78 const ctx = await browser.newContext();
79 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch { /* — */ } });
80 const page = await ctx.newPage();
81 await page.goto(tree.srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
82 await page.evaluate(async () => {
83 const o = await navigator.storage.getDirectory();
84 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(); };
85 await w('app.js', 'const x = {a:1}\n');
86 await w('notes.md', '# notes\n');
87 });
88 return { ctx, page };
89}
90const openIde = async (page, tree) => {
91 await page.goto(tree.srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
92 await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
93};
94const host = page => page.evaluate(async () => !!(await (await import('/js/ide.js')).loadExt()));
95async function installFile(page, name, bytes, opts = {}) {
96 return page.evaluate(async ({ name, b64, opts }) => {
97 const bin = atob(b64);
98 const u8 = new Uint8Array(bin.length);
99 for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
100 const h = await (await import('/js/ide.js')).loadExt();
101 const rec = await h.install(new File([u8], name), opts);
102 return rec.id;
103 }, { name, b64: Buffer.from(bytes).toString('base64'), opts });
104}
105
106// la página medida: cada petición, hasta que todo queda quieto
107async function measure(ctx, page, steps) {
108 const reqs = [];
109 let last = Date.now(), inflight = 0;
110 const onReq = r => { reqs.push(r.url()); inflight++; last = Date.now(); };
111 const onDone = () => { inflight--; last = Date.now(); };
112 ctx.on('request', onReq); ctx.on('requestfinished', onDone); ctx.on('requestfailed', onDone);
113 await steps();
114 await until(() => inflight <= 0 && Date.now() - last > 1500, { timeout: 30000, every: 100 });
115 ctx.off('request', onReq); ctx.off('requestfinished', onDone); ctx.off('requestfailed', onDone);
116 return reqs;
117}
118
119function summarize(tree, reqs) {
120 const origin = tree.srv.codeOrigin;
121 const own = [], cdn = [], sandbox = [];
122 for (const u of reqs) {
123 if (u.startsWith('data:') || u.startsWith('blob:')) continue;
124 const x = new URL(u);
125 if (x.origin === origin) own.push(x.pathname + x.search);
126 else if (x.hostname === 'localhost') sandbox.push(x.pathname);
127 else cdn.push(x.origin + x.pathname);
128 }
129 const bytes = own.reduce((n, p) => n + sizeOf(tree.web, p.split('?')[0]), 0);
130 return { own: own.sort(), cdn: cdn.sort(), sandbox, bytes };
131}
132
133const diff = (a, b) => {
134 const count = l => l.reduce((m, x) => m.set(x, (m.get(x) || 0) + 1), new Map());
135 const ca = count(a), cb = count(b), out = [];
136 for (const k of new Set([...a, ...b])) { const d = (ca.get(k) || 0) - (cb.get(k) || 0); if (d) out.push((d > 0 ? '+' : '') + d + ' ' + k); }
137 return out;
138};
139
140async function compare(label, run, budget) {
141 const r = {};
142 for (const k of ['tip', 'now']) r[k] = summarize(trees[k], await run(trees[k], k));
143 const d = diff(r.now.own, r.tip.own);
144 const l2 = r.now.own.filter(p => /^\/vendor\/x2\/|^\/js\/ext2\//.test(p));
145 ok(`${label}: nothing from level 2 (vendor, js/ext2) and nothing from the sandbox site`, !l2.length && !r.now.sandbox.length, [...l2, ...r.now.sandbox].join(' '));
146 ok(`${label}: the same ${r.tip.own.length} requests to Code’s site as the tip`, !d.length, d.slice(0, 6).join(' · '));
147 const dc = diff(r.now.cdn, r.tip.cdn);
148 ok(`${label}: the same ${r.tip.cdn.length} requests elsewhere (Monaco’s CDN) as the tip`, !dc.length, dc.slice(0, 4).join(' · '));
149 const delta = r.now.bytes - r.tip.bytes;
150 const grown = [...new Set(r.now.own.map(p => p.split('?')[0]))]
151 .map(p => [p, sizeOf(trees.now.web, p) - sizeOf(trees.tip.web, p)]).filter(([, n]) => n).sort((a, b) => b[1] - a[1]);
152 ok(`${label}: Code’s bytes within +${budget >= 2048 ? budget / 1024 + ' KB' : '1 KB'} of the tip (${r.tip.bytes} → ${r.now.bytes}, ${delta >= 0 ? '+' : ''}${delta})`, delta <= budget,
153 grown.slice(0, 8).map(([p, n]) => `${p} ${n > 0 ? '+' : ''}${n}`).join(' · '));
154 return r;
155}
156
157// ── 1. sin extensiones ──
158await compare('1 no extensions', async tree => {
159 const { ctx, page } = await freshPage(tree);
160 const reqs = await measure(ctx, page, async () => {
161 await openIde(page, tree);
162 await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
163 });
164 await ctx.close();
165 return reqs;
166}, BUDGET[1]);
167
168// ── 2. solo nivel 1: un tema instalado y elegido ──
169await compare('2 level 1 only', async tree => {
170 const { ctx, page } = await freshPage(tree);
171 await openIde(page, tree);
172 await host(page);
173 const id = await installFile(page, 'elf-theme.vsix', theme);
174 await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const t = h.themes().find(x => x.ext === id); await h.setTheme(t.id); }, id);
175 const reqs = await measure(ctx, page, async () => {
176 await openIde(page, tree);
177 await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
178 });
179 await ctx.close();
180 return reqs;
181}, BUDGET[2]);
182
183// ── 3. una extensión con código instalada, con el código apagado ──
184const runsOff = {};
185await compare('3 code extension installed, its code off', async (tree, k) => {
186 const { ctx, page } = await freshPage(tree);
187 await openIde(page, tree);
188 await host(page);
189 if (k === 'now') {
190 const id = await installFile(page, 'prettier.vsix', prettier, { withCode: true });
191 await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns(id, false); }, id);
192 runsOff.rec = await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const r = h.list().find(e => e.id === id); return { code: !!r.code, runs: r.runs }; }, id);
193 // el recinto que arrancó al instalarla se desmonta antes de medir
194 await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')), { timeout: 30000 });
195 } else await installFile(page, 'prettier.vsix', prettier);
196 const reqs = await measure(ctx, page, async () => {
197 await openIde(page, tree);
198 await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
199 });
200 await ctx.close();
201 return reqs;
202}, BUDGET[3]);
203ok('3 premise: the extension was installed with its code, and the code is off', runsOff.rec?.code === true && runsOff.rec?.runs === false, JSON.stringify(runsOff.rec));
204
205// ── 4. el panel abierto y una búsqueda hecha ──
206const fake = (name, extra) => ({ namespace: 'elffuss-test', name, version: '1.0.0', keywords: ['elffuss-bytes'], published: null,
207 manifest: { name, publisher: 'elffuss-test', version: '1.0.0', displayName: 'Bytes ' + name, engines: { vscode: '^1.80.0' }, ...extra } });
208const fakes = [
209 fake('web', { browser: './web.js', contributes: { commands: [{ command: 'b.x', title: 'X' }] } }),
210 fake('node', { main: './out.js' }),
211 fake('theme', { contributes: { themes: [{ label: 'T', uiTheme: 'vs-dark', path: './t.json' }] } }),
212];
213await compare('4 the panel open and a search done', async tree => {
214 const { ctx, page } = await freshPage(tree);
215 await mockOpenVsx(ctx, fakes);
216 const reqs = await measure(ctx, page, async () => {
217 await openIde(page, tree);
218 await page.click('#act-ext');
219 await page.waitForSelector('#ext-q');
220 await page.fill('#ext-q', 'elffuss-bytes');
221 await page.press('#ext-q', 'Enter');
222 await page.waitForFunction(() => document.querySelectorAll('#ext-results .ext-row').length === 3, null, { timeout: 15000 });
223 });
224 await ctx.close();
225 return reqs;
226}, BUDGET[4]);
227
228// ── 5. con el código encendido: el bundle una vez, verificado, y de la caché después ──
229{
230 const { ctx, page } = await freshPage(trees.now);
231 await openIde(page, trees.now);
232 await host(page);
233 const before = now.requests.length;
234 const id = await installFile(page, 'prettier.vsix', prettier, { withCode: true });
235 const st = await until(() => page.evaluate(async () => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' || s.state === 'error' ? s.state : null; }), { timeout: 90000 });
236 const manifest = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
237 const vendor = now.requests.slice(before).map(r => r.url.split('?')[0]).filter(u => u.startsWith('/vendor/x2/'));
238 const want = manifest.files.map(f => `/vendor/x2/${manifest.buildId}/${f.name}.gz`).sort();
239 ok('5 code on: the sandbox runs on the verified bundle', st === 'running', String(st));
240 ok('5 the manifest’s three files, once each, from its buildId', JSON.stringify(vendor.sort()) === JSON.stringify(want), vendor.join(' '));
241 const before2 = now.requests.length;
242 await openIde(page, trees.now);
243 const st2 = await until(() => page.evaluate(async () => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' || s.state === 'error' ? s.state : null; }), { timeout: 90000 });
244 const again = now.requests.slice(before2).map(r => r.url.split('?')[0]).filter(u => u.startsWith('/vendor/x2/'));
245 ok('5 after a reload the sandbox runs again and the server is not asked for the bundle again (HTTP cache)', st2 === 'running' && again.length === 0, `${st2}; ${again.join(' ')}`);
246 await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); await h.uninstall(id); }, id);
247 ok('5 uninstalling it takes the sandbox down', !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')))));
248 await ctx.close();
249}
250
251await browser.close();
252await now.close();
253await tip.close();
254fs.rmSync(tmp, { recursive: true, force: true });
255console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
256process.exit(fails ? 1 : 0);