Elffuss BraidHub

utopia-ia/elffuss-code public

86f3b789392d · 6.1 KiBRawPermalink
1// Cliente de Open VSX (open-vsx.org, de la Eclipse Foundation). La API, los
2// ficheros sueltos y los .vsix mandan Access-Control-Allow-Origin: *, así que
3// el navegador habla con Open VSX directamente: sin proxy, y nada de tu
4// proyecto sale nunca hacia allí — solo lo que buscas y lo que instalas.
5// (El Marketplace de Microsoft no se usa: sus términos solo permiten sus
6// productos.)
7
8export const BASE = 'https://open-vsx.org';
9const ORIGENES_ICONO = new Set(['https://open-vsx.org', 'https://openvsx.eclipsecontent.org']);
10export const BIG = 25 * 1024 * 1024; // por encima, se pregunta antes de bajar
11const MAX = 120 * 1024 * 1024; // tope duro de un .vsix
12
13class OpenVsxError extends Error {
14 constructor(msg, code) { super(msg); this.code = code; }
15}
16
17async function getJson(url, signal) {
18 let res;
19 try { res = await fetch(url, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); }
20 catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); }
21 if (res.status === 429) throw new OpenVsxError('Open VSX está limitando peticiones', 'rate');
22 if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, res.status === 404 ? 'notfound' : 'http');
23 return res.json();
24}
25// solo URLs de la propia API (las de ficheros redirigen después a su CDN)
26function deOpenVsx(u) {
27 try { const x = new URL(u); return x.origin === BASE ? x.href : null; } catch { return null; }
28}
29const seg = s => encodeURIComponent(String(s));
30
31const resumen = e => ({
32 namespace: String(e.namespace || ''), name: String(e.name || ''), version: String(e.version || ''),
33 displayName: String(e.displayName || e.name || ''), description: String(e.description || ''),
34 downloadCount: Number(e.downloadCount) || 0, verified: !!e.verified, deprecated: !!e.deprecated,
35 icon: (() => { try { const u = new URL(e.files?.icon); return ORIGENES_ICONO.has(u.origin) ? u.href : null; } catch { return null; } })(),
36});
37
38export async function search(query, { category = '', offset = 0, size = 20, signal } = {}) {
39 const q = new URLSearchParams({ size: String(size), offset: String(offset) });
40 if (query) q.set('query', query);
41 if (category) q.set('category', category);
42 if (query) q.set('sortBy', 'relevance');
43 else { q.set('sortBy', 'downloadCount'); q.set('sortOrder', 'desc'); }
44 const j = await getJson(`${BASE}/api/-/search?${q}`, signal);
45 return { total: Number(j.totalSize) || 0, offset: Number(j.offset) || 0, items: (j.extensions || []).map(resumen) };
46}
47
48export async function metadata(namespace, name, version = '', { signal } = {}) {
49 const j = await getJson(`${BASE}/api/${seg(namespace)}/${seg(name)}${version ? '/' + seg(version) : ''}`, signal);
50 if (j.error) throw new OpenVsxError(String(j.error), 'notfound');
51 return {
52 ...resumen(j), license: String(j.license || ''), categories: Array.isArray(j.categories) ? j.categories.map(String) : [],
53 files: Object.fromEntries(['download', 'sha256', 'manifest', 'license', 'readme'].map(k => [k, deOpenVsx(j.files?.[k])])),
54 homepage: String(j.homepage || ''), repository: String(j.repository || ''),
55 };
56}
57
58// package.json publicado: sirve para decir qué aplicaría sin bajar el .vsix.
59export async function manifest(meta, { signal } = {}) {
60 if (!meta.files.manifest) throw new OpenVsxError('esta versión no publica su package.json', 'notfound');
61 return getJson(meta.files.manifest, signal);
62}
63
64export async function text(url, { signal, max = 200_000 } = {}) {
65 const u = deOpenVsx(url);
66 if (!u) throw new OpenVsxError('URL fuera de Open VSX', 'http');
67 const res = await fetch(u, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' });
68 if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, 'http');
69 return (await res.text()).slice(0, max);
70}
71
72export async function sha256Hex(bytes) {
73 const d = await crypto.subtle.digest('SHA-256', bytes);
74 return [...new Uint8Array(d)].map(b => b.toString(16).padStart(2, '0')).join('');
75}
76
77// Baja el .vsix y comprueba su SHA-256 contra la que publica Open VSX.
78// `confirmLarge(mb)` decide si seguir con uno de más de 25 MB.
79export async function download(meta, { onProgress = () => {}, confirmLarge = async () => false, signal } = {}) {
80 if (!meta.files.download) throw new OpenVsxError('esta versión no se puede descargar', 'notfound');
81 const ctl = new AbortController();
82 signal?.addEventListener('abort', () => ctl.abort(), { once: true });
83 let res;
84 try { res = await fetch(meta.files.download, { signal: ctl.signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); }
85 catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); }
86 if (res.status === 429) throw new OpenVsxError('Open VSX está limitando peticiones', 'rate');
87 if (!res.ok) throw new OpenVsxError(`descarga: ${res.status}`, 'http');
88 const total = Number(res.headers.get('content-length')) || 0;
89 if (total > MAX) { ctl.abort(); throw new OpenVsxError(`demasiado grande (${(total / 1048576).toFixed(0)} MB)`, 'big'); }
90 if (total > BIG && !(await confirmLarge(Math.round(total / 1048576)))) { ctl.abort(); throw new OpenVsxError('cancelado', 'cancel'); }
91 const reader = res.body.getReader();
92 const trozos = [];
93 let n = 0;
94 for (;;) {
95 const { done, value } = await reader.read();
96 if (done) break;
97 n += value.length;
98 if (n > MAX) { ctl.abort(); throw new OpenVsxError('demasiado grande', 'big'); }
99 trozos.push(value);
100 onProgress(n, total);
101 }
102 const bytes = new Uint8Array(n);
103 let o = 0;
104 for (const t of trozos) { bytes.set(t, o); o += t.length; }
105 const sha = await sha256Hex(bytes);
106 let publicada = null;
107 if (meta.files.sha256) {
108 try { publicada = (await text(meta.files.sha256, { signal: ctl.signal, max: 200 })).trim().split(/\s+/)[0].toLowerCase(); }
109 catch { publicada = null; }
110 if (!/^[0-9a-f]{64}$/.test(publicada || '')) publicada = null; // no es una suma: como si no la publicara
111 }
112 if (publicada && publicada !== sha) throw new OpenVsxError('la suma SHA-256 no coincide con la publicada', 'sha');
113 return { bytes, sha256: sha, verified: !!publicada };
114}