| 1 | // Relevo del recinto de extensiones (nivel 2). Este fichero NO corre en Code: |
| 2 | // Code lo lee como texto y se lo entrega al recinto (otro sitio, sin red), que |
| 3 | // lo carga desde un blob:. Por eso no importa nada: recibe el bundle de VS Code |
| 4 | // ya cargado (`m`) y el MessagePort que creó la página. |
| 5 | // |
| 6 | // Qué hace: |
| 7 | // · arranca los servicios de VS Code sin interfaz, con un editor espejo |
| 8 | // oculto y servicios que fallan cerrados (abrir enlaces, portapapeles, |
| 9 | // diálogos, ficheros); |
| 10 | // · registra las extensiones con sus ficheros como blob: (el recinto nunca |
| 11 | // pide nada a la red: la página ya bajó y verificó todo al instalar); |
| 12 | // · mantiene copias de los documentos abiertos en Code, al día por versión; |
| 13 | // · captura los proveedores (formateo, hover, símbolos…) que registran las |
| 14 | // extensiones y los ejecuta cuando la página lo pide; |
| 15 | // · devuelve SIEMPRE datos planos: la página valida y reconstruye todo. |
| 16 | // |
| 17 | // La página no se fía de nada de lo que salga de aquí. |
| 18 | |
| 19 | const PROTOCOL = 1; |
| 20 | const MAX_DOC = 5 * 1024 * 1024; |
| 21 | const MAX_HANDLES = 2000; |
| 22 | |
| 23 | // registro de VS Code → tipo de proveedor que entiende la página |
| 24 | const KINDS = { |
| 25 | documentFormattingEditProvider: 'format', |
| 26 | documentRangeFormattingEditProvider: 'formatRange', |
| 27 | onTypeFormattingEditProvider: 'formatOnType', |
| 28 | completionProvider: 'completion', |
| 29 | hoverProvider: 'hover', |
| 30 | signatureHelpProvider: 'signature', |
| 31 | codeActionProvider: 'codeAction', |
| 32 | documentSymbolProvider: 'symbols', |
| 33 | definitionProvider: 'definition', |
| 34 | declarationProvider: 'declaration', |
| 35 | typeDefinitionProvider: 'typeDefinition', |
| 36 | implementationProvider: 'implementation', |
| 37 | referenceProvider: 'references', |
| 38 | renameProvider: 'rename', |
| 39 | documentHighlightProvider: 'highlights', |
| 40 | }; |
| 41 | // los que aún no se pasan a la página (fase 2): se cuentan, nada más |
| 42 | const LATER = ['codeLensProvider', 'inlayHintsProvider', 'colorProvider', 'linkProvider', 'foldingRangeProvider', 'selectionRangeProvider', |
| 43 | 'linkedEditingRangeProvider', 'inlineCompletionsProvider', 'documentSemanticTokensProvider', 'documentRangeSemanticTokensProvider', |
| 44 | 'documentPasteEditProvider', 'documentDropEditProvider', 'newSymbolNamesProvider', 'multiDocumentHighlightProvider', |
| 45 | 'inlineValuesProvider', 'evaluatableExpressionProvider']; |
| 46 | |
| 47 | const str = (v, max = 4096) => (typeof v === 'string' ? v.slice(0, max) : undefined); |
| 48 | const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : undefined); |
| 49 | const errText = e => String((e && (e.message || e.name)) || e || 'error').slice(0, 500); |
| 50 | |
| 51 | function emitter() { |
| 52 | const ls = new Set(); |
| 53 | const event = (fn, thisArg, store) => { |
| 54 | const f = thisArg ? fn.bind(thisArg) : fn; |
| 55 | ls.add(f); |
| 56 | const d = { dispose: () => ls.delete(f) }; |
| 57 | if (Array.isArray(store)) store.push(d); else if (store && typeof store.add === 'function') store.add(d); |
| 58 | return d; |
| 59 | }; |
| 60 | return { event, fire: v => { for (const f of [...ls]) { try { f(v); } catch { /* un oyente roto no para al resto */ } } } }; |
| 61 | } |
| 62 | |
| 63 | // Lo que la página acepta por mensaje (protocol.js: maxSize), contado igual que |
| 64 | // allí (texto ×2): aquí se recorta o se cambia por un error antes de mandar, |
| 65 | // para que algo legítimo pero enorme no cuente como una falta del recinto. |
| 66 | const CAP = { result: 16 << 20, 'doc.edit': 16 << 20 }; |
| 67 | const capOf = t => (CAP[t] || (1 << 20)) - 8192; |
| 68 | function approxSize(v, limit) { |
| 69 | let n = 0; |
| 70 | const stack = [v]; |
| 71 | while (stack.length) { |
| 72 | const x = stack.pop(); |
| 73 | if (typeof x === 'string') n += x.length * 2; |
| 74 | else if (typeof x === 'number' || typeof x === 'boolean' || x == null) n += 8; |
| 75 | else if (x instanceof ArrayBuffer || ArrayBuffer.isView(x)) n += x.byteLength; |
| 76 | else if (Array.isArray(x)) { n += 8; for (const y of x) stack.push(y); } |
| 77 | else if (typeof x === 'object') { for (const [k, y] of Object.entries(x)) { n += k.length * 2; stack.push(y); } } |
| 78 | if (n > limit) return n; |
| 79 | } |
| 80 | return n; |
| 81 | } |
| 82 | const LISTS = { 'deco.set': 'ranges', markers: 'markers', 'ui.pick': 'items', 'rpc.denied': 'top' }; |
| 83 | // La dirección externa como la abre VS Code: un texto, tal cual; un URI, con |
| 84 | // encodeURI(uri.toString(true)), que deja «=», «&» y «+» de la consulta como |
| 85 | // están (toString() los codificaría y sería otra dirección). |
| 86 | export function externalString(r) { |
| 87 | if (typeof r === 'string') return r; |
| 88 | try { if (r && typeof r.toString === 'function') return encodeURI(r.toString(true)); } catch { /* sustitutos sueltos */ } |
| 89 | return r && typeof r.toString === 'function' ? String(r.toString()) : ''; |
| 90 | } |
| 91 | |
| 92 | export function fit(msg) { |
| 93 | const cap = capOf(msg.t); |
| 94 | if (approxSize(msg, cap) <= cap) return msg; |
| 95 | if (msg.t === 'result') return { t: 'result', req: msg.req, ok: false, error: 'the answer was too large to pass to Code' }; |
| 96 | const key = LISTS[msg.t]; |
| 97 | if (!key || !Array.isArray(msg[key])) return null; |
| 98 | // antes de quitar elementos, lo que pesa y menos importa: los textos largos |
| 99 | let list = msg.t === 'deco.set' ? msg.ranges.map(({ hover, ...r }) => r) |
| 100 | : msg.t === 'markers' ? msg.markers.map(x => ({ ...x, message: String(x.message).slice(0, 500) })) : msg[key]; |
| 101 | while (list.length && approxSize({ ...msg, [key]: list }, cap) > cap) list = list.slice(0, list.length >> 1); |
| 102 | return { ...msg, [key]: list }; |
| 103 | } |
| 104 | |
| 105 | export async function start({ m, port, config, sandbox = {} }) { |
| 106 | const { monaco } = m; |
| 107 | const send = (msg, transfer) => { |
| 108 | const out = transfer && transfer.length ? msg : fit(msg); |
| 109 | if (!out) { try { port.postMessage({ t: 'log', level: 'warn', text: 'a message too large for Code was dropped: ' + String(msg.t).slice(0, 40) }); } catch { /* cerrado */ } return; } |
| 110 | try { port.postMessage(out, transfer || []); } catch (e) { try { port.postMessage({ t: 'log', level: 'error', text: 'unserializable message ' + msg.t + ': ' + errText(e) }); } catch { /* cerrado */ } } |
| 111 | }; |
| 112 | const log = (level, text, id) => send({ t: 'log', level, text: String(text).slice(0, 2000), ...(id ? { id } : {}) }); |
| 113 | |
| 114 | // Errores sin capturar del propio recinto (VS Code o una extensión): al |
| 115 | // registro de la página, con lo que se sepa de ellos, y no a la consola. |
| 116 | const describe = r => { |
| 117 | if (r instanceof Error) return (r.name + ': ' + r.message + ' ' + String(r.stack || '').split('\n').slice(1, 3).join(' ')).slice(0, 500); |
| 118 | try { return 'non-error ' + JSON.stringify(r, Object.getOwnPropertyNames(r || {})).slice(0, 500); } catch { return 'non-error ' + String(r).slice(0, 200); } |
| 119 | }; |
| 120 | const seenErrors = []; |
| 121 | const sandboxError = text => { seenErrors.push(text); if (seenErrors.length > 50) seenErrors.shift(); log('warn', text); }; |
| 122 | window.addEventListener('unhandledrejection', e => { e.preventDefault(); sandboxError('unhandled rejection in the sandbox: ' + describe(e.reason)); }); |
| 123 | window.addEventListener('error', e => { e.preventDefault(); sandboxError('uncaught error in the sandbox: ' + describe(e.error || e.message)); }); |
| 124 | |
| 125 | // ── cortafuegos y atribución: lo que llega del host de extensiones (RPC) ── |
| 126 | // Cada llamada del host de extensiones al hilo principal pasa por aquí. El |
| 127 | // código de las extensiones comparte el worker con el protocolo, así que |
| 128 | // puede fabricar tramas a mano (parcheando MessagePort.prototype) y VS Code |
| 129 | // llamaría a CUALQUIER función del actor con ese nombre. Aquí solo pasan los |
| 130 | // métodos «$…» que la página permite para cada actor (rpc-allowlist.json); |
| 131 | // el resto se rechaza (la extensión recibe un error) y se cuenta. También |
| 132 | // sirve para saber qué proveedores registra una extensión (y no VS Code) y |
| 133 | // para la foto de la superficie de la API. |
| 134 | const proto = m.RPCProtocol.prototype; |
| 135 | const actors = new Map(); // nombre → actor |
| 136 | let fromExtHost = 0; |
| 137 | const invokeOriginal = proto._doInvokeHandler; |
| 138 | const setOriginal = proto.set; |
| 139 | proto.set = function (identifier, value) { |
| 140 | try { actors.set(identifier.sid || m.getStringIdentifierForProxy(identifier.nid), value); } catch { /* — */ } |
| 141 | return setOriginal.call(this, identifier, value); |
| 142 | }; |
| 143 | const allowed = new Map(); // actor → Set(métodos); sin lista, nada pasa |
| 144 | for (const [a, ms] of Object.entries((config.rpc && typeof config.rpc.actors === 'object' && config.rpc.actors) || {})) { |
| 145 | if (Array.isArray(ms)) allowed.set(a, new Set(ms.filter(x => typeof x === 'string' && x.startsWith('$')))); |
| 146 | } |
| 147 | const NONE = new Set(); |
| 148 | const actorName = rpcId => { try { return String(m.getStringIdentifierForProxy(rpcId)); } catch { return 'actor#' + rpcId; } }; |
| 149 | const denials = { n: 0, by: new Map(), timer: null }; |
| 150 | const calls = new Map(); // «Actor.$método» → veces (diagnóstico para el censo) |
| 151 | function deny(actor, method) { |
| 152 | denials.n++; |
| 153 | const k = (actor + '.' + method).slice(0, 160); |
| 154 | denials.by.set(k, (denials.by.get(k) || 0) + 1); |
| 155 | if (denials.by.size > 200) denials.by.delete(denials.by.keys().next().value); |
| 156 | if (!denials.timer) { |
| 157 | denials.timer = setTimeout(() => { |
| 158 | denials.timer = null; |
| 159 | send({ t: 'rpc.denied', n: denials.n, top: [...denials.by].sort((a, b) => b[1] - a[1]).slice(0, 10) }); |
| 160 | }, 100); |
| 161 | } |
| 162 | } |
| 163 | // los fallos al activar una extensión llegan por aquí y no quedan en el |
| 164 | // estado de VS Code: se apuntan para decir por qué no arranca |
| 165 | const activationErrors = new Map(); // id → texto |
| 166 | proto._doInvokeHandler = function (rpcId, methodName, args) { |
| 167 | const actor = actorName(rpcId); |
| 168 | const method = typeof methodName === 'string' ? methodName : String(methodName); |
| 169 | if (!method.startsWith('$') || !(allowed.get(actor) || NONE).has(method)) { |
| 170 | deny(actor, method); |
| 171 | throw new Error('Elffuss Code does not let extensions call ' + actor + '.' + method.slice(0, 100)); |
| 172 | } |
| 173 | const ck = actor + '.' + method; |
| 174 | if (calls.has(ck) || calls.size < 1000) calls.set(ck, (calls.get(ck) || 0) + 1); |
| 175 | if (methodName === '$onExtensionActivationError') { |
| 176 | try { |
| 177 | const id = String((args[0] && (args[0].value || args[0]._lower)) || args[0]).toLowerCase(); |
| 178 | activationErrors.set(id, errText(args[1]) + (args[2] && args[2].dependency ? ` (missing dependency ${String(args[2].dependency).slice(0, 200)})` : '')); |
| 179 | setTimeout(() => status(id), 0); |
| 180 | } catch { /* — */ } |
| 181 | } |
| 182 | fromExtHost++; |
| 183 | try { return invokeOriginal.call(this, rpcId, methodName, args); } |
| 184 | finally { fromExtHost--; } |
| 185 | }; |
| 186 | |
| 187 | // ── preguntas a la página ── |
| 188 | // Lo que necesita al usuario (abrir una dirección, un aviso con botones, un |
| 189 | // diálogo, un selector, un cuadro de texto) se le pregunta a la página, que |
| 190 | // lo pinta como texto y contesta con datos planos ({t:'ui.result'}). La |
| 191 | // página contesta SIEMPRE, también cuando lo descarta (con null). |
| 192 | let nextAsk = 1; |
| 193 | const asks = new Map(); // req → resolve |
| 194 | function ask(t, payload, token) { |
| 195 | const req = nextAsk++; |
| 196 | return new Promise(resolve => { |
| 197 | asks.set(req, resolve); |
| 198 | if (token && typeof token.onCancellationRequested === 'function') { |
| 199 | token.onCancellationRequested(() => { if (asks.delete(req)) { send({ t: 'ui.cancel', req }); resolve(null); } }); |
| 200 | } |
| 201 | send({ t, req, ...payload }); |
| 202 | }); |
| 203 | } |
| 204 | const msgText = msg => (typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : msg && typeof msg.value === 'string' ? msg.value : msg == null ? '' : String(msg)); |
| 205 | const label = v => String(typeof v === 'string' ? v : v && typeof v.label === 'string' ? v.label : v == null ? '' : v).replace(/&&/g, '').slice(0, 200); |
| 206 | const SEV = { 0: 'info', 1: 'info', 2: 'warning', 3: 'error', info: 'info', warning: 'warning', error: 'error' }; |
| 207 | const sevOf = s => SEV[s] || 'info'; |
| 208 | const sourceOf = s => (s && typeof s === 'object' && typeof s.id === 'string' && /^[\w-]+\.[\w.-]+$/.test(s.id) ? s.id.toLowerCase().slice(0, 200) : undefined); |
| 209 | |
| 210 | // ── abrir direcciones ── |
| 211 | // http, https y mailto: la página pregunta enseñando la dirección entera y |
| 212 | // solo ella abre (si el usuario dice que sí). file: de un documento abierto: |
| 213 | // se enseña ese documento. Cualquier otra cosa (command:, vscode:, data:…) |
| 214 | // se rechaza. Nada sale nunca de aquí. |
| 215 | const openRefused = { n: 0 }; |
| 216 | const uriString = r => (typeof r === 'string' ? r : r && typeof r.toString === 'function' ? r.toString() : ''); |
| 217 | const opener = { |
| 218 | _serviceBrand: undefined, |
| 219 | registerOpener: () => ({ dispose() {} }), |
| 220 | registerValidator: () => ({ dispose() {} }), |
| 221 | registerExternalUriResolver: () => ({ dispose() {} }), |
| 222 | setDefaultExternalOpener() {}, |
| 223 | registerExternalOpener: () => ({ dispose() {} }), |
| 224 | async open(resource) { |
| 225 | const s = uriString(resource).slice(0, 8192); |
| 226 | const scheme = (/^([a-z][a-z0-9+.-]*):/i.exec(s) || [])[1]?.toLowerCase(); |
| 227 | if (scheme === 'http' || scheme === 'https' || scheme === 'mailto') return (await ask('open.request', { url: externalString(resource).slice(0, 8192) })) === true; |
| 228 | if (scheme === 'file' && docs.has(s)) { showDoc(s); return true; } |
| 229 | openRefused.n++; |
| 230 | log('warn', 'refused to open ' + s.slice(0, 200)); |
| 231 | return false; |
| 232 | }, |
| 233 | // sin túneles ni peticiones: la dirección tal cual |
| 234 | async resolveExternalUri(resource) { return { resolved: resource, dispose() {} }; }, |
| 235 | }; |
| 236 | const clipboard = { |
| 237 | _serviceBrand: undefined, |
| 238 | triggerPaste: () => undefined, |
| 239 | // la página solo escribe con un gesto reciente del usuario |
| 240 | writeText: async text => { if (typeof text === 'string' && text.length <= 500000) send({ t: 'clipboard.write', text }); }, |
| 241 | readText: async () => '', |
| 242 | readFindText: async () => '', |
| 243 | writeFindText: async () => {}, |
| 244 | writeResources: async () => {}, |
| 245 | readResources: async () => [], |
| 246 | hasResources: async () => false, |
| 247 | clearInternalState() {}, |
| 248 | readImage: async () => new Uint8Array(0), |
| 249 | }; |
| 250 | |
| 251 | // ── avisos ── |
| 252 | const handle = () => { |
| 253 | const closed = emitter(), visible = emitter(); |
| 254 | let isClosed = false; |
| 255 | return { |
| 256 | close() { if (!isClosed) { isClosed = true; closed.fire(); } }, |
| 257 | onDidClose: closed.event, onDidChangeVisibility: visible.event, |
| 258 | progress: { infinite() {}, total() {}, worked() {}, done() {} }, updateSeverity() {}, updateMessage() {}, updateActions() {}, |
| 259 | }; |
| 260 | }; |
| 261 | const filterChanged = emitter(); |
| 262 | // un aviso con botones (acciones o «choices»): la página dice cuál se pulsó |
| 263 | function toast(sev, message, actions, source, onCancel) { |
| 264 | const h = handle(); |
| 265 | const list = (Array.isArray(actions) ? actions : []).filter(a => a && typeof a.run === 'function').slice(0, 5); |
| 266 | ask('ui.notify', { sev: sevOf(sev), text: msgText(message).slice(0, 4096), actions: list.map(a => label(a.label) || '?'), ...(source ? { source } : {}) }).then(i => { |
| 267 | if (Number.isSafeInteger(i) && list[i]) { try { list[i].run(); } catch (e) { log('warn', 'notification action failed: ' + errText(e)); } } |
| 268 | else if (typeof onCancel === 'function') { try { onCancel(); } catch { /* — */ } } |
| 269 | h.close(); |
| 270 | }); |
| 271 | return h; |
| 272 | } |
| 273 | const notifications = { |
| 274 | _serviceBrand: undefined, |
| 275 | onDidChangeFilter: filterChanged.event, |
| 276 | setFilter() {}, getFilter: () => 0, getFilters: () => [], removeFilter() {}, |
| 277 | notify(n) { return toast(n && n.severity, n && n.message, n && n.actions && n.actions.primary, sourceOf(n && n.source)); }, |
| 278 | info(msg) { for (const x of [].concat(msg)) toast('info', x); }, |
| 279 | warn(msg) { for (const x of [].concat(msg)) toast('warning', x); }, |
| 280 | error(msg) { for (const x of [].concat(msg)) toast('error', x); }, |
| 281 | prompt(sev, message, choices, options) { return toast(sev, message, choices, sourceOf(options && options.source), options && options.onCancel); }, |
| 282 | status(message) { log('info', 'status: ' + msgText(message).slice(0, 500)); return { close() {}, dispose() {} }; }, |
| 283 | }; |
| 284 | |
| 285 | // ── diálogos modales (showXMessage con {modal: true}) ── |
| 286 | const dialogShown = emitter(), dialogWill = emitter(); |
| 287 | async function dialogAsk(type, message, detail, labels, cancel) { |
| 288 | const i = await ask('ui.dialog', { sev: sevOf(type), text: msgText(message).slice(0, 4096), ...(detail ? { detail: msgText(detail).slice(0, 4096) } : {}), buttons: labels.slice(0, 10), ...(cancel ? { cancel } : {}) }); |
| 289 | return Number.isSafeInteger(i) && i >= 0 && i < labels.length ? i : -1; |
| 290 | } |
| 291 | const dialogs = { |
| 292 | _serviceBrand: undefined, |
| 293 | onWillShowDialog: dialogWill.event, |
| 294 | onDidShowDialog: dialogShown.event, |
| 295 | async confirm(c = {}) { |
| 296 | const i = await dialogAsk(c.type, c.message, c.detail, [label(c.primaryButton) || 'OK'], label(c.cancelButton) || undefined); |
| 297 | return { confirmed: i === 0, checkboxChecked: false }; |
| 298 | }, |
| 299 | async prompt(p = {}) { |
| 300 | const buttons = (Array.isArray(p.buttons) ? p.buttons : []).slice(0, 10); |
| 301 | const cb = p.cancelButton; |
| 302 | const i = await dialogAsk(p.type, p.message, p.detail, buttons.map(b => label(b) || '?'), cb ? label(cb) : undefined); |
| 303 | const chosen = i >= 0 ? buttons[i] : (cb && typeof cb === 'object' ? cb : null); |
| 304 | const result = chosen && typeof chosen.run === 'function' ? await chosen.run({ checkboxChecked: false }) : undefined; |
| 305 | return { result, checkboxChecked: false }; |
| 306 | }, |
| 307 | input: async () => ({ confirmed: false }), |
| 308 | async info(message, detail) { await dialogAsk('info', message, detail, [], label('OK')); }, |
| 309 | async warn(message, detail) { await dialogAsk('warning', message, detail, [], label('OK')); }, |
| 310 | async error(message, detail) { await dialogAsk('error', message, detail, [], label('OK')); }, |
| 311 | about: async () => {}, |
| 312 | }; |
| 313 | |
| 314 | // ── progreso (withProgress) → la barra de estado de Code ── |
| 315 | let nextProgress = 1; |
| 316 | const progressService = { |
| 317 | _serviceBrand: undefined, |
| 318 | async withProgress(options, task) { |
| 319 | const id = nextProgress++; |
| 320 | const title = msgText(options && options.title).slice(0, 300); |
| 321 | let timer = null, pending = null; |
| 322 | const post = (text, done) => send({ t: 'ui.progress', id, text: String(text || '').slice(0, 500), done }); |
| 323 | post(title, false); |
| 324 | const progress = { |
| 325 | report(v) { |
| 326 | const m2 = v && typeof v.message === 'string' ? v.message : ''; |
| 327 | pending = title && m2 ? title + ': ' + m2 : (title || m2); |
| 328 | if (!timer) timer = setTimeout(() => { timer = null; post(pending, false); }, 250); |
| 329 | }, |
| 330 | }; |
| 331 | try { return await task(progress); } |
| 332 | finally { clearTimeout(timer); post('', true); } |
| 333 | }, |
| 334 | }; |
| 335 | const refuse = async () => { throw new Error('Not available in Elffuss Code.'); }; |
| 336 | const fileDialogs = { |
| 337 | _serviceBrand: undefined, |
| 338 | defaultFilePath: refuse, defaultFolderPath: refuse, defaultWorkspacePath: refuse, |
| 339 | pickFileFolderAndOpen: refuse, pickFileAndOpen: refuse, pickFolderAndOpen: refuse, pickWorkspaceAndOpen: refuse, |
| 340 | pickFileToSave: async () => undefined, preferredHome: refuse, |
| 341 | showSaveDialog: async () => undefined, showSaveConfirm: async () => 1, showOpenDialog: async () => undefined, |
| 342 | }; |
| 343 | |
| 344 | // ── editor espejo: lo que VS Code cree que es «el editor activo» ── |
| 345 | let mirror = null; |
| 346 | const activeChanged = emitter(), visibleChanged = emitter(); |
| 347 | const none = () => ({ dispose() {} }); |
| 348 | const nothing = (...a) => none; |
| 349 | const editorService = { |
| 350 | _serviceBrand: undefined, |
| 351 | onWillOpenEditor: nothing, onDidActiveEditorChange: activeChanged.event, onDidVisibleEditorsChange: visibleChanged.event, |
| 352 | onDidEditorsChange: nothing, onDidCloseEditor: nothing, onDidMostRecentlyActiveEditorsChange: nothing, |
| 353 | activeEditorPane: undefined, activeEditor: undefined, activeTextEditorLanguageId: undefined, |
| 354 | visibleEditorPanes: [], visibleEditors: [], editors: [], count: 0, mostRecentlyActiveEditors: [], |
| 355 | get activeTextEditorControl() { return mirror && mirror.getModel() ? mirror : undefined; }, |
| 356 | get visibleTextEditorControls() { return mirror ? [mirror] : []; }, |
| 357 | getVisibleTextEditorControls() { return mirror ? [mirror] : []; }, |
| 358 | // showTextDocument / vscode.open de un documento abierto: el espejo lo |
| 359 | // enseña y la página decide si cambia de pestaña (solo con un gesto |
| 360 | // reciente del usuario). De uno que no está abierto: nada. |
| 361 | getEditors: () => [], openEditors: async () => [], replaceEditors: async () => {}, |
| 362 | async openEditor(input) { |
| 363 | const r = input && (input.resource || (input.original && input.original.resource)); |
| 364 | const uri = r ? uriString(r) : null; |
| 365 | if (!uri || !docs.has(uri)) return undefined; |
| 366 | showDoc(uri); |
| 367 | return { getControl: () => mirror, input, group: undefined }; |
| 368 | }, |
| 369 | isOpened: () => false, isVisible: () => false, closeEditor: async () => {}, closeEditors: async () => {}, |
| 370 | findEditors: () => [], save: async () => ({ success: false, editors: [] }), saveAll: async () => ({ success: false, editors: [] }), |
| 371 | revert: async () => false, revertAll: async () => false, createScoped() { return this; }, |
| 372 | }; |
| 373 | |
| 374 | const host = document.createElement('div'); |
| 375 | host.style.cssText = 'position:fixed;left:0;top:0;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none'; |
| 376 | document.body.appendChild(host); |
| 377 | const mirrorBox = document.createElement('div'); |
| 378 | mirrorBox.style.cssText = 'width:400px;height:200px'; |
| 379 | host.appendChild(mirrorBox); |
| 380 | |
| 381 | // estado de lenguaje (lo que VS Code pinta en la barra de estado): Code no |
| 382 | // tiene esa barra; se acepta y no se enseña |
| 383 | const statusChanged = emitter(); |
| 384 | const languageStatus = { _serviceBrand: undefined, onDidChange: statusChanged.event, addStatus: () => ({ dispose() {} }), getLanguageStatus: () => [] }; |
| 385 | |
| 386 | await m.initialize({ |
| 387 | ...m.getExtensionServiceOverride({ enableWorkerExtensionHost: true }), |
| 388 | ...m.getKeybindingsServiceOverride(), |
| 389 | ...m.getConfigurationServiceOverride(), |
| 390 | [m.IEditorService.toString()]: editorService, |
| 391 | [m.IOpenerService.toString()]: opener, |
| 392 | [m.IClipboardService.toString()]: clipboard, |
| 393 | [m.INotificationService.toString()]: notifications, |
| 394 | [m.IDialogService.toString()]: dialogs, |
| 395 | [m.IFileDialogService.toString()]: fileDialogs, |
| 396 | [m.ILanguageStatusService.toString()]: languageStatus, |
| 397 | // (sin importar su identificador: VS Code lo resuelve por este nombre) |
| 398 | progressService, |
| 399 | }, host); |
| 400 | |
| 401 | const commandService = await m.getService(m.ICommandService); |
| 402 | const features = await m.getService(m.ILanguageFeaturesService); |
| 403 | const markerService = await m.getService(m.IMarkerService); |
| 404 | const extensionService = await m.getService(m.IExtensionService); |
| 405 | const contextKeys = await m.getService(m.IContextKeyService); |
| 406 | const quickInput = await m.getService(m.IQuickInputService); |
| 407 | const codeEditors = await m.getService(m.ICodeEditorService); |
| 408 | |
| 409 | // selector rápido y cuadro de texto: los pinta la página (solo texto: sin |
| 410 | // iconos ni botones). createQuickPick/createInputBox (la API completa) aún no. |
| 411 | const pickText = v => String(typeof v === 'string' ? v : v && typeof v.label === 'string' ? v.label : '').replace(/\$\([\w~-]{1,60}\)\s?/g, ''); |
| 412 | try { |
| 413 | quickInput.pick = async (picks, options = {}, token) => { |
| 414 | let list; |
| 415 | try { list = await Promise.resolve(picks); } catch { return undefined; } |
| 416 | if (!Array.isArray(list)) return undefined; |
| 417 | list = list.slice(0, 1000); |
| 418 | const items = list.map(it => (it && it.type === 'separator' |
| 419 | ? { sep: pickText(it.label).slice(0, 200) } |
| 420 | : { label: pickText(it && it.label).slice(0, 500), ...(it && typeof it.description === 'string' ? { description: pickText(it.description).slice(0, 500) } : {}), |
| 421 | ...(it && typeof it.detail === 'string' ? { detail: pickText(it.detail).slice(0, 1000) } : {}), ...(it && it.picked === true ? { picked: true } : {}) })); |
| 422 | const many = options.canPickMany === true; |
| 423 | const v = await ask('ui.pick', { items, options: { |
| 424 | ...(typeof options.title === 'string' ? { title: options.title.slice(0, 200) } : {}), |
| 425 | ...(typeof options.placeHolder === 'string' ? { placeHolder: options.placeHolder.slice(0, 200) } : {}), |
| 426 | canPickMany: many, matchOnDescription: options.matchOnDescription === true, matchOnDetail: options.matchOnDetail === true, |
| 427 | } }, token); |
| 428 | const ok = i => Number.isSafeInteger(i) && i >= 0 && i < list.length && list[i] && list[i].type !== 'separator'; |
| 429 | if (many) return Array.isArray(v) ? [...new Set(v)].filter(ok).map(i => list[i]) : undefined; |
| 430 | return ok(v) ? list[v] : undefined; |
| 431 | }; |
| 432 | quickInput.input = async (options = {}, token) => { |
| 433 | let validation = null, value = typeof options.value === 'string' ? options.value.slice(0, 10000) : ''; |
| 434 | // validación al aceptar: si la extensión pone un error, se vuelve a pedir |
| 435 | for (let n = 0; n < 10; n++) { |
| 436 | const v = await ask('ui.input', { options: { |
| 437 | ...(typeof options.title === 'string' ? { title: options.title.slice(0, 200) } : {}), |
| 438 | ...(typeof options.prompt === 'string' ? { prompt: options.prompt.slice(0, 1000) } : {}), |
| 439 | ...(typeof options.placeHolder === 'string' ? { placeHolder: options.placeHolder.slice(0, 200) } : {}), |
| 440 | value, password: options.password === true, ...(validation ? { validation } : {}), |
| 441 | } }, token); |
| 442 | if (typeof v !== 'string') return undefined; |
| 443 | if (typeof options.validateInput !== 'function') return v; |
| 444 | let r = null; |
| 445 | try { r = await options.validateInput(v); } catch { r = null; } |
| 446 | const text = typeof r === 'string' ? r : r && typeof r.content === 'string' && (r.severity === undefined || r.severity >= 3) ? r.content : ''; |
| 447 | if (!text) return v; |
| 448 | validation = text.slice(0, 500); |
| 449 | value = v.slice(0, 10000); |
| 450 | } |
| 451 | return undefined; |
| 452 | }; |
| 453 | quickInput.createQuickPick = () => { throw new Error('Not supported in Elffuss Code yet.'); }; |
| 454 | quickInput.createInputBox = () => { throw new Error('Not supported in Elffuss Code yet.'); }; |
| 455 | } catch { /* — */ } |
| 456 | |
| 457 | // lenguajes de la página (los de serie de Code y los del nivel 1) |
| 458 | const knownLangs = new Set(monaco.languages.getLanguages().map(l => l.id)); |
| 459 | for (const l of Array.isArray(config.languages) ? config.languages : []) { |
| 460 | if (!l || typeof l.id !== 'string' || knownLangs.has(l.id)) continue; |
| 461 | monaco.languages.register({ id: l.id, extensions: (l.extensions || []).filter(x => typeof x === 'string'), aliases: (l.aliases || []).filter(x => typeof x === 'string') }); |
| 462 | knownLangs.add(l.id); |
| 463 | } |
| 464 | |
| 465 | mirror = monaco.editor.create(mirrorBox, { |
| 466 | model: null, readOnly: false, automaticLayout: false, minimap: { enabled: false }, |
| 467 | hover: { enabled: false }, links: false, codeLens: false, inlayHints: { enabled: 'off' }, colorDecorators: false, |
| 468 | folding: false, 'semanticHighlighting.enabled': false, quickSuggestions: false, suggestOnTriggerCharacters: false, |
| 469 | parameterHints: { enabled: false }, lightbulb: { enabled: 'off' }, occurrencesHighlight: 'off', selectionHighlight: false, |
| 470 | stickyScroll: { enabled: false }, formatOnType: false, formatOnPaste: false, wordBasedSuggestions: 'off', |
| 471 | matchBrackets: 'never', renderValidationDecorations: 'off', |
| 472 | }); |
| 473 | mirror.onDidChangeModel(() => { activeChanged.fire(); visibleChanged.fire(); }); |
| 474 | activeChanged.fire(); |
| 475 | // el tema (claro, oscuro, alto contraste) que tiene Code: lo ven las extensiones |
| 476 | { const th = { light: 'vs', dark: 'vs-dark', hc: 'hc-black', 'hc-light': 'hc-light' }[config.theme]; if (th) monaco.editor.setTheme(th); } |
| 477 | |
| 478 | // ── proveedores: captura en cada registro de ILanguageFeaturesService ── |
| 479 | let nextHandle = 1; |
| 480 | const providers = new Map(); // handle → { kind, provider } |
| 481 | const later = { n: 0 }; |
| 482 | const kindCount = {}; // tipo → proveedores registrados (para el censo) |
| 483 | const lastExtension = { id: null }; |
| 484 | const selectorOf = sel => [].concat(sel).map(s => (typeof s === 'string' ? { language: s } |
| 485 | : s && typeof s === 'object' ? { language: str(s.language, 100), scheme: str(s.scheme, 50), pattern: str(typeof s.pattern === 'string' ? s.pattern : s.pattern && s.pattern.pattern, 500) } : null)).filter(Boolean); |
| 486 | for (const [name, kind] of Object.entries(KINDS)) { |
| 487 | const reg = features[name]; |
| 488 | if (!reg || typeof reg.register !== 'function') continue; |
| 489 | const orig = reg.register.bind(reg); |
| 490 | reg.register = (selector, provider) => { |
| 491 | const d = orig(selector, provider); |
| 492 | if (!fromExtHost) return d; // de VS Code mismo: no sale |
| 493 | const handle = nextHandle++; |
| 494 | const meta = {}; |
| 495 | if (kind === 'completion') { meta.triggerCharacters = (provider.triggerCharacters || []).filter(c => typeof c === 'string').slice(0, 50); meta.resolve = typeof provider.resolveCompletionItem === 'function'; } |
| 496 | if (kind === 'signature') { meta.triggerCharacters = (provider.signatureHelpTriggerCharacters || []).slice(0, 20); meta.retriggerCharacters = (provider.signatureHelpRetriggerCharacters || []).slice(0, 20); } |
| 497 | if (kind === 'formatOnType') meta.triggerCharacters = (provider.autoFormatTriggerCharacters || []).slice(0, 20); |
| 498 | if (kind === 'codeAction') { meta.kinds = (provider.providedCodeActionKinds || []).filter(k => typeof k === 'string').slice(0, 50); meta.resolve = typeof provider.resolveCodeAction === 'function'; } |
| 499 | if (kind === 'rename') meta.resolve = typeof provider.resolveRenameLocation === 'function'; |
| 500 | if (typeof provider.displayName === 'string') meta.displayName = provider.displayName.slice(0, 200); |
| 501 | if (provider.extensionId) meta.extension = str(provider.extensionId.value || provider.extensionId._lower || String(provider.extensionId), 200); |
| 502 | providers.set(handle, { kind, provider }); |
| 503 | kindCount[kind] = (kindCount[kind] || 0) + 1; |
| 504 | send({ t: 'providers.add', handle, kind, selector: selectorOf(selector), meta }); |
| 505 | return { dispose() { d.dispose(); if (providers.delete(handle)) send({ t: 'providers.remove', handle }); } }; |
| 506 | }; |
| 507 | } |
| 508 | const laterKinds = {}; |
| 509 | for (const name of LATER) { |
| 510 | const reg = features[name]; |
| 511 | if (!reg || typeof reg.register !== 'function') continue; |
| 512 | const orig = reg.register.bind(reg); |
| 513 | reg.register = (selector, provider) => { if (fromExtHost) { later.n++; laterKinds[name] = (laterKinds[name] || 0) + 1; } return orig(selector, provider); }; |
| 514 | } |
| 515 | |
| 516 | // ── setContext: la clave se pone aquí y la página la refleja ── |
| 517 | m.CommandsRegistry.registerCommand('setContext', (accessor, key, value) => { |
| 518 | if (typeof key !== 'string') return; |
| 519 | contextKeys.createKey(key, value); |
| 520 | if (/^[\w.:-]{1,100}$/.test(key) && (value === null || ['string', 'number', 'boolean', 'undefined'].includes(typeof value))) send({ t: 'ctx.set', key, value: value === undefined ? null : value }); |
| 521 | }); |
| 522 | |
| 523 | // ── extensiones ── |
| 524 | const exts = new Map(); // id → { reg, urls, state } |
| 525 | const unsupported = new Set(); |
| 526 | const extCommands = new Set(); // comandos que registraron las extensiones |
| 527 | m.CommandsRegistry.onDidRegisterCommand(id => { |
| 528 | // (los __vsc<uuid> son internos del host de extensiones, no de ninguna extensión) |
| 529 | if (fromExtHost && typeof id === 'string' && !id.startsWith('__vsc')) extCommands.add(id); |
| 530 | // sustituir el tecleo (Vim, Emacs…) no está soportado: se para esa extensión |
| 531 | if (id === 'type' && fromExtHost) { |
| 532 | log('warn', 'an extension registered the "type" command (it replaces typing): not supported'); |
| 533 | for (const [eid, e] of exts) if (e.state === 'active' || e.state === 'activating') unsupported.add(eid); |
| 534 | for (const eid of unsupported) removeExt(eid, 'unsupported', 'replaces typing (the "type" command), which Elffuss Code does not support'); |
| 535 | } |
| 536 | }); |
| 537 | |
| 538 | const MIME = { js: 'text/javascript', mjs: 'text/javascript', cjs: 'text/javascript', json: 'application/json', wasm: 'application/wasm', css: 'text/css', svg: 'image/svg+xml', png: 'image/png', txt: 'text/plain', md: 'text/markdown' }; |
| 539 | async function addExt({ id, manifest, files }) { |
| 540 | if (exts.has(id)) removeExt(id); |
| 541 | const reg = m.registerExtension(manifest, m.ExtensionHostKind.LocalWebWorker); |
| 542 | const urls = [], fileRegs = []; |
| 543 | for (const [p, bytes] of files) { |
| 544 | const type = MIME[String(p).split('.').pop().toLowerCase()] || 'application/octet-stream'; |
| 545 | const url = URL.createObjectURL(new Blob([bytes], { type })); |
| 546 | urls.push(url); |
| 547 | // (cada fichero queda registrado aparte: hay que soltarlo al quitarla, |
| 548 | // o volver a encenderla o actualizarla diría «ya existe») |
| 549 | fileRegs.push(reg.registerFileUrl('/' + p, url)); |
| 550 | } |
| 551 | exts.set(id, { reg, urls, fileRegs, state: 'installed' }); |
| 552 | await reg.whenReady(); |
| 553 | status(id); |
| 554 | } |
| 555 | function removeExt(id, state = 'stopped', text = '') { |
| 556 | const e = exts.get(id); |
| 557 | if (!e) return; |
| 558 | exts.delete(id); |
| 559 | try { e.reg.dispose(); } catch { /* — */ } |
| 560 | for (const d of e.fileRegs || []) { try { d && d.dispose(); } catch { /* — */ } } |
| 561 | setTimeout(() => { for (const u of e.urls) URL.revokeObjectURL(u); }, 5000); |
| 562 | send({ t: 'ext.status', id, state, text }); |
| 563 | } |
| 564 | function status(id) { |
| 565 | const e = exts.get(id); |
| 566 | if (!e) return; |
| 567 | const all = extensionService.getExtensionsStatus ? extensionService.getExtensionsStatus() : {}; |
| 568 | const key = Object.keys(all).find(k => k.toLowerCase() === id); |
| 569 | const st = key ? all[key] : null; |
| 570 | // no arrancó: el error de activación; arrancada: los errores que haya |
| 571 | // tenido después solo se cuentan en el texto |
| 572 | const failed = activationErrors.get(id); |
| 573 | const errors = [...(failed ? [failed] : []), ...(st ? [...(st.runtimeErrors || []).map(errText), ...(st.messages || []).filter(x => x && x.type === 3).map(x => errText(x.message))] : [])]; |
| 574 | const state = failed ? 'error' : st && st.activationTimes ? 'active' : st && st.activationStarted ? 'activating' : 'installed'; |
| 575 | const text = errors.slice(0, 3).join(' · ').slice(0, 1000); |
| 576 | if (state === e.state && text === (e.text || '')) return; |
| 577 | e.state = state; |
| 578 | e.text = text; |
| 579 | send({ t: 'ext.status', id, state, text, providersLater: later.n, openRefused: openRefused.n }); |
| 580 | } |
| 581 | if (extensionService.onDidChangeExtensionsStatus) extensionService.onDidChangeExtensionsStatus(ids => { for (const x of ids || []) status(String(x.value || x).toLowerCase()); }); |
| 582 | |
| 583 | // ── documentos ── |
| 584 | const docs = new Map(); // uri → { model, pageV, pending, steps, applying } |
| 585 | let applyingPage = false; |
| 586 | let fromPage = 0; // >0 mientras se aplica algo que mandó la página (no se le devuelve) |
| 587 | const uriOfModel = model => { if (!model) return null; const u = model.uri.toString(); return docs.has(u) ? u : null; }; |
| 588 | |
| 589 | // ── lo que una extensión hace en el editor activo → la página ── |
| 590 | // Selección y desplazamiento: VS Code los pide al editor (el espejo); aquí se |
| 591 | // copian a la página, que solo los aplica al documento activo. |
| 592 | let selTimer = null, revealTimer = null, revealPending = null; |
| 593 | const origSetSelections = mirror.setSelections.bind(mirror); |
| 594 | mirror.setSelections = function (sels, source) { |
| 595 | const r = origSetSelections(sels, source); |
| 596 | if (!fromPage && !selTimer) { |
| 597 | selTimer = setTimeout(() => { |
| 598 | selTimer = null; |
| 599 | const uri = uriOfModel(mirror.getModel()); |
| 600 | const s = mirror.getSelections() || []; |
| 601 | if (uri && s.length) send({ t: 'editor.selection', uri, selections: s.slice(0, 100).map(x => [x.selectionStartLineNumber, x.selectionStartColumn, x.positionLineNumber, x.positionColumn]) }); |
| 602 | }, 0); |
| 603 | } |
| 604 | return r; |
| 605 | }; |
| 606 | // Decoraciones (setDecorations): el tipo se registra en ICodeEditorService y |
| 607 | // los rangos se ponen en el espejo. A la página van solo datos planos; ella |
| 608 | // reconstruye el CSS con su lista blanca (decorations.js). |
| 609 | const DECO_KEYS = ['backgroundColor', 'outline', 'outlineColor', 'outlineStyle', 'outlineWidth', 'border', 'borderColor', 'borderRadius', 'borderSpacing', |
| 610 | 'borderStyle', 'borderWidth', 'fontStyle', 'fontWeight', 'textDecoration', 'cursor', 'color', 'opacity', 'letterSpacing', 'overviewRulerColor']; |
| 611 | const CONTENT_KEYS = ['contentText', 'border', 'borderColor', 'fontStyle', 'fontWeight', 'textDecoration', 'color', 'backgroundColor', 'margin', 'width', 'height', 'opacity']; |
| 612 | const plainPick = (o, keys) => { |
| 613 | const out = {}; |
| 614 | if (!o || typeof o !== 'object') return out; |
| 615 | for (const k of keys) { |
| 616 | const v = o[k]; |
| 617 | if (typeof v === 'string') out[k] = v.slice(0, 300); |
| 618 | else if (typeof v === 'number' && Number.isFinite(v)) out[k] = v; |
| 619 | else if (v && typeof v === 'object' && typeof v.id === 'string') out[k] = { themeColor: v.id.slice(0, 100) }; |
| 620 | } |
| 621 | return out; |
| 622 | }; |
| 623 | const withContent = (o, keys) => { |
| 624 | const out = plainPick(o, keys); |
| 625 | for (const side of ['before', 'after']) if (o && o[side] && typeof o[side] === 'object') out[side] = plainPick(o[side], CONTENT_KEYS); |
| 626 | return out; |
| 627 | }; |
| 628 | const decoOptions = o => ({ |
| 629 | ...withContent(o, DECO_KEYS), |
| 630 | ...(o && o.isWholeLine === true ? { isWholeLine: true } : {}), |
| 631 | ...(o && Number.isSafeInteger(o.rangeBehavior) ? { rangeBehavior: o.rangeBehavior } : {}), |
| 632 | ...(o && Number.isSafeInteger(o.overviewRulerLane) ? { overviewRulerLane: o.overviewRulerLane } : {}), |
| 633 | ...(o && o.light && typeof o.light === 'object' ? { light: withContent(o.light, DECO_KEYS) } : {}), |
| 634 | ...(o && o.dark && typeof o.dark === 'object' ? { dark: withContent(o.dark, DECO_KEYS) } : {}), |
| 635 | }); |
| 636 | const decoTypes = new Set(); |
| 637 | const decoKey = k => (typeof k === 'string' && /^[\w.-]{1,100}$/.test(k) ? k : null); |
| 638 | const registerType = codeEditors.registerDecorationType.bind(codeEditors); |
| 639 | codeEditors.registerDecorationType = function (description, key, options, parentTypeKey, editor) { |
| 640 | const r = registerType(description, key, options, parentTypeKey, editor); |
| 641 | if (decoKey(key) && !parentTypeKey && String(description).startsWith('exthost-api')) { |
| 642 | decoTypes.add(key); |
| 643 | send({ t: 'deco.type', key, options: decoOptions(options) }); |
| 644 | } |
| 645 | return r; |
| 646 | }; |
| 647 | const removeType = codeEditors.removeDecorationType.bind(codeEditors); |
| 648 | codeEditors.removeDecorationType = function (key) { |
| 649 | const r = removeType(key); |
| 650 | if (decoTypes.delete(key)) send({ t: 'deco.remove', key }); |
| 651 | return r; |
| 652 | }; |
| 653 | const sendDeco = (key, list) => { |
| 654 | const uri = uriOfModel(mirror.getModel()); |
| 655 | if (uri) send({ t: 'deco.set', key, uri, ranges: list.slice(0, 10000) }); |
| 656 | }; |
| 657 | const origDeco = mirror.setDecorationsByType.bind(mirror); |
| 658 | mirror.setDecorationsByType = function (description, key, opts) { |
| 659 | const r = origDeco(description, key, opts); |
| 660 | if (decoTypes.has(key)) { |
| 661 | sendDeco(key, (Array.isArray(opts) ? opts : []).slice(0, 10000).map(o => { |
| 662 | const range = o && R(o.range); |
| 663 | if (!range) return null; |
| 664 | const hover = o.hoverMessage ? [].concat(o.hoverMessage).slice(0, 10).map(md).filter(Boolean).map(h => (h.md ? { md: h.md.slice(0, 4096) } : { text: h.text.slice(0, 4096) })) : []; |
| 665 | const ro = o.renderOptions && typeof o.renderOptions === 'object' ? withContent(o.renderOptions, []) : null; |
| 666 | if (ro && o.renderOptions.light) ro.light = withContent(o.renderOptions.light, []); |
| 667 | if (ro && o.renderOptions.dark) ro.dark = withContent(o.renderOptions.dark, []); |
| 668 | return { range, ...(hover.length ? { hover } : {}), ...(ro && Object.keys(ro).length ? { ro } : {}) }; |
| 669 | }).filter(Boolean)); |
| 670 | } |
| 671 | return r; |
| 672 | }; |
| 673 | const origDecoFast = mirror.setDecorationsByTypeFast.bind(mirror); |
| 674 | mirror.setDecorationsByTypeFast = function (key, ranges) { |
| 675 | const r = origDecoFast(key, ranges); |
| 676 | if (decoTypes.has(key)) sendDeco(key, (Array.isArray(ranges) ? ranges : []).slice(0, 10000).map(x => { const range = R(x); return range ? { range } : null; }).filter(Boolean)); |
| 677 | return r; |
| 678 | }; |
| 679 | const origDecoRemove = mirror.removeDecorationsByType.bind(mirror); |
| 680 | mirror.removeDecorationsByType = function (key) { |
| 681 | const r = origDecoRemove(key); |
| 682 | if (decoTypes.has(key)) sendDeco(key, []); |
| 683 | return r; |
| 684 | }; |
| 685 | |
| 686 | for (const name of ['revealRange', 'revealRangeInCenter', 'revealRangeInCenterIfOutsideViewport', 'revealRangeAtTop']) { |
| 687 | const orig = mirror[name].bind(mirror); |
| 688 | mirror[name] = function (range, scrollType) { |
| 689 | const r = orig(range, scrollType); |
| 690 | const uri = uriOfModel(mirror.getModel()); |
| 691 | if (!fromPage && uri && range && Number.isSafeInteger(range.startLineNumber)) { |
| 692 | revealPending = { t: 'editor.reveal', uri, range: [range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn] }; |
| 693 | if (!revealTimer) revealTimer = setTimeout(() => { revealTimer = null; if (revealPending) send(revealPending); revealPending = null; }, 50); |
| 694 | } |
| 695 | return r; |
| 696 | }; |
| 697 | } |
| 698 | function openDoc({ uri, lang, text, v }) { |
| 699 | if (typeof text !== 'string' || text.length > MAX_DOC) return; |
| 700 | const u = monaco.Uri.parse(uri); |
| 701 | let d = docs.get(uri); |
| 702 | if (d) { resetDoc({ uri, text, v }); return; } |
| 703 | const language = knownLangs.has(lang) ? lang : 'plaintext'; |
| 704 | const model = monaco.editor.createModel(text, language, u); |
| 705 | d = { model, pageV: v, pending: false, steps: [], timer: null }; |
| 706 | docs.set(uri, d); |
| 707 | model.onDidChangeContent(e => { |
| 708 | if (applyingPage) return; |
| 709 | // cambio de una extensión (un comando que edita, p. ej.): se acumula y |
| 710 | // se manda en el mismo turno, contra la última versión que la página conoce |
| 711 | d.steps.push(e.changes.map(c => ({ range: [c.range.startLineNumber, c.range.startColumn, c.range.endLineNumber, c.range.endColumn], text: c.text }))); |
| 712 | if (!d.timer) d.timer = setTimeout(() => flushEdits(uri), 0); |
| 713 | }); |
| 714 | try { extensionService.activateByEvent('onLanguage:' + language); } catch { /* — */ } |
| 715 | } |
| 716 | function flushEdits(uri) { |
| 717 | const d = docs.get(uri); |
| 718 | if (!d) return; |
| 719 | d.timer = null; |
| 720 | if (!d.steps.length) return; |
| 721 | const steps = d.steps; d.steps = []; |
| 722 | if (d.pending) return; // ya hay uno en vuelo: la página mandará reset |
| 723 | d.pending = true; |
| 724 | send({ t: 'doc.edit', uri, base: d.pageV, steps }); |
| 725 | } |
| 726 | function applyPage(d, fn) { |
| 727 | applyingPage = true; |
| 728 | try { fn(); } finally { applyingPage = false; } |
| 729 | } |
| 730 | function resetDoc({ uri, text, v }) { |
| 731 | const d = docs.get(uri); |
| 732 | if (!d || typeof text !== 'string') return; |
| 733 | applyPage(d, () => { if (d.model.getValue() !== text) d.model.setValue(text); }); |
| 734 | d.pageV = v; d.pending = false; d.steps = []; |
| 735 | if (d.timer) { clearTimeout(d.timer); d.timer = null; } |
| 736 | } |
| 737 | function changeDoc({ uri, base, v, changes }) { |
| 738 | const d = docs.get(uri); |
| 739 | if (!d) return send({ t: 'doc.need', uri }); |
| 740 | if (d.pending) return; // esperando ack/reset de un cambio nuestro |
| 741 | if (d.pageV !== base) return send({ t: 'doc.need', uri }); |
| 742 | const model = d.model; |
| 743 | const edits = changes.map(c => { |
| 744 | const s = model.getPositionAt(c.o), e = model.getPositionAt(c.o + c.l); |
| 745 | return { range: new monaco.Range(s.lineNumber, s.column, e.lineNumber, e.column), text: c.t }; |
| 746 | }); |
| 747 | applyPage(d, () => model.applyEdits(edits)); |
| 748 | d.pageV = v; |
| 749 | } |
| 750 | function closeDoc({ uri }) { |
| 751 | const d = docs.get(uri); |
| 752 | if (!d) return; |
| 753 | docs.delete(uri); |
| 754 | if (mirror.getModel() === d.model) mirror.setModel(null); |
| 755 | d.model.dispose(); |
| 756 | } |
| 757 | function setActive({ uri, selections }) { |
| 758 | const d = uri ? docs.get(uri) : null; |
| 759 | const model = d ? d.model : null; |
| 760 | if (mirror.getModel() !== model) mirror.setModel(model); |
| 761 | if (model && Array.isArray(selections) && selections.length) { |
| 762 | fromPage++; |
| 763 | try { mirror.setSelections(selections.map(s => new monaco.Selection(s[0], s[1], s[2], s[3]))); } |
| 764 | finally { fromPage--; } |
| 765 | } |
| 766 | } |
| 767 | // una extensión quiere enseñar un documento abierto: el espejo lo enseña ya |
| 768 | // y la página cambia de pestaña si el usuario acaba de hacer algo |
| 769 | function showDoc(uri) { |
| 770 | if (!docs.has(uri)) return; |
| 771 | setActive({ uri }); |
| 772 | send({ t: 'editor.show', uri }); |
| 773 | } |
| 774 | |
| 775 | // ── diagnósticos de las extensiones → la página ── |
| 776 | const ownersOf = new Map(); // uri → Set(owner) |
| 777 | const pageOwners = new Map(); // uri → Set(«page:…») de los diagnósticos de la página |
| 778 | let markersSent = 0; |
| 779 | markerService.onMarkerChanged(resources => { |
| 780 | for (const r of resources) { |
| 781 | const uri = r.toString(); |
| 782 | if (!docs.has(uri)) continue; |
| 783 | const byOwner = new Map(); |
| 784 | for (const mk of markerService.read({ resource: r })) { |
| 785 | if (String(mk.owner).startsWith('page:')) continue; |
| 786 | if (!byOwner.has(mk.owner)) byOwner.set(mk.owner, []); |
| 787 | byOwner.get(mk.owner).push({ |
| 788 | severity: mk.severity, message: str(mk.message, 4096) || '', source: str(mk.source, 200), |
| 789 | code: typeof mk.code === 'string' || typeof mk.code === 'number' ? String(mk.code).slice(0, 200) : mk.code && typeof mk.code === 'object' ? String(mk.code.value).slice(0, 200) : undefined, |
| 790 | range: [mk.startLineNumber, mk.startColumn, mk.endLineNumber, mk.endColumn], |
| 791 | tags: Array.isArray(mk.tags) ? mk.tags.filter(x => x === 1 || x === 2) : undefined, |
| 792 | }); |
| 793 | } |
| 794 | for (const list of byOwner.values()) markersSent += list.length; |
| 795 | const prev = ownersOf.get(uri) || new Set(); |
| 796 | for (const owner of new Set([...prev, ...byOwner.keys()])) { |
| 797 | send({ t: 'markers', uri, owner: String(owner).slice(0, 200), markers: (byOwner.get(owner) || []).slice(0, 5000) }); |
| 798 | } |
| 799 | ownersOf.set(uri, new Set(byOwner.keys())); |
| 800 | } |
| 801 | }); |
| 802 | |
| 803 | // ── resultados de proveedores → datos planos ── |
| 804 | // Los ítems y comandos se quedan aquí, con un número (handle). Una lista de |
| 805 | // autocompletados o de acciones sigue viva mientras la página tenga alguno |
| 806 | // de sus ítems: sus comandos los guarda el host de extensiones hasta que la |
| 807 | // lista se suelta, y Monaco ejecuta el del ítem aceptado justo después de |
| 808 | // soltar la lista, así que se suelta con un margen. |
| 809 | const handles = new Map(); // handle → objeto que se queda aquí (comandos, ítems) |
| 810 | const listOf = new Map(); // handle de ítem → { list, refs } |
| 811 | let nextObj = 1; |
| 812 | const dropHandle = h => { |
| 813 | handles.delete(h); |
| 814 | const o = listOf.get(h); |
| 815 | if (!o) return; |
| 816 | listOf.delete(h); |
| 817 | o.refs.delete(h); |
| 818 | if (!o.refs.size) { try { o.list.dispose(); } catch { /* — */ } } |
| 819 | }; |
| 820 | const keep = obj => { |
| 821 | const h = nextObj++; |
| 822 | handles.set(h, obj); |
| 823 | if (handles.size > MAX_HANDLES) dropHandle(handles.keys().next().value); |
| 824 | return h; |
| 825 | }; |
| 826 | const adopt = (list, itemHandles) => { |
| 827 | if (!list || typeof list.dispose !== 'function') return; |
| 828 | if (!itemHandles.length) { try { list.dispose(); } catch { /* — */ } return; } |
| 829 | const o = { list, refs: new Set(itemHandles) }; |
| 830 | for (const h of itemHandles) listOf.set(h, o); |
| 831 | }; |
| 832 | const release = hs => setTimeout(() => { for (const h of hs) dropHandle(h); }, 3000); |
| 833 | const R = r => (r && typeof r === 'object' && 'startLineNumber' in r ? [r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn] : undefined); |
| 834 | const md = v => (typeof v === 'string' ? { text: v.slice(0, 65536) } : v && typeof v.value === 'string' ? { md: v.value.slice(0, 65536) } : undefined); |
| 835 | const cmd = c => (c && typeof c.id === 'string' ? { handle: keep(c), title: str(c.title, 500) || '' } : undefined); |
| 836 | const edit = e => (e && R(e.range) && typeof e.text === 'string' ? { range: R(e.range), text: e.text } : null); |
| 837 | const edits = list => (Array.isArray(list) ? list.map(edit).filter(Boolean).slice(0, 100000) : []); |
| 838 | const link = l => (l && l.uri && R(l.range) ? { uri: l.uri.toString(), range: R(l.range), targetSelectionRange: R(l.targetSelectionRange), originSelectionRange: R(l.originSelectionRange) } : null); |
| 839 | const locations = res => (res ? [].concat(res).map(link).filter(Boolean).slice(0, 10000) : []); |
| 840 | function workspaceEdit(we) { |
| 841 | if (!we) return undefined; |
| 842 | const out = []; |
| 843 | let other = 0; |
| 844 | for (const e of we.edits || []) { |
| 845 | if (e && e.resource && e.textEdit) { const te = edit(e.textEdit); if (te) out.push({ uri: e.resource.toString(), range: te.range, text: te.text }); } |
| 846 | else other++; |
| 847 | } |
| 848 | return { edits: out.slice(0, 100000), fileOps: other, rejectReason: str(we.rejectReason, 1000) }; |
| 849 | } |
| 850 | function symbol(s, depth = 0) { |
| 851 | if (!s || depth > 20) return null; |
| 852 | return { |
| 853 | name: str(s.name, 1000) || '', detail: str(s.detail, 1000) || '', kind: num(s.kind) ?? 0, tags: Array.isArray(s.tags) ? s.tags.filter(x => x === 1) : [], |
| 854 | range: R(s.range), selectionRange: R(s.selectionRange), |
| 855 | children: Array.isArray(s.children) ? s.children.map(c => symbol(c, depth + 1)).filter(Boolean).slice(0, 10000) : [], |
| 856 | }; |
| 857 | } |
| 858 | function completionItem(it) { |
| 859 | const label = typeof it.label === 'string' ? it.label : it.label && typeof it.label.label === 'string' ? { label: it.label.label, detail: str(it.label.detail, 1000), description: str(it.label.description, 1000) } : ''; |
| 860 | let range; |
| 861 | if (R(it.range)) range = R(it.range); |
| 862 | else if (it.range && R(it.range.insert) && R(it.range.replace)) range = { insert: R(it.range.insert), replace: R(it.range.replace) }; |
| 863 | return { |
| 864 | h: keep(it), label, kind: num(it.kind) ?? 0, tags: Array.isArray(it.tags) ? it.tags.filter(x => x === 1) : undefined, |
| 865 | detail: str(it.detail, 4096), documentation: md(it.documentation), sortText: str(it.sortText, 1000), filterText: str(it.filterText, 1000), |
| 866 | preselect: it.preselect === true, insertText: typeof it.insertText === 'string' ? it.insertText.slice(0, 100000) : '', insertTextRules: num(it.insertTextRules) ?? 0, |
| 867 | range, commitCharacters: Array.isArray(it.commitCharacters) ? it.commitCharacters.filter(c => typeof c === 'string').slice(0, 20) : undefined, |
| 868 | additionalTextEdits: it.additionalTextEdits ? edits(it.additionalTextEdits) : undefined, command: cmd(it.command), |
| 869 | }; |
| 870 | } |
| 871 | function codeAction(a) { |
| 872 | return { |
| 873 | h: keep(a), title: str(a.title, 1000) || '', kind: str(a.kind, 200), isPreferred: a.isPreferred === true, |
| 874 | disabled: str(a.disabled, 1000), edit: workspaceEdit(a.edit), command: cmd(a.command), isAI: a.isAI === true, |
| 875 | }; |
| 876 | } |
| 877 | |
| 878 | const tokens = new Map(); // req → CancellationTokenSource |
| 879 | async function invoke({ req, kind, handle, uri, v, args = {} }) { |
| 880 | const p = providers.get(handle); |
| 881 | const d = docs.get(uri); |
| 882 | if (!p || p.kind !== kind.split('.')[0]) return { stale: true }; |
| 883 | // resolver un ítem ya devuelto no depende de la versión (no hay posición) |
| 884 | const anyVersion = kind === 'completion.resolve' || kind === 'codeAction.resolve'; |
| 885 | if (!d || (!anyVersion && (d.pageV !== v || d.pending))) return { stale: true }; |
| 886 | const model = d.model; |
| 887 | const cts = new monaco.CancellationTokenSource(); |
| 888 | tokens.set(req, cts); |
| 889 | const token = cts.token; |
| 890 | const P = a => new monaco.Position(a[0], a[1]); |
| 891 | const opts = { tabSize: num(args.options && args.options.tabSize) ?? 4, insertSpaces: !!(args.options && args.options.insertSpaces) }; |
| 892 | const pr = p.provider; |
| 893 | try { |
| 894 | switch (kind) { |
| 895 | case 'format': return { edits: edits(await pr.provideDocumentFormattingEdits(model, opts, token)) }; |
| 896 | case 'formatRange': return { edits: edits(await pr.provideDocumentRangeFormattingEdits(model, monaco.Range.lift({ startLineNumber: args.range[0], startColumn: args.range[1], endLineNumber: args.range[2], endColumn: args.range[3] }), opts, token)) }; |
| 897 | case 'formatOnType': return { edits: edits(await pr.provideOnTypeFormattingEdits(model, P(args.position), String(args.ch || ''), opts, token)) }; |
| 898 | case 'hover': { |
| 899 | const h = await pr.provideHover(model, P(args.position), token, {}); |
| 900 | return h ? { contents: (h.contents || []).map(md).filter(Boolean).slice(0, 50), range: R(h.range) } : null; |
| 901 | } |
| 902 | case 'completion': { |
| 903 | const list = await pr.provideCompletionItems(model, P(args.position), { triggerKind: num(args.triggerKind) ?? 0, triggerCharacter: str(args.triggerCharacter, 10) }, token); |
| 904 | if (!list) return null; |
| 905 | const out = { incomplete: list.incomplete === true, suggestions: (list.suggestions || []).slice(0, 5000).map(completionItem) }; |
| 906 | adopt(list, out.suggestions.map(s => s.h)); |
| 907 | return out; |
| 908 | } |
| 909 | case 'completion.resolve': { |
| 910 | const item = handles.get(args.item); |
| 911 | if (!item || typeof pr.resolveCompletionItem !== 'function') return null; |
| 912 | const r = await pr.resolveCompletionItem(item, token); |
| 913 | return r ? completionItem(r) : null; |
| 914 | } |
| 915 | case 'signature': { |
| 916 | const ctx = { triggerKind: num(args.triggerKind) ?? 1, triggerCharacter: str(args.triggerCharacter, 10), isRetrigger: args.isRetrigger === true }; |
| 917 | const r = await pr.provideSignatureHelp(model, P(args.position), token, ctx); |
| 918 | if (!r || !r.value) return null; |
| 919 | const s = r.value; |
| 920 | const out = { |
| 921 | activeSignature: num(s.activeSignature) ?? 0, activeParameter: num(s.activeParameter) ?? 0, |
| 922 | signatures: (s.signatures || []).slice(0, 100).map(sig => ({ |
| 923 | label: str(sig.label, 4096) || '', documentation: md(sig.documentation), activeParameter: num(sig.activeParameter), |
| 924 | parameters: (sig.parameters || []).slice(0, 100).map(pa => ({ label: Array.isArray(pa.label) ? [num(pa.label[0]) ?? 0, num(pa.label[1]) ?? 0] : str(pa.label, 1000) || '', documentation: md(pa.documentation) })), |
| 925 | })), |
| 926 | }; |
| 927 | try { r.dispose && r.dispose(); } catch { /* — */ } |
| 928 | return out; |
| 929 | } |
| 930 | case 'codeAction': { |
| 931 | const range = monaco.Range.lift({ startLineNumber: args.range[0], startColumn: args.range[1], endLineNumber: args.range[2], endColumn: args.range[3] }); |
| 932 | const r = await pr.provideCodeActions(model, range, { trigger: args.trigger === 2 ? 2 : 1, only: str(args.only, 200) }, token); |
| 933 | if (!r) return null; |
| 934 | const out = { actions: (r.actions || []).slice(0, 500).map(codeAction) }; |
| 935 | adopt(r, out.actions.map(a => a.h)); |
| 936 | return out; |
| 937 | } |
| 938 | case 'codeAction.resolve': { |
| 939 | const a = handles.get(args.action); |
| 940 | if (!a || typeof pr.resolveCodeAction !== 'function') return null; |
| 941 | const r = await pr.resolveCodeAction(a, token); |
| 942 | return r ? codeAction(r) : null; |
| 943 | } |
| 944 | case 'symbols': return { symbols: ((await pr.provideDocumentSymbols(model, token)) || []).slice(0, 10000).map(s => symbol(s)).filter(Boolean) }; |
| 945 | case 'definition': return { locations: locations(await pr.provideDefinition(model, P(args.position), token)) }; |
| 946 | case 'declaration': return { locations: locations(await pr.provideDeclaration(model, P(args.position), token)) }; |
| 947 | case 'typeDefinition': return { locations: locations(await pr.provideTypeDefinition(model, P(args.position), token)) }; |
| 948 | case 'implementation': return { locations: locations(await pr.provideImplementation(model, P(args.position), token)) }; |
| 949 | case 'references': return { locations: locations(await pr.provideReferences(model, P(args.position), { includeDeclaration: args.includeDeclaration !== false }, token)) }; |
| 950 | case 'highlights': return { highlights: ((await pr.provideDocumentHighlights(model, P(args.position), token)) || []).slice(0, 10000).map(h => ({ range: R(h.range), kind: num(h.kind) ?? 0 })).filter(h => h.range) }; |
| 951 | case 'rename': return workspaceEdit(await pr.provideRenameEdits(model, P(args.position), String(args.newName || '').slice(0, 1000), token)) || null; |
| 952 | case 'rename.resolve': { |
| 953 | if (typeof pr.resolveRenameLocation !== 'function') return null; |
| 954 | const r = await pr.resolveRenameLocation(model, P(args.position), token); |
| 955 | return r ? { range: R(r.range), text: str(r.text, 1000), rejectReason: str(r.rejectReason, 1000) } : null; |
| 956 | } |
| 957 | default: return { error: 'unknown kind ' + kind }; |
| 958 | } |
| 959 | } finally { |
| 960 | tokens.delete(req); |
| 961 | cts.dispose(); |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | async function execCommand({ id, handle, uri, selections, v, args }) { |
| 966 | if (uri) { |
| 967 | const d = docs.get(uri); |
| 968 | if (!d || d.pageV !== v || d.pending) return { stale: true }; |
| 969 | setActive({ uri, selections }); |
| 970 | } |
| 971 | if (handle != null) { |
| 972 | const c = handles.get(handle); |
| 973 | if (!c) return { stale: true }; |
| 974 | return { value: plain(await commandService.executeCommand(c.id, ...(c.arguments || []))) }; |
| 975 | } |
| 976 | return { value: plain(await commandService.executeCommand(String(id), ...(Array.isArray(args) ? args : []))) }; |
| 977 | } |
| 978 | const plain = v => (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'number' ? v ?? null : typeof v === 'string' ? v.slice(0, 10000) : null); |
| 979 | |
| 980 | // superficie de la API, para la foto que vigilan las pruebas |
| 981 | function surface() { |
| 982 | const out = {}; |
| 983 | for (const [name, actor] of [...actors].sort((a, b) => (a[0] < b[0] ? -1 : 1))) { |
| 984 | const methods = new Set(); |
| 985 | for (let o = actor; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) { |
| 986 | for (const k of Object.getOwnPropertyNames(o)) { |
| 987 | if (!k.startsWith('$') || methods.has(k) || methods.has(k + ' (unsupported)')) continue; |
| 988 | // sin leer la propiedad: los métodos sin servicio son getters que lanzan |
| 989 | const d = Object.getOwnPropertyDescriptor(o, k); |
| 990 | if (d && typeof d.value === 'function') methods.add(k); |
| 991 | else if (d && d.get) methods.add(k + ' (unsupported)'); |
| 992 | } |
| 993 | } |
| 994 | out[name] = [...methods].sort(); |
| 995 | } |
| 996 | return { |
| 997 | actors: out, |
| 998 | commands: [...m.CommandsRegistry.getCommands().keys()].sort(), |
| 999 | overridden: ['IClipboardService', 'IDialogService', 'IEditorService', 'IFileDialogService', 'ILanguageStatusService', 'INotificationService', 'IOpenerService', 'IProgressService'], |
| 1000 | }; |
| 1001 | } |
| 1002 | |
| 1003 | // ── mensajes de la página ── |
| 1004 | port.onmessage = async ev => { |
| 1005 | const msg = ev.data; |
| 1006 | if (!msg || typeof msg !== 'object' || typeof msg.t !== 'string') return; |
| 1007 | try { |
| 1008 | switch (msg.t) { |
| 1009 | case 'ext.add': await addExt(msg); break; |
| 1010 | case 'ext.remove': removeExt(msg.id); break; |
| 1011 | case 'settings': await m.updateUserConfiguration(typeof msg.json === 'string' ? msg.json : '{}'); break; |
| 1012 | case 'doc.open': openDoc(msg); break; |
| 1013 | case 'doc.change': changeDoc(msg); break; |
| 1014 | case 'doc.reset': resetDoc(msg); break; |
| 1015 | case 'doc.lang': { const d = docs.get(msg.uri); if (d && knownLangs.has(msg.lang)) { monaco.editor.setModelLanguage(d.model, msg.lang); try { extensionService.activateByEvent('onLanguage:' + msg.lang); } catch { /* — */ } } break; } |
| 1016 | case 'doc.close': closeDoc(msg); break; |
| 1017 | case 'doc.ack': { const d = docs.get(msg.uri); if (d) { d.pageV = msg.v; d.pending = false; if (d.steps.length && !d.timer) d.timer = setTimeout(() => flushEdits(msg.uri), 0); } break; } |
| 1018 | case 'editor.active': setActive(msg); break; |
| 1019 | case 'invoke': { |
| 1020 | let value, ok = true; |
| 1021 | try { value = await invoke(msg); } catch (e) { ok = false; value = errText(e); } |
| 1022 | send(ok ? { t: 'result', req: msg.req, ok: true, value } : { t: 'result', req: msg.req, ok: false, error: value }); |
| 1023 | break; |
| 1024 | } |
| 1025 | case 'cancel': { const c = tokens.get(msg.req); if (c) c.cancel(); break; } |
| 1026 | // diagnósticos de la propia página (TS, JSON, CSS, HTML de Monaco): |
| 1027 | // las extensiones los ven (p. ej. para decorarlos), con dueño «page:…» |
| 1028 | case 'markers.page': { |
| 1029 | const uri = typeof msg.uri === 'string' ? msg.uri : ''; |
| 1030 | if (!docs.has(uri) || !Array.isArray(msg.markers)) break; |
| 1031 | const res = monaco.Uri.parse(uri); |
| 1032 | const byOwner = new Map(); |
| 1033 | for (const mk of msg.markers.slice(0, 5000)) { |
| 1034 | if (!mk || !Array.isArray(mk.range) || mk.range.length !== 4 || !mk.range.every(n => Number.isSafeInteger(n) && n >= 1)) continue; |
| 1035 | const owner = 'page:' + String(mk.owner || 'page').replace(/[^\w.-]/g, '').slice(0, 60); |
| 1036 | if (!byOwner.has(owner)) byOwner.set(owner, []); |
| 1037 | byOwner.get(owner).push({ |
| 1038 | severity: [1, 2, 4, 8].includes(mk.severity) ? mk.severity : 8, message: str(mk.message, 4096) || ' ', |
| 1039 | source: str(mk.source, 200), code: str(mk.code, 200), |
| 1040 | startLineNumber: mk.range[0], startColumn: mk.range[1], endLineNumber: mk.range[2], endColumn: mk.range[3], |
| 1041 | }); |
| 1042 | } |
| 1043 | const before = pageOwners.get(uri) || new Set(); |
| 1044 | for (const owner of new Set([...before, ...byOwner.keys()])) markerService.changeOne(owner, res, byOwner.get(owner) || []); |
| 1045 | pageOwners.set(uri, new Set(byOwner.keys())); |
| 1046 | break; |
| 1047 | } |
| 1048 | case 'theme': { |
| 1049 | const th = { light: 'vs', dark: 'vs-dark', hc: 'hc-black', 'hc-light': 'hc-light' }[msg.kind]; |
| 1050 | if (th) monaco.editor.setTheme(th); |
| 1051 | break; |
| 1052 | } |
| 1053 | case 'ui.result': { |
| 1054 | const r = asks.get(msg.req); |
| 1055 | if (!r) break; |
| 1056 | asks.delete(msg.req); |
| 1057 | const v = msg.value; |
| 1058 | const okInt = x => Number.isSafeInteger(x) && x >= 0 && x < 100000; |
| 1059 | r(v === true || v === false || okInt(v) ? v : typeof v === 'string' ? v.slice(0, 100000) : Array.isArray(v) && v.length <= 1000 && v.every(okInt) ? v : null); |
| 1060 | break; |
| 1061 | } |
| 1062 | case 'release': if (Array.isArray(msg.handles)) release(msg.handles.filter(h => Number.isSafeInteger(h)).slice(0, 5000)); break; |
| 1063 | case 'cmd.exec': { |
| 1064 | let value, ok = true; |
| 1065 | try { value = await execCommand(msg); } catch (e) { ok = false; value = errText(e); } |
| 1066 | send(ok ? { t: 'result', req: msg.req, ok: true, value } : { t: 'result', req: msg.req, ok: false, error: value }); |
| 1067 | break; |
| 1068 | } |
| 1069 | case 'activate': try { await extensionService.activateByEvent(String(msg.event)); } catch (e) { log('warn', 'activation event failed: ' + errText(e)); } break; |
| 1070 | case 'surface': { |
| 1071 | let value, ok = true; |
| 1072 | try { value = surface(); } catch (e) { ok = false; value = errText(e); } |
| 1073 | send(ok ? { t: 'result', req: msg.req, ok: true, value } : { t: 'result', req: msg.req, ok: false, error: value }); |
| 1074 | break; |
| 1075 | } |
| 1076 | case 'stats': { |
| 1077 | const st = extensionService.getExtensionsStatus ? extensionService.getExtensionsStatus() : {}; |
| 1078 | const exts2 = {}; |
| 1079 | for (const [k, v] of Object.entries(st)) { |
| 1080 | if (!exts.has(k.toLowerCase())) continue; |
| 1081 | exts2[k.toLowerCase()] = { |
| 1082 | started: !!v.activationStarted, activated: !!v.activationTimes, activationError: activationErrors.get(k.toLowerCase()), |
| 1083 | errors: [...(v.runtimeErrors || []).map(errText), ...(v.messages || []).map(x => errText(x && x.message))].slice(0, 5), |
| 1084 | }; |
| 1085 | } |
| 1086 | send({ t: 'result', req: msg.req, ok: true, value: { |
| 1087 | commands: [...extCommands].filter(c => typeof c === 'string').slice(0, 2000), providers: { ...kindCount }, later: { ...laterKinds }, |
| 1088 | markers: markersSent, errors: seenErrors.slice(-20), openRefused: openRefused.n, unsupported: [...unsupported], extensions: exts2, |
| 1089 | denied: denials.n, deniedBy: Object.fromEntries([...denials.by].slice(0, 50)), calls: Object.fromEntries([...calls].slice(0, 300)), |
| 1090 | } }); |
| 1091 | break; |
| 1092 | } |
| 1093 | case 'ping': send({ t: 'pong', n: msg.n, navBlocked: sandbox.navBlocked ? sandbox.navBlocked() : 0 }); break; |
| 1094 | default: log('warn', 'unknown message ' + msg.t.slice(0, 40)); |
| 1095 | } |
| 1096 | } catch (e) { |
| 1097 | log('error', msg.t + ': ' + errText(e)); |
| 1098 | } |
| 1099 | }; |
| 1100 | |
| 1101 | send({ t: 'ready', protocol: PROTOCOL, vscode: '1.138.0' }); |
| 1102 | } |