Elffuss BraidHub

utopia-ia/elffuss-code public

main · 23.7 KiBRawPermalink
1// Gestor de extensiones con código (nivel 2) dentro del panel de extensiones.
2// Lo carga js/ext/panel.js solo cuando hace falta: al desplegar el detalle de
3// un resultado, con el filtro «Funciona en Code», al pulsar «Instalar y
4// ejecutar su código…» o si hay instalada alguna extensión con código. Con
5// solo buscar no se carga.
6//
7// · lines(): qué funcionará, en el idioma de la interfaz (lo declarativo,
8// el código en el recinto, «necesita Node», lo que no saldrá aquí y el
9// resultado del censo);
10// · consent(): el diálogo antes de ejecutar código, con los tamaños;
11// · codeBlock(): los mandos de una extensión instalada con código;
12// · classifyResults(): el filtro «Funciona en Code».
13// Todo texto que viene de una extensión entra con textContent.
14import { tx } from '../ext/i18n.js';
15import './strings.js';
16import { classify, loadTested, validateSettings, VSCODE } from './classify.js';
17import { modal, loadCss } from './ui.js';
18import { runtimeInfo } from './vendor.js';
19import { uiLang } from '../i18n.js';
20
21// sus estilos (los mandos y las líneas de qué funcionará) viven en ext2.css
22if (globalThis.document) loadCss();
23
24// ¿Puede arrancar aquí el código de una extensión (navegador, sitio,
25// ?noext2, el interruptor del manifiesto)? Se mira una vez, al cargarse: las
26// líneas, el botón y el filtro lo dicen ANTES de que nadie pulse nada.
27let aqui = null;
28const aquiListo = globalThis.document
29 ? runtimeInfo().catch(() => ({ available: false, reason: 'manifest' })).then(r => (aqui = r))
30 : Promise.resolve(null);
31export const runtimeHere = () => aquiListo;
32
33const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
34const btn = (txt, cls = 'ghost') => { const b = el('button', cls, txt); b.type = 'button'; return b; };
35export const mb = n => (Number(n || 0) / 1e6).toFixed(1).replace('.', uiLang() === 'es' ? ',' : '.') + ' MB';
36
37const WORKBENCH_LABEL = { views: 'views', viewsContainers: 'views', viewsWelcome: 'views', customEditors: 'custom editors', notebooks: 'notebooks',
38 notebookRenderer: 'notebooks', walkthroughs: 'walkthroughs', debuggers: 'debugger', breakpoints: 'debugger', terminal: 'terminal', taskDefinitions: 'tasks',
39 problemMatchers: 'tasks', authentication: 'sign-in', chatParticipants: 'chat', languageModelTools: 'chat', mcpServerDefinitionProviders: 'MCP servers',
40 resourceLabelFormatters: 'file labels', submenus: 'menus', statusBarItems: 'status bar', remoteHelp: 'remote', typescriptServerPlugins: 'TypeScript plugins' };
41const unavailableList = c => [...new Set(c.unavailable.map(k => tx('wb_' + (WORKBENCH_LABEL[k] || 'other').replace(/\W+/g, '_'))))].join(', ');
42
43const declList = d => [
44 d.themes ? tx('themes', { n: d.themes }) : null, d.grammars ? tx('grammars', { n: d.grammars }) : null,
45 d.snippets ? tx('snippetsN', { n: d.snippets }) : null, d.languages ? tx('languages', { n: d.languages }) : null,
46].filter(Boolean).join(', ');
47const codeList = c => [
48 c.counts.commands ? tx('countCommands', { n: c.counts.commands }) : null, c.counts.keybindings ? tx('countKeys', { n: c.counts.keybindings }) : null,
49 c.counts.settings ? tx('countSettings', { n: c.counts.settings }) : null,
50].filter(Boolean).join(', ');
51export function reasonsText(c) {
52 return c.reasons.map(r => (r === 'engine' ? tx('reasonEngine', { v: VSCODE }) : r === 'proposals' ? tx('reasonProposals') : r === 'never' ? tx('reasonNever')
53 : r === 'deps' ? tx('reasonDeps', { list: c.deps.missing.join(', ') }) : r === 'census' ? tx('reasonCensus') : r)).join(' · ');
54}
55function censusText(t) {
56 if (t.state === 'active') {
57 const parts = [tx('testedStarts')];
58 if (t.commands) parts.push(tx('countCommands', { n: t.commands }));
59 const kinds = Object.keys(t.providers || {});
60 if (kinds.some(k => k.startsWith('format'))) parts.push(tx('testedFormatter'));
61 const feats = kinds.filter(k => !k.startsWith('format'));
62 if (feats.length) parts.push(tx('testedFeatures', { list: feats.slice(0, 6).join(', ') }));
63 if (t.diagnostics) parts.push(tx('testedDiagnostics'));
64 return parts.join(', ');
65 }
66 if (t.state === 'install-failed') return tx('testedTooBig', { e: t.error || '' }).trim();
67 if (t.state === 'unsupported' || t.unsupported) return tx('testedUnsupported', { e: t.unsupported || t.error || '' }).trim();
68 if (t.state === 'installed' || t.state === 'not-activated') return tx('testedNever');
69 return tx('testedFails', { e: String(t.error || '').slice(0, 160) }).trim();
70}
71
72// Las líneas de «qué funcionará» de una extensión (por su manifiesto). Son
73// lo único que se dice de ella: sin un «nada se puede aplicar» del nivel 1 al
74// lado de lo que sí corre (o de por qué no).
75export function linesFor(c, runtime = aqui) {
76 const out = [];
77 if (c.hasDeclarative) out.push({ cls: 'ext-applies', t: tx('lineWorksNow', { list: declList(c.declarative) }) });
78 if (c.runtime === 'browser') {
79 if (!c.eligible) out.push({ cls: 'ext-ignored', t: tx('lineRunsNot', { why: reasonsText(c) }) });
80 else if (runtime && !runtime.available) out.push({ cls: 'ext-ignored', t: tx('lineRunsNotHere', { why: tx('x2Unavail_' + runtime.reason) }) });
81 else out.push({ cls: 'ext-x2-runs', t: tx(codeList(c) ? 'lineRuns' : 'lineRunsBare', { list: codeList(c) }) });
82 if (c.eligible && c.warnings?.includes('proposals')) out.push({ cls: 'ext-ignored', t: tx('lineProposals') });
83 } else if (c.runtime === 'node') {
84 out.push({ cls: 'ext-ignored', t: tx('lineNode') + (c.hasDeclarative ? ' ' + tx('lineNodeDecl') : '') });
85 } else if (!c.hasDeclarative) out.push({ cls: 'ext-nothing', t: tx('nothing') });
86 if (c.unavailable.length) out.push({ cls: 'ext-ignored', t: tx('lineUnavailable', { list: unavailableList(c) }) });
87 if (c.runtime === 'browser') {
88 out.push(c.census ? { cls: c.census.state === 'active' ? 'ext-x2-tested' : 'ext-ignored', t: tx('lineTested', { text: censusText(c.census) }) }
89 : { cls: 'ext-x2-untested', t: tx('lineNotTested') });
90 }
91 return out;
92}
93
94// Las reglas del panel: `host` (js/ext/host.js) dice qué lenguajes trae
95// Monaco de serie y qué gramáticas no se aplicarían.
96async function opciones({ installedIds = new Set(), host = null } = {}) {
97 const [tested, rt] = await Promise.all([loadTested(), aquiListo]);
98 return {
99 tested, installed: installedIds, canRun: !!rt?.available,
100 builtinLanguage: host?.builtinLanguage || undefined, grammarSkippedFor: host?.grammarSkippedFor || undefined,
101 };
102}
103export async function describe(manifest, opts = {}) {
104 const c = classify(manifest, await opciones(opts));
105 return { cls: c, lines: linesFor(c) };
106}
107
108// el botón «Instalar y ejecutar su código…»: si sale y si está activo
109export function codeButton(c, runtime = aqui) {
110 if (!c || c.runtime !== 'browser') return { show: false };
111 if (runtime && !runtime.available) return { show: true, disabled: tx('x2Unavail_' + runtime.reason) };
112 if (!c.eligible) return { show: true, disabled: reasonsText(c) };
113 return { show: true, disabled: null };
114}
115
116// Lo que pesa el .vsix, ANTES de bajarlo: una petición HEAD a la misma
117// dirección de descarga (la misma que verá Open VSX al instalarla).
118export async function downloadSize(meta) {
119 const url = meta?.files?.download;
120 if (!url) return null;
121 try {
122 const r = await fetch(url, { method: 'HEAD', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(30000) });
123 const n = Number(r.headers.get('content-length'));
124 return r.ok && Number.isSafeInteger(n) && n > 0 ? n : null;
125 } catch { return null; }
126}
127
128// ── consentimiento ──
129// mode 'install' (desde la búsqueda), 'file' (.vsix suelto) o 'run' (ya
130// instalada). Devuelve 'code', 'declarative' o null.
131export async function consent({ name, publisher, version, license, cls, runtime, extensionBytes = null, downloadBytes = null, mode = 'install' }) {
132 const body = [];
133 body.push(el('p', 'x2-modal-text', tx('consentWho', { publisher: publisher || '?', v: version || '?', l: license || tx('noLicense') })));
134 body.push(el('p', 'x2-modal-text', tx('consentBody')));
135 const sizes = el('ul', 'x2-sizes');
136 if (runtime && runtime.bytes) sizes.appendChild(el('li', null, tx('consentRuntime', { mb: mb(runtime.bytes) })));
137 // el peso del .vsix llega de una petición HEAD: el diálogo no la espera, la
138 // línea dice «mirando…» y se completa al llegar (y lo anuncia)
139 const extLine = n => (n ? tx('consentExtDownload', { mb: mb(n) }) : extensionBytes ? tx('consentExt', { mb: mb(extensionBytes) }) : tx('consentExtUnknown'));
140 const ext = el('li', null, mode === 'run' ? tx('consentExtAlready', { mb: mb(extensionBytes) })
141 : typeof downloadBytes?.then === 'function' ? tx('consentExtChecking') : extLine(downloadBytes));
142 if (mode !== 'run' && typeof downloadBytes?.then === 'function') {
143 ext.setAttribute('aria-live', 'polite');
144 downloadBytes.then(n => n, () => null).then(n => { if (ext.isConnected) ext.textContent = extLine(n); });
145 }
146 sizes.appendChild(ext);
147 if (mode === 'file') sizes.appendChild(el('li', null, tx('consentFile')));
148 body.push(sizes);
149 if (cls && cls.unavailable.length) body.push(el('p', 'x2-note', tx('lineUnavailable', { list: unavailableList(cls) })));
150 if (cls && cls.deps.missing.length) body.push(el('p', 'x2-note', tx('reasonDeps', { list: cls.deps.missing.join(', ') })));
151 const buttons = [{ label: tx('x2Cancel'), value: null }];
152 if (mode !== 'run' && cls && cls.hasDeclarative) buttons.push({ label: tx('consentDecl'), value: 'declarative' });
153 buttons.push({ label: mode === 'run' ? tx('consentRunOnly') : tx('consentRun'), value: 'code', primary: true });
154 return modal({ id: 'x2-consent', title: tx('consentTitle', { name }), body, buttons, cancelValue: null, focus: 0 });
155}
156
157// ── instalar con su código, desde el panel ──
158// El consentimiento (qué verá, que no tiene red, cuánto se baja) y, si se
159// acepta, la instalación con su código (bajada de Open VSX, con su suma
160// SHA-256 publicada obligatoria). `ui` es lo del panel: host() y sus aviso(),
161// instala(src, botón, { withCode }), rotula(), inerte() y esInerte().
162export function codeInstall(ui) {
163 const disponible = async () => {
164 const r = await ui.host().codeRuntime();
165 if (!r.available) ui.aviso(tx('x2Unavail_' + r.reason), true);
166 return r.available ? r : null;
167 };
168 // «Instalar y ejecutar su código…» en un resultado: solo si trae código para
169 // el navegador; inerte (con el motivo) si no puede correr aquí
170 function button(acc, it, c, instalada) {
171 if (acc.querySelector('.ext-install-code')) return;
172 const cb = codeButton(c);
173 if (!cb.show || (instalada && instalada.version === it.version && instalada.code)) return;
174 const b = btn('', 'ghost ext-install-code');
175 ui.rotula(b, tx('btnInstallCode'), tx('btnInstallCodeNamed', { name: it.displayName }));
176 if (cb.disabled) { ui.inerte(b, true); b.title = cb.disabled; }
177 b.onclick = e => { e.stopPropagation(); if (!ui.esInerte(b)) fromResult(it, c, b); };
178 acc.appendChild(b);
179 // sin nada declarativo, «Instalar» a secas no haría nada (y si su código
180 // tampoco puede correr aquí, se dice por qué)
181 const inst = acc.querySelector('.ext-install');
182 if (!c.hasDeclarative && inst && !ui.esInerte(inst)) { ui.inerte(inst, true); inst.title = cb.disabled || tx('errCodeonly'); inst.className = 'ghost ext-install'; }
183 }
184 async function fromResult(it, c, boton) {
185 ui.aviso(null);
186 const runtime = await disponible();
187 if (!runtime) return;
188 const meta = await (await import('../ext/openvsx.js')).metadata(it.namespace, it.name, it.version).catch(() => null);
189 const v = await consent({ name: it.displayName, publisher: it.namespace, version: it.version, license: meta?.license, cls: c, runtime, extensionBytes: c.census?.bytes || null, downloadBytes: meta?.files?.download ? downloadSize(meta) : null });
190 if (v === 'declarative') return ui.instala(it, boton.closest('.ext-actions')?.querySelector('.ext-install') || null);
191 if (v === 'code') return ui.instala(it, boton, { withCode: true });
192 }
193 // una instalada solo con lo declarativo que trae código: se vuelve a bajar con él
194 async function installed(rec) {
195 const runtime = await disponible();
196 if (!runtime) return;
197 const meta = await (await import('../ext/openvsx.js')).metadata(rec.publisher, rec.name, rec.version).catch(() => null);
198 if ((await consent({ name: rec.displayName, publisher: rec.publisher, version: rec.version, license: rec.license, cls: null, runtime, downloadBytes: meta?.files?.download ? downloadSize(meta) : null })) !== 'code') return;
199 return ui.instala({ namespace: rec.publisher, name: rec.name, version: rec.version, displayName: rec.displayName }, null, { withCode: true });
200 }
201 // un .vsix suelto: su nombre, editor, versión y licencia se leen del propio
202 // fichero (es local), y se dice que no hay suma publicada con la que comprobarlo
203 async function file(f, { yaInstalada = false } = {}) {
204 const r = await ui.host().codeRuntime();
205 if (!r.available) { if (!yaInstalada) ui.aviso(tx('errCodeonly') + ' ' + tx('x2Unavail_' + r.reason), true); return; }
206 let who = { name: f.name, publisher: '', version: '', license: '' };
207 try {
208 const { readVsix } = await import('../ext/vsix.js');
209 const v = await readVsix(new Uint8Array(await f.arrayBuffer()), { lang: uiLang() });
210 who = { name: v.displayName || v.name || f.name, publisher: v.publisher, version: v.version, license: v.license };
211 } catch { /* el instalador dirá qué le pasa al fichero */ }
212 if ((await consent({ ...who, cls: null, runtime: r, extensionBytes: f.size, mode: 'file' })) !== 'code') { if (!yaInstalada) ui.aviso(tx('cancelled')); return; }
213 return ui.instala(f, null, { withCode: true });
214 }
215 return { button, installed, file };
216}
217
218// ── filtro «Funciona en Code»: clasifica una página de resultados ──
219// Cada manifiesto se pide una vez (4 a la vez) y se guarda por id@versión.
220export async function classifyResults(items, { ovsx, store, installedIds = new Set(), host = null, signal, onEach = () => {} } = {}) {
221 const opts = await opciones({ installedIds, host });
222 const out = new Map();
223 let i = 0;
224 const one = async it => {
225 const key = `${it.namespace}.${it.name}@${it.version}`.toLowerCase();
226 let manifest = null;
227 try { manifest = await store.getMeta('manifest:' + key); } catch { /* sin caché */ }
228 if (!manifest) {
229 try {
230 const meta = await ovsx.metadata(it.namespace, it.name, it.version, { signal });
231 manifest = await ovsx.manifest(meta, { signal });
232 if (manifest && JSON.stringify(manifest).length < 512 * 1024) store.setMeta('manifest:' + key, manifest).catch(() => {});
233 } catch (e) {
234 if (e?.name === 'AbortError') throw e;
235 out.set(key, null); // no se pudo comprobar: se enseña sin filtrar
236 onEach(it, null);
237 return;
238 }
239 }
240 const c = classify(manifest, opts);
241 out.set(key, c);
242 onEach(it, c, manifest);
243 };
244 const workers = Array.from({ length: Math.min(4, items.length) }, async () => { while (i < items.length) await one(items[i++]); });
245 await Promise.all(workers);
246 return out;
247}
248
249// ── mandos de una extensión instalada con código ──
250const STATE_KEY = { active: 'stateRunning', activating: 'stateStarting', installed: 'stateWaiting', error: 'stateError', stopped: 'stateStopped', unsupported: 'stateUnsupported' };
251// por qué un atajo no se ató (keys.js y commands.js dan el código)
252const KEY_SKIP = new Set(['reserved', 'invalid', 'platform', 'chords', 'unknown']);
253// por qué el recinto no arrancó o se paró (bridge.js, vendor.js, frame.js dan
254// el código; su mensaje es técnico y no va en el idioma de la interfaz)
255const NO_DISPONIBLE = new Set(['site', 'browser', 'off', 'url', 'manifest']);
256const FALLOS = new Set(['network', 'integrity', 'timeout', 'editor', 'violations', 'fatal', 'navigated', 'csp']);
257export const isRuntimeError = e => !!e && (NO_DISPONIBLE.has(e.code) || FALLOS.has(e.code) || e.code === 'disabled');
258export function runtimeErrorText(e) {
259 const code = e?.code === 'disabled' ? 'off' : String(e?.code || '').replace(/^x2-/, '');
260 if (NO_DISPONIBLE.has(code)) return tx('x2Unavail_' + code);
261 return tx('stateRuntime', { e: tx('x2Err_' + (FALLOS.has(code) ? code : 'other'), { file: e?.file ? ` (${e.file})` : '', code: code || '?' }) });
262}
263export function codeBlock(rec, { host, onGetCode, onMessage = () => {}, register = () => {} }) {
264 const box = el('div', 'ext-x2');
265 box.dataset.ext = rec.id;
266 const head = el('div', 'ext-x2-head');
267 const label = el('span', 'ext-x2-label', tx('codeHead') + ' ');
268 const st = el('span', 'ext-x2-state');
269 st.setAttribute('role', 'status');
270 label.appendChild(st);
271 head.appendChild(label);
272 const hasCode = !!rec.code;
273 // un botón de acción («Apagar el código», «Ejecutar código»): su nombre dice
274 // lo que hará, sin aria-pressed (un conmutador no cambia de nombre)
275 const toggle = btn(hasCode && rec.runs ? tx('stopCode') : hasCode ? tx('runCode') : tx('getCode'), 'ghost ext-x2-run' + (hasCode && rec.runs ? ' on' : ''));
276 toggle.dataset.k = 'x2run';
277 toggle.setAttribute('aria-label', tx(hasCode && rec.runs ? 'stopCodeNamed' : 'runCodeNamed', { name: rec.displayName }));
278 if (!hasCode && rec.source !== 'open-vsx') { toggle.setAttribute('aria-disabled', 'true'); toggle.title = tx('getCodeFile'); }
279 toggle.onclick = async () => {
280 if (toggle.getAttribute('aria-disabled') === 'true') return;
281 toggle.setAttribute('aria-disabled', 'true');
282 try {
283 if (!hasCode) { await onGetCode(rec); return; }
284 const on = !rec.runs;
285 const runtime = on ? await host.codeRuntime() : null;
286 if (on && !runtime.available) { onMessage(tx('x2Unavail_' + runtime.reason), true); return; }
287 const ok = await host.setRuns(rec.id, on, {
288 confirm: async info => (await consent({ name: rec.displayName, publisher: rec.publisher, version: rec.version, license: rec.license, cls: null, runtime: { bytes: info.runtimeBytes }, extensionBytes: info.extensionBytes, mode: 'run' })) === 'code',
289 });
290 if (ok === false) onMessage(tx('cancelled'));
291 } catch (e) { onMessage(isRuntimeError(e) || /^x2-/.test(e?.code || '') ? runtimeErrorText(e) : e, true); }
292 finally { toggle.removeAttribute('aria-disabled'); }
293 };
294 head.appendChild(toggle);
295 box.appendChild(head);
296 const dyn = el('div', 'ext-x2-dyn');
297 box.appendChild(dyn);
298
299 if (hasCode) {
300 // ajustes (JSON), validados contra lo que declara la extensión
301 const d = el('details', 'ext-x2-settings');
302 const s = el('summary', null, tx('settingsH'));
303 s.dataset.k = 'x2settings';
304 const ta = el('textarea', 'ext-x2-json');
305 ta.dataset.k = 'x2json';
306 ta.spellcheck = false;
307 ta.rows = 4;
308 ta.setAttribute('aria-label', tx('settingsFor', { name: rec.displayName }));
309 ta.value = JSON.stringify(rec.settings || {}, null, 2);
310 const save = btn(tx('settingsSave'));
311 save.dataset.k = 'x2save';
312 const msg = el('div', 'ext-x2-msg');
313 msg.setAttribute('role', 'status');
314 save.onclick = async () => {
315 const r = validateSettings(rec.code.manifest, ta.value);
316 if (!r.ok) {
317 msg.setAttribute('role', 'alert');
318 msg.textContent = tx('settingsBad', { e: r.errors.slice(0, 3).map(e => tx('set_' + e.code, { k: e.key, t: e.type, list: e.list, e: e.detail })).join(' · ') });
319 return;
320 }
321 try { await host.setSettings(rec.id, r.value); msg.setAttribute('role', 'status'); msg.textContent = tx('settingsSaved'); }
322 catch (e) { msg.setAttribute('role', 'alert'); msg.textContent = e?.message || String(e); }
323 };
324 d.append(s, ta, save, msg);
325 box.appendChild(d);
326 }
327
328 function update() {
329 const s = host.codeState();
330 const x = s.extensions.find(e => e.id === rec.id);
331 const runtimeOff = s.state === 'error' ? runtimeErrorText(s.error) : null;
332 st.textContent = !hasCode ? tx('stateNoCode') : !rec.runs ? tx('stateOff') : runtimeOff || (x ? tx(STATE_KEY[x.state] || 'stateWaiting', { e: x.text || '' }) : tx('stateStarting'));
333 dyn.replaceChildren();
334 if (!x) return;
335 // (las que arrancan con su primer comando están «listas»: el botón las arranca)
336 const cmds = s.commands.filter(c => c.ext === rec.id);
337 if (cmds.length && ['active', 'activating', 'installed'].includes(x.state)) {
338 const ul = el('ul', 'ext-x2-cmds');
339 ul.setAttribute('aria-label', tx('commandsH'));
340 for (const c of cmds.slice(0, 200)) {
341 const li = el('li');
342 li.appendChild(el('span', null, c.label));
343 const b = btn(tx('runCmd'), 'ghost ext-x2-cmd');
344 b.dataset.k = 'cmd:' + c.id;
345 b.setAttribute('aria-label', tx('runCmdNamed', { cmd: c.label }));
346 b.onclick = async () => {
347 const entry = host.codeCommands().find(e => e.id === c.id && e.ext === rec.id);
348 if (!entry) return;
349 // en el teléfono el panel tapa el editor: se cierra para ver el resultado
350 if (window.matchMedia?.('(max-width: 760px)').matches) document.getElementById('settings-panel').hidden = true;
351 await entry.run();
352 };
353 li.appendChild(b);
354 ul.appendChild(li);
355 }
356 dyn.appendChild(ul);
357 }
358 const langs = (s.formatters || {})[rec.id] || [];
359 if (langs.length) {
360 const d = el('details', 'ext-x2-fmt');
361 d.appendChild(el('summary', null, tx('formatterH', { n: langs.length })));
362 for (const lang of langs.slice(0, 60)) {
363 const row = el('label', 'ext-x2-fmtrow');
364 row.appendChild(el('span', null, tx('formatterFor', { lang })));
365 const sel = el('select');
366 sel.dataset.k = 'fmt:' + lang;
367 for (const [v, t] of [['extension', tx('fmtExt', { name: rec.displayName })], ['builtin', tx('fmtBuiltin')]]) { const o = el('option', null, t); o.value = v; sel.appendChild(o); }
368 sel.value = rec.formatter?.[lang] === 'builtin' ? 'builtin' : 'extension';
369 sel.onchange = () => host.setFormatter(rec.id, lang, sel.value);
370 row.appendChild(sel);
371 d.appendChild(row);
372 }
373 dyn.appendChild(d);
374 }
375 if (x.skipped?.length) {
376 const d = el('details', 'ext-x2-keys');
377 d.appendChild(el('summary', null, tx('skippedH', { n: x.skipped.length })));
378 const ul = el('ul');
379 for (const k of x.skipped.slice(0, 50)) ul.appendChild(el('li', null, `${k.key || '?'} → ${k.command || '?'}: ${k.conflict ? tx('keyConflict', { ext: k.conflict }) : tx('keySkip_' + (KEY_SKIP.has(k.code) ? k.code : 'invalid'))}`));
380 d.appendChild(ul);
381 dyn.appendChild(d);
382 }
383 if (x.log?.length) {
384 const d = el('details', 'ext-x2-log');
385 d.appendChild(el('summary', null, tx('logH', { n: x.log.length })));
386 d.appendChild(el('pre', null, x.log.slice(-50).map(l => `[${l.level}] ${l.text}`).join('\n')));
387 dyn.appendChild(d);
388 }
389 }
390 update();
391 register(host.onCodeChange(() => { if (box.isConnected) update(); }));
392 return box;
393}
394
395// Una línea para el encabezado de «Instaladas» cuando corre código; si el
396// usuario bloqueó las direcciones que piden las extensiones, se dice, con un
397// botón para deshacerlo
398export function runtimeLine(host, { onUnblock = () => {}, register = () => {} } = {}) {
399 const p = el('p', 'ext-x2-runtime muted');
400 const update = () => {
401 const s = host.codeState();
402 p.hidden = s.state !== 'running';
403 p.replaceChildren(tx('runtimeRunning') + (s.denials?.n ? ' · ' + tx('denials', { n: s.denials.n }) : ''));
404 if (s.state !== 'running' || !s.gate?.blocked) return;
405 p.appendChild(el('span', 'ext-x2-blocked', ' · ' + tx('x2Blocked', { n: s.gate.dropped || 0 }) + ' '));
406 const b = btn(tx('x2Unblock'), 'ghost ext-x2-unblock');
407 b.onclick = async () => { (await import('./bridge.js')).unblockAddresses(); onUnblock(); update(); };
408 p.appendChild(b);
409 };
410 update();
411 register(host.onCodeChange(() => { if (p.isConnected && !p.contains(document.activeElement)) update(); }));
412 return p;
413}