utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | 15afc5e2bb8bfe0217d07b983c53b8c3907ed74a6bf7e4a73b0e9715d93aa924 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-10 15:09 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 14:16 +02:00 |
| Parents | c09c8aa724ed |
8 files changed
added tests/ext_fixtures.mjs +195 −0
| @@ -0,0 +1,195 @@ | ||
| 1 | +// Extensiones de VS Code SINTÉTICAS para las pruebas: se construyen aquí, en | |
| 2 | +// memoria, sin red ni licencias de terceros. Un .vsix es un zip con | |
| 3 | +// extension/package.json y los ficheros que citan sus contribuciones. | |
| 4 | +import zlib from 'node:zlib'; | |
| 5 | + | |
| 6 | +const CRC = (() => { | |
| 7 | + const t = new Uint32Array(256); | |
| 8 | + for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } | |
| 9 | + return t; | |
| 10 | +})(); | |
| 11 | +const crc32 = b => { let c = 0xffffffff; for (const x of b) c = CRC[(c ^ x) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }; | |
| 12 | + | |
| 13 | +// files: [[nombre, contenido, { method }]] — method 8 (deflate, por defecto), | |
| 14 | +// 0 (sin comprimir) o cualquier otro número para fabricar una entrada ilegible. | |
| 15 | +export function zip(files) { | |
| 16 | + const locales = [], centrales = []; | |
| 17 | + let off = 0; | |
| 18 | + for (const [name, content, opts = {}] of files) { | |
| 19 | + const data = Buffer.isBuffer(content) ? content : Buffer.from(String(content), 'utf8'); | |
| 20 | + const method = opts.method ?? 8; | |
| 21 | + const comp = method === 8 ? zlib.deflateRawSync(data) : data; | |
| 22 | + const nb = Buffer.from(name, 'utf8'); | |
| 23 | + const crc = crc32(data); | |
| 24 | + const lh = Buffer.alloc(30); | |
| 25 | + lh.writeUInt32LE(0x04034b50, 0); lh.writeUInt16LE(20, 4); lh.writeUInt16LE(0x0800, 6); lh.writeUInt16LE(method, 8); | |
| 26 | + lh.writeUInt32LE(crc, 14); lh.writeUInt32LE(comp.length, 18); lh.writeUInt32LE(data.length, 22); | |
| 27 | + lh.writeUInt16LE(nb.length, 26); lh.writeUInt16LE(0, 28); | |
| 28 | + locales.push(lh, nb, comp); | |
| 29 | + const ch = Buffer.alloc(46); | |
| 30 | + ch.writeUInt32LE(0x02014b50, 0); ch.writeUInt16LE(20, 4); ch.writeUInt16LE(20, 6); ch.writeUInt16LE(0x0800, 8); ch.writeUInt16LE(method, 10); | |
| 31 | + ch.writeUInt32LE(crc, 16); ch.writeUInt32LE(comp.length, 20); ch.writeUInt32LE(opts.declaredSize ?? data.length, 24); | |
| 32 | + ch.writeUInt16LE(nb.length, 28); ch.writeUInt32LE(off, 42); | |
| 33 | + centrales.push(ch, nb); | |
| 34 | + off += 30 + nb.length + comp.length; | |
| 35 | + } | |
| 36 | + const cd = Buffer.concat(centrales); | |
| 37 | + const eocd = Buffer.alloc(22); | |
| 38 | + eocd.writeUInt32LE(0x06054b50, 0); eocd.writeUInt16LE(files.length, 8); eocd.writeUInt16LE(files.length, 10); | |
| 39 | + eocd.writeUInt32LE(cd.length, 12); eocd.writeUInt32LE(off, 16); | |
| 40 | + return new Uint8Array(Buffer.concat([...locales, cd, eocd])); | |
| 41 | +} | |
| 42 | + | |
| 43 | +const ENVOLTORIO = [ | |
| 44 | + ['extension.vsixmanifest', '<?xml version="1.0" encoding="utf-8"?><PackageManifest Version="2.0.0"/>'], | |
| 45 | + ['[Content_Types].xml', '<?xml version="1.0" encoding="utf-8"?><Types/>'], | |
| 46 | +]; | |
| 47 | + | |
| 48 | +// ── tema: JSONC con comentarios y comas finales, include encadenado, un color | |
| 49 | +// malicioso que no debe pasar, y un segundo tema en .tmTheme (plist). | |
| 50 | +export const THEME_DARK = { bg: '#102030', fg: '#E0E0E0', keyword: '#CC66FF', control: '#FF0055', comment: '#00AA44', string: '#FFAA00', number: '#33CCFF', tabActive: '#203040' }; | |
| 51 | +export function themeVsix() { | |
| 52 | + const pkg = { | |
| 53 | + name: 'elf-theme', publisher: 'elffuss-test', version: '1.0.0', displayName: '%displayName%', description: '%description%', | |
| 54 | + license: 'MIT', engines: { vscode: '^1.80.0' }, categories: ['Themes'], | |
| 55 | + main: './out/extension.js', // código: NO se ejecuta nunca | |
| 56 | + contributes: { | |
| 57 | + themes: [ | |
| 58 | + { id: 'Elf Dark', label: '%darkLabel%', uiTheme: 'vs-dark', path: './themes/elf-dark.json' }, | |
| 59 | + { label: 'Elf Light (tmTheme)', uiTheme: 'vs', path: './themes/elf-light.tmTheme' }, | |
| 60 | + ], | |
| 61 | + commands: [{ command: 'elf.hello', title: 'Hola' }], | |
| 62 | + iconThemes: [{ id: 'elf-icons', label: 'Elf icons', path: './icons.json' }], | |
| 63 | + }, | |
| 64 | + }; | |
| 65 | + const base = `{ | |
| 66 | + // base que incluye el tema oscuro | |
| 67 | + "colors": { "editorCursor.foreground": "#FFCC00", "editor.background": "#000000" }, | |
| 68 | + "tokenColors": [ | |
| 69 | + { "scope": "keyword, storage.type", "settings": { "foreground": "${THEME_DARK.keyword}" } }, | |
| 70 | + { "scope": "string", "settings": { "foreground": "${THEME_DARK.string}" } }, | |
| 71 | + { "scope": "constant.numeric", "settings": { "foreground": "${THEME_DARK.number}" } }, | |
| 72 | + ], | |
| 73 | + }`; | |
| 74 | + const dark = `{ | |
| 75 | + "$schema": "vscode://schemas/color-theme", // comentario con "comillas" y // barras | |
| 76 | + "name": "Elf Dark", | |
| 77 | + "include": "./base.json", | |
| 78 | + /* bloque | |
| 79 | + de comentario */ | |
| 80 | + "colors": { | |
| 81 | + "editor.background": "${THEME_DARK.bg}", | |
| 82 | + "editor.foreground": "${THEME_DARK.fg}", | |
| 83 | + "tab.activeBackground": "${THEME_DARK.tabActive}", | |
| 84 | + "editor.lineHighlightBackground": "#ffffff10", | |
| 85 | + "sideBar.background": "url(https://example.invalid/track.png)", | |
| 86 | + }, | |
| 87 | + "tokenColors": [ | |
| 88 | + { "scope": "keyword.control", "settings": { "foreground": "${THEME_DARK.control}" } }, | |
| 89 | + { "scope": ["comment"], "settings": { "foreground": "${THEME_DARK.comment}", "fontStyle": "italic" } }, | |
| 90 | + { "scope": "source.elfs keyword", "settings": { "foreground": "#123456" } }, | |
| 91 | + ], | |
| 92 | + }`; | |
| 93 | + const light = `<?xml version="1.0" encoding="UTF-8"?> | |
| 94 | +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | |
| 95 | +<plist version="1.0"><dict> | |
| 96 | + <key>name</key><string>Elf & Light</string> | |
| 97 | + <key>settings</key> | |
| 98 | + <array> | |
| 99 | + <dict><key>settings</key><dict> | |
| 100 | + <key>background</key><string>#FAFAF0</string> | |
| 101 | + <key>foreground</key><string>#202020</string> | |
| 102 | + <key>caret</key><string>#FF0000</string> | |
| 103 | + </dict></dict> | |
| 104 | + <!-- comentario --> | |
| 105 | + <dict><key>name</key><string>Comment</string><key>scope</key><string>comment</string> | |
| 106 | + <key>settings</key><dict><key>foreground</key><string>#808080</string><key>fontStyle</key><string>italic</string></dict></dict> | |
| 107 | + <dict><key>scope</key><string>keyword, storage</string> | |
| 108 | + <key>settings</key><dict><key>foreground</key><string>#AA0000</string></dict></dict> | |
| 109 | + </array> | |
| 110 | + <key>uuid</key><string><![CDATA[1234-<cdata>]]></string> | |
| 111 | + <key>count</key><integer>3</integer> | |
| 112 | + <key>flag</key><true/> | |
| 113 | +</dict></plist>`; | |
| 114 | + return zip([ | |
| 115 | + ...ENVOLTORIO, | |
| 116 | + ['extension/package.json', JSON.stringify(pkg, null, 2)], | |
| 117 | + ['extension/package.nls.json', JSON.stringify({ displayName: 'Elf Theme', description: 'Synthetic test theme', darkLabel: 'Elf Dark' })], | |
| 118 | + ['extension/package.nls.es.json', JSON.stringify({ displayName: 'Tema Elfo', darkLabel: 'Elfo Oscuro' })], | |
| 119 | + ['extension/LICENSE.txt', 'MIT License — test fixture'], | |
| 120 | + ['extension/themes/base.json', base], | |
| 121 | + ['extension/themes/elf-dark.json', dark], | |
| 122 | + ['extension/themes/elf-light.tmTheme', light], | |
| 123 | + ['extension/icons.json', '{}'], | |
| 124 | + // si alguien intentara leer el JS, esta entrada lanza (compresión 99) | |
| 125 | + ['extension/out/extension.js', 'throw new Error("must never run")', { method: 99 }], | |
| 126 | + ]); | |
| 127 | +} | |
| 128 | + | |
| 129 | +// ── lenguaje nuevo + gramática + configuración + snippets (también para JS) | |
| 130 | +export const ELFS = { lang: 'elfscript', ext: '.elfs', scope: 'source.elfs' }; | |
| 131 | +export function elfscriptVsix({ version = '1.0.0' } = {}) { | |
| 132 | + const pkg = { | |
| 133 | + name: 'elfscript', publisher: 'elffuss-test', version, displayName: 'ElfScript', description: 'Synthetic language for tests', | |
| 134 | + license: 'SEE LICENSE IN NOTICE.md', engines: { vscode: '^1.80.0' }, categories: ['Programming Languages', 'Snippets'], | |
| 135 | + contributes: { | |
| 136 | + languages: [{ id: ELFS.lang, aliases: ['ElfScript', 'elfs'], extensions: [ELFS.ext], filenames: ['Elffile'], filenamePatterns: ['**/spells/*.spell'], firstLine: '^#!.*\\belfs\\b', configuration: './language-configuration.json' }], | |
| 137 | + grammars: [ | |
| 138 | + { language: ELFS.lang, scopeName: ELFS.scope, path: './syntaxes/elfs.tmLanguage.json', tokenTypes: { 'string.quoted.single.elfs': 'other' } }, | |
| 139 | + { scopeName: 'source.elfs.rune', path: './syntaxes/rune.tmLanguage' }, | |
| 140 | + ], | |
| 141 | + snippets: [ | |
| 142 | + { language: ELFS.lang, path: './snippets/elfs.code-snippets' }, | |
| 143 | + { language: 'javascript', path: './snippets/js.json' }, | |
| 144 | + ], | |
| 145 | + configurationDefaults: { '[elfscript]': { 'editor.tabSize': 2 } }, | |
| 146 | + }, | |
| 147 | + }; | |
| 148 | + const grammar = { | |
| 149 | + name: 'ElfScript', scopeName: ELFS.scope, | |
| 150 | + patterns: [ | |
| 151 | + { include: '#comment' }, { include: '#keywords' }, { include: '#strings' }, { include: '#numbers' }, { include: 'source.elfs.rune' }, | |
| 152 | + ], | |
| 153 | + repository: { | |
| 154 | + comment: { match: '#.*$', name: 'comment.line.number-sign.elfs' }, | |
| 155 | + keywords: { patterns: [{ match: '\\b(spell|cast|end)\\b', name: 'keyword.control.elfs' }, { match: '\\bwith\\b', name: 'keyword.other.elfs' }] }, | |
| 156 | + strings: { begin: '"', end: '"', name: 'string.quoted.double.elfs' }, | |
| 157 | + numbers: { match: '\\b[0-9]+\\b', name: 'constant.numeric.elfs' }, | |
| 158 | + }, | |
| 159 | + }; | |
| 160 | + const rune = `<?xml version="1.0" encoding="UTF-8"?> | |
| 161 | +<plist version="1.0"><dict> | |
| 162 | + <key>scopeName</key><string>source.elfs.rune</string> | |
| 163 | + <key>patterns</key><array> | |
| 164 | + <dict><key>match</key><string>\\bᚱ\\w*</string><key>name</key><string>storage.type.rune.elfs</string></dict> | |
| 165 | + </array> | |
| 166 | +</dict></plist>`; | |
| 167 | + const config = `{ | |
| 168 | + "comments": { "lineComment": "#", "blockComment": ["#[", "]#"] }, | |
| 169 | + "brackets": [["{", "}"], ["[", "]"], ["(", ")"]], | |
| 170 | + "autoClosingPairs": [["{", "}"], ["[", "]"], { "open": "\\"", "close": "\\"", "notIn": ["string", "comment"] }], | |
| 171 | + "surroundingPairs": [["(", ")"], ["\\"", "\\""]], | |
| 172 | + "wordPattern": "[A-Za-z_][\\\\w-]*", | |
| 173 | + "indentationRules": { "increaseIndentPattern": "^\\\\s*spell\\\\b.*$", "decreaseIndentPattern": "^\\\\s*end\\\\b" }, | |
| 174 | + "onEnterRules": [{ "beforeText": "^\\\\s*spell\\\\b.*$", "action": { "indent": "indent" } }, { "beforeText": "(", "action": { "indent": "indent" } }], | |
| 175 | + "folding": { "markers": { "start": "^\\\\s*#region\\\\b", "end": "^\\\\s*#endregion\\\\b" } }, | |
| 176 | + }`; | |
| 177 | + const snippets = `{ | |
| 178 | + // un snippet con varios prefijos y cuerpo en varias líneas | |
| 179 | + "Spell": { "prefix": ["spell", "elfspell"], "body": ["spell \${1:name}", "\\tcast \${2:fire}", "end"], "description": "A spell block" }, | |
| 180 | + "Grupo": { | |
| 181 | + "Rune": { "prefix": "#rune", "body": "#rune \${1:ᚱ}", "description": "Rune comment" }, | |
| 182 | + }, | |
| 183 | + "Sin prefijo": { "body": "nada" }, | |
| 184 | + }`; | |
| 185 | + return zip([ | |
| 186 | + ...ENVOLTORIO, | |
| 187 | + ['extension/package.json', JSON.stringify(pkg, null, 2)], | |
| 188 | + ['extension/NOTICE.md', 'Synthetic fixture, public domain.'], | |
| 189 | + ['extension/language-configuration.json', config], | |
| 190 | + ['extension/syntaxes/elfs.tmLanguage.json', JSON.stringify(grammar)], | |
| 191 | + ['extension/syntaxes/rune.tmLanguage', rune], | |
| 192 | + ['extension/snippets/elfs.code-snippets', snippets], | |
| 193 | + ['extension/snippets/js.json', JSON.stringify({ 'Elf log': { prefix: 'elflog', body: "console.log('elf', $1);$0", description: 'Log with an elf' } })], | |
| 194 | + ]); | |
| 195 | +} |
added tests/ext_unit.mjs +132 −0
| @@ -0,0 +1,132 @@ | ||
| 1 | +// Pruebas en Node (sin navegador) de lo que no necesita Monaco: lectura del | |
| 2 | +// .vsix, JSONC/plist, colores, mapeo de temas, lenguajes y snippets. | |
| 3 | +// node tests/ext_unit.mjs | |
| 4 | +import { parseJsonc, parsePlist, hex6, isHexColor } from '../web/js/ext/formats.js'; | |
| 5 | +import { openZip, crc32 } from '../web/js/ext/unzip.js'; | |
| 6 | +import { readVsix, analyzeManifest, resolveNls } from '../web/js/ext/vsix.js'; | |
| 7 | +import { toMonacoTheme, toTextMateTheme, monarchRules, resolveScope, themeIdFor, chromeCss, builtinTheme, joinPath } from '../web/js/ext/themes.js'; | |
| 8 | +import { toLanguageConfiguration, matchLanguage, globToRegExp } from '../web/js/ext/languages.js'; | |
| 9 | +import { normalizeSnippets, replaceStart } from '../web/js/ext/snippets.js'; | |
| 10 | +import { zip, themeVsix, elfscriptVsix, THEME_DARK, ELFS } from './ext_fixtures.mjs'; | |
| 11 | + | |
| 12 | +let fails = 0; | |
| 13 | +const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; | |
| 14 | +const throws = async (fn, re) => { try { await fn(); return false; } catch (e) { return re ? re.test(e.message) : true; } }; | |
| 15 | + | |
| 16 | +// ── JSONC ── | |
| 17 | +{ | |
| 18 | + const j = parseJsonc('\uFEFF{ // c\n "a": "http://x//y", /* b */ "b": [1, 2, ], "c": {"d": "\\"/*no*/\\"",}, }'); | |
| 19 | + ok('JSONC: comentarios, comas finales y // dentro de cadenas', j.a === 'http://x//y' && j.b.length === 2 && j.c.d === '"/*no*/"', JSON.stringify(j)); | |
| 20 | + ok('JSONC: lo inválido sigue fallando', await throws(() => parseJsonc('{"a": 1,, "b": 2}'))); | |
| 21 | +} | |
| 22 | + | |
| 23 | +// ── plist ── | |
| 24 | +{ | |
| 25 | + const p = parsePlist(`<?xml version="1.0"?><!DOCTYPE plist><plist version="1.0"><dict> | |
| 26 | + <key>s</key><string>a <b> & AB</string><key>n</key><integer>42</integer><key>r</key><real>1.5</real> | |
| 27 | + <key>t</key><true/><key>f</key><false/><key>e</key><string/><key>arr</key><array><string>x</string><dict/><array/></array> | |
| 28 | + <key>cd</key><string><![CDATA[<raw & stuff>]]></string></dict></plist>`); | |
| 29 | + ok('plist: tipos, entidades y CDATA', p.s === 'a <b> & AB' && p.n === 42 && p.r === 1.5 && p.t === true && p.f === false && p.e === '' && p.arr.length === 3 && p.cd === '<raw & stuff>', JSON.stringify(p)); | |
| 30 | + ok('plist: roto → error', await throws(() => parsePlist('<plist><dict><key>a</key></dict></plist>'))); | |
| 31 | +} | |
| 32 | + | |
| 33 | +// ── colores ── | |
| 34 | +ok('hex6: #abc → #AABBCC', hex6('#abc') === '#AABBCC'); | |
| 35 | +ok('hex6: alfa mezclado sobre el fondo', hex6('#ffffff80', '#000000') === '#808080', hex6('#ffffff80', '#000000')); | |
| 36 | +ok('hex6: alfa sin fondo se descarta', hex6('#12345678') === '#123456'); | |
| 37 | +ok('colores no hex rechazados (url(), nombres, rgb())', !isHexColor('url(x)') && !isHexColor('red') && !isHexColor('rgb(1,2,3)') && hex6('#12') === null); | |
| 38 | + | |
| 39 | +// ── zip ── | |
| 40 | +{ | |
| 41 | + const z = zip([['a.txt', 'hola'], ['b/c.json', '{"x":1}', { method: 0 }], ['big.txt', 'x'.repeat(5000)]]); | |
| 42 | + const r = openZip(z, { maxEntry: 4000 }); | |
| 43 | + ok('zip: índice del directorio central', r.names.join(',') === 'a.txt,b/c.json,big.txt', r.names.join(',')); | |
| 44 | + ok('zip: deflate y stored', new TextDecoder().decode(await r.read('a.txt')) === 'hola' && new TextDecoder().decode(await r.read('b/c.json')) === '{"x":1}'); | |
| 45 | + ok('zip: tope por entrada', await throws(() => r.read('big.txt'), /pesa demasiado/)); | |
| 46 | + const bomba = zip([['bomb.txt', 'y'.repeat(100000), { declaredSize: 10 }]]); | |
| 47 | + ok('zip: una entrada que infla más de lo que declara se corta', await throws(() => openZip(bomba).read('bomb.txt'), /demasiado grande/)); | |
| 48 | + ok('zip: lo que no es zip se rechaza', await throws(() => openZip(new Uint8Array(100)), /no es un zip/)); | |
| 49 | + ok('crc32 conocido', crc32(new TextEncoder().encode('123456789')) === 0xcbf43926); | |
| 50 | +} | |
| 51 | + | |
| 52 | +// ── .vsix de tema ── | |
| 53 | +const tema = await readVsix(themeVsix(), { lang: 'es' }); | |
| 54 | +ok('vsix: id y nombre traducido (package.nls.es.json)', tema.id === 'elffuss-test.elf-theme' && tema.displayName === 'Tema Elfo' && tema.description === 'Synthetic test theme', `${tema.id} · ${tema.displayName} · ${tema.description}`); | |
| 55 | +ok('vsix: dos temas, etiqueta %clave% resuelta', tema.themes.length === 2 && tema.themes[0].label === 'Elfo Oscuro', tema.themes.map(t => t.label).join(' | ')); | |
| 56 | +{ | |
| 57 | + const d = tema.themes[0].data; | |
| 58 | + ok('tema: include encadenado (colores del base + propios)', d.colors['editorCursor.foreground'] === '#FFCC00' && d.colors['editor.background'] === THEME_DARK.bg); | |
| 59 | + ok('tema: color con url() descartado', !('sideBar.background' in d.colors)); | |
| 60 | + ok('tema: reglas del base primero y luego las propias', d.tokenColors[0].scope.join() === 'keyword,storage.type' && d.tokenColors.at(-1).scope[0] === 'source.elfs keyword', d.tokenColors.map(r => r.scope?.join('+')).join(' | ')); | |
| 61 | + const l = tema.themes[1].data; | |
| 62 | + ok('tema .tmTheme (plist): fondo/primer plano/cursor de la regla global', l.uiTheme === 'vs' && l.colors['editor.background'] === '#FAFAF0' && l.colors['editorCursor.foreground'] === '#FF0000'); | |
| 63 | +} | |
| 64 | +ok('vsix: el JS del paquete no se lee nunca (main ignorado, la entrada es ilegible y no falla)', tema.analysis.hasCode === true && !tema.warnings.length, tema.warnings.join('; ')); | |
| 65 | +ok('vsix: lo que no aplica, con motivo', tema.analysis.ignored.some(i => i.key === 'commands' && i.why === 'code') && tema.analysis.ignored.some(i => i.key === 'iconThemes' && i.why === 'later')); | |
| 66 | +ok('vsix: licencia leída del paquete', /MIT License/.test(tema.licenseText)); | |
| 67 | + | |
| 68 | +// ── mapeo del tema a Monaco ── | |
| 69 | +{ | |
| 70 | + const d = tema.themes[0].data; | |
| 71 | + const m = toMonacoTheme(d); | |
| 72 | + const regla = t => m.rules.find(r => r.token === t); | |
| 73 | + ok('Monaco: base y herencia', m.base === 'vs-dark' && m.inherit === true); | |
| 74 | + ok('Monaco: keyword ← keyword/storage.type', regla('keyword')?.foreground === THEME_DARK.keyword.slice(1), JSON.stringify(regla('keyword'))); | |
| 75 | + ok('Monaco: keyword.flow ← keyword.control (el selector más largo gana)', regla('keyword.flow')?.foreground === THEME_DARK.control.slice(1)); | |
| 76 | + ok('Monaco: comment con cursiva', regla('comment')?.foreground === THEME_DARK.comment.slice(1) && regla('comment')?.fontStyle === 'italic'); | |
| 77 | + ok('Monaco: string y number', regla('string')?.foreground === THEME_DARK.string.slice(1) && regla('number')?.foreground === THEME_DARK.number.slice(1)); | |
| 78 | + ok('Monaco: sin regla en el tema → color por defecto del tema, no el de serie', regla('tag')?.foreground === THEME_DARK.fg.slice(1), JSON.stringify(regla('tag'))); | |
| 79 | + ok('Monaco: los colores pasan tal cual (y el url() no)', m.colors['editor.background'] === THEME_DARK.bg && m.colors['tab.activeBackground'] === THEME_DARK.tabActive && !m.colors['sideBar.background']); | |
| 80 | + ok('Monaco: los selectores con contexto no se usan para Monarch', !m.rules.some(r => r.foreground === '123456')); | |
| 81 | + ok('resolveScope: keyword.control.flow → control; keyword.other → keyword', resolveScope(d.tokenColors, 'keyword.control.flow').foreground === THEME_DARK.control && resolveScope(d.tokenColors, 'keyword.other').foreground === THEME_DARK.keyword); | |
| 82 | + const tm = toTextMateTheme(d); | |
| 83 | + ok('TextMate: primera regla = colores por defecto del editor', tm.settings[0].settings.foreground === THEME_DARK.fg && tm.settings[0].settings.background === THEME_DARK.bg); | |
| 84 | + ok('TextMate: todos los colores en #RRGGBB', tm.settings.every(s => Object.entries(s.settings).every(([k, v]) => k === 'fontStyle' || /^#[0-9A-F]{6}$/.test(v)))); | |
| 85 | + ok('TextMate: conserva los selectores con contexto (los resuelve vscode-textmate)', tm.settings.some(s => s.scope?.[0] === 'source.elfs keyword')); | |
| 86 | + const lt = toMonacoTheme(tema.themes[1].data); | |
| 87 | + ok('Monaco (tmTheme claro): base vs y keyword', lt.base === 'vs' && lt.rules.find(r => r.token === 'keyword')?.foreground === 'AA0000'); | |
| 88 | + const b = builtinTheme('vs'); | |
| 89 | + ok('temas de serie con colores TextMate (Light+)', b.uiTheme === 'vs' && toTextMateTheme(b).settings.some(s => s.scope?.includes('comment') && s.settings.foreground === '#008000')); | |
| 90 | + const css = chromeCss(d); | |
| 91 | + ok('CSS de pestañas solo con colores hex', css.includes(THEME_DARK.tabActive) && !/url\(|example/.test(css), css.split('\n')[0]); | |
| 92 | + const usados = new Set(); | |
| 93 | + const id1 = themeIdFor('Elffuss-Test.Elf Theme', { id: 'Elf Dark (ñ)' }, 0, usados), id2 = themeIdFor('Elffuss-Test.Elf Theme', { id: 'Elf Dark (ñ)' }, 1, usados); | |
| 94 | + ok('ids de tema válidos para Monaco y únicos', /^[a-z0-9-]+$/.test(id1) && id1 !== id2, `${id1} · ${id2}`); | |
| 95 | + ok('monarchRules sin tokenColors no rompe', monarchRules({ uiTheme: 'vs', colors: {}, tokenColors: [] }).every(r => /^[0-9A-F]{6}$/.test(r.foreground || '000000'))); | |
| 96 | +} | |
| 97 | + | |
| 98 | +// ── .vsix de lenguaje + gramática + snippets ── | |
| 99 | +const elfs = await readVsix(elfscriptVsix()); | |
| 100 | +ok('vsix lenguaje: contribuciones leídas', elfs.languages.length === 1 && elfs.grammars.length === 2 && elfs.snippets.length === 2, `${elfs.languages.length}/${elfs.grammars.length}/${elfs.snippets.length} ${elfs.warnings.join(';')}`); | |
| 101 | +ok('vsix lenguaje: gramática plist (.tmLanguage)', elfs.grammars[1].scopeName === 'source.elfs.rune' && elfs.grammars[1].data.patterns.length === 1 && !elfs.grammars[1].language); | |
| 102 | +ok('vsix lenguaje: tokenTypes y licencia «SEE LICENSE IN»', elfs.grammars[0].tokenTypes['string.quoted.single.elfs'] === 'other' && /public domain/.test(elfs.licenseText)); | |
| 103 | +ok('vsix lenguaje: configurationDefaults no se aplica', elfs.analysis.ignored.some(i => i.key === 'configurationDefaults' && i.why === 'later')); | |
| 104 | +{ | |
| 105 | + const IA = { None: 0, Indent: 1, IndentOutdent: 2, Outdent: 3 }; | |
| 106 | + const conf = toLanguageConfiguration(elfs.languages[0].config, { languages: { IndentAction: IA } }); | |
| 107 | + ok('config: comentarios, corchetes y pares', conf.comments.lineComment === '#' && conf.comments.blockComment[0] === '#[' && conf.brackets.length === 3 && conf.autoClosingPairs.length === 3 && conf.autoClosingPairs[2].notIn[0] === 'string'); | |
| 108 | + ok('config: expresiones → RegExp', conf.wordPattern instanceof RegExp && conf.wordPattern.test('elf-name') && conf.indentationRules.increaseIndentPattern.test(' spell x')); | |
| 109 | + ok('config: onEnterRules con IndentAction y la regla con regex inválida fuera', conf.onEnterRules.length === 1 && conf.onEnterRules[0].action.indentAction === IA.Indent); | |
| 110 | + ok('config: folding markers', conf.folding.markers.start.test('#region a')); | |
| 111 | +} | |
| 112 | +{ | |
| 113 | + const c = [{ id: 'a', extensions: ['.mk'], filenames: ['Makefile'] }, ...elfs.languages]; | |
| 114 | + ok('lenguaje por nombre exacto', matchLanguage(c, 'src/Elffile') === ELFS.lang && matchLanguage(c, 'Makefile') === 'a'); | |
| 115 | + ok('lenguaje por extensión (sin distinguir mayúsculas)', matchLanguage(c, 'x/Y.ELFS') === ELFS.lang && matchLanguage(c, 'a.mk') === 'a'); | |
| 116 | + ok('lenguaje por patrón y por primera línea', matchLanguage(c, 'book/spells/fire.spell') === ELFS.lang && matchLanguage(c, 'run', '#!/usr/bin/env elfs') === ELFS.lang && matchLanguage(c, 'run', '#!/bin/sh') === null); | |
| 117 | + ok('glob: **, * y {a,b}', globToRegExp('**/*.{js,ts}').test('a/b/c.ts') && !globToRegExp('*.js').test('a/b.js')); | |
| 118 | +} | |
| 119 | +{ | |
| 120 | + const s = elfs.snippets[0].data; | |
| 121 | + ok('snippets: varios prefijos, cuerpo en líneas, grupo anidado, sin prefijo fuera', s.length === 3 && s[0].body === 'spell ${1:name}\n\tcast ${2:fire}\nend' && s.some(x => x.prefix === '#rune'), s.map(x => x.prefix).join(',')); | |
| 122 | + ok('snippets: rango sobre lo ya escrito (#ru → #rune)', replaceStart(' #ru', '#rune', 4) === 3 && replaceStart('x.elfl', 'elflog', 3) === 3 && replaceStart('foo', 'bar', 1) === 1); | |
| 123 | + ok('snippets: normalize tolera basura', normalizeSnippets(null).length === 0 && normalizeSnippets({ a: 1, b: { c: 'x' } }).length === 0); | |
| 124 | +} | |
| 125 | + | |
| 126 | +// ── utilidades ── | |
| 127 | +ok('joinPath no sale de la raíz', joinPath('extension/themes', './a/../b.json') === 'extension/themes/b.json' && await throws(() => joinPath('', '../x'))); | |
| 128 | +ok('resolveNls: %clave% y {message}', resolveNls({ a: '%k%', b: ['%m%'], c: '%no%' }, { k: 'K', m: { message: 'M' } }).b[0] === 'M'); | |
| 129 | +ok('analyzeManifest de un paquete solo con código', (() => { const a = analyzeManifest({ main: 'x.js', contributes: { commands: [{}] } }); return a.hasCode && !a.any; })()); | |
| 130 | + | |
| 131 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ EXTENSIONES (Node): vsix, formatos, temas, lenguajes y snippets OK'); | |
| 132 | +process.exit(fails ? 1 : 0); |
added web/js/ext/formats.js +163 −0
| @@ -0,0 +1,163 @@ | ||
| 1 | +// Formatos que traen las extensiones de VS Code: JSON con comentarios (JSONC), | |
| 2 | +// plist XML (.tmTheme / .tmLanguage) y colores hex. Sin DOM ni dependencias: | |
| 3 | +// se prueban en Node igual que en el navegador. | |
| 4 | + | |
| 5 | +// JSONC como lo lee VS Code: comentarios // y /* */ y comas finales. Recorre | |
| 6 | +// el texto respetando las cadenas, así un "http://…" dentro de un string no se | |
| 7 | +// toma por comentario. | |
| 8 | +export function parseJsonc(text) { | |
| 9 | + const s = String(text ?? '').replace(/^/, ''); | |
| 10 | + let out = ''; | |
| 11 | + let coma = false; // coma pendiente: se escribe solo si no cierra | |
| 12 | + for (let i = 0; i < s.length;) { | |
| 13 | + const c = s[i]; | |
| 14 | + if (c === '"') { | |
| 15 | + if (coma) { out += ','; coma = false; } | |
| 16 | + let j = i + 1; | |
| 17 | + while (j < s.length && s[j] !== '"') j += s[j] === '\\' ? 2 : 1; | |
| 18 | + out += s.slice(i, j + 1); | |
| 19 | + i = j + 1; | |
| 20 | + continue; | |
| 21 | + } | |
| 22 | + if (c === '/' && s[i + 1] === '/') { const e = s.indexOf('\n', i); i = e < 0 ? s.length : e; continue; } | |
| 23 | + if (c === '/' && s[i + 1] === '*') { const e = s.indexOf('*/', i + 2); i = e < 0 ? s.length : e + 2; continue; } | |
| 24 | + if (c === ',') { if (coma) out += ','; coma = true; i++; continue; } | |
| 25 | + if (c === ' ' || c === '\t' || c === '\n' || c === '\r') { out += c; i++; continue; } | |
| 26 | + if (coma) { if (c !== '}' && c !== ']') out += ','; coma = false; } | |
| 27 | + out += c; | |
| 28 | + i++; | |
| 29 | + } | |
| 30 | + if (coma) out += ','; | |
| 31 | + return JSON.parse(out); | |
| 32 | +} | |
| 33 | + | |
| 34 | +// plist XML de Apple (temas .tmTheme y gramáticas .tmLanguage). Analizador | |
| 35 | +// propio y mínimo: nunca resuelve entidades externas ni DTD, y funciona sin DOM. | |
| 36 | +const ENTIDADES = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" }; | |
| 37 | +function desentidad(t) { | |
| 38 | + return t.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => { | |
| 39 | + if (e[0] === '#') { | |
| 40 | + const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10); | |
| 41 | + return Number.isFinite(n) && n >= 0 && n <= 0x10ffff ? String.fromCodePoint(n) : m; | |
| 42 | + } | |
| 43 | + return ENTIDADES[e] ?? m; | |
| 44 | + }); | |
| 45 | +} | |
| 46 | + | |
| 47 | +export function parsePlist(text) { | |
| 48 | + const s = String(text ?? '').replace(/^/, ''); | |
| 49 | + let i = 0; | |
| 50 | + const fallo = msg => { throw new Error(`plist: ${msg} (posición ${i})`); }; | |
| 51 | + | |
| 52 | + // salta espacios, comentarios, <?xml?> y <!DOCTYPE> | |
| 53 | + function saltaRelleno() { | |
| 54 | + for (;;) { | |
| 55 | + while (i < s.length && /\s/.test(s[i])) i++; | |
| 56 | + if (s.startsWith('<!--', i)) { const e = s.indexOf('-->', i + 4); i = e < 0 ? s.length : e + 3; continue; } | |
| 57 | + if (s.startsWith('<?', i)) { const e = s.indexOf('?>', i + 2); i = e < 0 ? s.length : e + 2; continue; } | |
| 58 | + if (s.startsWith('<!DOCTYPE', i) || s.startsWith('<!doctype', i)) { const e = s.indexOf('>', i); i = e < 0 ? s.length : e + 1; continue; } | |
| 59 | + return; | |
| 60 | + } | |
| 61 | + } | |
| 62 | + // lee una etiqueta: { nombre, cierre, vacia } | |
| 63 | + function etiqueta() { | |
| 64 | + saltaRelleno(); | |
| 65 | + if (s[i] !== '<') fallo('se esperaba una etiqueta'); | |
| 66 | + const e = s.indexOf('>', i); | |
| 67 | + if (e < 0) fallo('etiqueta sin cerrar'); | |
| 68 | + let cuerpo = s.slice(i + 1, e).trim(); | |
| 69 | + i = e + 1; | |
| 70 | + const cierre = cuerpo.startsWith('/'); | |
| 71 | + const vacia = cuerpo.endsWith('/'); | |
| 72 | + cuerpo = cuerpo.replace(/^\//, '').replace(/\/$/, '').trim(); | |
| 73 | + return { nombre: cuerpo.split(/\s+/)[0], cierre, vacia }; | |
| 74 | + } | |
| 75 | + // texto hasta </nombre>, con CDATA y entidades | |
| 76 | + function texto(nombre) { | |
| 77 | + let out = ''; | |
| 78 | + for (;;) { | |
| 79 | + if (i >= s.length) fallo(`falta </${nombre}>`); | |
| 80 | + if (s.startsWith('<![CDATA[', i)) { | |
| 81 | + const e = s.indexOf(']]>', i + 9); | |
| 82 | + if (e < 0) fallo('CDATA sin cerrar'); | |
| 83 | + out += s.slice(i + 9, e); | |
| 84 | + i = e + 3; | |
| 85 | + } else if (s.startsWith('<!--', i)) { | |
| 86 | + const e = s.indexOf('-->', i + 4); | |
| 87 | + i = e < 0 ? s.length : e + 3; | |
| 88 | + } else if (s[i] === '<') { | |
| 89 | + const t = etiqueta(); | |
| 90 | + if (!t.cierre || t.nombre !== nombre) fallo(`se esperaba </${nombre}>`); | |
| 91 | + return out; | |
| 92 | + } else { | |
| 93 | + const e = s.indexOf('<', i); | |
| 94 | + const trozo = e < 0 ? s.slice(i) : s.slice(i, e); | |
| 95 | + out += desentidad(trozo); | |
| 96 | + i = e < 0 ? s.length : e; | |
| 97 | + } | |
| 98 | + } | |
| 99 | + } | |
| 100 | + function valor(t) { | |
| 101 | + switch (t.nombre) { | |
| 102 | + case 'dict': { | |
| 103 | + const o = {}; | |
| 104 | + if (t.vacia) return o; | |
| 105 | + for (;;) { | |
| 106 | + const k = etiqueta(); | |
| 107 | + if (k.cierre && k.nombre === 'dict') return o; | |
| 108 | + if (k.nombre !== 'key') fallo('se esperaba <key>'); | |
| 109 | + const clave = k.vacia ? '' : texto('key'); | |
| 110 | + const v = etiqueta(); | |
| 111 | + if (v.cierre) fallo('falta el valor de ' + clave); | |
| 112 | + o[clave] = valor(v); | |
| 113 | + } | |
| 114 | + } | |
| 115 | + case 'array': { | |
| 116 | + const a = []; | |
| 117 | + if (t.vacia) return a; | |
| 118 | + for (;;) { | |
| 119 | + const v = etiqueta(); | |
| 120 | + if (v.cierre && v.nombre === 'array') return a; | |
| 121 | + if (v.cierre) fallo('cierre inesperado'); | |
| 122 | + a.push(valor(v)); | |
| 123 | + } | |
| 124 | + } | |
| 125 | + case 'string': case 'date': case 'data': return t.vacia ? '' : texto(t.nombre); | |
| 126 | + case 'integer': return t.vacia ? 0 : parseInt(texto('integer'), 10); | |
| 127 | + case 'real': return t.vacia ? 0 : parseFloat(texto('real')); | |
| 128 | + case 'true': if (!t.vacia) texto('true'); return true; | |
| 129 | + case 'false': if (!t.vacia) texto('false'); return false; | |
| 130 | + default: return fallo('etiqueta desconocida <' + t.nombre + '>'); | |
| 131 | + } | |
| 132 | + } | |
| 133 | + const raiz = etiqueta(); | |
| 134 | + if (raiz.nombre !== 'plist') return valor(raiz); // plist sin envoltorio | |
| 135 | + if (raiz.vacia) return null; | |
| 136 | + const v = etiqueta(); | |
| 137 | + if (v.cierre) return null; | |
| 138 | + return valor(v); | |
| 139 | +} | |
| 140 | + | |
| 141 | +// Colores: solo #rgb, #rgba, #rrggbb o #rrggbbaa. Cualquier otra cosa (un | |
| 142 | +// url(), un nombre, una variable) no pasa: llegaría a Monaco o a una variable | |
| 143 | +// CSS y podría hacer una petición a un servidor de fuera. | |
| 144 | +const HEX = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i; | |
| 145 | +export const isHexColor = v => typeof v === 'string' && HEX.test(v); | |
| 146 | + | |
| 147 | +// → '#RRGGBB' en mayúsculas. El alfa se mezcla sobre `fondo` si se da (un | |
| 148 | +// comentario '#ffffff80' sobre fondo oscuro sale gris, como en VS Code) y si | |
| 149 | +// no, se descarta. null si el color no es válido. | |
| 150 | +export function hex6(v, fondo = null) { | |
| 151 | + if (!isHexColor(v)) return null; | |
| 152 | + let h = v.slice(1); | |
| 153 | + if (h.length <= 4) h = [...h].map(c => c + c).join(''); | |
| 154 | + const rgb = [0, 2, 4].map(k => parseInt(h.slice(k, k + 2), 16)); | |
| 155 | + const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1; | |
| 156 | + let final = rgb; | |
| 157 | + if (a < 1 && isHexColor(fondo)) { | |
| 158 | + const f = hex6(fondo).slice(1); | |
| 159 | + const bg = [0, 2, 4].map(k => parseInt(f.slice(k, k + 2), 16)); | |
| 160 | + final = rgb.map((c, k) => Math.round(c * a + bg[k] * (1 - a))); | |
| 161 | + } | |
| 162 | + return '#' + final.map(c => c.toString(16).padStart(2, '0')).join('').toUpperCase(); | |
| 163 | +} |
added web/js/ext/languages.js +113 −0
| @@ -0,0 +1,113 @@ | ||
| 1 | +// Lenguajes de VS Code (contributes.languages + language-configuration.json) | |
| 2 | +// → registro de Monaco y su configuración (comentarios, corchetes, sangría…). | |
| 3 | + | |
| 4 | +// Expresión de VS Code (cadena o { pattern, flags }) → RegExp. Las que no | |
| 5 | +// compilan en JavaScript se descartan, como hace VS Code. | |
| 6 | +function re(v) { | |
| 7 | + try { | |
| 8 | + if (typeof v === 'string') return new RegExp(v); | |
| 9 | + if (v && typeof v.pattern === 'string') return new RegExp(v.pattern, String(v.flags || '').replace(/[^dgimsuy]/g, '')); | |
| 10 | + } catch { /* inválida */ } | |
| 11 | + return undefined; | |
| 12 | +} | |
| 13 | +const par = p => (Array.isArray(p) && p.length === 2 && p.every(x => typeof x === 'string') ? { open: p[0], close: p[1] } | |
| 14 | + : p && typeof p.open === 'string' && typeof p.close === 'string' ? { open: p.open, close: p.close, ...(Array.isArray(p.notIn) && { notIn: p.notIn.filter(x => typeof x === 'string') }) } | |
| 15 | + : null); | |
| 16 | +const corchetes = l => (Array.isArray(l) ? l.filter(p => Array.isArray(p) && p.length === 2 && p.every(x => typeof x === 'string')) : undefined); | |
| 17 | + | |
| 18 | +// language-configuration.json → LanguageConfiguration de Monaco. | |
| 19 | +export function toLanguageConfiguration(j, monaco) { | |
| 20 | + if (!j || typeof j !== 'object') return {}; | |
| 21 | + const out = {}; | |
| 22 | + if (j.comments && typeof j.comments === 'object') { | |
| 23 | + const c = {}; | |
| 24 | + if (typeof j.comments.lineComment === 'string') c.lineComment = j.comments.lineComment; | |
| 25 | + if (corchetes([j.comments.blockComment])?.length) c.blockComment = j.comments.blockComment; | |
| 26 | + out.comments = c; | |
| 27 | + } | |
| 28 | + if (corchetes(j.brackets)) out.brackets = corchetes(j.brackets); | |
| 29 | + if (corchetes(j.colorizedBracketPairs)) out.colorizedBracketPairs = corchetes(j.colorizedBracketPairs); | |
| 30 | + if (Array.isArray(j.autoClosingPairs)) out.autoClosingPairs = j.autoClosingPairs.map(par).filter(Boolean); | |
| 31 | + if (Array.isArray(j.surroundingPairs)) out.surroundingPairs = j.surroundingPairs.map(par).filter(Boolean).map(({ open, close }) => ({ open, close })); | |
| 32 | + if (typeof j.autoCloseBefore === 'string') out.autoCloseBefore = j.autoCloseBefore; | |
| 33 | + const wp = re(j.wordPattern); | |
| 34 | + if (wp) out.wordPattern = wp; | |
| 35 | + if (j.indentationRules && typeof j.indentationRules === 'object') { | |
| 36 | + const ir = j.indentationRules; | |
| 37 | + const inc = re(ir.increaseIndentPattern), dec = re(ir.decreaseIndentPattern); | |
| 38 | + if (inc && dec) { | |
| 39 | + out.indentationRules = { increaseIndentPattern: inc, decreaseIndentPattern: dec }; | |
| 40 | + const nl = re(ir.indentNextLinePattern), un = re(ir.unIndentedLinePattern); | |
| 41 | + if (nl) out.indentationRules.indentNextLinePattern = nl; | |
| 42 | + if (un) out.indentationRules.unIndentedLinePattern = un; | |
| 43 | + } | |
| 44 | + } | |
| 45 | + if (j.folding && typeof j.folding === 'object') { | |
| 46 | + const f = {}; | |
| 47 | + if (typeof j.folding.offSide === 'boolean') f.offSide = j.folding.offSide; | |
| 48 | + const s = re(j.folding.markers?.start), e = re(j.folding.markers?.end); | |
| 49 | + if (s && e) f.markers = { start: s, end: e }; | |
| 50 | + out.folding = f; | |
| 51 | + } | |
| 52 | + if (Array.isArray(j.onEnterRules) && monaco) { | |
| 53 | + const IA = monaco.languages.IndentAction; | |
| 54 | + const acciones = { none: IA.None, indent: IA.Indent, indentOutdent: IA.IndentOutdent, outdent: IA.Outdent }; | |
| 55 | + out.onEnterRules = j.onEnterRules.map(r => { | |
| 56 | + const beforeText = re(r?.beforeText); | |
| 57 | + const indentAction = acciones[r?.action?.indent]; | |
| 58 | + if (!beforeText || indentAction === undefined) return null; | |
| 59 | + const regla = { beforeText, action: { indentAction } }; | |
| 60 | + const at = re(r.afterText), pl = re(r.previousLineText); | |
| 61 | + if (at) regla.afterText = at; | |
| 62 | + if (pl) regla.previousLineText = pl; | |
| 63 | + if (typeof r.action.appendText === 'string') regla.action.appendText = r.action.appendText; | |
| 64 | + if (Number.isInteger(r.action.removeText)) regla.action.removeText = r.action.removeText; | |
| 65 | + return regla; | |
| 66 | + }).filter(Boolean); | |
| 67 | + } | |
| 68 | + return out; | |
| 69 | +} | |
| 70 | + | |
| 71 | +// Glob de VS Code (filenamePatterns) → RegExp: **, *, ?, {a,b}. | |
| 72 | +export function globToRegExp(glob) { | |
| 73 | + let out = ''; | |
| 74 | + for (let i = 0; i < glob.length; i++) { | |
| 75 | + const c = glob[i]; | |
| 76 | + if (c === '*' && glob[i + 1] === '*') { out += glob[i + 2] === '/' ? '(?:.*/)?' : '.*'; i += glob[i + 2] === '/' ? 2 : 1; } | |
| 77 | + else if (c === '*') out += '[^/]*'; | |
| 78 | + else if (c === '?') out += '[^/]'; | |
| 79 | + else if (c === '{') { const e = glob.indexOf('}', i); if (e < 0) { out += '\\{'; continue; } out += '(?:' + glob.slice(i + 1, e).split(',').map(x => x.replace(/[.+^$()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')).join('|') + ')'; i = e; } | |
| 80 | + else out += c.replace(/[.+^$()|[\]\\]/g, '\\$&'); | |
| 81 | + } | |
| 82 | + return new RegExp('^' + out + '$', 'i'); | |
| 83 | +} | |
| 84 | + | |
| 85 | +// Lenguaje para una ruta según las contribuciones activas (las últimas | |
| 86 | +// instaladas mandan). Como VS Code: nombre exacto, luego patrones, luego la | |
| 87 | +// extensión más larga y, si se da el texto, la primera línea. | |
| 88 | +export function matchLanguage(contribs, path, primeraLinea = null) { | |
| 89 | + const base = String(path).split('/').pop(); | |
| 90 | + const low = base.toLowerCase(); | |
| 91 | + for (let i = contribs.length - 1; i >= 0; i--) if ((contribs[i].filenames || []).some(f => f === base)) return contribs[i].id; | |
| 92 | + for (let i = contribs.length - 1; i >= 0; i--) { | |
| 93 | + for (const g of contribs[i].filenamePatterns || []) { | |
| 94 | + try { if (globToRegExp(g).test(g.includes('/') ? path : base)) return contribs[i].id; } catch { /* patrón roto */ } | |
| 95 | + } | |
| 96 | + } | |
| 97 | + let mejor = null, largo = 0; | |
| 98 | + for (let i = contribs.length - 1; i >= 0; i--) { | |
| 99 | + for (const e of contribs[i].extensions || []) { | |
| 100 | + const el = String(e).toLowerCase(); | |
| 101 | + if (el && el.length > largo && low.endsWith(el)) { mejor = contribs[i].id; largo = el.length; } | |
| 102 | + } | |
| 103 | + } | |
| 104 | + if (mejor) return mejor; | |
| 105 | + if (primeraLinea != null) { | |
| 106 | + for (let i = contribs.length - 1; i >= 0; i--) { | |
| 107 | + const fl = contribs[i].firstLine; | |
| 108 | + if (typeof fl !== 'string') continue; | |
| 109 | + try { if (new RegExp(fl).test(primeraLinea)) return contribs[i].id; } catch { /* inválida */ } | |
| 110 | + } | |
| 111 | + } | |
| 112 | + return null; | |
| 113 | +} |
added web/js/ext/snippets.js +63 −0
| @@ -0,0 +1,63 @@ | ||
| 1 | +// Snippets de VS Code → sugerencias de Monaco que se insertan como snippet | |
| 2 | +// (mismo formato: $1, ${2:valor}, ${3|a,b|}, $TM_FILENAME…). | |
| 3 | + | |
| 4 | +// Fichero de snippets (JSON con comentarios ya parseado) → lista plana. Admite | |
| 5 | +// un nivel de anidado (grupos), prefijos en lista y cuerpos en lista de líneas. | |
| 6 | +export function normalizeSnippets(json) { | |
| 7 | + const out = []; | |
| 8 | + const uno = (nombre, s) => { | |
| 9 | + if (!s || typeof s !== 'object' || s.body == null) return false; | |
| 10 | + const prefijos = (Array.isArray(s.prefix) ? s.prefix : [s.prefix]).filter(p => typeof p === 'string' && p.trim()); | |
| 11 | + const body = Array.isArray(s.body) ? s.body.map(String).join('\n') : String(s.body); | |
| 12 | + const description = Array.isArray(s.description) ? s.description.join('\n') : (typeof s.description === 'string' ? s.description : ''); | |
| 13 | + for (const prefix of prefijos) out.push({ name: String(nombre), prefix: prefix.trim(), body, description }); | |
| 14 | + return true; | |
| 15 | + }; | |
| 16 | + if (!json || typeof json !== 'object') return out; | |
| 17 | + for (const [nombre, s] of Object.entries(json)) { | |
| 18 | + if (uno(nombre, s)) continue; | |
| 19 | + if (s && typeof s === 'object') for (const [n2, s2] of Object.entries(s)) uno(n2, s2); | |
| 20 | + } | |
| 21 | + return out.slice(0, 5000); | |
| 22 | +} | |
| 23 | + | |
| 24 | +const esPalabra = ch => /[\w$]/.test(ch || ''); | |
| 25 | + | |
| 26 | +// Columna donde empieza lo que el usuario ya escribió del prefijo. Si lo | |
| 27 | +// escrito es el principio literal del prefijo («#reg» de «#region»), se | |
| 28 | +// reemplaza eso; si no, la palabra bajo el cursor, que Monaco filtra en difuso. | |
| 29 | +export function replaceStart(lineaAntes, prefix, wordStart) { | |
| 30 | + const lo = lineaAntes.toLowerCase(), pre = prefix.toLowerCase(); | |
| 31 | + for (let p = Math.max(0, lo.length - pre.length); p < lo.length; p++) { | |
| 32 | + if (!pre.startsWith(lo.slice(p))) continue; | |
| 33 | + if (p > 0 && esPalabra(lo[p - 1]) && esPalabra(lo[p])) continue; // a media palabra, no | |
| 34 | + return p + 1; | |
| 35 | + } | |
| 36 | + return wordStart; | |
| 37 | +} | |
| 38 | + | |
| 39 | +// Un proveedor por lenguaje. `cargar()` devuelve (una vez, en diferido) la | |
| 40 | +// lista de snippets de todas las extensiones activas para ese lenguaje. | |
| 41 | +export function registerSnippets(monaco, language, cargar, origen = () => '') { | |
| 42 | + let lista = null; | |
| 43 | + const K = monaco.languages.CompletionItemKind.Snippet; | |
| 44 | + const R = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet; | |
| 45 | + return monaco.languages.registerCompletionItemProvider(language, { | |
| 46 | + async provideCompletionItems(model, position) { | |
| 47 | + lista ??= await cargar().catch(() => []); | |
| 48 | + if (!lista.length) return { suggestions: [] }; | |
| 49 | + const antes = model.getLineContent(position.lineNumber).slice(0, position.column - 1); | |
| 50 | + const palabra = model.getWordUntilPosition(position); | |
| 51 | + const suggestions = lista.map(s => ({ | |
| 52 | + label: s.prefix, | |
| 53 | + kind: K, | |
| 54 | + detail: s.description || s.name, | |
| 55 | + documentation: { value: (s.description ? s.description + '\n\n' : '') + '```\n' + s.body + '\n```' + (origen(s) ? '\n\n' + origen(s) : '') }, | |
| 56 | + insertText: s.body, | |
| 57 | + insertTextRules: R, | |
| 58 | + range: new monaco.Range(position.lineNumber, replaceStart(antes, s.prefix, palabra.startColumn), position.lineNumber, position.column), | |
| 59 | + })); | |
| 60 | + return { suggestions }; | |
| 61 | + }, | |
| 62 | + }); | |
| 63 | +} |
added web/js/ext/themes.js +332 −0
| @@ -0,0 +1,332 @@ | ||
| 1 | +// Temas de color de VS Code → Monaco. | |
| 2 | +// | |
| 3 | +// Un tema de VS Code trae dos cosas: `colors` (los del editor y del resto del | |
| 4 | +// banco de trabajo, que Monaco entiende tal cual) y `tokenColors`, reglas | |
| 5 | +// TextMate por ámbito («keyword.control», «string.quoted»…). Monaco colorea sus | |
| 6 | +// lenguajes de serie (Monarch) con clases propias («keyword», «string», | |
| 7 | +// «comment»…), así que a cada clase se le da el color del ámbito TextMate que | |
| 8 | +// la representa, con la misma regla que usa TextMate: gana el selector más | |
| 9 | +// largo que sea prefijo del ámbito. Los ficheros con gramática TextMate de una | |
| 10 | +// extensión no pasan por esta tabla: llevan los colores exactos (grammars.js). | |
| 11 | +import { parseJsonc, parsePlist, isHexColor, hex6 } from './formats.js'; | |
| 12 | + | |
| 13 | +export const BASES = ['vs-dark', 'vs', 'hc-black', 'hc-light']; | |
| 14 | + | |
| 15 | +// ── cargar un tema desde el paquete (como colorThemeData.ts de VS Code) ───── | |
| 16 | +const dirname = p => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : ''); | |
| 17 | +export function joinPath(base, rel) { | |
| 18 | + const out = []; | |
| 19 | + for (const seg of (base ? base + '/' : '').concat(String(rel)).split('/')) { | |
| 20 | + if (!seg || seg === '.') continue; | |
| 21 | + if (seg === '..') { if (!out.length) throw new Error('ruta fuera del paquete: ' + rel); out.pop(); } else out.push(seg); | |
| 22 | + } | |
| 23 | + return out.join('/'); | |
| 24 | +} | |
| 25 | + | |
| 26 | +// Ajustes globales de un .tmTheme (regla sin ámbito) → colores del editor. | |
| 27 | +const TMTHEME_COLORES = { | |
| 28 | + background: ['editor.background'], foreground: ['editor.foreground'], | |
| 29 | + selection: ['editor.selectionBackground'], inactiveSelection: ['editor.inactiveSelectionBackground'], | |
| 30 | + selectionHighlightColor: ['editor.selectionHighlightBackground'], | |
| 31 | + findMatchHighlight: ['editor.findMatchHighlightBackground'], currentFindMatchHighlight: ['editor.findMatchBackground'], | |
| 32 | + hoverHighlight: ['editor.hoverHighlightBackground'], wordHighlight: ['editor.wordHighlightBackground'], | |
| 33 | + wordHighlightStrong: ['editor.wordHighlightStrongBackground'], findRangeHighlight: ['editor.findRangeHighlightBackground'], | |
| 34 | + lineHighlight: ['editor.lineHighlightBackground'], rangeHighlight: ['editor.rangeHighlightBackground'], | |
| 35 | + caret: ['editorCursor.foreground'], invisibles: ['editorWhitespace.foreground'], | |
| 36 | + guide: ['editorIndentGuide.background'], activeGuide: ['editorIndentGuide.activeBackground'], | |
| 37 | +}; | |
| 38 | +function convertSettings(settings, out) { | |
| 39 | + for (const regla of settings) { | |
| 40 | + if (!regla || typeof regla !== 'object') continue; | |
| 41 | + if (!regla.scope && regla.settings && typeof regla.settings === 'object') { | |
| 42 | + for (const [k, v] of Object.entries(regla.settings)) { | |
| 43 | + for (const id of TMTHEME_COLORES[k] || []) if (typeof v === 'string') out.colors[id] = v; | |
| 44 | + } | |
| 45 | + } | |
| 46 | + out.tokenColors.push(regla); | |
| 47 | + } | |
| 48 | +} | |
| 49 | + | |
| 50 | +async function cargaEn(path, readText, out, prof) { | |
| 51 | + if (prof > 8) throw new Error('demasiados include en el tema'); | |
| 52 | + if (/\.json$/i.test(path)) { | |
| 53 | + const j = parseJsonc(await readText(path)); | |
| 54 | + if (typeof j.include === 'string') await cargaEn(joinPath(dirname(path), j.include), readText, out, prof + 1); | |
| 55 | + if (Array.isArray(j.settings)) { convertSettings(j.settings, out); return; } | |
| 56 | + if (j.colors && typeof j.colors === 'object') { | |
| 57 | + for (const [k, v] of Object.entries(j.colors)) { | |
| 58 | + if (v === 'default') delete out.colors[k]; | |
| 59 | + else if (typeof v === 'string') out.colors[k] = v; | |
| 60 | + } | |
| 61 | + } | |
| 62 | + if (Array.isArray(j.tokenColors)) out.tokenColors.push(...j.tokenColors); | |
| 63 | + else if (typeof j.tokenColors === 'string') { | |
| 64 | + const t = parsePlist(await readText(joinPath(dirname(path), j.tokenColors))); | |
| 65 | + if (Array.isArray(t?.settings)) convertSettings(t.settings, out); | |
| 66 | + } | |
| 67 | + if (typeof j.type === 'string') out.type = j.type; | |
| 68 | + } else { | |
| 69 | + const t = parsePlist(await readText(path)); | |
| 70 | + if (!Array.isArray(t?.settings)) throw new Error('el .tmTheme no tiene settings'); | |
| 71 | + convertSettings(t.settings, out); | |
| 72 | + } | |
| 73 | +} | |
| 74 | + | |
| 75 | +// Reglas TextMate normalizadas: { scope: [selectores], settings: { foreground, | |
| 76 | +// background, fontStyle } } con colores ya validados. | |
| 77 | +function normalizaReglas(reglas) { | |
| 78 | + const out = []; | |
| 79 | + for (const r of reglas) { | |
| 80 | + if (!r || typeof r !== 'object' || !r.settings || typeof r.settings !== 'object') continue; | |
| 81 | + const st = {}; | |
| 82 | + if (isHexColor(r.settings.foreground)) st.foreground = r.settings.foreground; | |
| 83 | + if (isHexColor(r.settings.background)) st.background = r.settings.background; | |
| 84 | + if (typeof r.settings.fontStyle === 'string') { | |
| 85 | + st.fontStyle = r.settings.fontStyle.split(/\s+/).filter(w => ['italic', 'bold', 'underline', 'strikethrough'].includes(w)).join(' '); | |
| 86 | + } | |
| 87 | + if (!Object.keys(st).length) continue; | |
| 88 | + const scope = Array.isArray(r.scope) ? r.scope.filter(x => typeof x === 'string').map(x => x.trim()).filter(Boolean) | |
| 89 | + : typeof r.scope === 'string' ? r.scope.split(',').map(x => x.trim()).filter(Boolean) : []; | |
| 90 | + out.push(scope.length ? { scope, settings: st } : { settings: st }); | |
| 91 | + } | |
| 92 | + return out; | |
| 93 | +} | |
| 94 | + | |
| 95 | +// Tema listo para guardar: { label, uiTheme, colors, tokenColors }. | |
| 96 | +export async function loadTheme(path, readText, { label = '', uiTheme = '' } = {}) { | |
| 97 | + const out = { colors: {}, tokenColors: [], type: '' }; | |
| 98 | + await cargaEn(path, readText, out, 0); | |
| 99 | + const colors = {}; | |
| 100 | + for (const [k, v] of Object.entries(out.colors)) if (isHexColor(v)) colors[k] = v; | |
| 101 | + const porTipo = { dark: 'vs-dark', light: 'vs', hc: 'hc-black', hcLight: 'hc-light', 'hc-light': 'hc-light' }; | |
| 102 | + const base = BASES.includes(uiTheme) ? uiTheme : porTipo[out.type] || 'vs-dark'; | |
| 103 | + return { label: String(label || ''), uiTheme: base, colors, tokenColors: normalizaReglas(out.tokenColors) }; | |
| 104 | +} | |
| 105 | + | |
| 106 | +// ── resolución TextMate: qué estilo toca a un ámbito ───────────────────────── | |
| 107 | +// Solo selectores simples («keyword.control»); los de contexto («source.js | |
| 108 | +// keyword») o con exclusiones no sirven para las clases sueltas de Monarch. | |
| 109 | +function selectoresSimples(regla) { | |
| 110 | + return (regla.scope || []).filter(s => !/[\s()|&,]|^-/.test(s)); | |
| 111 | +} | |
| 112 | +export function resolveScope(tokenColors, scope) { | |
| 113 | + const cands = []; | |
| 114 | + tokenColors.forEach((r, idx) => { | |
| 115 | + for (const sel of selectoresSimples(r)) { | |
| 116 | + if (scope === sel || scope.startsWith(sel + '.')) cands.push({ spec: sel.split('.').length, idx, st: r.settings }); | |
| 117 | + } | |
| 118 | + }); | |
| 119 | + cands.sort((a, b) => b.spec - a.spec || b.idx - a.idx); | |
| 120 | + const out = {}; | |
| 121 | + for (const c of cands) { | |
| 122 | + if (out.foreground === undefined && c.st.foreground) out.foreground = c.st.foreground; | |
| 123 | + if (out.fontStyle === undefined && typeof c.st.fontStyle === 'string') out.fontStyle = c.st.fontStyle; | |
| 124 | + } | |
| 125 | + return out; | |
| 126 | +} | |
| 127 | + | |
| 128 | +// Clase de Monaco (Monarch) → ámbitos TextMate que la representan, por orden. | |
| 129 | +// Incluye las clases con regla propia en los temas de serie de Monaco | |
| 130 | +// (string.key.json, delimiter.html…): si no se cubrieran, ganaría el color | |
| 131 | +// del tema de serie y el tema de la extensión quedaría a medias. | |
| 132 | +const MONARCH = [ | |
| 133 | + ['comment', ['comment']], | |
| 134 | + ['comment.doc', ['comment.block.documentation', 'comment']], | |
| 135 | + ['string', ['string']], | |
| 136 | + ['string.escape', ['constant.character.escape', 'string']], | |
| 137 | + ['string.key.json', ['support.type.property-name.json', 'support.type.property-name', 'variable.other.property']], | |
| 138 | + ['string.value.json', ['string.quoted.double.json', 'string']], | |
| 139 | + ['string.html', ['string.quoted.double.html', 'string']], | |
| 140 | + ['string.sql', ['string.quoted.single.sql', 'string']], | |
| 141 | + ['string.yaml', ['string.unquoted.plain.out.yaml', 'string']], | |
| 142 | + ['string.link', ['markup.underline.link', 'string']], | |
| 143 | + ['regexp', ['string.regexp']], | |
| 144 | + ['number', ['constant.numeric']], | |
| 145 | + ['number.hex', ['constant.numeric.hex', 'constant.numeric']], | |
| 146 | + ['constant', ['constant.language', 'constant']], | |
| 147 | + ['keyword', ['keyword', 'storage.type', 'storage']], | |
| 148 | + ['keyword.flow', ['keyword.control']], | |
| 149 | + ['keyword.flow.scss', ['keyword.control.at-rule', 'keyword.control', 'keyword']], | |
| 150 | + ['keyword.json', ['constant.language.json', 'constant.language']], | |
| 151 | + ['operator', ['keyword.operator']], | |
| 152 | + ['operator.scss', ['keyword.operator']], | |
| 153 | + ['operator.sql', ['keyword.operator']], | |
| 154 | + ['operator.swift', ['keyword.operator']], | |
| 155 | + ['delimiter', ['punctuation', 'meta.brace']], | |
| 156 | + ['delimiter.html', ['punctuation.definition.tag']], | |
| 157 | + ['delimiter.xml', ['punctuation.definition.tag']], | |
| 158 | + ['type', ['entity.name.type', 'support.type', 'storage.type']], | |
| 159 | + ['type.identifier', ['entity.name.type', 'entity.name.class', 'support.class']], | |
| 160 | + ['identifier', ['variable', 'variable.other.readwrite']], | |
| 161 | + ['variable', ['variable']], | |
| 162 | + ['variable.predefined', ['variable.language', 'support.variable']], | |
| 163 | + ['variable.parameter', ['variable.parameter']], | |
| 164 | + ['predefined', ['support.function', 'entity.name.function']], | |
| 165 | + ['predefined.sql', ['support.function', 'entity.name.function']], | |
| 166 | + ['annotation', ['meta.decorator', 'storage.type.annotation', 'entity.name.function.decorator']], | |
| 167 | + ['tag', ['entity.name.tag']], | |
| 168 | + ['tag.id.pug', ['entity.other.attribute-name.id', 'entity.name.tag']], | |
| 169 | + ['tag.class.pug', ['entity.other.attribute-name.class', 'entity.name.tag']], | |
| 170 | + ['meta.tag', ['entity.name.tag']], | |
| 171 | + ['meta.scss', ['keyword.control.at-rule', 'keyword']], | |
| 172 | + ['metatag', ['meta.tag.sgml', 'punctuation.definition.tag', 'entity.name.tag']], | |
| 173 | + ['metatag.html', ['meta.tag.sgml.doctype', 'punctuation.definition.tag', 'entity.name.tag']], | |
| 174 | + ['metatag.xml', ['meta.tag.preprocessor.xml', 'punctuation.definition.tag', 'entity.name.tag']], | |
| 175 | + ['metatag.content.html', ['string']], | |
| 176 | + ['key', ['support.type.property-name', 'entity.name.tag.yaml', 'variable.other.property']], | |
| 177 | + ['attribute.name', ['entity.other.attribute-name', 'support.type.property-name']], | |
| 178 | + ['attribute.value', ['string', 'support.constant.property-value']], | |
| 179 | + ['attribute.value.number', ['constant.numeric']], | |
| 180 | + ['attribute.value.number.css', ['constant.numeric']], | |
| 181 | + ['attribute.value.unit', ['keyword.other.unit', 'constant.numeric']], | |
| 182 | + ['attribute.value.unit.css', ['keyword.other.unit', 'constant.numeric']], | |
| 183 | + ['attribute.value.hex.css', ['constant.other.color', 'constant.numeric']], | |
| 184 | + ['attribute.value.html', ['string']], | |
| 185 | + ['attribute.value.xml', ['string']], | |
| 186 | + ['invalid', ['invalid']], | |
| 187 | + ['emphasis', ['markup.italic'], 'estilo'], | |
| 188 | + ['strong', ['markup.bold'], 'estilo'], | |
| 189 | + ['metatag.php', ['punctuation.section.embedded'], 'estilo'], | |
| 190 | +]; | |
| 191 | + | |
| 192 | +const DEF = { | |
| 193 | + 'vs-dark': { fg: '#D4D4D4', bg: '#1E1E1E' }, vs: { fg: '#000000', bg: '#FFFFFE' }, | |
| 194 | + 'hc-black': { fg: '#FFFFFF', bg: '#000000' }, 'hc-light': { fg: '#292929', bg: '#FFFFFF' }, | |
| 195 | +}; | |
| 196 | +function defaults(theme) { | |
| 197 | + const d = DEF[theme.uiTheme] || DEF['vs-dark']; | |
| 198 | + const global = (theme.tokenColors || []).find(r => !r.scope)?.settings || {}; | |
| 199 | + const bg = hex6(theme.colors?.['editor.background']) || hex6(global.background) || d.bg; | |
| 200 | + const fg = hex6(theme.colors?.['editor.foreground'], bg) || hex6(global.foreground, bg) || d.fg; | |
| 201 | + return { fg, bg }; | |
| 202 | +} | |
| 203 | + | |
| 204 | +export function monarchRules(theme) { | |
| 205 | + const { fg: defFg, bg } = defaults(theme); | |
| 206 | + const reglas = []; | |
| 207 | + for (const [token, scopes, modo] of MONARCH) { | |
| 208 | + let fg = null, fs; | |
| 209 | + for (const sc of scopes) { | |
| 210 | + const m = resolveScope(theme.tokenColors || [], sc); | |
| 211 | + if (modo === 'estilo') { if (m.fontStyle !== undefined) { fs = m.fontStyle; break; } continue; } | |
| 212 | + if (m.foreground) { fg = hex6(m.foreground, bg); fs = m.fontStyle; break; } | |
| 213 | + } | |
| 214 | + if (modo === 'estilo') { if (fs !== undefined) reglas.push({ token, fontStyle: fs }); continue; } | |
| 215 | + // sin regla en el tema: el color por defecto, que es lo que haría VS Code | |
| 216 | + // con un ámbito sin pintar (no el del tema de serie de Monaco) | |
| 217 | + const r = { token, foreground: (fg || defFg).slice(1) }; | |
| 218 | + if (fs !== undefined) r.fontStyle = fs; | |
| 219 | + reglas.push(r); | |
| 220 | + } | |
| 221 | + return reglas; | |
| 222 | +} | |
| 223 | + | |
| 224 | +// Datos para monaco.editor.defineTheme. `encodedTokensColors` (el mapa de | |
| 225 | +// colores de TextMate) solo cuando hay gramáticas TextMate activas. | |
| 226 | +export function toMonacoTheme(theme, encodedTokensColors = null) { | |
| 227 | + const colors = {}; | |
| 228 | + for (const [k, v] of Object.entries(theme.colors || {})) if (isHexColor(v)) colors[k] = v; | |
| 229 | + const data = { base: BASES.includes(theme.uiTheme) ? theme.uiTheme : 'vs-dark', inherit: true, rules: monarchRules(theme), colors }; | |
| 230 | + if (encodedTokensColors) data.encodedTokensColors = encodedTokensColors; | |
| 231 | + return data; | |
| 232 | +} | |
| 233 | + | |
| 234 | +// Tema en formato vscode-textmate (IRawTheme). Los colores van a '#RRGGBB' | |
| 235 | +// (el alfa mezclado sobre el fondo): Monaco no admite otra forma en su mapa de | |
| 236 | +// colores y los dos mapas tienen que deduplicar igual para que los índices | |
| 237 | +// coincidan. | |
| 238 | +export function toTextMateTheme(theme) { | |
| 239 | + const { fg, bg } = defaults(theme); | |
| 240 | + const settings = [{ settings: { foreground: fg, background: bg } }]; | |
| 241 | + for (const r of theme.tokenColors || []) { | |
| 242 | + if (!r.scope || !r.scope.length) continue; | |
| 243 | + const st = {}; | |
| 244 | + const f = hex6(r.settings.foreground, bg); if (f) st.foreground = f; | |
| 245 | + const b = hex6(r.settings.background, bg); if (b) st.background = b; | |
| 246 | + if (typeof r.settings.fontStyle === 'string') st.fontStyle = r.settings.fontStyle; | |
| 247 | + if (Object.keys(st).length) settings.push({ scope: r.scope, settings: st }); | |
| 248 | + } | |
| 249 | + return { name: theme.label || 'tema', settings }; | |
| 250 | +} | |
| 251 | + | |
| 252 | +// Colores TextMate para los temas de serie de Monaco: un fichero con gramática | |
| 253 | +// de una extensión se ve como en VS Code con Dark+/Light+/Alto contraste. | |
| 254 | +// Colores de los temas por defecto de VS Code (licencia MIT). | |
| 255 | +const R = (scope, foreground, fontStyle) => ({ scope: scope.split(',').map(s => s.trim()), settings: { ...(foreground && { foreground }), ...(fontStyle !== undefined && { fontStyle }) } }); | |
| 256 | +const TM_SERIE = { | |
| 257 | + 'vs-dark': ['#D4D4D4', '#1E1E1E', [ | |
| 258 | + R('comment', '#6A9955'), R('string', '#CE9178'), R('string.regexp', '#D16969'), R('constant.numeric, keyword.other.unit, markup.inserted', '#B5CEA8'), | |
| 259 | + R('constant.language, constant.character, keyword, storage, variable.language, entity.name.tag, meta.preprocessor', '#569CD6'), | |
| 260 | + R('constant.character.escape', '#D7BA7D'), R('keyword.control, entity.name.operator', '#C586C0'), R('keyword.operator', '#D4D4D4'), | |
| 261 | + R('entity.name.function, support.function', '#DCDCAA'), | |
| 262 | + R('entity.name.type, entity.name.class, entity.name.namespace, support.type, support.class', '#4EC9B0'), | |
| 263 | + R('variable, variable.parameter, support.variable, entity.other.attribute-name, support.type.property-name, constant.other.placeholder', '#9CDCFE'), | |
| 264 | + R('variable.other.constant', '#4FC1FF'), R('punctuation.definition.tag', '#808080'), R('invalid', '#F44747'), | |
| 265 | + R('entity.name.label', '#C8C8C8'), R('markup.deleted, markup.inline.raw', '#CE9178'), | |
| 266 | + R('markup.heading', '#569CD6', 'bold'), R('markup.bold', null, 'bold'), R('markup.italic', null, 'italic'), R('markup.underline.link', null, 'underline'), | |
| 267 | + ]], | |
| 268 | + vs: ['#000000', '#FFFFFE', [ | |
| 269 | + R('comment', '#008000'), R('string', '#A31515'), R('string.regexp', '#811F3F'), R('constant.numeric, keyword.other.unit, markup.inserted', '#098658'), | |
| 270 | + R('constant.language, constant.character, keyword, storage, variable.language, meta.preprocessor', '#0000FF'), | |
| 271 | + R('constant.character.escape', '#EE0000'), R('keyword.control, entity.name.operator', '#AF00DB'), R('keyword.operator', '#000000'), | |
| 272 | + R('entity.name.function, support.function', '#795E26'), | |
| 273 | + R('entity.name.type, entity.name.class, entity.name.namespace, support.type, support.class', '#267F99'), | |
| 274 | + R('variable, variable.parameter, support.variable, constant.other.placeholder', '#001080'), | |
| 275 | + R('entity.other.attribute-name, support.type.property-name', '#E50000'), R('variable.other.constant', '#0070C1'), | |
| 276 | + R('entity.name.tag, punctuation.definition.tag, markup.inline.raw', '#800000'), R('invalid', '#CD3131'), R('markup.deleted', '#A31515'), | |
| 277 | + R('markup.heading', '#800000', 'bold'), R('markup.bold', '#000080', 'bold'), R('markup.italic', null, 'italic'), R('markup.underline.link', null, 'underline'), | |
| 278 | + ]], | |
| 279 | + 'hc-black': ['#FFFFFF', '#000000', [ | |
| 280 | + R('comment', '#7CA668'), R('string', '#CE9178'), R('string.regexp', '#D16969'), R('constant.numeric, keyword.other.unit, markup.inserted', '#B5CEA8'), | |
| 281 | + R('constant.language, constant.character, keyword, storage, entity.name.tag, meta.preprocessor', '#569CD6'), | |
| 282 | + R('keyword.control', '#C586C0'), R('keyword.operator', '#D4D4D4'), R('entity.name.function, support.function', '#DCDCAA'), | |
| 283 | + R('entity.name.type, entity.name.class, entity.name.namespace, support.type, support.class', '#4EC9B0'), | |
| 284 | + R('variable, variable.language, variable.parameter, support.variable, entity.other.attribute-name', '#9CDCFE'), | |
| 285 | + R('punctuation.definition.tag', '#808080'), R('invalid', '#F44747'), R('markup.deleted', '#CE9178'), | |
| 286 | + R('markup.heading', '#6796E6', 'bold'), R('markup.bold', null, 'bold'), R('markup.italic', null, 'italic'), R('markup.underline.link', null, 'underline'), | |
| 287 | + ]], | |
| 288 | + 'hc-light': ['#292929', '#FFFFFF', [ | |
| 289 | + R('comment', '#515151'), R('string, constant.language, constant.character, keyword, storage, variable.language, entity.name.tag, meta.preprocessor, markup.inline.raw', '#0F4A85'), | |
| 290 | + R('string.regexp', '#811F3F'), R('constant.numeric, keyword.other.unit, markup.inserted', '#096D48'), | |
| 291 | + R('constant.character.escape', '#EE0000'), R('keyword.control, entity.name.operator, invalid', '#B5200D'), R('keyword.operator', '#000000'), | |
| 292 | + R('entity.name.function, support.function', '#5E2CBC'), | |
| 293 | + R('entity.name.type, entity.name.class, entity.name.namespace, support.type, support.class', '#185E73'), | |
| 294 | + R('variable, variable.parameter, support.variable, constant.other.placeholder', '#001080'), | |
| 295 | + R('entity.other.attribute-name, support.type.property-name', '#264F78'), R('variable.other.constant', '#02715D'), | |
| 296 | + R('punctuation.definition.tag', '#0F4A85'), R('markup.deleted', '#5A5A5A'), | |
| 297 | + R('markup.heading', '#0F4A85', 'bold'), R('markup.bold', '#000080', 'bold'), R('markup.italic', null, 'italic'), R('markup.underline.link', null, 'underline'), | |
| 298 | + ]], | |
| 299 | +}; | |
| 300 | +export function builtinTheme(id) { | |
| 301 | + const [fg, bg, tokenColors] = TM_SERIE[id] || TM_SERIE['vs-dark']; | |
| 302 | + return { label: id, uiTheme: TM_SERIE[id] ? id : 'vs-dark', colors: { 'editor.foreground': fg, 'editor.background': bg }, tokenColors, builtin: true }; | |
| 303 | +} | |
| 304 | + | |
| 305 | +// Ids de tema que Monaco acepta (/^[a-z0-9-]+$/i, o lanza «Illegal theme name!»). | |
| 306 | +const slug = s => String(s || '').toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''); | |
| 307 | +export function themeIdFor(extId, contrib, index, usados = new Set()) { | |
| 308 | + const base = ('x-' + slug(extId) + '-' + (slug(contrib.id || contrib.label) || 't' + index)).slice(0, 90).replace(/-+$/, ''); | |
| 309 | + let id = base; | |
| 310 | + for (let n = 2; usados.has(id); n++) id = base + '-' + n; | |
| 311 | + usados.add(id); | |
| 312 | + return id; | |
| 313 | +} | |
| 314 | + | |
| 315 | +// Las pestañas y el estado vacío del editor siguen al tema; el resto del IDE | |
| 316 | +// conserva su aspecto. Solo entran colores hex validados. | |
| 317 | +export function chromeCss(theme) { | |
| 318 | + const c = k => (isHexColor(theme.colors?.[k]) ? theme.colors[k] : null); | |
| 319 | + const { fg, bg } = defaults(theme); | |
| 320 | + const tabs = c('editorGroupHeader.tabsBackground') || c('tab.inactiveBackground') || bg; | |
| 321 | + const activa = c('tab.activeBackground') || bg; | |
| 322 | + const texto = c('tab.inactiveForeground') || fg; | |
| 323 | + const textoActiva = c('tab.activeForeground') || fg; | |
| 324 | + const borde = c('tab.border') || c('editorGroupHeader.tabsBorder') || c('editorGroup.border') || c('contrastBorder'); | |
| 325 | + const acento = c('tab.activeBorderTop') || c('tab.activeBorder') || c('focusBorder'); | |
| 326 | + return [ | |
| 327 | + `#tabs-bar { background: ${tabs};${borde ? ` border-bottom-color: ${borde};` : ''} }`, | |
| 328 | + `#tabs-bar .tab { color: ${texto};${borde ? ` border-right-color: ${borde};` : ''} }`, | |
| 329 | + `#tabs-bar .tab.active { background: ${activa}; color: ${textoActiva};${acento ? ` box-shadow: inset 0 2px 0 ${acento};` : ''} }`, | |
| 330 | + `#editor-empty { background: ${bg}; color: ${texto}; }`, | |
| 331 | + ].join('\n'); | |
| 332 | +} |
added web/js/ext/unzip.js +101 −0
| @@ -0,0 +1,101 @@ | ||
| 1 | +// Lector de .zip (un .vsix es un zip) sin dependencias: el directorio central | |
| 2 | +// se lee a mano y cada entrada se descomprime con DecompressionStream | |
| 3 | +// ('deflate-raw'), que ya traen los navegadores y Node. Solo se descomprime lo | |
| 4 | +// que se pide, con topes por entrada y en total: un zip puede declarar un | |
| 5 | +// tamaño y luego inflarse a gigas (zip bomb), así que se cuenta lo que sale de | |
| 6 | +// verdad, no lo que dice la cabecera. | |
| 7 | + | |
| 8 | +const u16 = (b, o) => b[o] | (b[o + 1] << 8); | |
| 9 | +const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; | |
| 10 | + | |
| 11 | +let CRC_TABLA = null; | |
| 12 | +export function crc32(bytes) { | |
| 13 | + if (!CRC_TABLA) { | |
| 14 | + CRC_TABLA = new Uint32Array(256); | |
| 15 | + for (let n = 0; n < 256; n++) { | |
| 16 | + let c = n; | |
| 17 | + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; | |
| 18 | + CRC_TABLA[n] = c >>> 0; | |
| 19 | + } | |
| 20 | + } | |
| 21 | + let c = 0xffffffff; | |
| 22 | + for (let i = 0; i < bytes.length; i++) c = CRC_TABLA[(c ^ bytes[i]) & 0xff] ^ (c >>> 8); | |
| 23 | + return (c ^ 0xffffffff) >>> 0; | |
| 24 | +} | |
| 25 | + | |
| 26 | +// Índice de entradas a partir del directorio central. | |
| 27 | +export function listEntries(input) { | |
| 28 | + const b = input instanceof Uint8Array ? input : new Uint8Array(input); | |
| 29 | + // el registro final (EOCD) está en los últimos 22 bytes + comentario (≤ 64 KB) | |
| 30 | + let eocd = -1; | |
| 31 | + for (let o = b.length - 22; o >= Math.max(0, b.length - 22 - 0xffff); o--) { | |
| 32 | + if (u32(b, o) === 0x06054b50) { eocd = o; break; } | |
| 33 | + } | |
| 34 | + if (eocd < 0) throw Object.assign(new Error('no es un zip (falta el directorio central)'), { code: 'notvsix' }); | |
| 35 | + const total = u16(b, eocd + 10); | |
| 36 | + const cdOffset = u32(b, eocd + 16); | |
| 37 | + if (total === 0xffff || cdOffset === 0xffffffff) throw new Error('zip64 no soportado'); | |
| 38 | + const entries = []; | |
| 39 | + const dec = new TextDecoder(); | |
| 40 | + let p = cdOffset; | |
| 41 | + for (let k = 0; k < total; k++) { | |
| 42 | + if (p + 46 > b.length || u32(b, p) !== 0x02014b50) throw new Error('directorio central corrupto'); | |
| 43 | + const flags = u16(b, p + 8); | |
| 44 | + const method = u16(b, p + 10); | |
| 45 | + const crc = u32(b, p + 16); | |
| 46 | + const csize = u32(b, p + 20); | |
| 47 | + const usize = u32(b, p + 24); | |
| 48 | + const nlen = u16(b, p + 28), xlen = u16(b, p + 30), clen = u16(b, p + 32); | |
| 49 | + const local = u32(b, p + 42); | |
| 50 | + const name = dec.decode(b.subarray(p + 46, p + 46 + nlen)).replace(/\\/g, '/'); | |
| 51 | + entries.push({ name, flags, method, crc, csize, usize, local }); | |
| 52 | + p += 46 + nlen + xlen + clen; | |
| 53 | + } | |
| 54 | + return entries; | |
| 55 | +} | |
| 56 | + | |
| 57 | +async function inflateRaw(datos, tope) { | |
| 58 | + const flujo = new Blob([datos]).stream().pipeThrough(new DecompressionStream('deflate-raw')); | |
| 59 | + const lector = flujo.getReader(); | |
| 60 | + const trozos = []; | |
| 61 | + let n = 0; | |
| 62 | + for (;;) { | |
| 63 | + const { done, value } = await lector.read(); | |
| 64 | + if (done) break; | |
| 65 | + n += value.length; | |
| 66 | + if (n > tope) { lector.cancel().catch(() => {}); throw new Error('entrada demasiado grande al descomprimir'); } | |
| 67 | + trozos.push(value); | |
| 68 | + } | |
| 69 | + const out = new Uint8Array(n); | |
| 70 | + let o = 0; | |
| 71 | + for (const t of trozos) { out.set(t, o); o += t.length; } | |
| 72 | + return out; | |
| 73 | +} | |
| 74 | + | |
| 75 | +// Abre el zip y devuelve un lector perezoso: names, has(name), read(name). | |
| 76 | +// `maxEntry` limita cada entrada y `maxTotal` lo que se descomprime en total. | |
| 77 | +export function openZip(input, { maxEntry = 8 << 20, maxTotal = 48 << 20 } = {}) { | |
| 78 | + const b = input instanceof Uint8Array ? input : new Uint8Array(input); | |
| 79 | + const entries = listEntries(b); | |
| 80 | + const porNombre = new Map(entries.filter(e => !e.name.endsWith('/')).map(e => [e.name, e])); | |
| 81 | + let gastado = 0; | |
| 82 | + async function read(name) { | |
| 83 | + const e = porNombre.get(name); | |
| 84 | + if (!e) throw new Error('no está en el paquete: ' + name); | |
| 85 | + if (e.flags & 1) throw new Error('entrada cifrada: ' + name); | |
| 86 | + if (e.usize > maxEntry) throw new Error(`${name} pesa demasiado (${e.usize} bytes)`); | |
| 87 | + if (gastado + e.usize > maxTotal) throw new Error('el paquete descomprime demasiado'); | |
| 88 | + if (e.local + 30 > b.length || u32(b, e.local) !== 0x04034b50) throw new Error('cabecera local corrupta: ' + name); | |
| 89 | + const inicio = e.local + 30 + u16(b, e.local + 26) + u16(b, e.local + 28); | |
| 90 | + const datos = b.subarray(inicio, inicio + e.csize); | |
| 91 | + if (datos.length !== e.csize) throw new Error('entrada truncada: ' + name); | |
| 92 | + let out; | |
| 93 | + if (e.method === 0) out = datos.slice(); | |
| 94 | + else if (e.method === 8) out = await inflateRaw(datos, Math.min(maxEntry, e.usize)); | |
| 95 | + else throw new Error(`compresión ${e.method} no soportada: ${name}`); | |
| 96 | + if (out.length !== e.usize || crc32(out) !== e.crc) throw new Error('CRC incorrecto: ' + name); | |
| 97 | + gastado += out.length; | |
| 98 | + return out; | |
| 99 | + } | |
| 100 | + return { names: [...porNombre.keys()], has: n => porNombre.has(n), read, entries }; | |
| 101 | +} |
added web/js/ext/vsix.js +157 −0
| @@ -0,0 +1,157 @@ | ||
| 1 | +// Un .vsix (zip) → lo que Elffuss Code sabe aplicar: temas, gramáticas, | |
| 2 | +// snippets y lenguajes. NUNCA se lee, importa ni evalúa JavaScript del | |
| 3 | +// paquete: `main` y `browser` se ignoran y solo se descomprimen el manifiesto, | |
| 4 | +// sus traducciones, la licencia y los ficheros que citan esas contribuciones. | |
| 5 | +import { openZip } from './unzip.js'; | |
| 6 | +import { parseJsonc, parsePlist } from './formats.js'; | |
| 7 | +import { loadTheme, joinPath } from './themes.js'; | |
| 8 | +import { normalizeSnippets } from './snippets.js'; | |
| 9 | + | |
| 10 | +export const SUPPORTED = ['themes', 'grammars', 'snippets', 'languages']; | |
| 11 | + | |
| 12 | +// Contribuciones que solo tienen sentido con el código de la extensión | |
| 13 | +// corriendo (haría falta un host de extensiones). El resto de las que no se | |
| 14 | +// aplican son declarativas: «todavía no». | |
| 15 | +const NEEDS_CODE = new Set([ | |
| 16 | + 'commands', 'menus', 'submenus', 'keybindings', 'views', 'viewsContainers', 'viewsWelcome', 'debuggers', | |
| 17 | + 'breakpoints', 'taskDefinitions', 'customEditors', 'notebooks', 'notebookRenderer', 'authentication', | |
| 18 | + 'walkthroughs', 'terminal', 'codeActions', 'configuration', 'typescriptServerPlugins', 'chatParticipants', | |
| 19 | + 'languageModelTools', 'mcpServerDefinitionProviders', 'remoteHelp', 'resourceLabelFormatters', 'statusBarItems', | |
| 20 | +]); | |
| 21 | + | |
| 22 | +// Lo que una extensión aplicaría aquí y lo que no, a partir de su package.json | |
| 23 | +// (sirve igual con el manifiesto que publica Open VSX que con el del .vsix). | |
| 24 | +export function analyzeManifest(pkg) { | |
| 25 | + const c = pkg && typeof pkg.contributes === 'object' && pkg.contributes ? pkg.contributes : {}; | |
| 26 | + const n = k => (Array.isArray(c[k]) ? c[k].length : 0); | |
| 27 | + const applies = { themes: n('themes'), grammars: n('grammars'), snippets: n('snippets'), languages: n('languages') }; | |
| 28 | + const ignored = []; | |
| 29 | + for (const k of Object.keys(c)) { | |
| 30 | + if (SUPPORTED.includes(k)) continue; | |
| 31 | + ignored.push({ key: k, why: NEEDS_CODE.has(k) ? 'code' : 'later' }); | |
| 32 | + } | |
| 33 | + const hasCode = typeof pkg?.main === 'string' || typeof pkg?.browser === 'string'; | |
| 34 | + const pack = Array.isArray(pkg?.extensionPack) ? pkg.extensionPack.filter(x => typeof x === 'string') : []; | |
| 35 | + const snippetLangs = [...new Set((c.snippets || []).map(s => s?.language).filter(x => typeof x === 'string'))]; | |
| 36 | + const languages = [...new Set([...(c.languages || []).map(l => l?.id), ...(c.grammars || []).map(g => g?.language)].filter(x => typeof x === 'string'))]; | |
| 37 | + return { applies, ignored, hasCode, pack, snippetLangs, languages, any: Object.values(applies).some(Boolean) }; | |
| 38 | +} | |
| 39 | + | |
| 40 | +// %clave% → texto de package.nls(.<idioma>).json, en todo el manifiesto. | |
| 41 | +export function resolveNls(pkg, nls) { | |
| 42 | + const msg = v => (typeof v === 'string' ? v : v && typeof v.message === 'string' ? v.message : null); | |
| 43 | + const walk = v => { | |
| 44 | + if (typeof v === 'string') { | |
| 45 | + const m = /^%([^%\s]+)%$/.exec(v); | |
| 46 | + return m && msg(nls?.[m[1]]) != null ? msg(nls[m[1]]) : v; | |
| 47 | + } | |
| 48 | + if (Array.isArray(v)) return v.map(walk); | |
| 49 | + if (v && typeof v === 'object') { const o = {}; for (const [k, x] of Object.entries(v)) o[k] = walk(x); return o; } | |
| 50 | + return v; | |
| 51 | + }; | |
| 52 | + return walk(pkg); | |
| 53 | +} | |
| 54 | + | |
| 55 | +const strs = v => (Array.isArray(v) ? v.filter(x => typeof x === 'string') : []); | |
| 56 | +const mapaStr = v => { | |
| 57 | + if (!v || typeof v !== 'object' || Array.isArray(v)) return undefined; | |
| 58 | + const o = {}; | |
| 59 | + for (const [k, x] of Object.entries(v)) if (typeof x === 'string') o[k] = x; | |
| 60 | + return o; | |
| 61 | +}; | |
| 62 | + | |
| 63 | +// Lee el paquete entero. Los fallos de una contribución suelta van a | |
| 64 | +// `warnings` y no tumban la instalación del resto. | |
| 65 | +export async function readVsix(bytes, { lang = 'en' } = {}) { | |
| 66 | + const zip = openZip(bytes); | |
| 67 | + const dec = new TextDecoder(); | |
| 68 | + const readText = async p => { | |
| 69 | + if (!p.startsWith('extension/')) throw new Error('ruta fuera de la extensión: ' + p); | |
| 70 | + return dec.decode(await zip.read(p)); | |
| 71 | + }; | |
| 72 | + if (!zip.has('extension/package.json')) throw Object.assign(new Error('no es una extensión de VS Code (falta extension/package.json)'), { code: 'notvsix' }); | |
| 73 | + let pkg = parseJsonc(await readText('extension/package.json')); | |
| 74 | + let nls = {}; | |
| 75 | + for (const f of ['extension/package.nls.json', `extension/package.nls.${lang}.json`]) { | |
| 76 | + if (zip.has(f)) { try { nls = { ...nls, ...parseJsonc(await readText(f)) }; } catch { /* traducción rota: se queda la clave */ } } | |
| 77 | + } | |
| 78 | + pkg = resolveNls(pkg, nls); | |
| 79 | + if (typeof pkg.name !== 'string' || typeof pkg.publisher !== 'string') throw new Error('package.json sin name/publisher'); | |
| 80 | + | |
| 81 | + const warnings = []; | |
| 82 | + const ruta = p => joinPath('extension', String(p)); | |
| 83 | + const c = pkg.contributes && typeof pkg.contributes === 'object' ? pkg.contributes : {}; | |
| 84 | + | |
| 85 | + const themes = []; | |
| 86 | + for (const [i, t] of (Array.isArray(c.themes) ? c.themes : []).entries()) { | |
| 87 | + if (!t || typeof t.path !== 'string') continue; | |
| 88 | + try { | |
| 89 | + const data = await loadTheme(ruta(t.path), readText, { label: t.label || t.id || t.path, uiTheme: t.uiTheme }); | |
| 90 | + themes.push({ index: i, id: typeof t.id === 'string' ? t.id : '', label: data.label, uiTheme: data.uiTheme, path: ruta(t.path), data }); | |
| 91 | + } catch (e) { warnings.push(`tema ${t.label || t.path}: ${e.message}`); } | |
| 92 | + } | |
| 93 | + | |
| 94 | + const grammars = []; | |
| 95 | + for (const g of Array.isArray(c.grammars) ? c.grammars : []) { | |
| 96 | + if (!g || typeof g.path !== 'string' || typeof g.scopeName !== 'string') continue; | |
| 97 | + try { | |
| 98 | + const p = ruta(g.path); | |
| 99 | + const text = await readText(p); | |
| 100 | + const data = /\.json$/i.test(p) ? parseJsonc(text) : parsePlist(text); | |
| 101 | + if (!data || typeof data !== 'object' || !Array.isArray(data.patterns) && !data.injectionSelector) throw new Error('no parece una gramática TextMate'); | |
| 102 | + grammars.push({ | |
| 103 | + path: p, scopeName: g.scopeName, data, | |
| 104 | + language: typeof g.language === 'string' ? g.language : undefined, | |
| 105 | + embeddedLanguages: mapaStr(g.embeddedLanguages), tokenTypes: mapaStr(g.tokenTypes), | |
| 106 | + injectTo: strs(g.injectTo), balancedBracketScopes: Array.isArray(g.balancedBracketScopes) ? strs(g.balancedBracketScopes) : undefined, | |
| 107 | + unbalancedBracketScopes: Array.isArray(g.unbalancedBracketScopes) ? strs(g.unbalancedBracketScopes) : undefined, | |
| 108 | + }); | |
| 109 | + } catch (e) { warnings.push(`gramática ${g.scopeName}: ${e.message}`); } | |
| 110 | + } | |
| 111 | + | |
| 112 | + const snippets = []; | |
| 113 | + const porRuta = new Map(); | |
| 114 | + for (const s of Array.isArray(c.snippets) ? c.snippets : []) { | |
| 115 | + if (!s || typeof s.path !== 'string' || typeof s.language !== 'string') continue; | |
| 116 | + const p = ruta(s.path); | |
| 117 | + try { | |
| 118 | + if (!porRuta.has(p)) porRuta.set(p, normalizeSnippets(parseJsonc(await readText(p)))); | |
| 119 | + if (porRuta.get(p).length) snippets.push({ language: s.language, path: p, data: porRuta.get(p) }); | |
| 120 | + } catch (e) { warnings.push(`snippets ${s.path}: ${e.message}`); } | |
| 121 | + } | |
| 122 | + | |
| 123 | + const languages = []; | |
| 124 | + for (const l of Array.isArray(c.languages) ? c.languages : []) { | |
| 125 | + if (!l || typeof l.id !== 'string' || !l.id) continue; | |
| 126 | + const entry = { | |
| 127 | + id: l.id, aliases: strs(l.aliases), extensions: strs(l.extensions), filenames: strs(l.filenames), | |
| 128 | + filenamePatterns: strs(l.filenamePatterns), mimetypes: strs(l.mimetypes), | |
| 129 | + firstLine: typeof l.firstLine === 'string' ? l.firstLine : undefined, configPath: null, config: null, | |
| 130 | + }; | |
| 131 | + if (typeof l.configuration === 'string') { | |
| 132 | + try { entry.configPath = ruta(l.configuration); entry.config = parseJsonc(await readText(entry.configPath)); } | |
| 133 | + catch (e) { warnings.push(`configuración de ${l.id}: ${e.message}`); entry.configPath = null; } | |
| 134 | + } | |
| 135 | + languages.push(entry); | |
| 136 | + } | |
| 137 | + | |
| 138 | + // licencia: la que diga «SEE LICENSE IN x» o el LICENSE* de la raíz | |
| 139 | + let licenseText = ''; | |
| 140 | + const ref = /^SEE LICEN[SC]E IN (.+)$/i.exec(String(pkg.license || ''))?.[1]?.trim(); | |
| 141 | + const candidatas = [ref && ruta(ref), ...zip.names.filter(n => /^extension\/licen[sc]e(\.[\w-]+|-[\w.-]+)?$/i.test(n))].filter(Boolean); | |
| 142 | + for (const f of candidatas) { | |
| 143 | + if (!zip.has(f)) continue; | |
| 144 | + try { licenseText = (await readText(f)).slice(0, 200_000); break; } catch { /* siguiente */ } | |
| 145 | + } | |
| 146 | + | |
| 147 | + return { | |
| 148 | + manifest: pkg, | |
| 149 | + publisher: pkg.publisher, name: pkg.name, version: String(pkg.version || '0.0.0'), | |
| 150 | + id: `${pkg.publisher}.${pkg.name}`.toLowerCase(), | |
| 151 | + displayName: typeof pkg.displayName === 'string' ? pkg.displayName : pkg.name, | |
| 152 | + description: typeof pkg.description === 'string' ? pkg.description : '', | |
| 153 | + license: typeof pkg.license === 'string' ? pkg.license : '', | |
| 154 | + licenseText, themes, grammars, snippets, languages, warnings, | |
| 155 | + analysis: analyzeManifest(pkg), | |
| 156 | + }; | |
| 157 | +} |