Elffuss BraidHub

utopia-ia/elffuss-code public

main · 15.2 KiBRawPermalink
1// Builds web/js/ext/popular.json: the "Popular" list of the Extensions panel.
2// Only extensions whose main value works in Code as soon as they are installed
3// (colour themes, highlighting for a language Code does not have yet, snippet
4// packs), ordered by Open VSX downloads.
5//
6// node tests/ext_popular_build.mjs --census <extensions.tsv> [--draft] [--n 36]
7//
8// --census the static census of the whole catalog (tests/catalog_census.mjs
9// writes tests/catalog-census/extensions.tsv; that is the default)
10// --draft print every candidate with its verdict and the reason it was left
11// out, and write nothing (to curate: add an entry to TEXT or SKIP)
12// --n how many entries (36)
13//
14// What it reads, all with GET and at most one request every 400 ms: for each
15// candidate its Open VSX metadata and published package.json (and
16// package.nls.json when names are %keys%), and once Monaco 0.52.2's bundle from
17// jsdelivr, to know which languages and file extensions Code already
18// highlights. Cached in tests/.cache/popular/, so a second run is offline.
19//
20// Rules, in order:
21// 1. census: runtime=none (no code at all), works=1, declarative=1, ranked
22// 2. not a built-in language pack (vscode.*) and not in SKIP
23// 3. the panel's own verdict (web/js/ext/verdict.js) is "works in Code" (full)
24// 4. nothing it brings duplicates Code: no grammar for a language Monaco
25// already highlights, for a file extension Monaco already claims, or for
26// VS Code's id of a language Code names differently (no file of its own)
27// 5. it has a hand-written one-line description in TEXT (es and en)
28import fs from 'node:fs';
29import path from 'node:path';
30import { fileURLToPath } from 'node:url';
31import { analyzeManifest, resolveNls } from '../web/js/ext/vsix.js';
32import { describe, factsFromManifest } from '../web/js/ext/verdict.js';
33
34const HERE = path.dirname(fileURLToPath(import.meta.url));
35const ROOT = path.resolve(HERE, '..');
36const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
37const CENSUS = path.resolve(arg('--census', path.join(HERE, 'catalog-census/extensions.tsv')));
38const DRAFT = process.argv.includes('--draft');
39const N = Number(arg('--n', 36));
40const CACHE = path.join(HERE, '.cache', 'popular');
41const OUT = path.join(ROOT, 'web/js/ext/popular.json');
42const API = 'https://open-vsx.org';
43const MONACO = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs/editor/editor.main.js';
44fs.mkdirSync(CACHE, { recursive: true });
45
46// Left out on purpose, with the reason.
47const SKIP = {
48 'ms-vscode.cpptools-themes': 'the Visual Studio colours Code already has as its default dark and light themes',
49 'ms-vscode.vscode-typescript-next': 'TypeScript and JavaScript are already highlighted',
50};
51
52// One plain line per entry: what you get. Kept by hand so it says what the
53// extension is FOR, not what its package.json lists.
54const TEXT = {
55 // themes
56 'gitpod.gitpod-theme': ['Los temas de Gitpod, claro y oscuro, de tonos suaves.', 'Gitpod\'s soft light and dark themes.'],
57 'dracula-theme.theme-dracula': ['Dracula: el tema oscuro de fondo morado y colores vivos.', 'Dracula: the dark theme with a purple background and vivid colours.'],
58 'GitHub.github-vscode-theme': ['Los temas de GitHub, claros y oscuros, también de alto contraste.', 'GitHub\'s light and dark themes, high-contrast ones included.'],
59 'jdinhlife.gruvbox': ['Gruvbox: tonos cálidos y retro, en claro y en oscuro.', 'Gruvbox: warm retro tones, light and dark.'],
60 'akamud.vscode-theme-onedark': ['One Dark, el tema oscuro clásico de Atom.', 'One Dark, Atom\'s classic dark theme.'],
61 'enkia.tokyo-night': ['Tokyo Night: oscuro, con los colores de Tokio de noche.', 'Tokyo Night: dark, in the colours of Tokyo at night.'],
62 'BeardedBear.beardedtheme': ['Bearded Theme: decenas de variantes, de muy oscuras a claras.', 'Bearded Theme: dozens of variants, from very dark to light.'],
63 'sdras.night-owl': ['Night Owl: pensado para programar de noche; también en claro.', 'Night Owl: made for coding at night; a light one too.'],
64 'ahmadawais.shades-of-purple': ['Shades of Purple: morados intensos y amarillo.', 'Shades of Purple: bold purples with yellow.'],
65 'arcticicestudio.nord-visual-studio-code': ['Nord: azules fríos del Ártico, sereno y limpio.', 'Nord: cool Arctic blues, calm and clean.'],
66 'johnpapa.winteriscoming': ['Winter is Coming: azul oscuro, negro y una versión clara.', 'Winter is Coming: dark blue, black and a light one.'],
67 'wesbos.theme-cobalt2': ['Cobalt2: azul cobalto con amarillo, de Wes Bos.', 'Cobalt2: cobalt blue with yellow, by Wes Bos.'],
68 'aleksa-codes.one-dark-modern-pro': ['One Dark Modern Pro: One Dark con los colores de la interfaz actual.', 'One Dark Modern Pro: One Dark with a modern interface palette.'],
69 'metaphore.kanagawa-vscode-color-theme': ['Kanagawa: colores de la estampa japonesa La gran ola.', 'Kanagawa: colours from the Japanese print The Great Wave.'],
70 'liviuschera.noctis': ['Noctis: once temas, claros y oscuros, de colores templados.', 'Noctis: eleven light and dark themes in calm colours.'],
71 'jolaleye.horizon-theme-vscode': ['Horizon: oscuro y cálido, con rosas y naranjas.', 'Horizon: warm and dark, with pinks and oranges.'],
72 'antfu.theme-vitesse': ['Vitesse: temas sobrios en claro, oscuro y negro.', 'Vitesse: understated light, dark and black themes.'],
73 // languages Code does not have
74 'wholroyd.jinja': ['Resalta plantillas Jinja (.j2, .jinja), también dentro de HTML y YAML.', 'Highlights Jinja templates (.j2, .jinja), inside HTML and YAML too.'],
75 'mikestead.dotenv': ['Resalta los ficheros .env de variables de entorno.', 'Highlights .env files of environment variables.'],
76 'bpruitt-goddard.mermaid-markdown-syntax-highlighting': ['Resalta diagramas Mermaid (.mmd, .mermaid).', 'Highlights Mermaid diagrams (.mmd, .mermaid).'],
77 'bbenoist.Doxygen': ['Resalta ficheros de documentación Doxygen (.dox).', 'Highlights Doxygen documentation files (.dox).'],
78 'IBM.output-colorizer': ['Colorea ficheros de log (.log): fechas, niveles, errores.', 'Colours log files (.log): dates, levels, errors.'],
79 'bbenoist.Nix': ['Resalta el lenguaje Nix (.nix).', 'Highlights the Nix language (.nix).'],
80 'mrmlnc.vscode-apache': ['Resalta la configuración de Apache (.htaccess, .conf).', 'Highlights Apache configuration (.htaccess, .conf).'],
81 // snippets
82 'EricSia.pythonsnippets3': ['Snippets de Python: bucles, clases, funciones y más con un prefijo.', 'Python snippets: loops, classes, functions and more from a prefix.'],
83 'xabikos.JavaScriptSnippets': ['Snippets de JavaScript y TypeScript: imports, funciones flecha, console.log…', 'JavaScript and TypeScript snippets: imports, arrow functions, console.log…'],
84 'johnpapa.Angular2': ['Snippets de Angular: componentes, servicios y rutas en TypeScript y HTML.', 'Angular snippets: components, services and routes in TypeScript and HTML.'],
85 'eventyret.bootstrap-4-cdn-snippet': ['Snippets de Bootstrap 4: la página base con el CDN y sus componentes.', 'Bootstrap 4 snippets: the starter page with the CDN and its components.'],
86 'dannysteenman.cdk-snippets': ['Snippets de AWS CDK para Python y TypeScript.', 'AWS CDK snippets for Python and TypeScript.'],
87 'onecentlin.laravel5-snippets': ['Snippets de Laravel en PHP: rutas, modelos, consultas.', 'Laravel snippets in PHP: routes, models, queries.'],
88 'Nash.awesome-flutter-snippets': ['Snippets de Flutter en Dart: widgets y su estructura.', 'Flutter snippets in Dart: widgets and their boilerplate.'],
89 'hollowtree.vue-snippets': ['Snippets de Vue 2 en JavaScript, TypeScript y HTML.', 'Vue 2 snippets in JavaScript, TypeScript and HTML.'],
90 'HansUXdev.bootstrap5-snippets': ['Snippets de Bootstrap 5 y Font Awesome en HTML.', 'Bootstrap 5 and Font Awesome snippets in HTML.'],
91 'robole.markdown-snippets': ['Snippets de Markdown: tablas, enlaces, imágenes, listas de tareas.', 'Markdown snippets: tables, links, images, task lists.'],
92 'imgildev.vscode-tailwindcss-snippets': ['Snippets de Tailwind CSS en HTML.', 'Tailwind CSS snippets in HTML.'],
93 'donjayamanne.jquerysnippets': ['Más de 130 snippets de jQuery en JavaScript y HTML.', 'Over 130 jQuery snippets in JavaScript and HTML.'],
94};
95
96const sleep = ms => new Promise(r => setTimeout(r, ms));
97let next = 0, requests = 0;
98async function get(url, { json = true, notFound = false } = {}) {
99 const file = path.join(CACHE, encodeURIComponent(url).slice(0, 240));
100 if (fs.existsSync(file)) { const t = fs.readFileSync(file, 'utf8'); return t === '\u0000404' ? null : json ? JSON.parse(t) : t; }
101 for (let i = 1; i <= 5; i++) {
102 const wait = next - Date.now();
103 next = Math.max(Date.now(), next) + 400;
104 if (wait > 0) await sleep(wait);
105 requests++;
106 const r = await fetch(url, { headers: { 'User-Agent': 'elffuss-code-popular' } }).catch(() => null);
107 if (!r || r.status === 429 || r.status >= 500) { await sleep(5000 * i); continue; }
108 if (r.status === 404 && notFound) { fs.writeFileSync(file, '\u0000404'); return null; }
109 if (!r.ok) throw new Error(`HTTP ${r.status} ${url}`);
110 const t = await r.text();
111 fs.writeFileSync(file, t);
112 return json ? JSON.parse(t) : t;
113 }
114 throw new Error('gave up: ' + url);
115}
116
117// ── what Code already highlights: Monaco's languages and their file extensions ──
118const bundle = await get(MONACO, { json: false });
119const builtin = new Set();
120const claimed = new Set();
121for (const m of bundle.matchAll(/id:"([\w.+-]+)",extensions:\[([^\]]*)\]/g)) {
122 builtin.add(m[1]);
123 for (const x of m[2].matchAll(/"([^"]+)"/g)) claimed.add(x[1].toLowerCase());
124}
125for (const m of bundle.matchAll(/registerLanguage\(\{id:"([\w.+-]+)"/g)) builtin.add(m[1]);
126if (builtin.size < 60 || !claimed.has('.js') || !claimed.has('.json')) throw new Error(`could not read Monaco's languages from ${MONACO} (${builtin.size} found)`);
127// the panel's host, as Node sees it (no extension installed)
128const host = {
129 builtinLanguage: id => builtin.has(id),
130 grammarSkippedFor: id => id === 'json' || id === 'plaintext', // Monaco's built-ins without Monarch
131 languageName: () => null,
132 languageExtensions: () => [],
133};
134
135// ── 1. census ──
136if (!fs.existsSync(CENSUS)) throw new Error(`no census at ${CENSUS}: pass --census <extensions.tsv>`);
137const [head, ...lines] = fs.readFileSync(CENSUS, 'utf8').trim().split('\n');
138const cols = head.split('\t');
139const rows = lines.map(l => Object.fromEntries(l.split('\t').map((v, i) => [cols[i], v])));
140const candidates = rows.filter(r => r.runtime === 'none' && r.works === '1' && r.declarative === '1' && /^\d+$/.test(r.rank))
141 .sort((a, b) => a.rank - b.rank);
142console.log(`census: ${rows.length} extensions; ${candidates.length} with no code that work in Code`);
143
144// a grammar duplicates Code when its language is Monaco's, or when every file
145// extension of that language is already Monaco's
146function duplicates(pkg) {
147 const c = pkg.contributes || {};
148 const langs = Array.isArray(c.languages) ? c.languages : [];
149 const out = [];
150 for (const g of Array.isArray(c.grammars) ? c.grammars : []) {
151 const id = g?.language;
152 if (typeof id !== 'string') continue; // injections: they add to another grammar
153 if (builtin.has(id)) { out.push(id); continue; }
154 const own = langs.filter(l => l?.id === id);
155 const exts = own.flatMap(l => (Array.isArray(l.extensions) ? l.extensions : [])).map(x => String(x).toLowerCase());
156 const names = own.flatMap(l => [...(Array.isArray(l.filenames) ? l.filenames : []), ...(Array.isArray(l.filenamePatterns) ? l.filenamePatterns : [])]);
157 if (!exts.length && !names.length) out.push(`${id} (no file of its own: VS Code's id for a language Code names differently)`);
158 // a file extension Monaco already has would be taken over (PostCSS claims .css)
159 else if (exts.some(x => claimed.has(x))) out.push(`${id} (${exts.filter(x => claimed.has(x)).join(' ')})`);
160 }
161 return out;
162}
163
164function kindOf(f) {
165 if (f.highlight.length || f.settingsOnly.length) return 'language';
166 if (f.snippets.length) return 'snippets';
167 if (f.themes.length) return 'theme';
168 return null;
169}
170
171const picked = [];
172const draft = [];
173for (const r of candidates) {
174 if (!DRAFT && picked.length >= N) break;
175 if (DRAFT && r.rank > 3000) break;
176 const why = reason => draft.push({ rank: r.rank, id: r.id, reason });
177 if (r.id.startsWith('vscode.')) { why('built-in language pack'); continue; }
178 if (SKIP[r.id]) { why('skip: ' + SKIP[r.id]); continue; }
179 const [ns, name] = [r.id.slice(0, r.id.indexOf('.')), r.id.slice(r.id.indexOf('.') + 1)];
180 const base = `${API}/api/${encodeURIComponent(ns)}/${encodeURIComponent(name)}/${encodeURIComponent(r.version)}`;
181 const meta = await get(base, { notFound: true });
182 if (!meta || meta.error) { why('no metadata'); continue; }
183 if (meta.deprecated) { why('deprecated'); continue; }
184 let pkg = await get(`${base}/file/package.json`, { notFound: true });
185 if (!pkg) { why('no package.json'); continue; }
186 if (JSON.stringify(pkg.contributes || {}).includes('"%')) {
187 const nls = await get(`${base}/file/package.nls.json`, { notFound: true });
188 if (nls) pkg = resolveNls(pkg, nls);
189 }
190 const a = analyzeManifest(pkg);
191 const f = factsFromManifest(host, a);
192 const v = describe(f);
193 if (v.kind !== 'full') { why(`verdict ${v.kind}: ${v.verdict}`); continue; }
194 const dup = duplicates(pkg);
195 if (dup.length) { why(`duplicates Code: ${dup.join(', ')}`); continue; }
196 const kind = kindOf(f);
197 if (!kind) { why('nothing'); continue; }
198 const text = TEXT[r.id];
199 if (text === null) { why('left out by hand'); continue; }
200 if (!text) { why(`NEEDS TEXT (${kind}): ${v.verdict} | ${meta.displayName}: ${meta.description}`); continue; }
201 draft.push({ rank: r.rank, id: r.id, reason: `OK ${kind}: ${v.verdict}` });
202 picked.push({
203 id: r.id, namespace: meta.namespace, name: meta.name, version: meta.version,
204 displayName: String(meta.displayName || meta.name), kind,
205 description: { es: text[0], en: text[1] },
206 downloads: Number(meta.downloadCount) || 0, rank: Number(r.rank), verified: !!meta.verified,
207 // what the panel needs to give its verdict with no request (vsix.js analyzeManifest)
208 analysis: {
209 hasCode: a.hasCode, browserEntry: a.browserEntry, categories: a.categories, sizes: a.sizes, webviews: a.webviews,
210 ignored: a.ignored, pack: a.pack, themeLabels: a.themeLabels, grammarLangs: a.grammarLangs, languageList: a.languageList, snippetLangs: a.snippetLangs,
211 },
212 });
213}
214
215if (DRAFT) {
216 for (const d of draft) console.log(`${String(d.rank).padStart(5)} ${d.id.padEnd(55)} ${d.reason}`);
217 console.log(`\n${picked.length} would be picked; ${requests} requests`);
218 process.exit(0);
219}
220if (picked.length < N) throw new Error(`only ${picked.length} of ${N}: run with --draft and add TEXT entries`);
221const top10 = new Set(picked.slice(0, 10).map(p => p.kind));
222if (top10.size < 3) console.warn(`warning: the top 10 has only ${[...top10].join(', ')}`);
223const out = {
224 schema: 1,
225 note: 'Generated by tests/ext_popular_build.mjs from the Open VSX census; do not edit by hand.',
226 census: path.basename(path.dirname(CENSUS)) + '/' + path.basename(CENSUS),
227 items: picked,
228};
229fs.writeFileSync(OUT, JSON.stringify(out, null, 1) + '\n');
230console.log(`${picked.length} entries → ${path.relative(ROOT, OUT)}; ${requests} requests`);
231for (const p of picked) console.log(`${String(p.rank).padStart(5)} ${p.kind.padEnd(9)} ${p.id}`);