| 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 | |
| 8 | export const BASE = 'https://open-vsx.org'; |
| 9 | const ORIGENES_ICONO = new Set(['https://open-vsx.org', 'https://openvsx.eclipsecontent.org']); |
| 10 | export const BIG = 25 * 1024 * 1024; // por encima, se pregunta antes de bajar |
| 11 | const MAX = 120 * 1024 * 1024; // tope duro de un .vsix |
| 12 | |
| 13 | // `code` lo traduce el panel; `status` y `mb` son datos para el mensaje. |
| 14 | class OpenVsxError extends Error { |
| 15 | constructor(msg, code, extra = {}) { super(msg); this.code = code; Object.assign(this, extra); } |
| 16 | } |
| 17 | |
| 18 | async function getJson(url, signal) { |
| 19 | let res; |
| 20 | try { res = await fetch(url, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); } |
| 21 | catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); } |
| 22 | if (res.status === 429) throw new OpenVsxError('Open VSX está limitando peticiones', 'rate'); |
| 23 | if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, res.status === 404 ? 'notfound' : 'http', { status: res.status }); |
| 24 | return res.json(); |
| 25 | } |
| 26 | // solo URLs de la propia API (las de ficheros redirigen después a su CDN) |
| 27 | function deOpenVsx(u) { |
| 28 | try { const x = new URL(u); return x.origin === BASE ? x.href : null; } catch { return null; } |
| 29 | } |
| 30 | const seg = s => encodeURIComponent(String(s)); |
| 31 | |
| 32 | // «…/api/ns/name/<plataforma>/<versión>/file/x.vsix» → la plataforma, o '' |
| 33 | // (las publicadas por plataforma no tienen package.json en la ruta sin ella) |
| 34 | function plataformaDe(download) { |
| 35 | try { |
| 36 | const p = new URL(download).pathname.split('/').filter(Boolean); |
| 37 | return p[0] === 'api' && p.length === 7 && p[5] === 'file' && /^[a-z0-9-]+$/.test(p[3]) ? p[3] : ''; |
| 38 | } catch { return ''; } |
| 39 | } |
| 40 | const resumen = e => ({ |
| 41 | namespace: String(e.namespace || ''), name: String(e.name || ''), version: String(e.version || ''), |
| 42 | platform: plataformaDe(e.files?.download), |
| 43 | displayName: String(e.displayName || e.name || ''), description: String(e.description || ''), |
| 44 | downloadCount: Number(e.downloadCount) || 0, verified: !!e.verified, deprecated: !!e.deprecated, |
| 45 | icon: (() => { try { const u = new URL(e.files?.icon); return ORIGENES_ICONO.has(u.origin) ? u.href : null; } catch { return null; } })(), |
| 46 | }); |
| 47 | |
| 48 | export async function search(query, { category = '', offset = 0, size = 20, signal } = {}) { |
| 49 | const q = new URLSearchParams({ size: String(size), offset: String(offset) }); |
| 50 | if (query) q.set('query', query); |
| 51 | if (category) q.set('category', category); |
| 52 | if (query) q.set('sortBy', 'relevance'); |
| 53 | else { q.set('sortBy', 'downloadCount'); q.set('sortOrder', 'desc'); } |
| 54 | const j = await getJson(`${BASE}/api/-/search?${q}`, signal); |
| 55 | return { total: Number(j.totalSize) || 0, offset: Number(j.offset) || 0, items: (j.extensions || []).map(resumen) }; |
| 56 | } |
| 57 | |
| 58 | export async function metadata(namespace, name, version = '', { signal } = {}) { |
| 59 | const j = await getJson(`${BASE}/api/${seg(namespace)}/${seg(name)}${version ? '/' + seg(version) : ''}`, signal); |
| 60 | if (j.error) throw new OpenVsxError(String(j.error), 'notfound'); |
| 61 | return { |
| 62 | ...resumen(j), license: String(j.license || ''), categories: Array.isArray(j.categories) ? j.categories.map(String) : [], |
| 63 | files: Object.fromEntries(['download', 'sha256', 'manifest', 'license', 'readme'].map(k => [k, deOpenVsx(j.files?.[k])])), |
| 64 | homepage: String(j.homepage || ''), repository: String(j.repository || ''), |
| 65 | }; |
| 66 | } |
| 67 | |
| 68 | // package.json publicado: sirve para decir qué aplicaría sin bajar el .vsix. |
| 69 | export async function manifest(meta, { signal } = {}) { |
| 70 | if (!meta.files.manifest) throw new OpenVsxError('esta versión no publica su package.json', 'notfound'); |
| 71 | return getJson(meta.files.manifest, signal); |
| 72 | } |
| 73 | |
| 74 | // El package.json de un resultado de búsqueda, sin pedir antes sus metadatos: |
| 75 | // una sola petición por fila para decir qué haría antes de instalarla. |
| 76 | export function manifestOf({ namespace, name, version, platform = '' }, { signal } = {}) { |
| 77 | return getJson(`${BASE}/api/${seg(namespace)}/${seg(name)}/${platform ? seg(platform) + '/' : ''}${seg(version)}/file/package.json`, signal); |
| 78 | } |
| 79 | |
| 80 | export async function text(url, { signal, max = 200_000 } = {}) { |
| 81 | const u = deOpenVsx(url); |
| 82 | if (!u) throw new OpenVsxError('URL fuera de Open VSX', 'http'); |
| 83 | const res = await fetch(u, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); |
| 84 | if (!res.ok) throw new OpenVsxError(`Open VSX respondió ${res.status}`, 'http', { status: res.status }); |
| 85 | return (await res.text()).slice(0, max); |
| 86 | } |
| 87 | |
| 88 | export async function sha256Hex(bytes) { |
| 89 | const d = await crypto.subtle.digest('SHA-256', bytes); |
| 90 | return [...new Uint8Array(d)].map(b => b.toString(16).padStart(2, '0')).join(''); |
| 91 | } |
| 92 | |
| 93 | // Baja el .vsix y comprueba su SHA-256 contra la que publica Open VSX. |
| 94 | // `confirmLarge(mb)` decide si seguir con uno de más de 25 MB. |
| 95 | // `requireHash` (instalar para ejecutar su código): sin suma publicada, o si |
| 96 | // la publicada no se pudo leer, NO se instala (falla cerrado). |
| 97 | export async function download(meta, { onProgress = () => {}, confirmLarge = async () => false, signal, requireHash = false } = {}) { |
| 98 | if (!meta.files.download) throw new OpenVsxError('esta versión no se puede descargar', 'notfound'); |
| 99 | if (requireHash && !meta.files.sha256) throw new OpenVsxError('Open VSX no publica la suma SHA-256 de esta versión', 'nosha'); |
| 100 | const ctl = new AbortController(); |
| 101 | signal?.addEventListener('abort', () => ctl.abort(), { once: true }); |
| 102 | let res; |
| 103 | try { res = await fetch(meta.files.download, { signal: ctl.signal, credentials: 'omit', referrerPolicy: 'no-referrer' }); } |
| 104 | catch (e) { if (e.name === 'AbortError') throw e; throw new OpenVsxError(e.message || 'sin red', 'net'); } |
| 105 | if (res.status === 429) throw new OpenVsxError('Open VSX está limitando peticiones', 'rate'); |
| 106 | if (!res.ok) throw new OpenVsxError(`descarga: ${res.status}`, res.status === 404 ? 'notfound' : 'http', { status: res.status }); |
| 107 | const total = Number(res.headers.get('content-length')) || 0; |
| 108 | if (total > MAX) { ctl.abort(); throw new OpenVsxError(`demasiado grande (${(total / 1048576).toFixed(0)} MB)`, 'big', { mb: Math.round(total / 1048576) }); } |
| 109 | if (total > BIG && !(await confirmLarge(Math.round(total / 1048576)))) { ctl.abort(); throw new OpenVsxError('cancelado', 'cancel'); } |
| 110 | const reader = res.body.getReader(); |
| 111 | const trozos = []; |
| 112 | let n = 0; |
| 113 | for (;;) { |
| 114 | const { done, value } = await reader.read(); |
| 115 | if (done) break; |
| 116 | n += value.length; |
| 117 | if (n > MAX) { ctl.abort(); throw new OpenVsxError('demasiado grande', 'big', { mb: Math.round(n / 1048576) }); } |
| 118 | trozos.push(value); |
| 119 | onProgress(n, total); |
| 120 | } |
| 121 | const bytes = new Uint8Array(n); |
| 122 | let o = 0; |
| 123 | for (const t of trozos) { bytes.set(t, o); o += t.length; } |
| 124 | const sha = await sha256Hex(bytes); |
| 125 | let publicada = null; |
| 126 | if (meta.files.sha256) { |
| 127 | try { publicada = (await text(meta.files.sha256, { signal: ctl.signal, max: 200 })).trim().split(/\s+/)[0].toLowerCase(); } |
| 128 | catch { publicada = null; } |
| 129 | if (!/^[0-9a-f]{64}$/.test(publicada || '')) publicada = null; // no es una suma: como si no la publicara |
| 130 | } |
| 131 | if (requireHash && !publicada) throw new OpenVsxError('no se pudo leer la suma SHA-256 publicada', 'nosha'); |
| 132 | if (publicada && publicada !== sha) throw new OpenVsxError('la suma SHA-256 no coincide con la publicada', 'sha'); |
| 133 | return { bytes, sha256: sha, verified: !!publicada }; |
| 134 | } |