| 1 | // Lo que una extensión hará de verdad en Code, dicho en llano y en una línea, |
| 2 | // antes de instalarla y después. Nada de términos internos (los nombres de |
| 3 | // las contribuciones, «main/browser», «host de extensiones»): el usuario ve |
| 4 | // qué funciona, qué no, y si lo que no funciona llegará o no. |
| 5 | // |
| 6 | // Entrada: los «hechos» de una extensión (del package.json de Open VSX antes de |
| 7 | // instalar, o del registro ya instalado; panel.js los arma): |
| 8 | // hasCode, browserEntry, categories, sizes {clave de contribución: cuántas}, |
| 9 | // webviews, ignored [{key}], themes [nombre], highlight [{name, exts}], |
| 10 | // settingsOnly [nombre], snippets [{name, count|null}] |
| 11 | import { tx } from './i18n.js'; |
| 12 | import { uiLang } from '../i18n.js'; |
| 13 | |
| 14 | export function listaO(xs) { |
| 15 | const v = [...new Set(xs.filter(Boolean))]; |
| 16 | try { return new Intl.ListFormat(uiLang(), { type: 'disjunction' }).format(v); } catch { return v.join(', '); } |
| 17 | } |
| 18 | export function lista(xs) { |
| 19 | const v = [...new Set(xs.filter(Boolean))]; |
| 20 | try { return new Intl.ListFormat(uiLang(), { type: 'conjunction' }).format(v); } catch { return v.join(', '); } |
| 21 | } |
| 22 | export const esTexto = x => typeof x === 'string' && !!x.trim() && !/^%[^%\s]+%$/.test(x); |
| 23 | const corta = (xs, n = 4) => (xs.length > n ? [...xs.slice(0, n), tx('andMore', { n: xs.length - n })] : xs); |
| 24 | |
| 25 | // Categorías de Open VSX que hablan de una función que hace su código. |
| 26 | const POR_CATEGORIA = { |
| 27 | Formatters: 'fFormat', Linters: 'fLint', Debuggers: 'fDebug', Visualization: 'fPreview', Notebooks: 'fNotebooks', |
| 28 | Testing: 'fTesting', 'SCM Providers': 'fScm', 'Data Science': 'fData', 'Machine Learning': 'fAI', AI: 'fAI', Chat: 'fAI', |
| 29 | Keymaps: 'fKeys', Education: null, Other: null, Themes: null, Snippets: null, 'Programming Languages': null, 'Language Packs': 'fLangPack', |
| 30 | Azure: 'fCloud', 'Extension Packs': null, |
| 31 | }; |
| 32 | // Contribuciones que necesitan el código de la extensión, en palabras llanas. |
| 33 | const POR_CLAVE = { |
| 34 | commands: 'fCommands', menus: 'fCommands', submenus: 'fCommands', keybindings: 'fKeys', customEditors: 'fPreview', |
| 35 | views: 'fPanels', viewsContainers: 'fPanels', viewsWelcome: 'fPanels', debuggers: 'fDebug', breakpoints: 'fDebug', |
| 36 | taskDefinitions: 'fTasks', notebooks: 'fNotebooks', notebookRenderer: 'fNotebooks', configuration: 'fSettings', |
| 37 | jsonValidation: 'fJsonCheck', semanticTokenTypes: 'fSemantic', semanticTokenScopes: 'fSemantic', semanticTokenModifiers: 'fSemantic', |
| 38 | iconThemes: 'fIcons', productIconThemes: 'fIcons', terminal: 'fTerminal', chatParticipants: 'fAI', languageModelTools: 'fAI', |
| 39 | mcpServerDefinitionProviders: 'fAI', authentication: 'fAccounts', walkthroughs: 'fWalk', statusBarItems: 'fStatus', |
| 40 | codeActions: 'fCodeActions', typescriptServerPlugins: 'fLangServer', problemMatchers: 'fTasks', problemPatterns: 'fTasks', |
| 41 | resourceLabelFormatters: null, configurationDefaults: null, remoteHelp: null, colors: null, icons: 'fIcons', |
| 42 | }; |
| 43 | // Lo que ni con la siguiente versión funcionaría aquí: ventanas propias |
| 44 | // (vistas web, editores a medida), depuradores, terminales, cuadernos. |
| 45 | const NUNCA = new Set(['customEditors', 'notebookRenderer', 'notebooks', 'debuggers', 'terminal', 'views', 'viewsContainers']); |
| 46 | const DECLARATIVAS = new Set(['Themes', 'Snippets', 'Programming Languages']); |
| 47 | |
| 48 | // Funciones que no funcionan, en llano y sin repetir. |
| 49 | export function missingFeatures(f) { |
| 50 | const claves = []; |
| 51 | // las categorías hablan de lo que hace su código: sin código no falta nada |
| 52 | // (un paquete de snippets que se etiqueta «Machine Learning» no deja de funcionar) |
| 53 | if (f.hasCode) for (const c of f.categories || []) if (POR_CATEGORIA[c]) claves.push(POR_CATEGORIA[c]); |
| 54 | const principales = [...new Set(claves)]; |
| 55 | for (const i of f.ignored || []) { |
| 56 | const k = Object.hasOwn(POR_CLAVE, i.key) ? POR_CLAVE[i.key] : 'fOther'; |
| 57 | if (k) claves.push(k); |
| 58 | } |
| 59 | return { principales: principales.map(k => tx(k)), todas: [...new Set(claves)].map(k => tx(k)) }; |
| 60 | } |
| 61 | |
| 62 | // Lo principal que no funciona: lo que dicen sus categorías o, si no dicen |
| 63 | // nada, sus funciones concretas; «otras funciones» sola no explica nada. |
| 64 | function loPrincipal(principales, faltan) { |
| 65 | const concretas = faltan.filter(x => x !== tx('fOther')); |
| 66 | return lista((principales.length ? principales : concretas.length ? concretas : [tx('fOwn')]).slice(0, 3)); |
| 67 | } |
| 68 | |
| 69 | // ── de un package.json analizado (vsix.js analyzeManifest) o de un registro |
| 70 | // instalado a los «hechos» de arriba. `h` es el host de extensiones (host.js) |
| 71 | // o algo con la misma forma: builtinLanguage, grammarSkippedFor, languageName, |
| 72 | // languageExtensions. Así el panel, las pruebas y el generador de la lista de |
| 73 | // populares (tests/ext_popular_build.mjs) dicen lo mismo. |
| 74 | const BONITOS = { |
| 75 | javascript: 'JavaScript', typescript: 'TypeScript', javascriptreact: 'JavaScript React', typescriptreact: 'TypeScript React', |
| 76 | html: 'HTML', css: 'CSS', scss: 'SCSS', less: 'Less', json: 'JSON', jsonc: 'JSON', vue: 'Vue', python: 'Python', markdown: 'Markdown', |
| 77 | shellscript: 'Shell', go: 'Go', rust: 'Rust', java: 'Java', php: 'PHP', ruby: 'Ruby', csharp: 'C#', cpp: 'C++', c: 'C', yaml: 'YAML', |
| 78 | }; |
| 79 | export function languageName(h, id, langs = []) { |
| 80 | return langs.find(l => l.id === id && esTexto(l.name))?.name || h?.languageName?.(id) || BONITOS[id] || id; |
| 81 | } |
| 82 | export function languageExts(h, id, langs = []) { |
| 83 | const propias = langs.filter(l => l.id === id).flatMap(l => l.extensions || []); |
| 84 | return [...new Set(propias.length ? propias : h?.languageExtensions?.(id) || [])]; |
| 85 | } |
| 86 | function facts(h, base, { themes = [], grammarLangs = [], langs = [], snippets = [] }) { |
| 87 | const salta = l => !!h?.grammarSkippedFor?.(l); |
| 88 | const deSerie = id => !!h?.builtinLanguage?.(id); |
| 89 | const conGram = [...new Set(grammarLangs.filter(l => l && !salta(l)))]; |
| 90 | // snippets de un lenguaje que Code no tiene (javascriptreact, vue…) no |
| 91 | // saldrían nunca: ni se cuentan ni se prometen. Y un mismo fichero que sirve |
| 92 | // a varios lenguajes se cuenta una vez. |
| 93 | const existe = id => langs.some(l => l.id === id) || !!h?.languageName?.(id) || deSerie(id); |
| 94 | const porLang = new Map(); |
| 95 | const vistos = new Set(); |
| 96 | for (const s of snippets.filter(x => existe(x.language))) { |
| 97 | const n = !Number.isFinite(s.count) ? NaN : s.key && vistos.has(s.key) ? 0 : s.count; |
| 98 | if (s.key) vistos.add(s.key); |
| 99 | porLang.set(s.language, (porLang.has(s.language) ? porLang.get(s.language) : 0) + n); |
| 100 | } |
| 101 | return { |
| 102 | ...base, themes, |
| 103 | highlight: conGram.map(id => ({ id, name: languageName(h, id, langs), exts: languageExts(h, id, langs) })), |
| 104 | settingsOnly: langs.filter(l => l.config && !deSerie(l.id) && !conGram.includes(l.id)).map(l => languageName(h, l.id, langs)), |
| 105 | keepsBuiltin: [...new Set(grammarLangs.filter(l => l && salta(l)))].map(id => languageName(h, id, langs)), |
| 106 | snippets: [...porLang].map(([id, n]) => ({ id, name: languageName(h, id, langs), count: Number.isFinite(n) ? n : null })), |
| 107 | }; |
| 108 | } |
| 109 | export function factsFromManifest(h, a) { |
| 110 | return facts(h, { hasCode: a.hasCode, browserEntry: a.browserEntry, categories: a.categories || [], sizes: a.sizes || {}, webviews: a.webviews, ignored: a.ignored || [], pack: a.pack || [] }, { |
| 111 | themes: a.themeLabels || [], grammarLangs: a.grammarLangs || [], langs: a.languageList || [], |
| 112 | snippets: (a.snippetLangs || []).map(language => ({ language, count: null })), |
| 113 | }); |
| 114 | } |
| 115 | export function factsFromRecord(h, e) { |
| 116 | // registros de antes de guardar categorías: se asume que lo que se aplica es lo principal |
| 117 | const categories = e.categories || ['Programming Languages']; |
| 118 | return facts(h, { hasCode: e.hasCode, browserEntry: !!e.browserEntry, categories, sizes: e.sizes || {}, webviews: e.webviews, ignored: e.ignored || [], pack: e.pack || [] }, { |
| 119 | themes: (e.themes || []).map(t => t.label), grammarLangs: (e.grammars || []).map(g => g.language ?? null), |
| 120 | langs: (e.languages || []).map(l => ({ id: l.id, name: l.aliases?.[0], extensions: l.extensions || [], config: !!l.configKey })), |
| 121 | snippets: (e.snippets || []).map(s => ({ language: s.language, key: s.key, count: Number.isFinite(s.count) ? s.count : null })), |
| 122 | }); |
| 123 | } |
| 124 | |
| 125 | // ¿Hace algo al instalarla? Lo que decide el filtro «Solo las que funcionan en |
| 126 | // Code» del panel: entera o en parte (lo principal funciona). Las que solo |
| 127 | // funcionarían por su código, o en las que lo principal es su código y solo |
| 128 | // quedaría un resto (unos snippets de una extensión de depurar), no. |
| 129 | export const works = v => v.kind === 'full' || v.kind === 'partial'; |
| 130 | |
| 131 | export function describe(f) { |
| 132 | const partes = []; // { tipo, texto } |
| 133 | const themes = f.themes || [], highlight = f.highlight || [], settingsOnly = f.settingsOnly || [], snippets = f.snippets || []; |
| 134 | // el package.json de Open VSX puede traer los nombres sin traducir (%clave%): |
| 135 | // entonces se cuentan en vez de nombrarlos |
| 136 | const conNombre = themes.filter(esTexto); |
| 137 | if (themes.length) partes.push({ tipo: 'theme', texto: conNombre.length === themes.length ? tx('pThemes', { n: themes.length, list: lista(corta(themes.map(t => tx('quoted', { x: t })))) }) : tx('pThemesCount', { n: themes.length }) }); |
| 138 | if (highlight.length) partes.push({ tipo: 'highlight', texto: tx('pHighlight', { list: lista(corta(highlight.map(h => h.name))) }) }); |
| 139 | if (settingsOnly.length) partes.push({ tipo: 'settings', texto: tx('pSettings', { list: lista(corta(settingsOnly)) }) }); |
| 140 | if (snippets.length) { |
| 141 | const total = snippets.every(s => Number.isFinite(s.count)) ? snippets.reduce((a, s) => a + s.count, 0) : null; |
| 142 | const langs = lista(corta([...new Set(snippets.map(s => s.name))])); |
| 143 | partes.push({ tipo: 'snippets', texto: total != null ? tx('pSnippetsN', { n: total, list: langs }) : tx('pSnippets', { list: langs }) }); |
| 144 | } |
| 145 | const usable = partes.length > 0; |
| 146 | const hasCode = !!f.hasCode; |
| 147 | const sizes = f.sizes || {}; |
| 148 | const nunca = !!f.webviews || Object.keys(sizes).some(k => NUNCA.has(k)); |
| 149 | const { principales, todas } = missingFeatures(f); |
| 150 | const faltan = hasCode && !todas.length ? [tx('fOwn')] : todas; |
| 151 | // ¿lo principal es lo que hace su código? Si no se declara como tema, |
| 152 | // snippets o lenguaje; si trae ventanas propias; o si casi todo son comandos |
| 153 | const categorias = f.categories || []; |
| 154 | const codigoManda = hasCode && (!usable || !categorias.some(c => DECLARATIVAS.has(c)) || nunca || (sizes.commands || 0) >= 10); |
| 155 | const futuro = !hasCode ? null : f.browserEntry && !nunca ? 'next' : 'never'; |
| 156 | const queTraen = lista(partes.map(p => p.texto)); |
| 157 | const lineas = []; |
| 158 | let kind, verdict; |
| 159 | if (!usable) { |
| 160 | kind = hasCode ? 'code' : 'nothing'; |
| 161 | if (hasCode) { |
| 162 | verdict = tx('vMainBroken', { what: loPrincipal(principales, faltan) }); |
| 163 | lineas.push(tx(futuro === 'next' ? 'vNextVersion' : 'vNever')); |
| 164 | } else verdict = tx('nothing'); |
| 165 | } else if (!hasCode && !faltan.length) { |
| 166 | kind = 'full'; |
| 167 | verdict = tx('vFull', { list: queTraen }); |
| 168 | } else if (codigoManda) { |
| 169 | kind = 'mostlyCode'; |
| 170 | verdict = tx('vMainBroken', { what: loPrincipal(principales, faltan) }); |
| 171 | lineas.push(tx('vOnly', { list: queTraen })); |
| 172 | lineas.push(tx(futuro === 'next' ? 'vNextVersion' : 'vNever')); |
| 173 | } else { |
| 174 | kind = 'partial'; |
| 175 | verdict = tx('vPartial', { list: queTraen }); |
| 176 | lineas.push(tx(!hasCode ? 'vMissingLater' : futuro === 'next' ? 'vMissingNext' : 'vMissingNever', { list: lista(faltan) })); |
| 177 | } |
| 178 | const tipos = [...new Set(partes.map(p => p.tipo === 'settings' ? 'highlight' : p.tipo))]; |
| 179 | const soloQue = tipos.length === 1 ? { theme: 'installOnlyThemes', highlight: 'installOnlyHighlight', snippets: 'installOnlySnippets' }[tipos[0]] : 'installOnlyWorking'; |
| 180 | const button = kind === 'full' ? { key: 'install', style: 'primary', disabled: false } |
| 181 | : kind === 'partial' ? { key: soloQue, style: 'primary', disabled: false } |
| 182 | : kind === 'mostlyCode' ? { key: soloQue, style: 'ghost', disabled: false } |
| 183 | : { key: kind === 'code' ? 'notHere' : 'nothingHere', style: 'ghost', disabled: true }; |
| 184 | return { kind, verdict, lines: lineas, button, future: futuro, usable, missing: faltan, parts: partes }; |
| 185 | } |