| 1 | // Puente del nivel 2: arranca y para el recinto donde corre el código de las |
| 2 | // extensiones, y conecta el editor de Code con él. |
| 3 | // |
| 4 | // Este módulo NO se carga en el camino por defecto: lo importa js/ext/host.js |
| 5 | // (que a su vez solo existe para quien usa extensiones) cuando hay al menos |
| 6 | // una extensión activa con su código encendido y el usuario ya vio el tamaño. |
| 7 | // Orden: manifiesto → bundle verificado (vendor.js) → relevo como texto → |
| 8 | // iframe en el otro sitio (frame.js) → boot por el MessagePort → «ready» → |
| 9 | // documentos, proveedores y comandos. Cualquier fallo lo deja todo parado. |
| 10 | import { sandboxOrigin } from './config.js'; |
| 11 | import { loadManifest, loadVendor, supported, disabledByUrl, runtimeInfo, RUNTIME_KEY } from './vendor.js'; |
| 12 | import { openSandbox } from './frame.js'; |
| 13 | import { validate, isPlainData, PROTOCOL, LIMITS } from './protocol.js'; |
| 14 | import { EditorPort } from './docs.js'; |
| 15 | import { Features } from './features.js'; |
| 16 | import { Commands } from './commands.js'; |
| 17 | import { ExtUI, loadCss, userActive } from './ui.js'; |
| 18 | import { OpenGate, installAgentGate, markTouched } from './gates.js'; |
| 19 | import { Decorations } from './decorations.js'; |
| 20 | import * as convert from './convert.js'; |
| 21 | import { tx } from '../ext/i18n.js'; |
| 22 | import './strings.js'; |
| 23 | |
| 24 | const READY_TIMEOUT = 60000; |
| 25 | const CALL_TIMEOUT = 30000; |
| 26 | |
| 27 | export { supported, disabledByUrl, runtimeInfo, RUNTIME_KEY }; |
| 28 | |
| 29 | // Manifiesto que ve el recinto: solo lo que el host de extensiones necesita. |
| 30 | // Fuera `main` (así no cabe un host de Node), lo declarativo que ya aplica el |
| 31 | // nivel 1 en la página (temas, gramáticas, snippets, lenguajes) y los atajos y |
| 32 | // menús (los ata la página). |
| 33 | export function sandboxManifest(manifest, installed = new Set()) { |
| 34 | const keep = ['name', 'displayName', 'publisher', 'version', 'engines', 'browser', 'activationEvents', 'capabilities', 'l10n']; |
| 35 | const out = {}; |
| 36 | for (const k of keep) if (manifest[k] !== undefined) out[k] = structuredClone(manifest[k]); |
| 37 | out.extensionDependencies = (Array.isArray(manifest.extensionDependencies) ? manifest.extensionDependencies : []) |
| 38 | .filter(d => typeof d === 'string' && installed.has(d.toLowerCase())); |
| 39 | const c = manifest.contributes && typeof manifest.contributes === 'object' ? manifest.contributes : {}; |
| 40 | out.contributes = {}; |
| 41 | for (const k of ['commands', 'configuration', 'configurationDefaults']) if (c[k] !== undefined) out.contributes[k] = structuredClone(c[k]); |
| 42 | // sus lenguajes los registra la página; que sigan activándola como en VS Code |
| 43 | const langs = (Array.isArray(c.languages) ? c.languages : []).map(l => l && l.id).filter(id => typeof id === 'string' && /^[\w.+-]{1,100}$/.test(id)); |
| 44 | if (langs.length) out.activationEvents = [...new Set([...(Array.isArray(out.activationEvents) ? out.activationEvents : []), ...langs.map(id => 'onLanguage:' + id)])]; |
| 45 | return out; |
| 46 | } |
| 47 | |
| 48 | // rpc-allowlist.json: { schema: 1, actors: { Actor: ['$método', …] }, hostSetup: { … } } |
| 49 | const validActorMap = o => !!o && typeof o === 'object' && !Array.isArray(o) |
| 50 | && Object.entries(o).every(([a, ms]) => /^MainThread\w{1,80}$/.test(a) && Array.isArray(ms) && ms.length <= 200 && ms.every(x => typeof x === 'string' && /^\$\w{1,100}$/.test(x))); |
| 51 | export function validAllowlist(j) { |
| 52 | return !!j && j.schema === 1 && validActorMap(j.actors) && (j.hostSetup === undefined || validActorMap(j.hostSetup)); |
| 53 | } |
| 54 | // lo que manda al recinto: las dos listas juntas (actor → métodos) |
| 55 | export function allowedCalls(j) { |
| 56 | const out = {}; |
| 57 | for (const src of [j.actors, j.hostSetup || {}]) for (const [a, ms] of Object.entries(src)) out[a] = [...new Set([...(out[a] || []), ...ms])]; |
| 58 | return out; |
| 59 | } |
| 60 | |
| 61 | const listeners = new Set(); |
| 62 | let session = null; |
| 63 | // Las que el recinto marcó «no soportada» (sustituyen el tecleo): no vuelven a |
| 64 | // entrar en esta pestaña. Y lo último que pidió host.js, para rehacer el recinto. |
| 65 | const refused = new Map(); // id → motivo |
| 66 | let lastSync = null; |
| 67 | // el tema de Code (claro, oscuro, alto contraste): host.js lo dice al cambiar |
| 68 | let themeKind = 'dark'; |
| 69 | export function setTheme(kind) { |
| 70 | if (!['light', 'dark', 'hc', 'hc-light'].includes(kind) || kind === themeKind) return; |
| 71 | themeKind = kind; |
| 72 | if (session && session.state === 'running') session.post({ t: 'theme', kind }); |
| 73 | } |
| 74 | let lastError = null; |
| 75 | const emit = () => { for (const f of listeners) { try { f(); } catch { /* — */ } } }; |
| 76 | export const onChange = fn => { listeners.add(fn); return () => listeners.delete(fn); }; |
| 77 | |
| 78 | const refusedList = () => [...refused].map(([id, text]) => ({ id, state: 'unsupported', text, log: [], skipped: [] })); |
| 79 | export function state() { |
| 80 | if (!session) return { state: lastError ? 'error' : 'stopped', error: lastError, extensions: refusedList(), commands: [], denials: { n: 0, top: [] } }; |
| 81 | return { |
| 82 | state: session.state, error: session.error, violations: session.violations, |
| 83 | denials: { n: session.denials.n, top: session.denials.top.map(x => [...x]) }, |
| 84 | ui: { dropped: { ...session.ui.dropped } }, |
| 85 | gate: { shown: session.gate.shown.map(x => ({ ...x })), opened: session.gate.opened, dropped: session.gate.dropped, blocked: session.gate.blocked }, |
| 86 | extensions: [...[...session.status.values()].filter(s => !refused.has(s.id)).map(s => ({ ...s, skipped: session.commands ? session.commands.skipped(s.id).map(x => ({ ...x })) : [] })), ...refusedList()], |
| 87 | commands: session.commands ? session.commands.entries().map(({ id, label, hint, ext }) => ({ id, label, hint, ext })) : [], |
| 88 | formatters: session.features ? session.features.formatters() : {}, |
| 89 | }; |
| 90 | } |
| 91 | export const commands = () => (session?.commands ? session.commands.entries() : []); |
| 92 | // «Desbloquear» del panel: las extensiones vuelven a poder pedir direcciones |
| 93 | export const unblockAddresses = () => { session?.gate.unblock(); }; |
| 94 | export const runCommand = (id, args) => (session ? session.runCommand(id, args) : Promise.resolve(null)); |
| 95 | // foto de la superficie de la API del recinto (para las pruebas: tests/x2-surface.json) |
| 96 | export const surface = () => (session && session.state === 'running' ? session.request({ t: 'surface' }) : Promise.resolve(null)); |
| 97 | // para el censo: qué registraron las extensiones, y lanzar un evento de activación |
| 98 | export const stats = () => (session && session.state === 'running' ? session.request({ t: 'stats' }) : Promise.resolve(null)); |
| 99 | export const activate = event => { if (session && session.state === 'running' && typeof event === 'string' && /^[\w:.*-]{1,200}$/.test(event)) session.post({ t: 'activate', event }); }; |
| 100 | |
| 101 | class Session { |
| 102 | constructor({ monaco, readCode }) { |
| 103 | this.monaco = monaco; |
| 104 | this.readCode = readCode; |
| 105 | this.state = 'starting'; |
| 106 | this.error = null; |
| 107 | this.violations = 0; |
| 108 | this.status = new Map(); // id → { id, state, text, log[] } |
| 109 | this.pending = new Map(); // req → resolve |
| 110 | this.nextReq = 1; |
| 111 | this.added = new Map(); // id → version |
| 112 | this.disposables = []; |
| 113 | this.markerOwners = new Map(); // uri → Set(owner) |
| 114 | this.contextKeys = new Map(); |
| 115 | this.denials = { n: 0, top: [] }; // llamadas que el cortafuegos de RPC rechazó |
| 116 | this.names = new Map(); // id → nombre visible (para decir quién pide algo) |
| 117 | this.ui = new ExtUI({ nameOf: id => this.names.get(id) || null, log: (level, text, id) => this.log(id || null, level, text) }); |
| 118 | this.gate = new OpenGate({ |
| 119 | log: (level, text) => this.log(null, level, text), |
| 120 | // lo bloqueado no se calla: la barra de estado lo dice, y el panel lo enseña con «Desbloquear» |
| 121 | onDropped: () => statusbar(tx('x2BlockedDropped')), |
| 122 | onChange: () => emit(), |
| 123 | }); |
| 124 | this.restoreAgent = null; |
| 125 | this.readyPromise = new Promise((res, rej) => { this.onReady = res; this.onFail = rej; }); |
| 126 | } |
| 127 | |
| 128 | post(msg, transfer) { |
| 129 | if (!this.port) return; |
| 130 | if (!isPlainData(msg)) { console.warn('[x2] mensaje no plano, no se manda:', msg?.t); return; } |
| 131 | this.port.postMessage(msg, transfer || []); |
| 132 | } |
| 133 | |
| 134 | async start() { |
| 135 | if (!supported()) throw Object.assign(new Error('level 2 needs Chrome or Edge in this version'), { code: 'browser' }); |
| 136 | const origin = sandboxOrigin(); |
| 137 | if (!origin) throw Object.assign(new Error('level 2 is not available on this site'), { code: 'site' }); |
| 138 | const manifest = await loadManifest(); |
| 139 | if (!manifest.enabled) throw Object.assign(new Error('level 2 is turned off'), { code: 'off' }); |
| 140 | const vendor = await loadVendor(manifest); |
| 141 | const relayRes = await fetch(new URL('./sandbox-relay.js', import.meta.url), { cache: 'no-cache', credentials: 'same-origin' }); |
| 142 | if (!relayRes.ok) throw Object.assign(new Error('relay: HTTP ' + relayRes.status), { code: 'network' }); |
| 143 | const relay = await relayRes.text(); |
| 144 | // lista de llamadas permitidas del cortafuegos de RPC: sin ella no se arranca |
| 145 | const rpc = await fetch(new URL('./rpc-allowlist.json', import.meta.url), { cache: 'no-cache', credentials: 'same-origin' }) |
| 146 | .then(r => (r.ok ? r.json() : null)).catch(() => null); |
| 147 | if (!validAllowlist(rpc)) throw Object.assign(new Error('the extension sandbox\'s call list is missing or broken'), { code: 'manifest' }); |
| 148 | if (this.state === 'stopped') return; |
| 149 | this.frame = await openSandbox(origin, { onLost: e => this.fail(e) }); |
| 150 | if (this.state === 'stopped') { this.frame.close(); return; } |
| 151 | this.port = this.frame.port; |
| 152 | this.port.onmessage = ev => this.receive(ev.data); |
| 153 | const config = { |
| 154 | protocol: PROTOCOL, |
| 155 | lang: document.documentElement.lang || 'en', |
| 156 | theme: themeKind, |
| 157 | languages: this.monaco.languages.getLanguages().slice(0, 1000).map(l => ({ id: l.id, extensions: (l.extensions || []).slice(0, 50), aliases: (l.aliases || []).slice(0, 10) })), |
| 158 | rpc: { actors: allowedCalls(rpc) }, |
| 159 | }; |
| 160 | this.post({ t: 'boot', vendor: vendor.map(f => ({ role: f.role, name: f.name, bytes: f.bytes })), relay, config }, vendor.map(f => f.bytes)); |
| 161 | let timer; |
| 162 | await Promise.race([this.readyPromise, new Promise((_, rej) => { timer = setTimeout(() => rej(Object.assign(new Error('the extension sandbox did not start'), { code: 'timeout' })), READY_TIMEOUT); })]) |
| 163 | .finally(() => clearTimeout(timer)); |
| 164 | try { localStorage.setItem(RUNTIME_KEY, manifest.buildId); } catch { /* sin almacenamiento */ } |
| 165 | loadCss(); |
| 166 | // ide.js crea el editor después de cargar las extensiones: se le espera |
| 167 | this.editor = await this.waitEditor(); |
| 168 | if (this.state === 'stopped') return; |
| 169 | // (la misma instancia de ide.js que ya usa la página: sus pestañas abiertas) |
| 170 | this.ide = await import('../ide.js').catch(() => null); |
| 171 | if (this.state === 'stopped') return; |
| 172 | this.wire(); |
| 173 | this.state = 'running'; |
| 174 | emit(); |
| 175 | } |
| 176 | |
| 177 | // el editor de la página: el de #editor (ide.js) |
| 178 | pageEditor() { |
| 179 | const host = document.getElementById('editor'); |
| 180 | return this.monaco.editor.getEditors().find(e => host && host.contains(e.getContainerDomNode())) || null; |
| 181 | } |
| 182 | |
| 183 | waitEditor(timeout = 60000) { |
| 184 | const ya = this.pageEditor(); |
| 185 | if (ya) return Promise.resolve(ya); |
| 186 | return new Promise((resolve, reject) => { |
| 187 | const mira = () => { const e = this.pageEditor(); if (e) { sub.dispose(); clearTimeout(t); resolve(e); } }; |
| 188 | const sub = this.monaco.editor.onDidCreateEditor(() => setTimeout(mira, 0)); |
| 189 | const t = setTimeout(() => { sub.dispose(); reject(Object.assign(new Error('Code\'s editor is not open'), { code: 'editor' })); }, timeout); |
| 190 | }); |
| 191 | } |
| 192 | |
| 193 | wire() { |
| 194 | const monaco = this.monaco; |
| 195 | const editor = this.editor; |
| 196 | this.docs = new EditorPort({ |
| 197 | monaco, editor, post: m => this.post(m), |
| 198 | notify: (what, path) => statusbar(what === 'big' ? tx('x2DocBig', { path }) : tx('x2DocDiscarded')), |
| 199 | // las pestañas que ya estaban abiertas antes de que arrancara el recinto |
| 200 | openTabs: () => this.ide?.openTabModels?.() || [], |
| 201 | }); |
| 202 | this.features = new Features({ |
| 203 | monaco, docs: this.docs, |
| 204 | call: (kind, handle, model, args, token) => this.invoke(kind, handle, model, args, token), |
| 205 | touched: model => this.touch(model), |
| 206 | release: hs => { if (hs.length) this.post({ t: 'release', handles: hs.slice(0, 5000) }); }, |
| 207 | report: (handle, kind, why) => this.log(null, 'warn', `a ${kind} provider was not connected: ${why}`), |
| 208 | }); |
| 209 | this.commands = new Commands({ |
| 210 | monaco, editor, |
| 211 | run: (id, args) => this.runCommand(id, args), |
| 212 | onReport: (id, skipped) => this.log(id, 'warn', `${skipped.length} keybinding(s) skipped: ` + skipped.map(s => `${s.key || '?'} (${s.why})`).join(', ')), |
| 213 | }); |
| 214 | this.disposables.push(monaco.editor.registerCommand(convert.HANDLE_COMMAND, (_, handle) => this.post({ t: 'cmd.exec', req: this.nextReq++, handle, ...this.docs.activeState() }))); |
| 215 | // enlaces del editor (Cmd+clic) mientras corren extensiones: una dirección |
| 216 | // pudo escribirla una extensión, así que pregunta como open.request |
| 217 | // (toString(true): la dirección como está escrita, sin volver a codificarla) |
| 218 | this.disposables.push(monaco.editor.registerLinkOpener({ |
| 219 | open: async uri => { await this.gate.request(typeof uri?.toString === 'function' ? uri.toString(true) : String(uri), { fromEditor: true }); return true; }, |
| 220 | })); |
| 221 | this.decorations = new Decorations({ monaco, editor, docs: this.docs }); |
| 222 | // los diagnósticos de la propia página (TS, JSON, CSS, HTML), para las |
| 223 | // extensiones que los decoran (Error Lens y similares) |
| 224 | const pendientes = new Map(); // uri del recinto → modelo |
| 225 | let reloj = null; |
| 226 | const programa = model => { |
| 227 | const uri = model && !model.isDisposed() && this.docs.uriOf(model); |
| 228 | if (!uri) return; |
| 229 | pendientes.set(uri, model); |
| 230 | reloj ??= setTimeout(() => { |
| 231 | reloj = null; |
| 232 | for (const [u, m2] of pendientes) { |
| 233 | if (m2.isDisposed()) continue; |
| 234 | const markers = monaco.editor.getModelMarkers({ resource: m2.uri }).filter(x => !String(x.owner).startsWith('x2:')).slice(0, 5000).map(x => ({ |
| 235 | owner: String(x.owner).slice(0, 60), severity: x.severity, message: String(x.message).slice(0, 4096), |
| 236 | ...(typeof x.source === 'string' ? { source: x.source.slice(0, 200) } : {}), |
| 237 | ...(typeof x.code === 'string' ? { code: x.code.slice(0, 200) } : x.code && typeof x.code.value === 'string' ? { code: x.code.value.slice(0, 200) } : {}), |
| 238 | range: [x.startLineNumber, x.startColumn, x.endLineNumber, x.endColumn], |
| 239 | })); |
| 240 | this.post({ t: 'markers.page', uri: u, markers }); |
| 241 | } |
| 242 | pendientes.clear(); |
| 243 | }, 300); |
| 244 | }; |
| 245 | this.disposables.push(monaco.editor.onDidChangeMarkers(uris => { for (const u of uris) programa(monaco.editor.getModel(u)); })); |
| 246 | this.disposables.push(editor.onDidChangeModel(() => setTimeout(() => programa(editor.getModel()), 0))); |
| 247 | setTimeout(() => programa(editor.getModel()), 0); |
| 248 | // el agente: sus peticiones web y los runtimes del Bridge preguntan antes |
| 249 | import('../tools/index.js').then(({ TOOLS }) => { |
| 250 | if (this.state === 'stopped' || this.state === 'error' || this.restoreAgent) return; |
| 251 | this.restoreAgent = installAgentGate(TOOLS, { log: (level, text) => this.log(null, level, text) }); |
| 252 | }).catch(e => this.log(null, 'warn', 'agent gate not installed: ' + (e?.message || e))); |
| 253 | this.docs.start(); |
| 254 | } |
| 255 | |
| 256 | receive(msg) { |
| 257 | const r = validate(msg); |
| 258 | if (!r.ok) { |
| 259 | if (++this.violations > LIMITS.violations) this.fail(Object.assign(new Error('the extension sandbox misbehaved'), { code: 'violations' })); |
| 260 | return; |
| 261 | } |
| 262 | switch (msg.t) { |
| 263 | case 'ready': this.onReady(); break; |
| 264 | case 'fatal': this.fail(Object.assign(new Error('the extension sandbox failed: ' + (msg.text || msg.reason)), { code: 'fatal' })); break; |
| 265 | case 'ext.status': { |
| 266 | const s = this.status.get(msg.id) || { id: msg.id, log: [] }; |
| 267 | s.state = msg.state; s.text = msg.text || ''; |
| 268 | this.status.set(msg.id, s); |
| 269 | // quitarla en el recinto no para su código: se rehace sin ella |
| 270 | if (msg.state === 'unsupported' && !refused.has(msg.id)) { refused.set(msg.id, s.text); if (lastSync) setTimeout(() => sync(lastSync), 0); } |
| 271 | emit(); |
| 272 | break; |
| 273 | } |
| 274 | case 'log': this.log(msg.id || null, msg.level, msg.text); break; |
| 275 | case 'providers.add': this.features?.add(msg); emit(); break; |
| 276 | case 'providers.remove': this.features?.remove(msg.handle); emit(); break; |
| 277 | case 'result': { const p = this.pending.get(msg.req); if (p) { this.pending.delete(msg.req); p(msg.ok ? msg.value : (this.log(null, 'warn', 'call failed: ' + msg.error), null)); } break; } |
| 278 | case 'doc.edit': this.docs?.applyEdit(msg, { onTouched: m => this.touch(m) }); break; |
| 279 | case 'doc.need': this.docs?.need(msg.uri); break; |
| 280 | case 'markers': this.markers(msg); break; |
| 281 | case 'ctx.set': this.context(msg.key, msg.value); break; |
| 282 | case 'rpc.denied': |
| 283 | if (msg.n >= this.denials.n) { this.denials = { n: msg.n, top: msg.top }; emit(); } |
| 284 | break; |
| 285 | // lo que la extensión le pide al usuario: siempre se contesta |
| 286 | case 'ui.notify': this.reply(msg.req, this.ui.notify(msg)); break; |
| 287 | case 'ui.dialog': this.reply(msg.req, this.ui.dialog(msg)); break; |
| 288 | case 'ui.pick': this.reply(msg.req, this.ui.pick(msg)); break; |
| 289 | case 'ui.input': this.reply(msg.req, this.ui.input(msg)); break; |
| 290 | case 'ui.cancel': this.ui.cancel(msg.req); break; |
| 291 | case 'ui.progress': this.ui.setProgress(msg); break; |
| 292 | case 'clipboard.write': this.ui.clipboard(msg.text); break; |
| 293 | case 'open.request': this.reply(msg.req, this.openRequest(msg.url)); break; |
| 294 | case 'editor.show': this.show(msg.uri); break; |
| 295 | case 'editor.reveal': this.reveal(msg.uri, msg.range); break; |
| 296 | case 'editor.selection': this.selection(msg.uri, msg.selections); break; |
| 297 | case 'deco.type': this.decorations?.type(msg.key, msg.options); break; |
| 298 | case 'deco.set': this.decorations?.set(msg.key, msg.uri, msg.ranges); break; |
| 299 | case 'deco.remove': this.decorations?.remove(msg.key); break; |
| 300 | case 'pong': break; |
| 301 | default: break; |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // contesta una pregunta del recinto con un valor plano (o null si falla) |
| 306 | reply(req, promise) { |
| 307 | Promise.resolve(promise).then(v => v, () => null).then(v => { |
| 308 | if (this.state === 'stopped' || this.state === 'error') return; |
| 309 | this.post({ t: 'ui.result', req, value: isPlainData(v) ? (v ?? null) : null }); |
| 310 | }); |
| 311 | } |
| 312 | |
| 313 | // abrir una dirección externa: el diálogo de gates.js, que enseña la |
| 314 | // dirección entera; solo se abre si el usuario lo pide |
| 315 | openRequest(url) { return this.gate.request(url); } |
| 316 | |
| 317 | // el texto de una extensión entró en este documento: su vista previa HTML |
| 318 | // preguntará antes (gates.js) |
| 319 | touch(model) { |
| 320 | const path = model && this.docs?.pathOf(model); |
| 321 | if (path) markTouched(path).catch(() => {}); |
| 322 | } |
| 323 | |
| 324 | // una extensión quiere enseñar un documento abierto: solo se cambia de |
| 325 | // pestaña si el usuario acaba de hacer algo (un clic, una tecla); si no, el |
| 326 | // recinto vuelve a ver la pestaña de verdad |
| 327 | async show(uri) { |
| 328 | const model = this.docs?.modelForUri(uri); |
| 329 | const path = model && this.docs.pathOf(model); |
| 330 | if (!path) return; |
| 331 | if (this.editor.getModel() === model) return; |
| 332 | if (!userActive()) { this.log(null, 'info', 'an extension asked to show ' + path + ' without a recent click; the tab did not change'); this.docs.sendActive(); return; } |
| 333 | try { await (await import('../ide.js')).openFile(path); } catch { this.docs.sendActive(); } |
| 334 | } |
| 335 | |
| 336 | reveal(uri, range) { |
| 337 | const model = this.docs?.modelForUri(uri); |
| 338 | if (!model || this.editor.getModel() !== model) return; |
| 339 | const r = convert.range(this.monaco, model, range); |
| 340 | if (r) this.editor.revealRangeInCenterIfOutsideViewport(r); |
| 341 | } |
| 342 | |
| 343 | selection(uri, selections) { |
| 344 | const model = this.docs?.modelForUri(uri); |
| 345 | if (!model || this.editor.getModel() !== model) return; |
| 346 | const sels = selections.map(s => { |
| 347 | const a = model.validatePosition({ lineNumber: s[0], column: s[1] }), b = model.validatePosition({ lineNumber: s[2], column: s[3] }); |
| 348 | return { selectionStartLineNumber: a.lineNumber, selectionStartColumn: a.column, positionLineNumber: b.lineNumber, positionColumn: b.column }; |
| 349 | }); |
| 350 | if (sels.length) this.editor.setSelections(sels); |
| 351 | } |
| 352 | |
| 353 | log(id, level, text) { |
| 354 | const s = id ? this.status.get(id) || { id, state: 'installed', text: '', log: [] } : null; |
| 355 | if (s) { s.log.push({ level, text }); if (s.log.length > 200) s.log.shift(); this.status.set(id, s); } |
| 356 | (level === 'error' ? console.warn : console.debug)('[x2]', id || '', text); |
| 357 | } |
| 358 | |
| 359 | markers({ uri, owner, markers }) { |
| 360 | const model = this.docs?.modelForUri(uri); |
| 361 | if (!model) return; |
| 362 | const key = 'x2:' + owner; |
| 363 | this.monaco.editor.setModelMarkers(model, key, convert.markers(this.monaco, model, markers)); |
| 364 | if (!this.markerOwners.has(model)) this.markerOwners.set(model, new Set()); |
| 365 | this.markerOwners.get(model).add(key); |
| 366 | } |
| 367 | |
| 368 | context(key, value) { |
| 369 | if (!this.editor) return; |
| 370 | let k = this.contextKeys.get(key); |
| 371 | if (!k) { k = this.editor.createContextKey(key, value ?? undefined); this.contextKeys.set(key, k); } |
| 372 | else k.set(value ?? undefined); |
| 373 | } |
| 374 | |
| 375 | invoke(kind, handle, model, args, token) { |
| 376 | const uri = this.docs?.uriOf(model); |
| 377 | if (!uri || this.state !== 'running') return Promise.resolve(null); |
| 378 | const req = this.nextReq++; |
| 379 | return new Promise(resolve => { |
| 380 | let done = false; |
| 381 | const finish = v => { if (done) return; done = true; clearTimeout(timer); sub?.dispose(); this.pending.delete(req); resolve(v && typeof v === 'object' && v.stale ? null : v ?? null); }; |
| 382 | const timer = setTimeout(() => { this.post({ t: 'cancel', req }); finish(null); }, CALL_TIMEOUT); |
| 383 | const sub = token?.onCancellationRequested?.(() => { this.post({ t: 'cancel', req }); finish(null); }); |
| 384 | this.pending.set(req, finish); |
| 385 | this.post({ t: 'invoke', req, kind, handle, uri, v: model.getVersionId(), args }); |
| 386 | }); |
| 387 | } |
| 388 | |
| 389 | request(msg, timeout = CALL_TIMEOUT) { |
| 390 | const req = this.nextReq++; |
| 391 | return new Promise(resolve => { |
| 392 | const timer = setTimeout(() => { this.pending.delete(req); resolve(null); }, timeout); |
| 393 | this.pending.set(req, v => { clearTimeout(timer); resolve(v); }); |
| 394 | this.post({ ...msg, req }); |
| 395 | }); |
| 396 | } |
| 397 | |
| 398 | async runCommand(id, args) { |
| 399 | if (this.state !== 'running') return null; |
| 400 | for (let attempt = 0; attempt < 2; attempt++) { |
| 401 | const req = this.nextReq++; |
| 402 | const plainArgs = args === undefined ? undefined : isPlainData(args) ? [].concat(args) : undefined; |
| 403 | const v = await new Promise(resolve => { |
| 404 | const timer = setTimeout(() => { this.pending.delete(req); resolve(null); }, CALL_TIMEOUT); |
| 405 | this.pending.set(req, x => { clearTimeout(timer); resolve(x); }); |
| 406 | this.post({ t: 'cmd.exec', req, id, args: plainArgs, ...this.docs.activeState() }); |
| 407 | }); |
| 408 | if (!(v && v.stale)) return v ? v.value ?? null : null; |
| 409 | await new Promise(r => setTimeout(r, 50)); |
| 410 | } |
| 411 | return null; |
| 412 | } |
| 413 | |
| 414 | // ¿sobra alguna de las que ya están, o cambió de versión? (ver sync()) |
| 415 | stale(records) { |
| 416 | const want = new Map(records.map(r => [r.id, r.version])); |
| 417 | for (const [id, version] of this.added) if (want.get(id) !== version) return true; |
| 418 | return false; |
| 419 | } |
| 420 | |
| 421 | async sync(records) { |
| 422 | const want = new Map(records.map(r => [r.id, r])); |
| 423 | for (const id of [...this.added.keys()]) { |
| 424 | if (!want.has(id) || want.get(id).version !== this.added.get(id)) { |
| 425 | this.post({ t: 'ext.remove', id }); |
| 426 | this.commands?.remove(id); |
| 427 | this.added.delete(id); |
| 428 | this.status.delete(id); |
| 429 | } |
| 430 | } |
| 431 | const installed = new Set(records.map(r => r.id)); |
| 432 | for (const r of records) this.names.set(r.id, String(r.displayName || r.id).slice(0, 200)); |
| 433 | this.features?.setPrefs(new Map(records.map(r => [r.id, r.formatter && typeof r.formatter === 'object' ? r.formatter : {}]))); |
| 434 | // los ajustes de todas, juntos (sin «__proto__», que cambiaría el prototipo) |
| 435 | const settings = {}; |
| 436 | for (const r of records) { |
| 437 | if (!r.settings || typeof r.settings !== 'object') continue; |
| 438 | for (const [k, v] of Object.entries(r.settings)) if (k !== '__proto__') settings[k] = v; |
| 439 | } |
| 440 | this.post({ t: 'settings', json: JSON.stringify(settings) }); |
| 441 | for (const r of records) { |
| 442 | if (this.added.has(r.id)) continue; |
| 443 | const manifest = r.code?.manifest; |
| 444 | if (!manifest || typeof manifest.browser !== 'string') { this.status.set(r.id, { id: r.id, state: 'error', text: 'no browser entry', log: [] }); continue; } |
| 445 | let files; |
| 446 | try { files = await this.readCode(r); } |
| 447 | catch (e) { this.status.set(r.id, { id: r.id, state: 'error', text: 'its files could not be read: ' + (e?.message || e), log: [] }); continue; } |
| 448 | if (this.state === 'stopped') return; |
| 449 | this.added.set(r.id, r.version); |
| 450 | this.status.set(r.id, { id: r.id, state: 'installed', text: '', log: [] }); |
| 451 | this.post({ t: 'ext.add', id: r.id, version: r.version, manifest: sandboxManifest(manifest, installed), files }, files.map(f => f[1])); |
| 452 | this.commands.set({ id: r.id, displayName: r.displayName, manifest }); |
| 453 | } |
| 454 | emit(); |
| 455 | } |
| 456 | |
| 457 | fail(e) { |
| 458 | this.error = { code: e?.code || 'error', message: String(e?.message || e), ...(typeof e?.file === 'string' ? { file: e.file.slice(0, 100) } : {}) }; |
| 459 | lastError = this.error; |
| 460 | console.warn('[x2] nivel 2 parado:', this.error.message); |
| 461 | this.stop('error'); |
| 462 | } |
| 463 | |
| 464 | stop(state = 'stopped') { |
| 465 | if (this.state === 'stopped' || this.state === 'error') return; |
| 466 | this.state = state; |
| 467 | for (const p of this.pending.values()) { try { p(null); } catch { /* — */ } } |
| 468 | this.pending.clear(); |
| 469 | try { this.ui.dispose(); } catch { /* — */ } |
| 470 | try { this.restoreAgent?.(); } catch { /* — */ } |
| 471 | this.restoreAgent = null; |
| 472 | try { this.decorations?.dispose(); } catch { /* — */ } |
| 473 | try { this.features?.dispose(); } catch { /* — */ } |
| 474 | try { this.commands?.dispose(); } catch { /* — */ } |
| 475 | try { this.docs?.dispose(); } catch { /* — */ } |
| 476 | for (const [model, owners] of this.markerOwners) { |
| 477 | if (!model.isDisposed()) for (const o of owners) this.monaco.editor.setModelMarkers(model, o, []); |
| 478 | } |
| 479 | this.markerOwners.clear(); |
| 480 | for (const k of this.contextKeys.values()) { try { k.reset(); } catch { /* — */ } } |
| 481 | this.contextKeys.clear(); |
| 482 | for (const d of this.disposables) { try { d.dispose(); } catch { /* — */ } } |
| 483 | this.disposables = []; |
| 484 | try { this.port?.close(); } catch { /* — */ } |
| 485 | try { this.frame?.close(); } catch { /* — */ } |
| 486 | this.port = null; |
| 487 | emit(); |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | function statusbar(text) { |
| 492 | const el = document.getElementById('statusbar'); |
| 493 | if (el) el.textContent = text; |
| 494 | } |
| 495 | |
| 496 | // Lo llama js/ext/host.js tras cada cambio: con al menos una extensión |
| 497 | // activa con su código encendido, el recinto está arrancado y al día; sin |
| 498 | // ninguna, se desmonta (sin recargar la página). |
| 499 | let cola = Promise.resolve(); |
| 500 | export function sync(args) { |
| 501 | const { monaco, records, readCode } = args; |
| 502 | lastSync = args; |
| 503 | const run = async () => { |
| 504 | const live = disabledByUrl() ? [] : records.filter(r => r && r.enabled && r.runs && !refused.has(r.id)); |
| 505 | // Quitar una extensión del host de extensiones no para su código ni sus |
| 506 | // proveedores (VS Code reinicia el host para eso): si sobra alguna de las |
| 507 | // que ya corren, o cambió de versión, el recinto se rehace con las demás. |
| 508 | if (session && session.state === 'running' && session.stale(live)) { session.stop(); session = null; } |
| 509 | if (!live.length) { if (session) { session.stop(); session = null; } emit(); return state(); } |
| 510 | if (!session || session.state === 'error' || session.state === 'stopped') { |
| 511 | lastError = null; |
| 512 | session = new Session({ monaco, readCode }); |
| 513 | emit(); |
| 514 | try { await session.start(); } |
| 515 | catch (e) { session.fail(e); return state(); } |
| 516 | } |
| 517 | await session.sync(live); |
| 518 | return state(); |
| 519 | }; |
| 520 | const r = cola.then(run, run); |
| 521 | cola = r.catch(() => {}); |
| 522 | return r; |
| 523 | } |
| 524 | |
| 525 | export function stop() { |
| 526 | const r = cola.then(() => { if (session) { session.stop(); session = null; } emit(); }); |
| 527 | cola = r.catch(() => {}); |
| 528 | return r; |
| 529 | } |